@extends('layouts.layout1')
@section('title', 'Arsip Buku || 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: #d1d5db;
            --border-color: #e5e7eb;
            --border-hover: #667eea;
            --shadow-soft: 0 4px 6px rgba(0, 0, 0, 0.1);
            --shadow-medium: 0 12px 24px rgba(0, 0, 0, 0.15);
        }

        [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: #6b7280;
            --border-color: #4b5563;
            --border-hover: #667eea;
            --shadow-soft: 0 4px 6px rgba(102, 126, 234, 0.1);
            --shadow-medium: 0 12px 24px rgba(102, 126, 234, 0.2);
        }

        /* 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: 3rem;
            font-weight: 700;
            margin-bottom: 1rem;
            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 */
        .archive-section {
            padding: 4rem 2rem;
            background-color: var(--bg-primary);
        }

        .section-title {
            text-align: center;
            font-size: 2.5rem;
            font-weight: 700;
            color: var(--text-primary);
            margin-bottom: 1rem;
        }

        .section-subtitle {
            text-align: center;
            font-size: 1.125rem;
            color: var(--text-secondary);
            margin-bottom: 3rem;
            max-width: 600px;
            margin-left: auto;
            margin-right: auto;
        }

        /* Card Grid */
        .archive-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
            gap: 2rem;
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 1rem;
        }

        /* Archive Card */
        .archive-card {
            background: var(--bg-card);
            border-radius: 16px;
            overflow: hidden;
            box-shadow: var(--shadow-soft);
            transition: all 0.3s ease;
            cursor: pointer;
            border: 1px solid var(--border-color);
        }

        .archive-card:hover {
            transform: translateY(-8px);
            box-shadow: var(--shadow-medium);
        }

        .archive-image {
            width: 100%;
            height: 250px;
            object-fit: cover;
            background-color: var(--border-color);
        }

        .archive-content {
            padding: 1.5rem;
        }

        .archive-category {
            display: inline-block;
            padding: 0.25rem 0.75rem;
            background: linear-gradient(135deg, var(--judges-base) 0%,  var(--judges-base) 100%);
            color: white;
            font-size: 0.75rem;
            font-weight: 600;
            border-radius: 12px;
            margin-bottom: 0.75rem;
            text-transform: uppercase;
        }

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

        .archive-description {
            font-size: 0.9375rem;
            color: var(--text-secondary);
            line-height: 1.6;
            margin-bottom: 1.5rem;
            display: -webkit-box;
            -webkit-line-clamp: 3;
            -webkit-box-orient: vertical;
            overflow: hidden;
        }

        .archive-actions {
            display: flex;
            gap: 0.75rem;
        }

        .btn-download,
        .btn-view {
            flex: 1;
            padding: 0.75rem 1rem;
            border-radius: 8px;
            font-weight: 600;
            font-size: 0.875rem;
            text-align: center;
            text-decoration: none;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 0.5rem;
        }

        .btn-download {
            background: linear-gradient(135deg, var(--judges-base) 0%,  var(--judges-base) 100%);
            color: white;
            border: none;
        }

        .btn-download:hover {
            background: linear-gradient(135deg, var(--judges-base) 0%,  var(--judges-base) 100%);
            transform: translateY(-2px);
            box-shadow: 0 4px 12px var(--judges-base);
            color: white;
        }

        .btn-view {
            background: var(--bg-card);
            color: var(--judges-base);
            border: 2px solid var(--judges-base);
        }

        .btn-view:hover {
            background: var(--judges-base);
            color: white;
        }

        /* Empty State */
        .empty-state {
            text-align: center;
            padding: 4rem 2rem;
        }

        .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;
        }

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

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

        /* 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"] .archive-section,
        body.dark-mode .archive-section {
            background-color: var(--bg-primary) !important;
            background: var(--bg-primary) !important;
        }

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

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

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

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

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

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

        /* Dark mode for buttons */
        [data-theme="dark"] .btn-view,
        body.dark-mode .btn-view {
            background: var(--bg-card) !important;
            color: #93c5fd !important;
            border-color: #93c5fd !important;
        }

        [data-theme="dark"] .btn-view:hover,
        body.dark-mode .btn-view:hover {
            background: #93c5fd !important;
            color: var(--bg-primary) !important;
        }

        /* Dark mode for container elements */
        [data-theme="dark"] .container,
        body.dark-mode .container {
            color: var(--text-primary) !important;
        }

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

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

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

            .archive-grid {
                grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
                gap: 1.5rem;
            }
        }
    </style>

    <!-- Hero Section -->
    <section class="hero-section">
        <div class="hero-content">
            <h1 class="hero-title">Arsip Buku</h1>
            <div class="hero-divider"></div>
            <p class="hero-subtitle">
                Koleksi buku, dokumen, dan arsip penting yang dapat menjadi referensi
                dan sumber informasi untuk program perumahan dan pembangunan.
            </p>
        </div>
    </section>

    <!-- Archive Cards Section -->
    <section class="archive-section">
        <div class="container">
            <h2 class="section-title">Koleksi Arsip Buku</h2>
            <p class="section-subtitle">
                Akses berbagai buku dan dokumen penting untuk mendukung program perumahan
            </p>

            <!-- Controls: Category filter + Sort + Search -->
            <div class="archive-controls" style="display:flex;gap:0.75rem;align-items:center;justify-content:center;margin-bottom:1.5rem;flex-wrap:wrap;">
                <!-- <div style="min-width:220px;">
                    <select id="typeFilter" style="width:100%;padding:0.5rem 0.75rem;border-radius:8px;border:1px solid var(--border-color);background:var(--bg-card);color:var(--text-primary);">
                        <option value="">Semua Tipe</option>
                    </select>
                </div> -->

                <!-- <div style="min-width:200px; ">
                    <select id="archiveSortSelect" style="width:100%;padding:0.5rem 0.75rem;border-radius:8px;border:1px solid var(--border-color);background:var(--bg-card);color:var(--text-primary);">
                        <option value="">Urutkan: Default</option>
                        <option value="type-asc">Type A → Z</option>
                        <option value="type-desc">Type Z → A</option>
                        <option value="created-desc">Terbaru</option>
                        <option value="created-asc">Terlama</option>
                    </select>
                </div> -->

                <div style="flex:1;min-width:260px;max-width:640px;">
                    <input id="archiveSearchInput" type="search" placeholder="Cari judul, deskripsi, atau kategori..." style="width:100%;padding:0.5rem 0.75rem;border-radius:8px;border:1px solid var(--border-color);background:var(--bg-card);color:var(--text-primary);">
                </div>
            </div>

            <!-- Loading State -->
            <div id="loading-container" class="loading-container">
                <div class="spinner"></div>
            </div>

            <!-- Cards Grid -->
            <div id="archive-grid" class="archive-grid" style="display: none;">
                <!-- Cards will be inserted here by JavaScript -->
            </div>

            <!-- Empty State -->
            <div id="empty-state" class="empty-state" style="display: none;">
                <div class="empty-state-icon">📚</div>
                <p class="empty-state-text">Belum ada Arsip Buku yang tersedia saat ini.</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']
        });

        // Your existing JavaScript code continues here...
        $(document).ready(function() {
            const BASE_URL = "{{ env('BASE_URL') }}";
            const DAERAH = "{{ env('DAERAH') }}";

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

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

                    // Hide loading
                    $('#loading-container').hide();

                            // Get archives from response
                            const archives = response.local?.archives || [];

                            console.log('Archives:', archives);

                            // Keep master copy for filtering
                            window.allArchives = archives;

                            if (archives.length > 0) {
                                // Show grid
                                $('#archive-grid').show();

                                // Populate types dropdown
                                populateTypes(archives);

                                // Render all cards initially
                                renderArchiveCards(archives);
                            } else {
                                // Show empty state
                                $('#empty-state').show();
                            }
                },
                error: function(xhr, status, error) {
                    console.error('Error fetching data:', error);
                    console.error('Status:', status);
                    console.error('Response:', xhr.responseText);

                    // Hide loading
                    $('#loading-container').hide();

                    // Show empty state
                    $('#empty-state').show();
                    $('#empty-state .empty-state-text').text(
                        'Terjadi kesalahan saat memuat data. Silakan coba lagi nanti.');
                }
            });

            function renderArchiveCards(archives) {
                const grid = $('#archive-grid');
                grid.empty();

                archives.forEach(archive => {
                    const imageUrl = archive.path_image ?
                        `${BASE_URL}/${archive.path_image}` :
                        'https://placehold.co/400x300?text=No+Image';

                    const fileUrl = archive.link_archive ?
                        `${archive.link_archive}` :
                        '#';

                    const categoryObj = archive.type || archive.category || null;
                    const categoryName = categoryObj?.name || 'Buku Umum';
                    const title = archive.title || 'Untitled';
                    const description = archive.description || 'Tidak ada deskripsi tersedia.';

                    const card = `
                        <div class="archive-card">
                            <img src="${imageUrl}" 
                                 alt="${title}" 
                                 class="archive-image"
                                 onerror="this.src='https://placehold.co/400x300?text=No+Image'">
                            <div class="archive-content">
                                <span class="archive-category">${categoryName}</span>
                                <h3 class="archive-title">${title}</h3>
                                <p class="archive-description">${description}</p>
                                <div class="archive-actions">
                                    ${fileUrl !== '#' ? `
                                                <a href="${fileUrl}" 
                                                   target="_blank" 
                                                   class="btn-download"
                                                   download>
                                                    <svg width="16" height="16" fill="currentColor" viewBox="0 0 16 16">
                                                        <path d="M.5 9.9a.5.5 0 0 1 .5.5v2.5a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-2.5a.5.5 0 0 1 1 0v2.5a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2v-2.5a.5.5 0 0 1 .5-.5z"/>
                                                        <path d="M7.646 11.854a.5.5 0 0 0 .708 0l3-3a.5.5 0 0 0-.708-.708L8.5 10.293V1.5a.5.5 0 0 0-1 0v8.793L5.354 8.146a.5.5 0 1 0-.708.708l3 3z"/>
                                                    </svg>
                                                    Download
                                                </a>
                                            ` : ''}
                                    <a href="${imageUrl}" 
                                       target="_blank" 
                                       class="btn-view">
                                        <svg width="16" height="16" fill="currentColor" viewBox="0 0 16 16">
                                            <path d="M10.5 8a2.5 2.5 0 1 1-5 0 2.5 2.5 0 0 1 5 0z"/>
                                            <path d="M0 8s3-5.5 8-5.5S16 8 16 8s-3 5.5-8 5.5S0 8 0 8zm8 3.5a3.5 3.5 0 1 0 0-7 3.5 3.5 0 0 0 0 7z"/>
                                        </svg>
                                        Lihat Detail
                                    </a>
                                </div>
                            </div>
                        </div>
                    `;

                    grid.append(card);
                });
            }

            // Helper: produce a stable key for an archive's type
            function typeKeyForArchive(a) {
                if (!a) return '__no_type';
                const cat = a.type || a.category;
                if (!cat) return '__no_type';
                if (typeof cat === 'string') return cat.trim().toLowerCase();
                if (cat.id !== undefined && cat.id !== null) return String(cat.id);
                if (cat.name) return (cat.name || '').trim().toLowerCase();
                // fallback to any type_id or category_id numeric identifier
                if (a.type_id !== undefined && a.type_id !== null) return String(a.type_id);
                if (a.category_id !== undefined && a.category_id !== null) return String(a.category_id);
                return '__no_type';
            }

            // Populate type select from archives (supports string or object types)
            function populateTypes(archives) {
                const types = new Map();
                let hasNoType = false;
                archives.forEach(a => {
                    const cat = a.type || a.category;
                    if (!cat) {
                        hasNoType = true;
                        return;
                    }

                    let key, label;
                    if (typeof cat === 'string') {
                        key = cat.trim().toLowerCase();
                        label = cat.trim();
                    } else if (cat.id !== undefined && cat.id !== null) {
                        key = String(cat.id);
                        label = (cat.name || key).toString();
                    } else if (cat.name) {
                        key = (cat.name || '').trim().toLowerCase();
                        label = (cat.name || '').trim();
                    } else {
                        return;
                    }

                    if (key && !types.has(key)) {
                        types.set(key, label);
                    }
                });

                if (hasNoType) {
                    types.set('__no_type', 'Tanpa Tipe');
                }

                // Debug: log discovered types to help diagnose missing ones
                console.debug('Discovered types:', Array.from(types.entries()));

                const select = $('#typeFilter');
                // Clear but keep first option (Semua Tipe)
                select.find('option:not(:first)').remove();

                // Sort by label for nicer UX
                Array.from(types.entries()).sort((a,b)=> a[1].localeCompare(b[1])).forEach(([key,label]) => {
                    const opt = document.createElement('option');
                    opt.value = key;
                    opt.text = label;
                    select.append(opt);
                });
            }

            // Debounce helper
            function debounce(fn, wait) {
                let t;
                return function() {
                    const args = arguments;
                    clearTimeout(t);
                    t = setTimeout(() => fn.apply(this, args), wait);
                };
            }

            // Apply current filters (type + search)
            function applyFilters() {
                const q = ($('#archiveSearchInput').val() || '').trim().toLowerCase();
                const selectedTypeKey = ($('#typeFilter').val() || '');
                const selectedSort = ($('#archiveSortSelect').val() || '');
                const filtered = (window.allArchives || []).filter(a => {
                    // Type filter using stable keys
                    if (selectedTypeKey) {
                        const aKey = typeKeyForArchive(a) || '';
                        if (aKey !== selectedTypeKey) return false;
                    }

                    if (!q) return true;

                    const title = (a.title || '').toLowerCase();
                    const desc = (a.description || '').toLowerCase();
                    const cname = ((typeof a.type === 'string') ? a.type : (a.type?.name || a.category?.name || '')).toLowerCase();

                    return title.includes(q) || desc.includes(q) || cname.includes(q);
                });

                // Apply sorting
                const sorted = sortArchives(filtered, selectedSort);

                if (sorted.length > 0) {
                    $('#archive-grid').show();
                    $('#empty-state').hide();
                } else {
                    $('#archive-grid').hide();
                    $('#empty-state').show();
                }

                renderArchiveCards(sorted);
            }

            // Sort helper: returns a new sorted array
            function sortArchives(arr, sortKey) {
                if (!sortKey) return arr.slice();
                const copy = arr.slice();
                if (sortKey === 'type-asc' || sortKey === 'type-desc') {
                    copy.sort((a,b)=>{
                        const aType = (a.type?.name || a.category?.name || '').toString().toLowerCase();
                        const bType = (b.type?.name || b.category?.name || '').toString().toLowerCase();
                        if (aType < bType) return sortKey === 'type-asc' ? -1 : 1;
                        if (aType > bType) return sortKey === 'type-asc' ? 1 : -1;
                        return 0;
                    });
                    return copy;
                }

                if (sortKey === 'created-desc' || sortKey === 'created-asc') {
                    copy.sort((a,b)=>{
                        const ta = new Date(a.createdAt || a.created_at || a.updatedAt || 0).getTime();
                        const tb = new Date(b.createdAt || b.created_at || b.updatedAt || 0).getTime();
                        return sortKey === 'created-desc' ? tb - ta : ta - tb;
                    });
                    return copy;
                }

                return copy;
            }

            // Wire controls after document ready
            $('#typeFilter').on('change', applyFilters);
            $('#archiveSortSelect').on('change', applyFilters);
            $('#archiveSearchInput').on('input', debounce(applyFilters, 300));
        });
    </script>
    <x-footer_one />
@endsection
