@extends('layouts.layoutadmin')
@section('title', 'Arsip Admin')

@section('styles')
    <link rel="stylesheet" href="https://cdn.datatables.net/1.11.5/css/jquery.dataTables.min.css">
    <style>
        body {
            background: #f4f4f4;
        }

        

        .admin-dashboard {
            display: flex;
            min-height: 100vh;
            background: #f4f4f4;
        }

        .sidebar {
            width: 260px;
            background: #23272b;
            color: #fff;
            display: flex;
            flex-direction: column;
            padding: 24px 0 0 0;
            border-right: 1px solid #e5e7eb;
        }

        .sidebar .sidebar-header {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 0 24px 24px 24px;
            font-size: 1.1rem;
            font-weight: 700;
        }

        .sidebar .sidebar-header i {
            font-size: 1.6rem;
            color: #22c1b6;
        }

        .sidebar .sidebar-header span {
            font-size: 1.1rem;
            font-weight: 700;
            color: #fff;
        }

        .sidebar-nav {
            flex: 1;
            padding: 0 0 0 0;
        }

        .sidebar-nav ul {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        .sidebar-nav li {
            margin-bottom: 4px;
        }

        .sidebar-nav a {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 10px 28px;
            color: #bfc5c9;
            text-decoration: none;
            border-radius: 8px 0 0 8px;
            font-size: 1rem;
            transition: background 0.2s, color 0.2s;
        }

        .sidebar-nav a.active,
        .sidebar-nav a:hover {
            background: #22c1b6;
            color: #fff;
        }

        .main {
            flex: 1;
            display: flex;
            flex-direction: column;
            background: #f4f4f4;
        }

        .main-header {
            background: #fff;
            padding: 24px 32px 16px 32px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            border-bottom: 1px solid #e5e7eb;
        }

        /* Keep admin header/navbar white regardless of site dark/light mode */
        body.dark-mode .admin-dashboard .main-header,
        .admin-dashboard .main-header {
            background: #ffffff !important;
            color: #222 !important;
            border-bottom: 1px solid #e5e7eb !important;
        }

        /* Ensure header child elements keep their intended colors in dark mode */
        body.dark-mode .admin-dashboard .main-header .title,
        body.dark-mode .admin-dashboard .main-header .subtitle,
        body.dark-mode .admin-dashboard .main-header .header-actions,
        body.dark-mode .admin-dashboard .main-header .header-actions * {
            color: inherit !important;
            background: transparent !important;
        }

        .main-header .header-actions {
            display: flex;
            align-items: center;
            gap: 16px;
        }

        .main-header .header-actions button {
            background: #d72660;
            color: #fff;
            border: none;
            border-radius: 8px;
            padding: 8px 18px;
            font-weight: 600;
            font-size: 1rem;
            cursor: pointer;
        }

        .main-header .header-actions button:hover {
            background: #b61f50;
        }

        .main-header .header-actions i {
            font-size: 1.3rem;
            color: #535963;
            background: #f4f4f4;
            border-radius: 50%;
            padding: 6px;
            margin-right: 2px;
            cursor: pointer;
        }
        
        .title {
            font-size: 1.4rem;
            font-weight: 700;
            color: #222;
        }

        .subtitle {
            color: #6b7280;
            font-size: 1.05rem;
            margin-top: 2px;
        }

        .header-actions {
            display: flex;
            align-items: center;
            gap: 16px;
        }

        .btn-primary {
            background: linear-gradient(135deg, #1da89c 0%, #22c1b6 100%);
            color: #fff;
            border: none;
            border-radius: 8px;
            padding: 10px 28px;
            font-weight: 600;
            font-size: 1rem;
            cursor: pointer;
            transition: all 0.2s;
        }

        .btn-primary:hover {
            background: #1da89c;
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(34, 193, 182, 0.3);
        }

        .btn-secondary {
            background: #6b7280;
            color: #fff;
            border: none;
            border-radius: 8px;
            padding: 8px 22px;
            font-weight: 600;
            font-size: 1rem;
            cursor: pointer;
            transition: background 0.2s;
            margin-right: 12px;
        }

        .btn-secondary:hover {
            background: #4b5563;
        }

        .btn-danger {
            background: #ef4444;
            color: #fff;
            border: none;
            border-radius: 8px;
            padding: 8px 22px;
            font-weight: 600;
            font-size: 1rem;
            cursor: pointer;
            transition: all 0.2s;
        }

        .btn-danger:hover {
            background: #dc2626;
            transform: translateY(-1px);
        }

        .main-content {
            padding: 32px;
        }

        .content-section {
            background: #fff;
            border-radius: 12px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
            padding: 32px;
            margin-top: 2rem;
        }

        .section-title {
            font-size: 1.3rem;
            font-weight: 700;
            color: #23272b;
            margin-bottom: 1.5rem;
        }

        .badge {
            display: inline-block;
            padding: 6px 16px;
            border-radius: 8px;
            font-weight: 600;
            font-size: 0.95rem;
        }

        .alert-success {
            background: #d1fae5;
            color: #065f46;
            border-radius: 8px;
            padding: 10px 18px;
            margin-bottom: 1rem;
        }

        .alert-error {
            background: #fee2e2;
            color: #991b1b;
            border-radius: 8px;
            padding: 10px 18px;
            margin-bottom: 1rem;
        }

        /* Tab Styles */
        .tab-container {
            margin-bottom: 2rem;
        }

        .tab-buttons {
            display: flex;
            border-bottom: 2px solid #e5e7eb;
            margin-bottom: 2rem;
        }

        .tab-button {
            padding: 12px 24px;
            background: none;
            border: none;
            color: #6b7280;
            font-weight: 600;
            cursor: pointer;
            border-bottom: 2px solid transparent;
            transition: all 0.3s;
        }

        .tab-button.active {
            color: #22c1b6;
            border-bottom-color: #22c1b6;
        }

        .tab-content {
            display: none;
        }

        .tab-content.active {
            display: block;
        }

        /* DataTables Enhanced Styling */
        .dataTables_wrapper {
            padding: 1.5rem;
            background: #ffffff;
            border-radius: 12px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
        }

        .dataTables_filter input {
            border: 2px solid #e5e7eb !important;
            border-radius: 8px !important;
            padding: 8px 16px !important;
            font-size: 14px !important;
            width: 250px !important;
            transition: all 0.3s ease !important;
        }

        .dataTables_filter input:focus {
            border-color: #22c1b6 !important;
            outline: none !important;
            box-shadow: 0 0 0 3px rgba(34, 193, 182, 0.1) !important;
        }

        #archiveTable thead th,
        #archiveTypeTable thead th {
            background: #f2f2f2 !important;
            color: black !important;
            font-weight: 600 !important;
            padding: 12px 8px !important;
            border: none !important;
            text-align: center !important;
            font-size: 14px !important;
        }

        #archiveTable tbody td,
        #archiveTypeTable tbody td {
            padding: 12px 8px !important;
            vertical-align: middle !important;
            border-bottom: 1px solid #f3f4f6 !important;
            font-size: 13px !important;
            text-align: center !important;
        }

        #archiveTable tbody tr:hover,
        #archiveTypeTable tbody tr:hover {
            background-color: #f8fafc !important;
        }

        .dataTables_info {
            color: #6b7280 !important;
            font-size: 14px !important;
            font-weight: 500 !important;
        }

        .dataTables_paginate .paginate_button {
            border: 1px solid #e5e7eb !important;
            border-radius: 6px !important;
            margin: 0 2px !important;
            padding: 6px 12px !important;
            color: #374151 !important;
            background: white !important;
        }

        .dataTables_paginate .paginate_button:hover {
            background: #22c1b6 !important;
            border-color: #22c1b6 !important;
            color: white !important;
        }

        .dataTables_paginate .paginate_button.current {
            background: #22c1b6 !important;
            border-color: #22c1b6 !important;
            color: white !important;
        }

        .img-thumb {
            max-width: 100px;
            max-height: 80px;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(34, 193, 182, 0.12);
            transition: all 0.3s ease;
            cursor: pointer;
            object-fit: cover;
        }

        .img-thumb:hover {
            transform: scale(1.05);
            box-shadow: 0 4px 16px rgba(102, 126, 234, 0.25);
        }

        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            align-items: center;
            justify-content: center;
        }

        .modal-content {
            background: #fff;
            border-radius: 12px;
            padding: 32px 28px;
            max-width: 500px;
            width: 90%;
            margin: auto;
            box-shadow: 0 8px 32px rgba(34, 193, 182, 0.18);
            animation: modalSlideIn 0.3s ease;
            max-height: 90vh;
            overflow-y: auto;
        }

        @keyframes modalSlideIn {
            from {
                opacity: 0;
                transform: translateY(-20px);
            }

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

        .modal-header {
            font-size: 1.3rem;
            font-weight: 700;
            margin-bottom: 20px;
            color: #23272b;
            text-align: center;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            font-weight: 600;
            margin-bottom: 8px;
            display: block;
            color: #374151;
        }

        .form-group input[type="text"],
        .form-group input[type="url"],
        .form-group input[type="file"],
        .form-group textarea,
        .form-group select {
            width: 100%;
            padding: 12px 16px;
            border-radius: 8px;
            border: 2px solid #e5e7eb;
            background: #fff !important;
            color: #333;
            font-size: 1rem;
            margin-top: 4px;
            box-sizing: border-box;
            transition: border-color 0.3s ease;
        }

        .form-group input:focus,
        .form-group textarea:focus,
        .form-group select:focus {
            border-color: #22c1b6;
            outline: none;
            box-shadow: 0 0 0 3px rgba(34, 193, 182, 0.1);
            background: #fff !important;
        }

        .form-group select {
            width: 100%;
            padding: 12px 16px;
            border-radius: 8px;
            border: 2px solid #e5e7eb;
            background: #fff !important;
            color: #333;
            font-size: 1rem;
            margin-top: 4px;
            box-sizing: border-box;
            transition: border-color 0.3s ease;
        }

        .form-group select:focus {
            border-color: #22c1b6;
            outline: none;
            box-shadow: 0 0 0 3px rgba(34, 193, 182, 0.1);
            background: #fff !important;
        }

        .form-group select option {
            background: #fff !important;
            color: #333 !important;
            padding: 8px;
        }

        .form-group select option:disabled {
            background: #fff !important;
            color: #999 !important;
        }

        /* Force dropdown visibility */
        #archive_type_id {
            display: block !important;
            visibility: visible !important;
            opacity: 1 !important;
            height: auto !important;
            min-height: 44px !important;
            -webkit-appearance: menulist !important;
            -moz-appearance: menulist !important;
            appearance: menulist !important;
        }

        .form-group textarea {
            resize: vertical;
            min-height: 80px;
        }

        .modal-actions {
            display: flex;
            gap: 12px;
            justify-content: center;
            margin-top: 24px;
        }

        .alert {
            padding: 12px 20px;
            border-radius: 8px;
            margin-bottom: 1rem;
            font-weight: 600;
            animation: alertSlideIn 0.3s ease;
        }

        @keyframes alertSlideIn {
            from {
                opacity: 0;
                transform: translateY(-10px);
            }

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

        .alert-success {
            background: #d1fae5;
            color: #065f46;
            border-left: 4px solid #22c1b6;
        }

        .alert-error {
            background: #fee2e2;
            color: #991b1b;
            border-left: 4px solid #ef4444;
        }

        .checkbox-group {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-top: 8px;
        }

        .checkbox-group input[type="checkbox"] {
            width: auto;
            margin: 0;
        }

        /* Toast Notification Styles */
        .toast-container {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 9999;
            display: flex;
            flex-direction: column;
            gap: 10px;
            max-width: 400px;
        }

        .toast {
            background: white;
            padding: 16px 20px;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            display: flex;
            align-items: center;
            gap: 12px;
            min-width: 300px;
            animation: slideInRight 0.6s cubic-bezier(0.16, 1, 0.3, 1);
            border-left: 4px solid;
            position: relative;
            overflow: hidden;
            transform: translateX(0);
            will-change: transform, opacity;
        }

        .toast.toast-success {
            border-left-color: #10b981;
        }

        .toast.toast-error {
            border-left-color: #ef4444;
        }

        .toast.toast-info {
            border-left-color: #3b82f6;
        }

        .toast.toast-warning {
            border-left-color: #f59e0b;
        }

        .toast-icon {
            font-size: 24px;
            flex-shrink: 0;
        }

        .toast-success .toast-icon {
            color: #10b981;
        }

        .toast-error .toast-icon {
            color: #ef4444;
        }

        .toast-info .toast-icon {
            color: #3b82f6;
        }

        .toast-warning .toast-icon {
            color: #f59e0b;
        }

        .toast-content {
            flex: 1;
        }

        .toast-message {
            color: #1f2937;
            font-size: 14px;
            line-height: 1.5;
            font-weight: 500;
        }

        .toast-close {
            background: none;
            border: none;
            color: #6b7280;
            font-size: 20px;
            cursor: pointer;
            padding: 0;
            width: 24px;
            height: 24px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 4px;
            transition: all 0.2s;
            flex-shrink: 0;
        }

        .toast-close:hover {
            background: #f3f4f6;
            color: #1f2937;
        }

        .toast-progress {
            position: absolute;
            bottom: 0;
            left: 0;
            height: 3px;
            background: currentColor;
            opacity: 0.3;
            animation: toastProgress 5s linear;
        }

        .toast-success .toast-progress {
            color: #10b981;
        }

        .toast-error .toast-progress {
            color: #ef4444;
        }

        .toast-info .toast-progress {
            color: #3b82f6;
        }

        .toast-warning .toast-progress {
            color: #f59e0b;
        }

        @keyframes slideInRight {
            0% {
                transform: translateX(120%);
                opacity: 0;
            }
            100% {
                transform: translateX(0);
                opacity: 1;
            }
        }

        @keyframes slideOutRight {
            0% {
                transform: translateX(0);
                opacity: 1;
            }
            100% {
                transform: translateX(120%);
                opacity: 0;
            }
        }

        @keyframes toastProgress {
            from {
                width: 100%;
            }
            to {
                width: 0%;
            }
        }

        .toast.hiding {
            animation: slideOutRight 0.4s ease-in forwards;
        }
    </style>
@endsection

@section('content')
    <div class="admin-dashboard">
        @include('admin.components.sidebar')
        <main class="main">
            <div class="main-header">
                <div>
                    <div class="title">Manajement Arsip</div>
                    <div class="subtitle">Kelola arsip dan tipe arsip</div>
                </div>
                <div class="header-actions">
                    <a href="feedback"><i class="fas fa-bell"></i></a>
                    <a href="pengaturan-situs"><i class="fas fa-cog"></i></a>
                    <form method="POST" action="{{ route('logout') }}" style="display:inline;">
                        @csrf
                        <button type="submit">Keluar</button>
                    </form>
                </div>
            </div>
            <div class="main-content">
                <!-- Toast Container -->
                <div class="toast-container" id="toast-container"></div>

                <!-- Tab Container -->
                <div class="tab-container">
                    <div class="tab-buttons">
                        <button class="tab-button active" onclick="switchTab('archive')">Arsip</button>
                        <button class="tab-button" onclick="switchTab('archiveType')">Tipe Arsip</button>
                    </div>

                    <!-- Archive Tab -->
                    <div id="archive-tab" class="tab-content active">
                        <div class="content-section">
                            <div
                                style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1.5rem;">
                                <div class="section-title">Daftar Arsip</div>
                                <div style="display:flex;gap:12px;align-items:center;">
                                    <input id="archiveSearchInput" type="search" placeholder="Cari arsip, judul, tipe..." style="padding:8px 10px;border-radius:8px;border:1px solid #e5e7eb;min-width:260px;">
                                    <div class="header-actions">
                                        <button class="btn-secondary" onclick="loadArchives()">
                                            <i class="fas fa-sync-alt"></i> Refresh
                                        </button>
                                        <button class="btn-primary" onclick="openAddArchiveModal()">
                                            <i class="fas fa-plus"></i> Tambah Arsip
                                        </button>
                                    </div>
                                </div>
                            </div>
                            <div id="archiveListContainer"></div>
                        </div>
                    </div>

                    <!-- Archive Type Tab -->
                    <div id="archiveType-tab" class="tab-content">
                        <div class="content-section">
                            <div
                                style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1.5rem;">
                                <div class="section-title">Daftar Tipe Arsip</div>
                                <div class="header-actions">
                                    <button class="btn-secondary" onclick="loadArchiveTypes()">
                                        <i class="fas fa-sync-alt"></i> Refresh
                                    </button>
                                    <button class="btn-primary" onclick="openAddArchiveTypeModal()">
                                        <i class="fas fa-plus"></i> Tambah Tipe Arsip
                                    </button>
                                </div>
                            </div>
                            <div id="archiveTypeListContainer"></div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Modal Add/Edit Archive -->
            <div id="archiveModal" class="modal">
                <div class="modal-content">
                    <div class="modal-header" id="archiveModalTitle">Tambah Arsip</div>
                    <form id="archiveForm">
                        <input type="hidden" id="archive_id">
                        <div class="form-group">
                            <label for="archive_title">Judul Arsip *</label>
                            <input type="text" id="archive_title" required placeholder="Masukkan judul arsip">
                        </div>
                        <div class="form-group">
                            <label for="archive_description">Deskripsi</label>
                            <textarea id="archive_description" placeholder="Masukkan deskripsi arsip"></textarea>
                        </div>
                        <div class="form-group">
                            <label for="archive_type_id">Tipe Arsip *</label>
                            <select id="archive_type_id" name="archive_type_id" required
                                style="background:#fff;color:#333;">
                                <option value="">Pilih tipe arsip</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="archive_image">Gambar Arsip</label>
                            <input type="file" id="archive_image" accept="image/*">
                            <small style="color: #6b7280; font-size: 0.9rem;">Format: JPG, PNG, WebP (Max: 5MB)</small>
                        </div>
                        <div class="form-group">
                            <label for="archive_link">Link Arsip</label>
                            <input type="url" id="archive_link" placeholder="https://example.com/arsip">
                        </div>
                        <div class="form-group">
                            <div class="checkbox-group">
                                <input type="checkbox" id="archive_inherited">
                                <label for="archive_inherited">Arsip Turunan</label>
                            </div>
                        </div>
                        <div class="modal-actions">
                            <button type="submit" class="btn-primary">
                                <i class="fas fa-save"></i> Simpan
                            </button>
                            <button type="button" class="btn-danger" onclick="closeArchiveModal()">
                                <i class="fas fa-times"></i> Batal
                            </button>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Modal Add/Edit Archive Type -->
            <div id="archiveTypeModal" class="modal">
                <div class="modal-content">
                    <div class="modal-header" id="archiveTypeModalTitle">Tambah Tipe Arsip</div>
                    <form id="archiveTypeForm">
                        <input type="hidden" id="archiveType_id">
                        <div class="form-group">
                            <label for="archiveType_name">Nama Tipe Arsip *</label>
                            <input type="text" id="archiveType_name" required placeholder="Masukkan nama tipe arsip">
                        </div>
                        <div class="form-group">
                            <label for="archiveType_description">Deskripsi</label>
                            <textarea id="archiveType_description" placeholder="Masukkan deskripsi tipe arsip" maxlength="100"></textarea>
                            <small style="color: #6b7280; font-size: 0.9rem;">Maksimal 100 karakter</small>
                        </div>
                        <div class="modal-actions">
                            <button type="submit" class="btn-primary">
                                <i class="fas fa-save"></i> Simpan
                            </button>
                            <button type="button" class="btn-danger" onclick="closeArchiveTypeModal()">
                                <i class="fas fa-times"></i> Batal
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </main>
    </div>

    <script>
        const baseUrl = '{{ env('BASE_URL') }}';
        let archiveList = [];
        let archiveTypeList = [];
        // Client-side search & sort state for archives
        let currentArchiveFilter = '';
        let currentArchiveSort = { key: 'createdAt', dir: 'desc' };
        let _archiveSearchDebounce = null;
        let archiveDataTableRef = null;

        // Sorting helper for archive table (clickable headers)
        function sortArchive(key) {
            if (!key) return;
            if (currentArchiveSort.key === key) {
                currentArchiveSort.dir = currentArchiveSort.dir === 'asc' ? 'desc' : 'asc';
            } else {
                currentArchiveSort.key = key;
                currentArchiveSort.dir = 'asc';
            }

            // If DataTable is active, forward ordering to it
            if (archiveDataTableRef && typeof archiveDataTableRef.order === 'function') {
                const colIndexMap = { title: 0, type: 1, is_inherited: 3, createdAt: 5 };
                const idx = colIndexMap[key] !== undefined ? colIndexMap[key] : 0;
                try {
                    archiveDataTableRef.order([idx, currentArchiveSort.dir]).draw();
                } catch (e) {
                    // fallback to re-render
                    renderArchiveList();
                }
            } else {
                renderArchiveList();
            }
        }

        function showAlert(message, type = 'success') {
            const toastContainer = document.getElementById('toast-container');
            
            // Create toast element
            const toast = document.createElement('div');
            toast.className = `toast toast-${type}`;
            
            // Determine icon based on type
            let icon = '';
            switch(type) {
                case 'success':
                    icon = '<i class="fas fa-check-circle"></i>';
                    break;
                case 'error':
                    icon = '<i class="fas fa-exclamation-circle"></i>';
                    break;
                case 'warning':
                    icon = '<i class="fas fa-exclamation-triangle"></i>';
                    break;
                case 'info':
                    icon = '<i class="fas fa-info-circle"></i>';
                    break;
                default:
                    icon = '<i class="fas fa-check-circle"></i>';
            }
            
            toast.innerHTML = `
                <div class="toast-icon">${icon}</div>
                <div class="toast-content">
                    <div class="toast-message">${message}</div>
                </div>
                <button class="toast-close" onclick="this.parentElement.remove()">
                    <i class="fas fa-times"></i>
                </button>
                <div class="toast-progress"></div>
            `;
            
            // Add toast with slight delay for smoother appearance
            requestAnimationFrame(() => {
                toastContainer.appendChild(toast);
            });
            
            // Auto remove after 5 seconds
            setTimeout(() => {
                toast.classList.add('hiding');
                setTimeout(() => {
                    if (toast.parentElement) {
                        toast.remove();
                    }
                }, 400);
            }, 5000);
        }

        function getAuthToken() {
            return '{{ session('auth.token') }}';
        }

        // Tab Functions
        function switchTab(tabName) {
            console.log('=== SWITCHING TAB ===');
            console.log('Tab name:', tabName);

            try {
                // Remove active class from all tabs
                document.querySelectorAll('.tab-button').forEach(btn => btn.classList.remove('active'));
                document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active'));

                // Add active class to selected tab
                const tabButton = document.querySelector(`button[onclick="switchTab('${tabName}')"]`);
                const tabContent = document.getElementById(`${tabName}-tab`);

                if (!tabButton || !tabContent) {
                    console.error('Tab button or content not found for:', tabName);
                    return;
                }

                tabButton.classList.add('active');
                tabContent.classList.add('active');

                // Load data for the active tab
                if (tabName === 'archive') {
                    console.log('Loading archives for tab...');
                    loadArchives();
                } else if (tabName === 'archiveType') {
                    console.log('Loading archive types for tab...');
                    loadArchiveTypes(true); // true to render the list
                }
            } catch (error) {
                console.error('Error switching tab:', error);
                showAlert('Gagal beralih tab: ' + error.message, 'error');
            }
        }

        // Archive Functions
        async function loadArchives() {
            try {
                const token = getAuthToken();
                // console.log('=== LOADING ARCHIVES ===');
                // console.log('Token:', token ? 'Present' : 'Missing');
                // console.log('BaseURL:', baseUrl);

                // Load archive types first if not loaded yet (for type name lookup)
                if (!archiveTypeList || archiveTypeList.length === 0) {
                    console.log('Loading archive types first for type name lookup...');
                    await loadArchiveTypes(false); // false = don't render list
                }

                const url = `${baseUrl}/api/admin/archive`;
                // console.log('Fetching from:', url);

                const res = await fetch(url, {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });

                console.log('Response status:', res.status);

                if (!res.ok) {
                    const errorText = await res.text();
                    console.error('Error response:', errorText);
                    throw new Error(`Gagal fetch arsip (${res.status}): ${errorText}`);
                }

                const data = await res.json();
                // console.log('Raw data received:', data);

                archiveList = Array.isArray(data) ? data : (data.data || []);
                // console.log('Processed archiveList:', archiveList);
                // console.log('archiveList length:', archiveList.length);

                renderArchiveList();
            } catch (err) {
                console.error('Error loading archives:', err);
                showAlert('Gagal memuat arsip: ' + err.message, 'error');
                archiveList = []; // Reset to empty array on error
            }
        }

        function renderArchiveList() {
            const container = document.getElementById('archiveListContainer');

            if (!container) {
                console.error('Container element "archiveListContainer" not found!');
                return;
            }

            if (!archiveList || archiveList.length === 0) {
                container.innerHTML =
                    '<div style="padding:2rem;text-align:center;color:#9ca3af;font-size:1.1rem;">Belum ada arsip. Klik tombol "Tambah Arsip" untuk menambahkan data baru.</div>';
                return;
            }

            // console.log('=== RENDERING ARCHIVE LIST ===');
            // console.log('archiveList length:', archiveList.length);
            // console.log('First archive:', archiveList[0]);

            // // Debug: Check what fields are available
            // if (archiveList.length > 0) {
            //     console.log('Available fields in first archive:', Object.keys(archiveList[0]));
            //     console.log('Type field:', archiveList[0].type);
            //     console.log('Type ID:', archiveList[0].type_id);
            //     console.log('Archive image:', archiveList[0].archive_image);
            //     console.log('Path image:', archiveList[0].path_image);
            // }

            // Apply client-side search filter
            const filter = (currentArchiveFilter || '').trim().toLowerCase();
            let items = archiveList.filter(a => {
                if (!filter) return true;
                const title = (a.title || '').toString().toLowerCase();
                const description = (a.description || '').toString().toLowerCase();
                let typeName = '';
                if (a.type && a.type.name) typeName = a.type.name.toString().toLowerCase();
                else if (a.type_id) {
                    const found = archiveTypeList.find(t => t.id == a.type_id);
                    if (found) typeName = (found.name || '').toString().toLowerCase();
                }
                return title.includes(filter) || description.includes(filter) || typeName.includes(filter) || (a.link_archive || '').toString().toLowerCase().includes(filter);
            });

            // Apply client-side sorting (if DataTable not used it will still reflect ordering)
            function getArchiveValue(o, key) {
                if (key === 'title') return (o.title || '').toString().toLowerCase();
                if (key === 'type') return (o.type && o.type.name ? o.type.name : (archiveTypeList.find(t => t.id == o.type_id) || {}).name || '').toString().toLowerCase();
                if (key === 'is_inherited') return o.is_inherited ? 1 : 0;
                if (key === 'createdAt' || key === 'created_at') return Date.parse(o.createdAt || o.created_at) || 0;
                return (o[key] || '').toString().toLowerCase();
            }

            const sortKey = currentArchiveSort.key;
            const sortDir = currentArchiveSort.dir === 'asc' ? 1 : -1;
            items.sort((a, b) => {
                const va = getArchiveValue(a, sortKey);
                const vb = getArchiveValue(b, sortKey);
                if (typeof va === 'number' && typeof vb === 'number') return (va - vb) * sortDir;
                if (va < vb) return -1 * sortDir;
                if (va > vb) return 1 * sortDir;
                return 0;
            });

            container.innerHTML = `<table id="archiveTable" class="display" style="width:100%;border-radius:12px;overflow:hidden;">
        <thead>
            <tr>
                <th style="cursor:pointer;width:20%;" onclick="sortArchive('title')">Judul ${currentArchiveSort.key==='title' ? (currentArchiveSort.dir==='asc' ? '▲' : '▼') : ''}</th>
                <th style="cursor:pointer;width:12%;" onclick="sortArchive('type')">Tipe ${currentArchiveSort.key==='type' ? (currentArchiveSort.dir==='asc' ? '▲' : '▼') : ''}</th>
                <th style="width:10%;">Gambar</th>
                <th style="width:10%;">Link</th>
                <th style="cursor:pointer;width:10%;" onclick="sortArchive('is_inherited')">Turunan ${currentArchiveSort.key==='is_inherited' ? (currentArchiveSort.dir==='asc' ? '▲' : '▼') : ''}</th>
                <th style="cursor:pointer;width:12%;" onclick="sortArchive('createdAt')">Tanggal ${currentArchiveSort.key==='createdAt' ? (currentArchiveSort.dir==='asc' ? '▲' : '▼') : ''}</th>
                <th style="width:180px;">Aksi</th>
            </tr>
        </thead>
        <tbody>
        ${items.map(archive => {
            const archiveId = archive.id ? String(archive.id).trim() : '';
            if (!archiveId) {
                console.warn('Archive missing ID:', archive);
                return '';
            }
            
            const createdDate = archive.createdAt ? new Date(archive.createdAt).toLocaleDateString('id-ID') : 'N/A';
            
            // Get type name by matching type_id with archiveTypeList
            let typeName = 'N/A';
            if (archive.type && archive.type.name) {
                // Backend includes type object
                typeName = archive.type.name;
            } else if (archive.type_id && archiveTypeList.length > 0) {
                // Backend only includes type_id, need to lookup from archiveTypeList
                const foundType = archiveTypeList.find(t => t.id == archive.type_id);
                typeName = foundType ? foundType.name : 'N/A';
            //     console.log(`
            // Archive "${archive.title}"
            // type_id: $ {
            //     archive.type_id
            // }, found type: `, foundType);
            }
            
            // Try multiple possible field names for image
            const imagePath = archive.archive_image || archive.path_image || archive.image || null;
            const imgTag = imagePath ? '<img src="' + baseUrl + '/' + imagePath + '" class="img-thumb" alt="Archive" onclick="window.open(\'' + baseUrl + '/' + imagePath + '\',\'_blank\')">' : '<span style="color:#9ca3af;">No Image</span>';
            
            const linkTag = archive.link_archive ? '<a href="' + archive.link_archive + '" target="_blank" style="color:#22c1b6;">Lihat Link</a>' : '<span style="color:#9ca3af;">No Link</span>';
            const inheritedBg = archive.is_inherited ? '#d1fae5' : '#fee2e2';
            const inheritedColor = archive.is_inherited ? '#065f46' : '#991b1b';
            const inheritedText = archive.is_inherited ? 'Ya' : 'Tidak';
            
            return '<tr><td style="font-weight:600;font-size:0.95rem;text-align:left;max-width:200px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">' + (archive.title || 'No Title') + '</td><td style="color:#6b7280;">' + typeName + '</td><td>' + imgTag + '</td><td>' + linkTag + '</td><td><span class="badge" style="background:' + inheritedBg + ';color:' + inheritedColor + '; ">' + inheritedText + '</span></td><td style="color:#6b7280;">' + createdDate + '</td><td style="white-space:nowrap;"><button class="btn-primary" style="padding:6px 12px;border-radius:6px;font-size:0.85rem;margin-right:4px;" onclick="openEditArchiveModal(\'' + archiveId + '\')"><i class="fas fa-edit"></i> Edit</button><button class="btn-danger" style="padding:6px 12px;border-radius:6px;font-size:0.85rem;" onclick="deleteArchive(\'' + archiveId + '\')"><i class="fas fa-trash"></i> Hapus</button></td></tr>';
        }).join('')}
        </tbody>
    </table>`;
            // Initialize DataTable if available; keep reference for search forwarding
            if (window.$ && window.$.fn.dataTable) {
                if (archiveDataTableRef) {
                    try { archiveDataTableRef.destroy(); } catch (e) { /* ignore */ }
                    archiveDataTableRef = null;
                    // Remove any leftover DOM DataTables wrappers
                    document.querySelectorAll('#archiveTable_wrapper').forEach(n => n.remove());
                }
                archiveDataTableRef = $('#archiveTable').DataTable({
                    "order": [[5, currentArchiveSort.dir === 'asc' ? 'asc' : 'desc']],
                    "pageLength": 10,
                    "responsive": true,
                    "autoWidth": false,
                    "columnDefs": [
                        { "width": "20%", "targets": 0 }, // Judul
                        { "width": "12%", "targets": 1 }, // Tipe
                        { "width": "10%", "targets": 2 }, // Gambar
                        { "width": "10%", "targets": 3 }, // Link
                        { "width": "10%", "targets": 4 }, // Turunan
                        { "width": "12%", "targets": 5 }, // Tanggal
                        { "width": "180px", "targets": 6, "orderable": false } // Aksi
                    ],
                    "language": {
                        "search": "Cari:",
                        "lengthMenu": "Tampilkan _MENU_ data per halaman",
                        "info": "Menampilkan _START_ sampai _END_ dari _TOTAL_ data",
                        "paginate": {
                            "first": "Pertama",
                            "last": "Terakhir",
                            "next": "Selanjutnya",
                            "previous": "Sebelumnya"
                        }
                    }
                });

                // Forward custom search input to DataTable search if present
                const searchInput = document.getElementById('archiveSearchInput');
                if (searchInput) {
                    // attach handler if not attached
                    if (!searchInput._dtHandlerAttached) {
                        searchInput.addEventListener('input', function (e) {
                            clearTimeout(_archiveSearchDebounce);
                            _archiveSearchDebounce = setTimeout(() => {
                                currentArchiveFilter = (e.target.value || '').trim();
                                if (archiveDataTableRef) {
                                    archiveDataTableRef.search(currentArchiveFilter).draw();
                                } else {
                                    renderArchiveList();
                                }
                            }, 220);
                        });
                        searchInput._dtHandlerAttached = true;
                    }

                    // apply existing filter
                    if (currentArchiveFilter && archiveDataTableRef) {
                        archiveDataTableRef.search(currentArchiveFilter).draw();
                    }
                }
            } else {
                // If DataTables not available, attach simple search handler that re-renders
                const searchInput = document.getElementById('archiveSearchInput');
                if (searchInput && !searchInput._handlerAttached) {
                    searchInput.addEventListener('input', function (e) {
                        clearTimeout(_archiveSearchDebounce);
                        _archiveSearchDebounce = setTimeout(() => {
                            currentArchiveFilter = (e.target.value || '').trim();
                            renderArchiveList();
                        }, 220);
                    });
                    searchInput._handlerAttached = true;
                }
            }
        }

        async function openAddArchiveModal() {
            console.log('=== OPENING ADD ARCHIVE MODAL ===');
            try {
                // Load archive types first (don't render list)
                console.log('Loading archive types for dropdown...');
                await loadArchiveTypes(false);
                // console.log('Archive types loaded successfully:', archiveTypeList);

                // Reset form
                document.getElementById('archiveForm').reset();
                document.getElementById('archive_id').value = '';
                document.getElementById('archiveModalTitle').textContent = 'Tambah Arsip';

                // Show modal FIRST
                document.getElementById('archiveModal').style.display = 'flex';

                // Small delay to ensure DOM is ready
                await new Promise(resolve => setTimeout(resolve, 100));

                // Populate dropdown AFTER modal is visible
                populateArchiveTypeDropdown();

                // Debug: Check if dropdown is actually visible in UI
                const dropdown = document.getElementById('archive_type_id');
                console.log('After modal open - Dropdown getBoundingClientRect:', dropdown?.getBoundingClientRect());
                console.log('After modal open - Dropdown offsetHeight:', dropdown?.offsetHeight);
                console.log('After modal open - Dropdown offsetWidth:', dropdown?.offsetWidth);

            } catch (error) {
                console.error('Error opening add archive modal:', error);
                showAlert('Gagal memuat form tambah arsip: ' + error.message, 'error');
            }
        }

        async function openEditArchiveModal(id) {
            try {
                console.log('=== OPENING EDIT ARCHIVE MODAL ===');
                console.log('Received ID:', id, 'Type:', typeof id);

                const cleanId = String(id).trim();
                if (!cleanId || cleanId === 'undefined' || cleanId === 'null') {
                    console.error('Invalid ID for edit:', id);
                    showAlert('ID tidak valid untuk edit', 'error');
                    return;
                }

                const numericId = parseInt(cleanId);
                const archive = archiveList.find(a => a.id == numericId || a.id == cleanId);

                console.log('Looking for archive with ID:', cleanId, 'or', numericId);
                console.log('Found archive:', archive);

                if (!archive) {
                    console.error('Archive not found with ID:', cleanId);
                    showAlert('Arsip tidak ditemukan', 'error');
                    return;
                }

                // Load archive types first before populating dropdown
                console.log('Loading archive types for edit modal...');
                await loadArchiveTypes(false); // false for not rendering list

                console.log('Populating form with archive data...');
                document.getElementById('archive_id').value = archive.id;
                document.getElementById('archive_title').value = archive.title;
                document.getElementById('archive_description').value = archive.description || '';
                document.getElementById('archive_link').value = archive.link_archive || '';
                document.getElementById('archive_inherited').checked = archive.is_inherited;

                // Populate dropdown BEFORE showing modal and setting value
                populateArchiveTypeDropdown();
                document.getElementById('archive_type_id').value = archive.type_id || '';

                document.getElementById('archiveModalTitle').textContent = 'Edit Arsip';

                // Show modal after everything is populated
                document.getElementById('archiveModal').style.display = 'flex';

                console.log('Edit modal opened successfully with type_id:', archive.type_id);
            } catch (error) {
                console.error('Error opening edit archive modal:', error);
                showAlert('Gagal memuat form edit: ' + error.message, 'error');
            }
        }

        function populateArchiveTypeDropdown() {
            // console.log('=== POPULATING ARCHIVE TYPE DROPDOWN ===');
            const dropdown = document.getElementById('archive_type_id');

            // console.log('Dropdown element:', dropdown);
            // console.log('Modal display style:', document.getElementById('archiveModal')?.style.display);

            if (!dropdown) {
                console.error('Dropdown element not found!');
                return;
            }

            // Clear existing options
            dropdown.innerHTML = '';
            console.log('Dropdown cleared, current options count:', dropdown.options.length);

            // Add default option
            const defaultOption = document.createElement('option');
            defaultOption.value = '';
            defaultOption.textContent = 'Pilih tipe arsip';
            dropdown.appendChild(defaultOption);
            console.log('Default option added, current options count:', dropdown.options.length);

            // console.log('archiveTypeList:', archiveTypeList);
            // console.log('archiveTypeList length:', archiveTypeList ? archiveTypeList.length : 0);
            // console.log('archiveTypeList is Array?:', Array.isArray(archiveTypeList));

            if (!archiveTypeList || archiveTypeList.length === 0) {
                console.warn('No archive types available - dropdown will only have default option');
                dropdown.disabled = false;
                return;
            }

            console.log('Starting to add options to dropdown...');
            archiveTypeList.forEach((type, index) => {
                console.log(`Adding type ${index}:`, type);
                console.log(`  - ID: ${type.id}, Name: ${type.name}`);
                const option = document.createElement('option');
                option.value = type.id;
                option.textContent = type.name;
                // Set explicit styles for options
                option.style.background = '#fff';
                option.style.color = '#333';
                dropdown.appendChild(option);
                console.log(`  - Option added, total options now: ${dropdown.options.length}`);
            });

            // Enable dropdown and ensure proper styling
            dropdown.disabled = false;
            dropdown.style.background = '#fff';
            dropdown.style.color = '#333';

            console.log('=== DROPDOWN POPULATION COMPLETE ===');
            console.log('Final options count:', dropdown.options.length);
            console.log('Final dropdown HTML:', dropdown.outerHTML);
            console.log('Dropdown visible?:', dropdown.offsetParent !== null);
            console.log('Dropdown disabled?:', dropdown.disabled);
            console.log('Dropdown computed display:', window.getComputedStyle(dropdown).display);
            console.log('Dropdown computed visibility:', window.getComputedStyle(dropdown).visibility);
            console.log('Dropdown computed opacity:', window.getComputedStyle(dropdown).opacity);
            console.log('Dropdown computed height:', window.getComputedStyle(dropdown).height);
            console.log('Dropdown parent form-group:', dropdown.closest('.form-group'));

            // Force styling to ensure visibility
            dropdown.style.display = 'block';
            dropdown.style.visibility = 'visible';
            dropdown.style.opacity = '1';
            dropdown.style.width = '100%';
            dropdown.style.height = 'auto';
            dropdown.style.minHeight = '44px';
            dropdown.style.zIndex = '1';

            console.log('After force styling - dropdown HTML:', dropdown.outerHTML);
        }

        function closeArchiveModal() {
            document.getElementById('archiveModal').style.display = 'none';
        }

        document.getElementById('archiveForm').addEventListener('submit', async function(e) {
            e.preventDefault();

            const id = document.getElementById('archive_id').value;
            const title = document.getElementById('archive_title').value.trim();
            const description = document.getElementById('archive_description').value.trim();
            const typeId = document.getElementById('archive_type_id').value;
            const linkArchive = document.getElementById('archive_link').value.trim();
            const isInherited = document.getElementById('archive_inherited').checked;
            const imageInput = document.getElementById('archive_image');
            const token = getAuthToken();

            console.log('=== ARCHIVE FORM SUBMISSION ===');

            if (!title) {
                showAlert('Judul harus diisi!', 'error');
                return;
            }

            if (!typeId) {
                showAlert('Tipe arsip harus dipilih!', 'error');
                return;
            }

            const formData = new FormData();

            // Append all required fields
            formData.append('title', title || '');
            formData.append('description', description || '');
            formData.append('type_id', typeId || '');
            formData.append('link_archive', linkArchive || '');
            formData.append('is_inherited', isInherited ? 1 : 0);

            // Append image if selected
            if (imageInput && imageInput.files && imageInput.files[0]) {
                formData.append('archive_image', imageInput.files[0]);
                console.log('Image file added:', imageInput.files[0].name, imageInput.files[0].size, 'bytes');
            } else {
                console.log('No image file selected - will send without image');
            }

            // Log FormData contents
            console.log('=== FORMDATA CONTENTS ===');
            for (let [key, value] of formData.entries()) {
                if (value instanceof File) {
                    console.log(`${key}: ${value.name} (${value.size} bytes, type: ${value.type})`);
                } else {
                    console.log(`${key}: ${value} (type: ${typeof value})`);
                }
            }
            console.log('Total FormData entries:', Array.from(formData.entries()).length);

            try {
                let url = `${baseUrl}/api/admin/archive`;
                let method = 'POST';
                if (id) {
                    url += `/${id}`;
                    method = 'PUT';
                }

                console.log('Submitting to URL:', url);
                console.log('Method:', method);

                const res = await fetch(url, {
                    method,
                    headers: {
                        'Authorization': `Bearer ${token}`
                    },
                    body: formData
                });

                console.log('Response status:', res.status);
                console.log('Response statusText:', res.statusText);

                if (res.ok) {
                    const responseData = await res.json();
                    console.log('Success response:', responseData);
                    showAlert('Arsip berhasil disimpan!', 'success');
                    closeArchiveModal();
                    loadArchives();
                } else {
                    // Clone response to read multiple times
                    const clonedResponse = res.clone();
                    let errorMessage = 'Unknown error';

                    try {
                        const errorJson = await res.json();
                        console.error('Error JSON response:', errorJson);
                        errorMessage = errorJson.message || errorJson.error || JSON.stringify(errorJson);
                    } catch (jsonError) {
                        console.log('Failed to parse as JSON, trying text...');
                        try {
                            const errorText = await clonedResponse.text();
                            console.error('Error text response:', errorText);
                            errorMessage = errorText.substring(0, 200); // Limit length
                        } catch (textError) {
                            console.error('Failed to read response:', textError);
                            errorMessage = `HTTP ${res.status}: ${res.statusText}`;
                        }
                    }
                    showAlert(`Gagal simpan data (${res.status}): ${errorMessage}`, 'error');
                }
            } catch (err) {
                console.error('Fetch error:', err);
                showAlert('Gagal simpan: ' + err.message, 'error');
            }
        });

        async function deleteArchive(id) {
            console.log('=== DELETE ARCHIVE ===');

            const cleanId = String(id).trim();
            if (!cleanId || cleanId === 'undefined' || cleanId === 'null') {
                console.error('Invalid ID:', id);
                showAlert('ID arsip tidak valid', 'error');
                return;
            }

            if (!confirm('Yakin ingin menghapus arsip ini?')) return;

            const token = getAuthToken();
            const url = `${baseUrl}/api/admin/archive/${cleanId}`;

            try {
                const res = await fetch(url, {
                    method: 'DELETE',
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
                if (res.ok) {
                    showAlert('Arsip berhasil dihapus!', 'success');
                    loadArchives();
                } else {
                    const errorData = await res.text();
                    showAlert('Gagal hapus data: ' + errorData, 'error');
                }
            } catch (err) {
                showAlert('Gagal hapus: ' + err.message, 'error');
            }
        }

        // Archive Type Functions
        async function loadArchiveTypes(renderList = true) {
            try {
                const token = getAuthToken();
                // console.log('=== LOADING ARCHIVE TYPES ===');
                // console.log('Token:', token ? 'Present' : 'Missing');
                // console.log('BaseURL:', baseUrl);

                const url = `${baseUrl}/api/admin/archive-type`;
                // console.log('Fetching from:', url);

                const res = await fetch(url, {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });

                console.log('Response status:', res.status);

                if (!res.ok) {
                    const errorText = await res.text();
                    console.error('Error response:', errorText);
                    throw new Error(`Gagal fetch tipe arsip (${res.status}): ${errorText}`);
                }

                const data = await res.json();
                // console.log('Raw data received:', data);

                archiveTypeList = Array.isArray(data) ? data : (data.data || []);
                // console.log('Processed archiveTypeList:', archiveTypeList);
                // console.log('archiveTypeList length:', archiveTypeList.length);
                if (renderList) {
                    renderArchiveTypeList();
                }

                return archiveTypeList;
            } catch (err) {
                console.error('Error loading archive types:', err);
                showAlert('Gagal memuat tipe arsip: ' + err.message, 'error');
                archiveTypeList = []; // Reset to empty array on error
                throw err;
            }
        }

        function renderArchiveTypeList() {
            const container = document.getElementById('archiveTypeListContainer');

            if (!container) {
                console.error('Container element "archiveTypeListContainer" not found!');
                return;
            }

            if (!archiveTypeList || archiveTypeList.length === 0) {
                container.innerHTML =
                    '<div style="padding:2rem;text-align:center;color:#9ca3af;font-size:1.1rem;">Belum ada tipe arsip. Klik tombol "Tambah Tipe Arsip" untuk menambahkan data baru.</div>';
                return;
            }

            // console.log('=== RENDERING ARCHIVE TYPE LIST ===');
            // console.log('archiveTypeList length:', archiveTypeList.length);
            // console.log('First type:', archiveTypeList[0]);

            container.innerHTML = `<table id="archiveTypeTable" class="display" style="width:100%;border-radius:12px;overflow:hidden;">
        <thead>
            <tr>
                <th>Nama</th>
                <th>Deskripsi</th>
                <th>Tanggal Dibuat</th>
                <th>Aksi</th>
            </tr>
        </thead>
        <tbody>
        ${archiveTypeList.map(type => {
            const typeId = type.id ? String(type.id).trim() : '';
            if (!typeId) {
                console.warn('Archive type missing ID:', type);
                return '';
            }
            
            const createdDate = type.createdAt ? new Date(type.createdAt).toLocaleDateString('id-ID') : 'N/A';
            
            return '<tr><td style="font-weight:600;font-size:1.05rem;text-align:left;">' + (type.name || 'No Name') + '</td><td style="color:#6b7280;text-align:left;">' + (type.description || 'No Description') + '</td><td style="color:#6b7280;">' + createdDate + '</td><td><button class="btn-primary" style="padding:6px 16px;border-radius:8px;font-size:0.9rem;margin-right:6px;" onclick="openEditArchiveTypeModal(\'' + typeId + '\')"><i class="fas fa-edit"></i> Edit</button><button class="btn-danger" style="padding:6px 16px;border-radius:8px;font-size:0.9rem;" onclick="deleteArchiveType(\'' + typeId + '\')"><i class="fas fa-trash"></i> Hapus</button></td></tr>';
        }).join('')}
        </tbody>
    </table>`;

            if (window.$ && window.$.fn.dataTable) {
                $('#archiveTypeTable').DataTable({
                    "order": [
                        [2, "desc"]
                    ], // Sort by date descending
                    "pageLength": 10,
                    "responsive": true,
                    "language": {
                        "search": "Cari:",
                        "lengthMenu": "Tampilkan _MENU_ data per halaman",
                        "info": "Menampilkan _START_ sampai _END_ dari _TOTAL_ data",
                        "paginate": {
                            "first": "Pertama",
                            "last": "Terakhir",
                            "next": "Selanjutnya",
                            "previous": "Sebelumnya"
                        }
                    }
                });
            }
        }

        function openAddArchiveTypeModal() {
            document.getElementById('archiveTypeForm').reset();
            document.getElementById('archiveType_id').value = '';
            document.getElementById('archiveTypeModalTitle').textContent = 'Tambah Tipe Arsip';
            document.getElementById('archiveTypeModal').style.display = 'flex';
        }

        function openEditArchiveTypeModal(id) {
            // console.log('=== OPENING EDIT ARCHIVE TYPE MODAL ===');
            // console.log('Received ID:', id, 'Type:', typeof id);

            const cleanId = String(id).trim();
            if (!cleanId || cleanId === 'undefined' || cleanId === 'null') {
                console.error('Invalid ID for edit:', id);
                showAlert('ID tidak valid untuk edit', 'error');
                return;
            }

            const numericId = parseInt(cleanId);
            const archiveType = archiveTypeList.find(t => t.id == numericId || t.id == cleanId);

            // console.log('Looking for archive type with ID:', cleanId, 'or', numericId);
            // console.log('Found archive type:', archiveType);

            if (!archiveType) {
                console.error('Archive type not found with ID:', cleanId);
                showAlert('Tipe arsip tidak ditemukan', 'error');
                return;
            }

            document.getElementById('archiveType_id').value = archiveType.id;
            document.getElementById('archiveType_name').value = archiveType.name;
            document.getElementById('archiveType_description').value = archiveType.description || '';
            document.getElementById('archiveTypeModalTitle').textContent = 'Edit Tipe Arsip';
            document.getElementById('archiveTypeModal').style.display = 'flex';
        }

        function closeArchiveTypeModal() {
            document.getElementById('archiveTypeModal').style.display = 'none';
        }

        document.getElementById('archiveTypeForm').addEventListener('submit', async function(e) {
            e.preventDefault();

            const id = document.getElementById('archiveType_id').value;
            const name = document.getElementById('archiveType_name').value.trim();
            const description = document.getElementById('archiveType_description').value.trim();
            const token = getAuthToken();

            console.log('=== ARCHIVE TYPE FORM SUBMISSION ===');

            if (!name) {
                showAlert('Nama tipe arsip harus diisi!', 'error');
                return;
            }

            const formData = {
                name: name,
                description: description
            };

            console.log('FormData:', formData);

            try {
                let url = `${baseUrl}/api/admin/archive-type`;
                let method = 'POST';
                if (id) {
                    url += `/${id}`;
                    method = 'PUT';
                }
                const res = await fetch(url, {
                    method,
                    headers: {
                        'Authorization': `Bearer ${token}`,
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(formData)
                });
                if (res.ok) {
                    showAlert('Tipe arsip berhasil disimpan!', 'success');
                    closeArchiveTypeModal();
                    loadArchiveTypes();
                } else {
                    const errorData = await res.text();
                    showAlert('Gagal simpan data: ' + errorData, 'error');
                }
            } catch (err) {
                showAlert('Gagal simpan: ' + err.message, 'error');
            }
        });

        async function deleteArchiveType(id) {
            console.log('=== DELETE ARCHIVE TYPE ===');

            const cleanId = String(id).trim();
            if (!cleanId || cleanId === 'undefined' || cleanId === 'null') {
                console.error('Invalid ID:', id);
                showAlert('ID tipe arsip tidak valid', 'error');
                return;
            }

            if (!confirm('Yakin ingin menghapus tipe arsip ini?')) return;

            const token = getAuthToken();
            const url = `${baseUrl}/api/admin/archive-type/${cleanId}`;

            try {
                const res = await fetch(url, {
                    method: 'DELETE',
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
                if (res.ok) {
                    showAlert('Tipe arsip berhasil dihapus!', 'success');
                    loadArchiveTypes();
                } else {
                    const errorData = await res.text();
                    showAlert('Gagal hapus data: ' + errorData, 'error');
                }
            } catch (err) {
                showAlert('Gagal hapus: ' + err.message, 'error');
            }
        }

        // Close modal when clicking outside
        window.onclick = function(event) {
            const archiveModal = document.getElementById('archiveModal');
            const archiveTypeModal = document.getElementById('archiveTypeModal');

            if (event.target === archiveModal) {
                closeArchiveModal();
            }
            if (event.target === archiveTypeModal) {
                closeArchiveTypeModal();
            }
        }

        // Initialize on page load
        document.addEventListener('DOMContentLoaded', function() {
            // console.log('=== PAGE INITIALIZATION ===');
            // console.log('DOM loaded successfully');
            // console.log('Base URL:', baseUrl);
            console.log('Auth token:', getAuthToken() ? 'Present' : 'Missing');

            // Verify essential elements exist
            const archiveContainer = document.getElementById('archiveListContainer');
            const typeContainer = document.getElementById('archiveTypeListContainer');
            // console.log('Archive container found:', !!archiveContainer);
            // console.log('Type container found:', !!typeContainer);

            // Load jQuery and DataTables
            if (!window.$) {
                console.log('jQuery not found, loading...');
                const scriptJq = document.createElement('script');
                scriptJq.src = 'https://code.jquery.com/jquery-3.6.0.min.js';
                scriptJq.onload = () => {
                    console.log('jQuery loaded successfully');
                    const scriptDt = document.createElement('script');
                    scriptDt.src = 'https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js';
                    scriptDt.onload = () => {
                        console.log('DataTables loaded successfully');
                        console.log('Starting to load archives...');
                        loadArchives(); // Load initial data
                    };
                    scriptDt.onerror = () => {
                        console.error('Failed to load DataTables');
                        showAlert('Gagal memuat DataTables library', 'error');
                    };
                    document.body.appendChild(scriptDt);
                };
                scriptJq.onerror = () => {
                    console.error('Failed to load jQuery');
                    showAlert('Gagal memuat jQuery library', 'error');
                };
                document.body.appendChild(scriptJq);
            } else {
                // console.log('jQuery already loaded');
                // console.log('Starting to load archives...');
                loadArchives(); // Load initial data
            }
        });
    </script>
@endsection
