@extends('layouts.layout1')
@section('title', 'Artikel || KLINIK PKP JAWA 3')

@section('content')
    <style>
        /* CSS Custom Properties for better dark mode support */
        :root {
            --bg-primary: #f9fafb;
            --bg-secondary: #ffffff;
            --bg-card: #ffffff;
            --bg-card-hover: #f8fafc;
            --text-primary: #1f2937;
            --text-secondary: #6b7280;
            --text-muted: #9ca3af;
            --border-color: #e5e7eb;
            --border-hover: var(--judges-base);
            --modal-bg: #ffffff;
            --modal-footer-bg: #f9fafb;
        }

        [data-theme="dark"],
        body.dark-mode {
            --bg-primary: #1f2937;
            --bg-secondary: #111827;
            --bg-card: #374151;
            --bg-card-hover: #4b5563;
            --text-primary: #f9fafb;
            --text-secondary: #d1d5db;
            --text-muted: #9ca3af;
            --border-color: #4b5563;
            --border-hover: var(--judges-base);
            --modal-bg: #374151;
            --modal-footer-bg: #2d3748;
        }

 /* Hero Section */
        .hero-section {
            background: linear-gradient(135deg, var(--judges-base) 0%,  var(--judges-base) 100%);
            min-height: 500px;
            display: flex;
            align-items: center;
            justify-content: center;
            position: relative;
            overflow: hidden;
            padding: 4rem 2rem;
        }

        .hero-section::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1440 320"><path fill="%23ffffff" fill-opacity="0.1" d="M0,96L48,112C96,128,192,160,288,160C384,160,480,128,576,112C672,96,768,96,864,112C960,128,1056,160,1152,160C1248,160,1344,128,1392,112L1440,96L1440,320L1392,320C1344,320,1248,320,1152,320C1056,320,960,320,864,320C768,320,672,320,576,320C480,320,384,320,288,320C192,320,96,320,48,320L0,320Z"></path></svg>') no-repeat bottom;
            background-size: cover;
        }

        .hero-content {
            position: relative;
            z-index: 1;
            max-width: 800px;
            text-align: center;
            color: white;
        }

        .hero-title {
            font-size: 2.5rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.2);
            color: #f9fafb;
        }

    .hero-subtitle {
            font-size: 1.25rem;
            margin-bottom: 2rem;
            opacity: 0.95;
            line-height: 1.8;
            max-width: 600px;
            margin-left: auto;
            margin-right: auto;
        }

        .hero-divider {
            width: 100px;
            height: 4px;
            background: white;
            margin: 2rem auto;
            border-radius: 2px;
        }

        /* Container Section */
        .article-section {
            padding: 2rem 1rem;
            background-color: var(--bg-primary);
            min-height: 60vh;
        }

        .container-content {
            max-width: 1400px;
            margin: 0 auto;
            padding: 0 1rem;
        }

        /* Search and Filter Section */
        .search-filter-section {
            background: var(--bg-card);
            border-radius: 16px;
            padding: 1.5rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
            border: 1px solid var(--border-color);
        }

        .search-container {
            position: relative;
            margin-bottom: 1.5rem;
            max-width: 600px;
            margin-left: auto;
            margin-right: auto;
        }

        .search-input {
            width: 100%;
            padding: 12px 20px 12px 50px;
            border: 2px solid var(--border-color);
            border-radius: 12px;
            font-size: 16px;
            background: var(--bg-card);
            color: var(--text-primary);
            transition: all 0.3s ease;
        }

        .search-input:focus {
            outline: none;
            border-color: var(--judges-base);
            box-shadow: 0 0 0 3px color-mix(in srgb, var(--judges-base) 10%, transparent);
        }

        .search-icon {
            position: absolute;
            left: 16px;
            top: 50%;
            transform: translateY(-50%);
            color: var(--text-muted);
            font-size: 18px;
        }

        .clear-search {
            position: absolute;
            right: 16px;
            top: 50%;
            transform: translateY(-50%);
            background: none;
            border: none;
            color: var(--text-muted);
            cursor: pointer;
            font-size: 18px;
            display: none;
            padding: 4px;
            border-radius: 4px;
            transition: all 0.2s ease;
        }

        .clear-search:hover {
            color: var(--text-primary);
            background: var(--bg-primary);
        }

        /* Filter Tabs - Modern Design */
        .filter-tabs {
            display: flex;
            justify-content: flex-start;
            gap: 0.5rem;
            flex-wrap: wrap;
        }

        .filter-tab {
            padding: 8px 20px;
            background: var(--bg-primary);
            border: 2px solid var(--border-color);
            border-radius: 20px;
            font-weight: 600;
            font-size: 14px;
            color: var(--text-secondary);
            cursor: pointer;
            transition: all 0.3s ease;
            white-space: nowrap;
            display: inline-flex;
            align-items: center;
            gap: 6px;
        }

        .filter-tab:hover {
            border-color: var(--judges-base);
            color: var(--judges-base);
            transform: translateY(-1px);
            box-shadow: 0 2px 8px color-mix(in srgb, var(--judges-base) 20%, transparent);
        }

        .filter-tab.active {
            background: var(--judges-base);
            border-color: var(--judges-base);
            color: white;
            box-shadow: 0 2px 8px color-mix(in srgb, var(--judges-base) 30%, transparent);
        }

        .filter-count {
            background: rgba(255, 255, 255, 0.2);
            padding: 2px 6px;
            border-radius: 10px;
            font-size: 12px;
            font-weight: 700;
        }

        .filter-tab.active .filter-count {
            background: rgba(255, 255, 255, 0.3);
        }

        /* Article Cards - Compact Grid */
        .article-cards {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 1.5rem;
            margin-top: 2rem;
        }

        .article-card {
            background: var(--bg-card);
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
            overflow: hidden;
            transition: all 0.3s ease;
            border: 1px solid var(--border-color);
            position: relative;
        }

        .article-card:hover {
            transform: translateY(-4px);
            box-shadow: 0 8px 25px rgba(0, 0, 0, 0.12);
            border-color: var(--judges-base);
        }

        .article-card-image {
            width: 100%;
            height: 180px;
            object-fit: cover;
            background: linear-gradient(135deg, #aeb0b4ff 0%, #aeb0b4ff 100%);
        }

        .article-card-image-container {
            position: relative;
            width: 100%;
            height: 180px;
            overflow: hidden;
            background: linear-gradient(135deg, #aeb0b4ff 0%, #aeb0b4ff 100%);
        }

        .article-card-badge {
            position: absolute;
            top: 12px;
            right: 12px;
            background: var(--judges-base);
            color: white;
            padding: 4px 12px;
            border-radius: 12px;
            font-size: 11px;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
        }

        .article-card-body {
            padding: 1.25rem;
        }

        .article-title {
            font-size: 1.1rem;
            font-weight: 700;
            color: var(--text-primary);
            margin-bottom: 0.75rem;
            line-height: 1.4;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
            height: 2.8rem;
        }

        .article-excerpt {
            color: var(--text-secondary);
            font-size: 0.9rem;
            line-height: 1.5;
            margin-bottom: 1rem;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
            height: 2.7rem;
        }

        .article-meta {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding-top: 1rem;
            border-top: 1px solid var(--border-color);
        }

        .article-date {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            color: var(--text-muted);
            font-size: 0.8rem;
        }

        .btn-read-more {
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            padding: 6px 12px;
            background: var(--judges-base);
            color: white;
            border-radius: 6px;
            text-decoration: none;
            font-weight: 600;
            font-size: 0.8rem;
            transition: all 0.3s ease;
        }

        .btn-read-more:hover {
            background: white;
            color: var(--judges-base);
            border: 1px solid var(--judges-base);
            opacity: 0.9;
            transform: translateY(-1px);
            box-shadow: 0 4px 12px color-mix(in srgb, var(--judges-base) 30%, transparent);
        }

        /* Results Info */
        .results-info {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin: 1.5rem 0 1rem 0;
            padding: 0 0.5rem;
        }

        .year-header {
            font-size: 1.125rem;
            font-weight: 700;
            margin: 1.5rem 0 0.75rem;
            color: var(--text-primary);
        }

        .year-group {
            margin-bottom: 1.25rem;
        }

        .results-count {
            color: var(--text-secondary);
            font-size: 0.9rem;
            font-weight: 500;
        }

        .sort-options {
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .sort-label {
            color: var(--text-secondary);
            font-size: 0.9rem;
            font-weight: 500;
        }

        .sort-select {
            padding: 6px 12px;
            border: 1px solid var(--border-color);
            border-radius: 8px;
            background: var(--bg-card);
            color: var(--text-primary);
            font-size: 0.9rem;
            cursor: pointer;
        }

        .sort-select:focus {
            outline: none;
            border-color: var(--judges-base);
        }
        .empty-state {
            text-align: center;
            padding: 4rem 2rem;
            background: var(--bg-card);
            border-radius: 16px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
        }

        .empty-state-icon {
            font-size: 4rem;
            color: var(--text-muted);
            margin-bottom: 1rem;
        }

        .empty-state-text {
            font-size: 1.125rem;
            color: var(--text-secondary);
        }

        /* Loading */
        .loading-container {
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 4rem;
            color: var(--text-primary);
        }

        .spinner {
            width: 50px;
            height: 50px;
            border: 4px solid var(--border-color);
            border-top-color: var(--judges-base);
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            to {
                transform: rotate(360deg);
            }
        }

        /* Responsive */
        @media (max-width: 768px) {
            .hero-title {
                font-size: 2rem;
            }

            .hero-subtitle {
                font-size: 1rem;
            }

            .section-title {
                font-size: 2rem;
            }

            .article-cards {
                grid-template-columns: 1fr;
            }

            .filter-tabs {
                flex-direction: column;
                align-items: stretch;
            }

            .filter-tab {
                text-align: center;
            }
        }

        /* Modal Styles */
        .modal-overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.75);
            backdrop-filter: blur(4px);
            z-index: 99999;
            animation: fadeIn 0.3s ease;
            overflow-y: auto;
            padding: 2rem 0;
            align-items: flex-start;
            justify-content: center;
        }

        .modal-detail {
            display: none;
            position: fixed;
            top: 2rem;
            left: 50%;
            transform: translateX(-50%);
            background: var(--modal-bg);
            border-radius: 20px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
            max-width: 900px;
            width: 90%;
            max-height: calc(100vh - 4rem);
            overflow-y: auto;
            animation: slideUp 0.3s ease;
            z-index: 100000;
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
            }

            to {
                opacity: 1;
            }
        }

        @keyframes slideUp {
            from {
                opacity: 0;
                transform: translateY(30px);
            }

            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .modal-header-image {
            width: 100%;
            height: 400px;
            object-fit: cover;
            border-radius: 20px 20px 0 0;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }

        .modal-close {
            position: absolute;
            top: 1.5rem;
            right: 1.5rem;
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border: none;
            color: #1f2937;
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all 0.3s ease;
            font-size: 1.5rem;
            line-height: 1;
            z-index: 100001;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
        }

        .modal-close:hover {
            background: var(--judges-base);
            color: white;
            transform: rotate(90deg);
        }

        .modal-content {
            padding: 2rem;
        }

        .modal-meta {
            display: flex;
            align-items: center;
            gap: 1rem;
            margin-bottom: 1.5rem;
            flex-wrap: wrap;
        }

        .modal-category {
            display: inline-block;
            padding: 0.5rem 1rem;
            background: var(--judges-base);
            color: white;
            border-radius: 20px;
            font-size: 0.875rem;
            font-weight: 700;
        }

        .modal-badge {
            display: inline-block;
            padding: 0.5rem 1rem;
            background: var(--bg-primary);
            color: var(--judges-base);
            border-radius: 20px;
            font-size: 0.875rem;
            font-weight: 700;
        }

        .modal-date {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            color: var(--text-secondary);
            font-size: 0.875rem;
        }

        .modal-title {
            font-size: 2rem;
            font-weight: 700;
            color: var(--text-primary);
            line-height: 1.4;
            margin-bottom: 1.5rem;
        }

        .modal-body-text {
            font-size: 1.125rem;
            line-height: 1.8;
            color: var(--text-primary);
            margin-bottom: 2rem;
            white-space: pre-wrap;
            word-wrap: break-word;
        }

        .modal-divider {
            height: 2px;
            background: var(--judges-base);
            margin: 2rem 0;
            border-radius: 2px;
        }

        .modal-footer {
            padding: 1.5rem 2rem;
            background: var(--modal-footer-bg);
            border-radius: 0 0 20px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .modal-share-text {
            font-weight: 600;
            color: var(--text-secondary);
        }

        .btn-close-modal {
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            padding: 0.75rem 1.5rem;
            background: var(--judges-base);
            color: white;
            border-radius: 8px;
            border: none;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .btn-close-modal:hover {
            background: var(--judges-base);
            opacity: 0.9;
            transform: translateY(-2px);
            box-shadow: 0 6px 16px color-mix(in srgb, var(--judges-base) 40%, transparent);
        }

        @media (max-width: 768px) {
            .modal-detail {
                width: 95%;
                margin: 1rem auto;
            }

            .modal-header-image {
                height: 250px;
            }

            .modal-content {
                padding: 1.5rem;
            }

            .modal-title {
                font-size: 1.5rem;
            }

            .modal-body-text {
                font-size: 1rem;
            }

            .modal-footer {
                flex-direction: column;
                gap: 1rem;
                text-align: center;
            }
        }

        /* Dark Mode Support - Comprehensive */
        [data-theme="dark"] .hero-section,
        body.dark-mode .hero-section {
            background: linear-gradient(135deg, #374151 0%, #1f2937 100%) !important;
        }

        [data-theme="dark"] .hero-title,
        [data-theme="dark"] .hero-subtitle,
        [data-theme="dark"] .hero-divider,
        body.dark-mode .hero-title,
        body.dark-mode .hero-subtitle,
        body.dark-mode .hero-divider {
            color: #f9fafb !important;
        }

        /* Force dark mode compatibility for all elements */
        [data-theme="dark"] .article-section,
        body.dark-mode .article-section {
            background: var(--bg-primary) !important;
            background-color: var(--bg-primary) !important;
        }

        [data-theme="dark"] .section-title,
        [data-theme="dark"] #main-title,
        body.dark-mode .section-title,
        body.dark-mode #main-title {
            color: var(--text-primary) !important;
        }

        [data-theme="dark"] .section-subtitle,
        [data-theme="dark"] #main-subtitle,
        body.dark-mode .section-subtitle,
        body.dark-mode #main-subtitle {
            color: var(--text-secondary) !important;
        }

        [data-theme="dark"] .filter-tab,
        [data-theme="dark"] .article-card,
        [data-theme="dark"] .empty-state,
        [data-theme="dark"] .modal-detail,
        body.dark-mode .filter-tab,
        body.dark-mode .article-card,
        body.dark-mode .empty-state,
        body.dark-mode .modal-detail {
            background: var(--bg-card) !important;
            border-color: var(--border-color) !important;
            color: var(--text-primary) !important;
        }

        [data-theme="dark"] .article-title,
        [data-theme="dark"] .modal-title,
        body.dark-mode .article-title,
        body.dark-mode .modal-title {
            color: var(--text-primary) !important;
        }

        [data-theme="dark"] .article-excerpt,
        [data-theme="dark"] .empty-state-text,
        [data-theme="dark"] .modal-body-text,
        [data-theme="dark"] .modal-share-text,
        body.dark-mode .article-excerpt,
        body.dark-mode .empty-state-text,
        body.dark-mode .modal-body-text,
        body.dark-mode .modal-share-text {
            color: var(--text-secondary) !important;
        }

        [data-theme="dark"] .article-date,
        [data-theme="dark"] .modal-date,
        [data-theme="dark"] .empty-state-icon,
        body.dark-mode .article-date,
        body.dark-mode .modal-date,
        body.dark-mode .empty-state-icon {
            color: var(--text-muted) !important;
        }

        [data-theme="dark"] .article-category,
        [data-theme="dark"] .modal-badge,
        body.dark-mode .article-category,
        body.dark-mode .modal-badge {
            background: var(--bg-primary) !important;
            color: var(--judges-base) !important;
        }

        [data-theme="dark"] .article-meta,
        body.dark-mode .article-meta {
            border-top-color: var(--border-color) !important;
        }

        [data-theme="dark"] .modal-footer,
        body.dark-mode .modal-footer {
            background: var(--modal-footer-bg) !important;
        }

        [data-theme="dark"] .modal-close,
        body.dark-mode .modal-close {
            background: rgba(255, 255, 255, 0.1) !important;
            color: var(--text-primary) !important;
        }

        [data-theme="dark"] .modal-close:hover,
        body.dark-mode .modal-close:hover {
            background: var(--judges-base) !important;
            color: white !important;
        }

        /* SVG icons in dark mode */
        [data-theme="dark"] .btn-read-more svg,
        [data-theme="dark"] .btn-close-modal svg,
        [data-theme="dark"] .article-date svg,
        [data-theme="dark"] .modal-date svg,
        body.dark-mode .btn-read-more svg,
        body.dark-mode .btn-close-modal svg,
        body.dark-mode .article-date svg,
        body.dark-mode .modal-date svg {
            fill: currentColor !important;
        }

        /* Dark mode for dynamically generated content */
        [data-theme="dark"] .filter-tab:hover,
        body.dark-mode .filter-tab:hover {
            background: var(--bg-card-hover) !important;
            color: var(--judges-base) !important;
        }

        [data-theme="dark"] .article-card:hover,
        body.dark-mode .article-card:hover {
            background: var(--bg-card-hover) !important;
        }
    </style>

    <!-- Hero Section -->
    <section class="hero-section">
        <div class="hero-content">
            <h1 class="hero-title">Artikel</h1>
            <div class="hero-divider"></div>
            <p class="hero-subtitle">
                Kumpulan artikel, berita, dan informasi terkini seputar perumahan,
                pembangunan, dan program-program Kementerian PKP.
            </p>
        </div>
    </section>

    <!-- Article Section -->
    <section class="article-section">
        <div class="container-content">
            <!-- Search and Filter Section -->
            <div class="search-filter-section">
                <!-- Search Bar -->
                <div class="search-container">
                    <i class="fas fa-search search-icon"></i>
                    <input type="text" class="search-input" id="search-input" placeholder="Cari judul artikel...">
                    <button class="clear-search" id="clear-search" onclick="clearSearch()">
                        <i class="fas fa-times"></i>
                    </button>
                </div>

                <!-- Filter Tabs -->
                <div class="filter-tabs" id="filter-tabs">
                    <button class="filter-tab active" onclick="filterArticles('all')" data-filter="all">
                        <i class="fas fa-list"></i>
                        <span>Semua</span>
                        <span class="filter-count" id="count-all">0</span>
                    </button>
                    <button class="filter-tab" onclick="filterArticles('local')" data-filter="local">
                        <i class="fas fa-map-marker-alt"></i>
                        <span>Artikel Lokal</span>
                        <span class="filter-count" id="count-local">0</span>
                    </button>
                    <button class="filter-tab" onclick="filterArticles('inherited')" data-filter="inherited">
                        <i class="fas fa-globe"></i>
                        <span>Berita dari Klinik PKP Jawa-III</span>
                        <span class="filter-count" id="count-inherited">0</span>
                    </button>
                </div>
            </div>

            <!-- Results Info and Sort -->
            <div class="results-info">
                <div class="results-count" id="results-count">
                    Menampilkan 0 artikel
                </div>
                <div class="sort-options">
                    <span class="sort-label">Urutkan:</span>
                    <select class="sort-select" id="sort-select" onchange="sortArticles()">
                        <option value="newest">Terbaru</option>
                        <option value="oldest">Terlama</option>
                        <option value="title">Judul A-Z</option>
                    </select>
                    <div style="margin-left:0.75rem;display:inline-flex;align-items:center;gap:0.5rem;">
                        <span class="sort-label">Tahun:</span>
                        <select id="yearSelect" class="sort-select" style="min-width:120px;">
                            <option value="">Semua Tahun</option>
                            <option value="2026">2026</option>
                            <option value="2025">2025</option>
                            <!-- <option value="2024">2024</option>
                            <option value="2023">2023</option>
                            <option value="2022">2022</option> -->
                        </select>
                    </div>
                </div>
            </div>

            <!-- Loading State -->
            <div id="loading-container" class="loading-container">
                <div class="spinner"></div>
                <p style="margin-left: 1rem;">Memuat artikel...</p>
            </div>

            <!-- Article Cards -->
            <div id="article-cards" class="article-cards" style="display: none;">
                <!-- Article cards will be inserted here -->
            </div>

            <!-- Empty State -->
            <div id="empty-state" class="empty-state" style="display: none;">
                <div class="empty-state-icon">
                    <i class="fas fa-newspaper"></i>
                </div>
                <h3>Tidak ada artikel ditemukan</h3>
                <p class="empty-state-text">Coba ubah kata kunci pencarian atau filter yang dipilih</p>
            </div>
        </div>
    </section>


    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script>
        // Add dynamic dark mode class detection
        function syncDarkMode() {
            const isDarkMode = document.documentElement.getAttribute('data-theme') === 'dark';
            if (isDarkMode) {
                document.body.classList.add('dark-mode');
            } else {
                document.body.classList.remove('dark-mode');
            }
        }

        // Initial sync
        syncDarkMode();

        // Watch for theme changes
        const observer = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {
                if (mutation.type === 'attributes' && mutation.attributeName === 'data-theme') {
                    syncDarkMode();
                }
            });
        });

        observer.observe(document.documentElement, {
            attributes: true,
            attributeFilter: ['data-theme']
        });

        // Article management
        let allArticles = {
            all: [],
            local: [],
            inherited: []
        };
        let currentFilter = 'all';
        let currentSort = 'newest';
        let currentSearch = '';

        $(document).ready(function() {
            const BASE_URL = "{{ env('BASE_URL') }}";
            const DAERAH = "{{ env('DAERAH') }}";

            console.log('=== ARTIKEL PAGE INIT ===');
            console.log('BASE_URL:', BASE_URL);
            console.log('DAERAH:', DAERAH);

            // Show loading state initially
            $('#loading-container').show();
            $('#article-cards').hide();
            $('#empty-state').hide();

            // Setup search functionality
            setupSearch();

            // Wire year select change inside ready to ensure element exists
            $('#yearSelect').on('change', applyFiltersAndSearch);

            console.log('Fetching data from:', `${BASE_URL}/api/public/sites/${DAERAH}`);

            // Fetch local articles data
            $.ajax({
                url: `${BASE_URL}/api/public/sites/${DAERAH}`,
                method: 'GET',
                success: function(response) {
                    console.log('=== API SUCCESS ===');
                    console.log('API Response (Full):', response);

                    // Get local articles from response
                    allArticles.local = response.local?.articles || [];

                    // Get inherited articles from response
                    allArticles.inherited = response.inherited?.articles || [];

                    // Combine for 'all'
                    allArticles.all = [...allArticles.local, ...allArticles.inherited];

                    console.log('Local Articles Count:', allArticles.local.length);
                    console.log('Inherited Articles Count:', allArticles.inherited.length);
                    console.log('All Articles Combined Count:', allArticles.all.length);
                    console.log('Sample article:', allArticles.all[0]);

                    // Check if we have any articles to display
                    checkAndDisplayArticles();
                },
                error: function(xhr, status, error) {
                    console.error('=== API ERROR ===');
                    console.error('Status:', status);
                    console.error('Error:', error);
                    console.error('Response:', xhr.responseText);
                    
                    $('#loading-container').hide();
                    $('#empty-state').show();
                    $('#empty-state .empty-state-text').text(
                        'Terjadi kesalahan saat memuat data. Silakan coba lagi nanti.');
                }
            });
        });

        function checkAndDisplayArticles() {
            console.log('=== CHECKING AND DISPLAYING ARTICLES ===');
            
            // Hide loading once we have data
            $('#loading-container').hide();
            
            // Update filter counts
            updateFilterCounts();

            console.log('Total articles available:', allArticles.all.length);
            console.log('Current filter:', currentFilter);
            console.log('Articles for current filter:', allArticles[currentFilter].length);

            if (allArticles.all.length > 0) {
                console.log('Showing article cards and applying filters');
                $('#article-cards').show();
                $('#empty-state').hide();
                applyFiltersAndSearch(); // Use new function
            } else {
                console.log('No articles found, showing empty state');
                $('#article-cards').hide();
                $('#empty-state').show();
            }
        }

        function showArticleDetail(articleId) {
            // Find article from current filter
            const articles = allArticles[currentFilter];
            const article = articles.find(a => a.id === articleId);

            if (article) {
                const BASE_URL = "{{ env('BASE_URL') }}";

                // Set image
                const imageUrl = article.path_image ? `${BASE_URL}/${article.path_image}` : '';
                if (imageUrl) {
                    $('#modal-image').attr('src', imageUrl).attr('alt', article.title).show();
                } else {
                    $('#modal-image').hide();
                }

                // Set category
                $('#modal-category').text(article.category?.name || 'Umum');

                // Set badge if inherited
                if (article.is_inherited) {
                    $('#modal-badge').text('KRS Jawa-III').show();
                } else {
                    $('#modal-badge').hide();
                }

                // Set date
                const dobj = getArticleDate(article);
                const date = dobj ? dobj.toLocaleDateString('id-ID', { year: 'numeric', month: 'long', day: 'numeric' }) : 'Tanggal tidak tersedia';
                $('#modal-date-text').text(date);

                // Set title
                $('#modal-title').text(article.title || 'Tanpa Judul');

                // Set body content
                $('#modal-body').text(article.body || 'Tidak ada konten');

                // Show modal
                $('#modal-overlay').show().css('display', 'block');
                $('#modal-detail').show().css('display', 'block');
                $('body').css('overflow', 'hidden');

                // // Scroll page to top
                // window.scrollTo({
                //     top: 0,
                //     behavior: 'smooth'
                // });

                // Scroll modal overlay to top
                $('#modal-overlay').scrollTop(0);
            }
        }

        function closeModal() {
            $('#modal-overlay').hide().css('display', 'none');
            $('#modal-detail').hide().css('display', 'none');
            $('body').css('overflow', 'auto');
        }

        // Close modal with ESC key
        $(document).keydown(function(e) {
            if (e.key === "Escape") {
                closeModal();
            }
        });

        // Close modal when clicking outside
        $(document).on('click', '#modal-overlay', function(e) {
            if (e.target === this) {
                closeModal();
            }
        });

        // Search functionality
        function setupSearch() {
            const searchInput = $('#search-input');
            const clearButton = $('#clear-search');

            searchInput.on('input', function() {
                const value = $(this).val().trim();
                currentSearch = value.toLowerCase();

                if (value.length > 0) {
                    clearButton.show();
                } else {
                    clearButton.hide();
                }

                // Delay search to avoid too many requests
                clearTimeout(window.searchTimeout);
                window.searchTimeout = setTimeout(function() {
                    applyFiltersAndSearch();
                }, 300);
            });

            // Clear search
            clearButton.on('click', function() {
                searchInput.val('');
                currentSearch = '';
                $(this).hide();
                applyFiltersAndSearch();
            });
        }

        function clearSearch() {
            $('#search-input').val('');
            $('#clear-search').hide();
            currentSearch = '';
            applyFiltersAndSearch();
        }

        // Enhanced filter function
        function filterArticles(type) {
            currentFilter = type;
            
            // Update active tab
            $('.filter-tab').removeClass('active');
            $(`.filter-tab[data-filter="${type}"]`).addClass('active');
            
            applyFiltersAndSearch();
        }

        // Sort articles
        function sortArticles() {
            currentSort = $('#sort-select').val();
            applyFiltersAndSearch();
        }

        // Helper to get a Date from article (support multiple field names)
        function getArticleDate(a) {
            if (!a) return null;
            const candidates = [a.createdAt, a.created_at, a.updatedAt, a.updated_at];
            for (let i = 0; i < candidates.length; i++) {
                const v = candidates[i];
                if (!v) continue;
                const d = new Date(v);
                if (!isNaN(d.getTime())) return d;
            }
            return null;
        }

        // Apply filters, search and sort
        function applyFiltersAndSearch() {
            console.log('=== APPLYING FILTERS AND SEARCH ===');
            console.log('Current filter:', currentFilter);
            console.log('Current search:', currentSearch);
            console.log('Current sort:', currentSort);
            
            let articles = [...allArticles[currentFilter]];
            console.log('Articles before filtering:', articles.length);

            // Apply search filter
            if (currentSearch) {
                articles = articles.filter(article => 
                    (article.title || '').toLowerCase().includes(currentSearch) ||
                    (article.body || '').toLowerCase().includes(currentSearch)
                );
                console.log('Articles after search filter:', articles.length);
            }

            // Apply sorting (use helper to read date fields)
            articles.sort((a, b) => {
                switch (currentSort) {
                    case 'oldest': {
                        const da = getArticleDate(a)?.getTime() || 0;
                        const db = getArticleDate(b)?.getTime() || 0;
                        return da - db;
                    }
                    case 'title':
                        return (a.title || '').localeCompare(b.title || '');
                    case 'newest':
                    default: {
                        const da = getArticleDate(a)?.getTime() || 0;
                        const db = getArticleDate(b)?.getTime() || 0;
                        return db - da;
                    }
                }
            });

            console.log('Articles after sorting:', articles.length);
            const selectedYear = $('#yearSelect').val() || '';

            // If a specific year is selected, filter articles to that year (use helper)
            let finalArticles = articles;
            if (selectedYear) {
                finalArticles = articles.filter(a => {
                    const d = getArticleDate(a);
                    const y = d ? d.getFullYear() : 'Unknown';
                    return String(y) === String(selectedYear);
                });
            }

            console.log('Final articles to render after year filter:', finalArticles.length);
            renderFilteredArticles(finalArticles);
            updateResultsInfo(finalArticles.length);
        }

        // Render filtered articles (supports optional year filter)
        function renderFilteredArticles(articles, selectedYear) {
            console.log('=== RENDERING ARTICLES ===');
            console.log('Articles to render:', articles.length, 'selectedYear:', selectedYear);
            
            const cardsContainer = $('#article-cards');
            const emptyState = $('#empty-state');
            const loadingContainer = $('#loading-container');

            loadingContainer.hide();

            if (articles.length === 0) {
                console.log('No articles to show, displaying empty state');
                cardsContainer.hide();
                emptyState.show();
                return;
            }

            emptyState.hide();
            cardsContainer.show().empty();

            const BASE_URL = "{{ env('BASE_URL') }}";

            function createCard(article) {
                const isInherited = article.is_inherited || false;
                const title = article.title || 'Tanpa Judul';
                const excerpt = article.body ? 
                    (article.body.length > 120 ? article.body.substring(0, 120) + '...' : article.body) : 
                    'Tidak ada konten tersedia';

                const date = new Date(article.createdAt).toLocaleDateString('id-ID', {
                    year: 'numeric',
                    month: 'long',
                    day: 'numeric'
                });

                const imageUrl = article.path_image ? `${BASE_URL}/${article.path_image}` : '';

                return $(`
                    <div class="article-card" onclick="showArticleDetail(${article.id})">
                        <div class="article-card-image-container">
                            ${imageUrl ? 
                                `<img class="article-card-image" src="${imageUrl}" alt="${title}">` : 
                                `<div class="article-card-image"></div>`
                            }
                            ${isInherited ? 
                                `<span class="article-card-badge">Berita</span>` : 
                                `<span class="article-card-badge">Artikel</span>`
                            }
                        </div>
                        <div class="article-card-body">
                            <h3 class="article-title">${title}</h3>
                            <p class="article-excerpt">${excerpt}</p>
                            <div class="article-meta">
                                <div class="article-date">
                                    <i class="fas fa-calendar-alt"></i>
                                    <span>${date}</span>
                                </div>
                                <a href="/artikel/${article.id}" class="btn-read-more">
                                    Baca Selengkapnya
                                    <svg width="14" height="14" fill="currentColor" viewBox="0 0 16 16">
                                        <path fill-rule="evenodd" d="M1 8a.5.5 0 0 1 .5-.5h11.793l-3.147-3.146a.5.5 0 0 1 .708-.708l4 4a.5.5 0 0 1 0 .708l-4 4a.5.5 0 0 1-.708-.708L13.293 8.5H1.5A.5.5 0 0 1 1 8z"/>
                                    </svg>
                                </a>
                            </div>
                        </div>
                    </div>
                `);
            }

            // Render flat list (articles already filtered by year in caller)
            articles.forEach(article => {
                cardsContainer.append(createCard(article));
            });
        }

        // Update results info
        function updateResultsInfo(count) {
            const resultText = count === 0 ? 'Tidak ada artikel ditemukan' : 
                              count === 1 ? 'Menampilkan 1 artikel' : 
                              `Menampilkan ${count} artikel`;
            $('#results-count').text(resultText);
        }

        // Update filter counts
        function updateFilterCounts() {
            $('#count-all').text(allArticles.all.length);
            $('#count-local').text(allArticles.local.length);
            $('#count-inherited').text(allArticles.inherited.length);
        }
    </script>
    <x-footer_one />
@endsection
