
<?php $__env->startSection('title', 'Kelola Berita'); ?>

<?php $__env->startSection('styles'); ?>
    <link rel="stylesheet" href="https://cdn.datatables.net/1.11.5/css/jquery.dataTables.min.css">
<?php $__env->stopSection(); ?>

<style>
    /* 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;
    }
</style>

<?php $__env->startSection('content'); ?>
    <link rel="stylesheet" href="<?php echo e(asset('assets/css/beritaAdmin.css')); ?>">
    <div class="admin-dashboard">
        <?php echo $__env->make('admin.components.sidebar', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>

        <main class="main">
            <div class="main-header">
                <div>
                    <div class="title">Kelola Berita</div>
                    <div class="subtitle">Manajemen Artikel dan Berita</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="<?php echo e(route('logout')); ?>" style="display:inline;">
                        <?php echo csrf_field(); ?>
                        <button type="submit">Keluar</button>
                    </form>
                </div>
            </div>

            <div class="main-content">
                <!-- Toast Container -->
                <div class="toast-container" id="toast-container"></div>

                <!-- Tab Navigation -->
                <div class="content-section" style="padding: 0;">
                    <div class="tab-nav" style="display: flex; border-bottom: 1px solid #e5e7eb;">
                        <button id="articlesTabBtn" class="tab-btn active" onclick="switchTab('articles')">
                            <i class="fas fa-newspaper"></i> Kelola Artikel
                        </button>
                        <button id="categoriesTabBtn" class="tab-btn" onclick="switchTab('categories')">
                            <i class="fas fa-tags"></i> Kelola Kategori
                        </button>
                    </div>
                </div>

                <!-- Articles Tab Content -->
                <div id="articlesTab">

                    <!-- Edit News Modal -->
                    <div id="editNewsModal" class="modal">
                        <div class="modal-content">
                            <div class="modal-header">
                                <div class="modal-title">Edit Berita</div>
                                <span class="close" onclick="closeEditModal()">&times;</span>
                            </div>
                            <div class="form-container">
                                <form id="editNewsForm">
                                    <input type="hidden" id="edit_article_id" name="id">

                                    <div class="form-row">
                                        <div class="form-group">
                                            <label for="edit_title">Judul Berita</label>
                                            <input type="text" id="edit_title" name="title" required minlength="10"
                                                maxlength="255">
                                            <small class="form-hint">Judul harus 10-255 karakter</small>
                                        </div>
                                        <div class="form-group">
                                            <label for="edit_category_id">Kategori</label>
                                            <select id="edit_category_id" name="category_id" required
                                                onclick="ensureCategoriesLoaded(this)">
                                                <option value="">Pilih Kategori</option>
                                                <!-- Categories will be populated dynamically -->
                                            </select>
                                        </div>
                                    </div>

                                    <div class="form-group">
                                        <label for="edit_body">Isi Berita</label>
                                        <textarea id="edit_body" name="body" required placeholder="Tulis isi berita di sini..." minlength="100"
                                            maxlength="5000"></textarea>
                                        <small class="form-hint">Isi berita harus 100-5000 karakter</small>
                                        <div class="character-counter"><span id="editBodyCounter">0</span>/5000 karakter
                                        </div>
                                    </div>

                                    <div class="form-row">
                                        <div class="form-group">
                                            <label for="edit_article">Ganti Gambar Berita (opsional)</label>
                                            <input type="file" id="edit_article" name="article" accept="image/*">
                                            <div id="current_image_container" style="margin-top:10px;">
                                                <small>Gambar saat ini:</small>
                                                <div id="current_image_preview" style="margin-top:5px;"></div>
                                            </div>
                                        </div>
                                        <div class="form-group">
                                            <label for="edit_is_inherited">Status Distribusi</label>
                                            <select id="edit_is_inherited" name="is_inherited">
                                                <option value="0">Tidak Diturunkan (hanya untuk site ini)</option>
                                                <option value="1">Diturunkan (tersedia untuk semua site)</option>
                                            </select>
                                            <small class="form-hint">Pilih "Diturunkan" agar berita tersedia untuk semua
                                                site</small>
                                        </div>
                                    </div>

                                    <div class="form-actions">
                                        <button type="button" class="btn-secondary"
                                            onclick="closeEditModal()">Batal</button>
                                        <button type="submit" class="btn-primary">Simpan Perubahan</button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>

                    <!-- Add News Form -->
                    <div class="content-section">
                        <div class="section-header">
                            <div class="section-title">Tambah Berita Baru</div>
                            <div style="display: flex; gap: 10px;">
                                <button type="button" class="btn-secondary" onclick="reloadCategories()"
                                    id="refreshCategoriesBtn" title="Muat ulang data kategori">
                                    <i class="fas fa-sync-alt"></i> Refresh Kategori
                                </button>
                                <button type="button" class="btn-primary" onclick="loadCategoriesAndToggleForm()">
                                    <i class="fas fa-plus"></i> Tambah Berita
                                </button>
                            </div>
                        </div>

                        <div id="addNewsForm" class="form-container" style="display: none;">
                            <form id="newsForm" enctype="multipart/form-data">
                                <div class="form-row">
                                    <div class="form-group">
                                        <label for="title">Judul Berita</label>
                                        <input type="text" id="title" name="title" required minlength="10"
                                            maxlength="255">
                                        <small class="form-hint">Judul harus 10-255 karakter</small>
                                    </div>
                                    <div class="form-group">
                                        <label for="category_id">Kategori</label>
                                        <select id="category_id" name="category_id" required
                                            onclick="ensureCategoriesLoaded(this)"
                                            style="display: block !important; width: 100%; padding: 12px 16px; border: 1px solid #d1d5db; border-radius: 8px; font-size: 1rem; background-color: #fff; color: #374151;">
                                            <option value="">Pilih Kategori</option>
                                        </select>
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label for="body">Isi Berita</label>
                                    <textarea id="body" name="body" required placeholder="Tulis isi berita di sini..." minlength="100"
                                        maxlength="5000"></textarea>
                                    <small class="form-hint">Isi berita harus 100-5000 karakter</small>
                                    <div class="character-counter"><span id="bodyCounter">0</span>/5000 karakter</div>
                                </div>

                                <div class="form-row">
                                    <div class="form-group">
                                        <label for="article">Gambar Berita</label>
                                        <input type="file" id="article" name="article" accept="image/*" required>
                                    </div>
                                    <div class="form-group">
                                        <label for="is_inherited">Status Distribusi</label>
                                        <select id="is_inherited" name="is_inherited">
                                            <option value="0">Tidak Diturunkan (hanya untuk site ini)</option>
                                            <option value="1">Diturunkan (tersedia untuk semua site)</option>
                                        </select>
                                        <small class="form-hint">Pilih "Diturunkan" agar berita tersedia untuk semua
                                            site</small>
                                    </div>
                                </div>

                                <div class="form-actions">
                                    <button type="button" class="btn-secondary" onclick="toggleAddForm()">Batal</button>
                                    <button type="submit" class="btn-primary">Simpan Berita</button>
                                </div>
                            </form>
                        </div>
                    </div>

                    <!-- News List -->
                    <div class="content-section">
                        <div class="section-header">
                            <div class="section-title">Daftar Berita</div>
                            <div style="display:flex; gap:12px; align-items:center;">
                                <input id="newsSearchInput" type="search" placeholder="Cari berita, judul, kategori..." style="padding:8px 10px; border-radius:8px; border:1px solid #e5e7eb; min-width:260px;">
                                <button type="button" class="btn-secondary" onclick="loadNews()" id="refreshBtn">
                                    <i class="fas fa-sync-alt"></i> Refresh
                                </button>
                            </div>
                        </div>

                        <div id="newsListContainer">
                            <div class="loading">
                                <i class="fas fa-spinner fa-spin"></i> Memuat data berita...
                            </div>
                        </div>
                    </div>
                </div>

                <!-- End of Articles Tab -->
            </div>

            <!-- Categories Tab Content -->
            <div id="categoriesTab" style="display: flex;padding-left: 30px;padding-right: 30px">
                <!-- Category Form Modal -->
                <div id="categoryFormModal" class="modal">
                    <div class="modal-content">
                        <div class="modal-header">
                            <div class="modal-title" id="categoryModalTitle">Tambah Kategori Baru</div>
                            <span class="close" onclick="closeCategoryModal()">&times;</span>
                        </div>
                        <div class="form-container">
                            <form id="categoryForm">
                                <input type="hidden" id="category_id" name="id">

                                <div class="form-group">
                                    <label for="category_name">Nama Kategori</label>
                                    <input type="text" id="category_name" name="name" required maxlength="255">
                                    <small class="form-hint">Nama kategori harus unik</small>
                                </div>

                                <div class="form-group">
                                    <label for="category_description">Deskripsi</label>
                                    <textarea id="category_description" name="description" maxlength="500"></textarea>
                                    <small class="form-hint">Maksimal 500 karakter</small>
                                    <div class="character-counter"><span id="categoryDescCounter">0</span>/500 karakter
                                    </div>
                                </div>

                                <div class="form-actions">
                                    <button type="button" class="btn-secondary"
                                        onclick="closeCategoryModal()">Batal</button>
                                    <button type="submit" class="btn-primary">Simpan Kategori</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>

                <!-- Category Management -->
                <div class="content-section">
                    <div class="section-header">
                        <div class="section-title">Kelola Kategori Artikel</div>
                        <button type="button" class="btn-primary" onclick="openAddCategoryModal()">
                            <i class="fas fa-plus"></i> Tambah Kategori
                        </button>
                    </div>

                    <div id="categoryListContainer">
                        <div class="loading">
                            <i class="fas fa-spinner fa-spin"></i> Memuat data kategori...
                        </div>
                    </div>
                </div>
            </div>
            <!-- End of Categories Tab -->

        </main>
    </div>

    <script>
        let categories = [];
        let newsList = [];
        let adminSiteId = null;
        // Client-side state for news search & sorting
        let currentNewsFilter = '';
        let currentNewsSort = { key: 'created_at', dir: 'desc' };
        let _newsSearchDebounce = null;

        // Function to get auth token
        function getAuthToken() {
            const sessionToken = '<?php echo e(session('auth.token') ?? ''); ?>';
            if (sessionToken) {
                return sessionToken;
            }

            return localStorage.getItem('auth_token') ||
                sessionStorage.getItem('auth_token');
        }

        // Function to get admin site_id from session
        function getAdminSiteId() {
            const sessionSiteId = '<?php echo e(session('auth.user.site_id') ?? ''); ?>';
            if (sessionSiteId) {
                return parseInt(sessionSiteId);
            }

            const userData = localStorage.getItem('auth_user');
            if (userData) {
                try {
                    const user = JSON.parse(userData);
                    return user.site_id;
                } catch (e) {
                    console.error('Error parsing user data:', e);
                }
            }
            return null;
        }

        // Function to make authenticated API calls
        async function apiCall(endpoint, method = 'GET', data = null) {
            const token = getAuthToken();
            if (!token) {
                throw new Error('Token autentikasi tidak ditemukan. Silakan login ulang.');
            }

            const baseUrl = '<?php echo e(config('services.auth_api.base_url')); ?>';
            const url = `${baseUrl}/${endpoint.startsWith('/') ? endpoint.substring(1) : endpoint}`;

            // console.log('API Call:', method, url);
            console.log('Token:', token ? 'Present' : 'Missing');

            const headers = {
                'Authorization': `Bearer ${token}`,
                'Accept': 'application/json'
            };

            const options = {
                method: method,
                headers: headers
            };

            if (data) {
                if (data instanceof FormData) {
                    // Don't set Content-Type for FormData, let browser set it
                    options.body = data;
                } else {
                    headers['Content-Type'] = 'application/json';
                    options.body = JSON.stringify(data);
                }
            }

            // console.log('Request options:', options);

            const response = await fetch(url, options);
            console.log('Response status:', response.status);

            if (response.status === 401) {
                if (window.handleSessionExpired) window.handleSessionExpired();
                throw new Error('Session expired. Silakan login ulang.');
            }

            if (!response.ok) {
                const errorData = await response.json().catch(() => ({}));
                console.error('API Error:', errorData);
                throw new Error(errorData.message || `HTTP Error: ${response.status}`);
            }

            if (response.status === 204) {
                // No Content, return null or empty object
                console.log('API Response: No Content (204)');
                return null;
            }
            const result = await response.json();
            // console.log('API Response:', result);
            return result;
        }

        // Character counter function
        function setupCharacterCounter(inputId, counterId, maxLength) {
            const textarea = document.getElementById(inputId);
            const counter = document.getElementById(counterId);

            function updateCounter() {
                const currentLength = textarea.value.length;
                counter.textContent = currentLength;

                // Add visual feedback when approaching limit
                if (currentLength > maxLength * 0.9) {
                    counter.parentElement.classList.add('exceeding');
                } else {
                    counter.parentElement.classList.remove('exceeding');
                }
            }

            textarea.addEventListener('input', updateCounter);

            // Initialize counter on load
            updateCounter();
        }

        // Load categories from API
        async function loadCategories() {
            try {
                console.log('Loading categories...');
                const response = await apiCall('api/admin/article-category');
                console.log('Categories response:', response);

                // Handle both wrapped and direct array responses
                categories = Array.isArray(response) ? response : (response.data || response);
                console.log('Processed categories:', categories);

                // Populate all category dropdowns that exist in the DOM
                populateAllCategoryDropdowns();

                return categories;
            } catch (error) {
                // Cek session expired jika ada response dari fetch
                if (error && error.response && window.isSessionExpiredResponse) {
                    window.isSessionExpiredResponse(error.response).then(isExpired => {
                        if (isExpired && window.handleSessionExpired) window.handleSessionExpired();
                    });
                }
                // Fallback: jika error.message mengandung session expired
                if (error && error.message && window.isSessionExpiredResponse) {
                    // Simulasi response-like object
                    const fakeResponse = { status: 401, json: async () => ({ message: error.message }) };
                    window.isSessionExpiredResponse(fakeResponse).then(isExpired => {
                        if (isExpired && window.handleSessionExpired) window.handleSessionExpired();
                    });
                }
                console.error('Error loading categories:', error);
                showAlert('Gagal memuat kategori: ' + error.message, 'error');
                throw error;
            }
        }

        // Function to populate all category dropdowns in the page
        function populateAllCategoryDropdowns() {
            console.log('Populating all category dropdowns...');
            const dropdowns = [
                document.getElementById('category_id'),
                document.getElementById('edit_category_id')
            ];

            dropdowns.forEach(dropdown => {
                if (dropdown) {
                    console.log(`Populating dropdown: ${dropdown.id}`);
                    populateDropdown(dropdown);
                }
            });
        }

        // Helper function to populate dropdown
        function populateDropdown(categorySelect) {
            console.log('=== POPULATE DROPDOWN START ===');
            console.log('categorySelect element:', categorySelect);
            console.log('categories array:', categories);
            console.log('categories length:', categories.length);

            if (!categorySelect) {
                console.error('Category select element is null!');
                return false;
            }

            try {
                // Clear existing options
                categorySelect.innerHTML = '';
                console.log('Cleared existing options');

                // Add default option
                const defaultOption = document.createElement('option');
                defaultOption.value = '';
                defaultOption.textContent = 'Pilih Kategori';
                categorySelect.appendChild(defaultOption);
                console.log('Added default option');

                if (categories && categories.length > 0) {
                    categories.forEach((category, index) => {
                        if (!category || !category.id || !category.name) {
                            console.warn(`Invalid category at index ${index}:`, category);
                            return; // Skip this iteration
                        }

                        console.log(`Processing category ${index}:`, category);
                        const option = document.createElement('option');
                        option.value = category.id;
                        option.textContent = category.name;
                        categorySelect.appendChild(option);
                        console.log(`Added option: ${category.name} (ID: ${category.id})`);
                    });

                    console.log('Final select options count:', categorySelect.options.length);

                    // Verify options are actually there
                    for (let i = 0; i < categorySelect.options.length; i++) {
                        console.log(
                            `Option ${i}: value="${categorySelect.options[i].value}", text="${categorySelect.options[i].textContent}"`
                        );
                    }

                    console.log('Categories populated successfully!');
                    return true;
                } else {
                    console.log('No categories found to populate');
                    return false;
                }
            } catch (error) {
                console.error('Error populating dropdown:', error);
                return false;
            } finally {
                console.log('=== POPULATE DROPDOWN END ===');
            }
        }

        // Load news from API
        async function loadNews() {
            try {
                const refreshBtn = document.getElementById('refreshBtn');
                refreshBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Memuat...';

                const response = await apiCall('api/admin/article');
                newsList = response.data || response;

                renderNewsList();

                refreshBtn.innerHTML = '<i class="fas fa-sync-alt"></i> Refresh';
            } catch (error) {
                console.error('Error loading news:', error);
                document.getElementById('newsListContainer').innerHTML =
                    `<div class="loading" style="color: #dc2626;">
                        <i class="fas fa-exclamation-triangle"></i> Error: ${error.message}
                    </div>`;
                refreshBtn.innerHTML = '<i class="fas fa-sync-alt"></i> Refresh';
            }
        }

        // Render news list
        function renderNewsList() {
            const container = document.getElementById('newsListContainer');
            const baseUrl = '<?php echo e(rtrim(env('BASE_URL'), '/')); ?>';

            if (!newsList || newsList.length === 0) {
                container.innerHTML = `<div class="loading"><i class="fas fa-info-circle"></i> Belum ada berita yang tersedia.</div>`;
                return;
            }

            // Apply search filter
            const filter = (currentNewsFilter || '').trim().toLowerCase();
            let filtered = newsList.filter(n => {
                if (!filter) return true;
                const title = (n.title || '').toString().toLowerCase();
                const body = (n.body || '').toString().toLowerCase();
                const category = (getCategoryName(n.category_id) || '').toString().toLowerCase();
                const siteId = (n.site_id || '').toString();
                return title.includes(filter) || body.includes(filter) || category.includes(filter) || siteId === filter;
            });

            // Sort
            function getNewsValue(n, key) {
                if (key === 'title') return (n.title || '').toString().toLowerCase();
                if (key === 'category') return (getCategoryName(n.category_id) || '').toString().toLowerCase();
                if (key === 'site_id') return Number(n.site_id || 0);
                if (key === 'is_inherited') return (n.is_inherited == '1' || n.is_inherited === true) ? 1 : 0;
                if (key === 'created_at') return Date.parse(n.created_at || n.createdAt) || 0;
                return (n[key] || '').toString().toLowerCase();
            }

            const sortKey = currentNewsSort.key;
            const sortDir = currentNewsSort.dir === 'asc' ? 1 : -1;
            filtered.sort((a, b) => {
                const va = getNewsValue(a, sortKey);
                const vb = getNewsValue(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;
            });

            const site_id = getAdminSiteId();

            // Build table with clickable headers for sorting
            const tableHTML = `
                <table class="news-table">
                    <thead>
                        <tr>
                            <th>Gambar</th>
                            <th style="cursor:pointer;" onclick="sortNews('title')">Judul ${currentNewsSort.key==='title' ? (currentNewsSort.dir==='asc' ? '▲' : '▼') : ''}</th>
                            <th style="cursor:pointer;" onclick="sortNews('category')">Kategori ${currentNewsSort.key==='category' ? (currentNewsSort.dir==='asc' ? '▲' : '▼') : ''}</th>
                            <th style="cursor:pointer;" onclick="sortNews('site_id')">Site ID ${currentNewsSort.key==='site_id' ? (currentNewsSort.dir==='asc' ? '▲' : '▼') : ''}</th>
                            <th style="cursor:pointer;" onclick="sortNews('is_inherited')">Inherited ${currentNewsSort.key==='is_inherited' ? (currentNewsSort.dir==='asc' ? '▲' : '▼') : ''}</th>
                            <th style="cursor:pointer;" onclick="sortNews('created_at')">Tanggal ${currentNewsSort.key==='created_at' ? (currentNewsSort.dir==='asc' ? '▲' : '▼') : ''}</th>
                            <th>Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
                        ${filtered.map(news => {
                            let imgTag = '<div class="news-image" style="background:#f3f4f6;display:flex;align-items:center;justify-content:center;color:#9ca3af;">No Image</div>';
                            if (news.path_image) {
                                let cleanPath = news.path_image.replace(/^\/+/, '').replace(/\\/g, '/');
                                let imgUrl = news.path_image.startsWith('http') ? news.path_image : (baseUrl + '/' + cleanPath);
                                imgTag = `<img src="${imgUrl}" class="news-image" alt="${imgUrl}">`;
                            }
                            return `
                                <tr>
                                    <td>${imgTag}</td>
                                    <td>
                                        <strong>${news.title}</strong>
                                        <div style="font-size:0.9rem;color:#6b7280;margin-top:4px;">
                                            ${news.body ? news.body.substring(0, 120) + (news.body.length > 120 ? '...' : '') : ''}
                                        </div>
                                    </td>
                                    <td>
                                        ${getCategoryName(news.category_id)}
                                    </td>
                                    <td>
                                        <span class="badge ${news.site_id == site_id ? 'badge-success' : 'badge-warning'}">Site ${news.site_id || 'N/A'}</span>
                                    </td>
                                    <td>
                                        <span class="badge ${news.is_inherited == '1' || news.is_inherited === true ? 'badge-success' : 'badge-warning'}">
                                            ${news.is_inherited == '1' || news.is_inherited === true ? 'Ya' : 'Tidak'}
                                        </span>
                                    </td>
                                    <td>
                                        ${(news.created_at || news.createdAt) ? new Date(news.created_at || news.createdAt).toLocaleDateString('id-ID') : 'N/A'}
                                    </td>
                                    <td class="action-buttons" style="white-space: nowrap;">
                                        ${news.site_id == site_id ? `
                                            <button class="btn-primary" style="padding: 8px 16px;" onclick="openEditModal(${news.id})">
                                                <i class="fas fa-edit"></i> Edit
                                            </button>
                                            <button class="btn-danger" onclick="deleteNews(${news.id})">
                                                <i class="fas fa-trash"></i> Hapus
                                            </button>
                                        ` : `
                                            <span class="badge badge-warning">Read Only</span>
                                        `}</td>
                                </tr>
                            `;
                        }).join('')}
                    </tbody>
                </table>`;

            container.innerHTML = tableHTML;

            // Attach search input handler (debounced)
            const searchInput = document.getElementById('newsSearchInput');
            if (searchInput && !searchInput._handlerAttached) {
                searchInput.addEventListener('input', function (e) {
                    clearTimeout(_newsSearchDebounce);
                    _newsSearchDebounce = setTimeout(() => {
                        currentNewsFilter = (e.target.value || '').trim();
                        renderNewsList();
                    }, 220);
                });
                searchInput._handlerAttached = true;
            }
        }

        // Get category name by ID
        function getCategoryName(categoryId) {
            // console.log('Looking for category ID:', categoryId, 'in categories:', categories);
            const category = categories.find(cat => cat.id == categoryId);
            const result = category ? category.name : `Unknown (ID: ${categoryId})`;
            // console.log('Category name result:', result);
            return result;
        }

        // Sort news by column (toggle asc/desc)
        function sortNews(key) {
            if (currentNewsSort.key === key) {
                currentNewsSort.dir = currentNewsSort.dir === 'asc' ? 'desc' : 'asc';
            } else {
                currentNewsSort.key = key;
                currentNewsSort.dir = 'asc';
            }
            renderNewsList();
        }

        // Toggle add news form
        function toggleAddForm() {
            const form = document.getElementById('addNewsForm');
            const isVisible = form.style.display !== 'none';

            console.log('=== TOGGLE ADD FORM ===');
            console.log('Form currently visible:', isVisible);

            if (isVisible) {
                console.log('Closing form...');
                form.style.display = 'none';
                return;
            }

            // Reset the form fields
            document.getElementById('newsForm').reset();

            // Show the form first
            form.style.display = 'block';

            // Get the category dropdown
            const categorySelect = document.getElementById('category_id');
            if (!categorySelect) {
                console.error('Category select element not found!');
                return;
            }

            console.log('Current categories in memory:', categories.length);

            // Force immediate direct update of the dropdown HTML
            categorySelect.innerHTML = '<option value="">Pilih Kategori</option>';

            if (categories.length > 0) {
                // We already have categories, just add them directly to the HTML
                categories.forEach(cat => {
                    categorySelect.innerHTML += `<option value="${cat.id}">${cat.name}</option>`;
                });
                console.log('Added categories directly to dropdown HTML:', categories.length);
            } else {
                // We need to fetch categories
                categorySelect.innerHTML = '<option value="">Loading categories...</option>';

                // Make a fresh API call using jQuery-style approach (more compatible)
                const xhr = new XMLHttpRequest();
                xhr.open('GET', '<?php echo e(config('services.auth_api.base_url')); ?>/api/admin/article-category', true);
                xhr.setRequestHeader('Authorization', `Bearer ${getAuthToken()}`);
                xhr.setRequestHeader('Accept', 'application/json');

                xhr.onload = function() {
                    if (xhr.status >= 200 && xhr.status < 300) {
                        const data = JSON.parse(xhr.responseText);
                        const fetchedCategories = Array.isArray(data) ? data : (data.data || data);

                        // Update global categories
                        categories = fetchedCategories;

                        // Update dropdown directly with HTML
                        categorySelect.innerHTML = '<option value="">Pilih Kategori</option>';
                        categories.forEach(cat => {
                            categorySelect.innerHTML += `<option value="${cat.id}">${cat.name}</option>`;
                        });

                        console.log('Fetched and added categories to dropdown:', categories.length);
                    } else {
                        console.error('Failed to load categories:', xhr.status);
                        categorySelect.innerHTML = '<option value="">Error loading categories</option>';
                        showAlert('Failed to load categories: ' + xhr.statusText, 'error');
                    }
                };

                xhr.onerror = function() {
                    console.error('Network error when loading categories');
                    categorySelect.innerHTML = '<option value="">Network error</option>';
                    showAlert('Network error when loading categories', 'error');
                };

                xhr.send();
            }
        }

        // Delete news
        async function deleteNews(articleId) {
            if (!confirm('Apakah Anda yakin ingin menghapus berita ini?')) {
                return;
            }

            try {
                const siteId = getAdminSiteId();
                if (!siteId) {
                    showAlert('Site ID admin tidak ditemukan. Silakan login ulang.', 'error');
                    return;
                }
                await apiCall(`api/admin/article/${articleId}`, 'DELETE', { site_id: siteId });
                showAlert('Berita berhasil dihapus!', 'success');
                loadNews();
            } catch (error) {
                console.error('Error deleting news:', error);
                showAlert('Error: ' + error.message, 'error');
            }
        }

        // Show toast notification
        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);
        }

        // Edit modal functions
        async function openEditModal(articleId) {
            try {
                const response = await apiCall(`api/admin/article/${articleId}`, 'GET');
                const article = response.data || response;

                console.log('Article to edit:', article);

                // Populate form fields
                document.getElementById('edit_article_id').value = article.id;
                document.getElementById('edit_title').value = article.title || '';
                document.getElementById('edit_body').value = article.body || '';
                document.getElementById('edit_category_id').value = article.category_id || '';
                document.getElementById('edit_is_inherited').value = article.is_inherited === true || article
                    .is_inherited === '1' ? '1' : '0';

                // Show current image if available
                const imageContainer = document.getElementById('current_image_container');
                const imagePreview = document.getElementById('current_image_preview');

                if (article.article) {
                    imageContainer.style.display = 'block';
                    imagePreview.innerHTML =
                        `<img src="${article.article}" style="max-width: 200px; max-height: 150px; border-radius: 4px;" alt="Current Image">`;
                } else {
                    imageContainer.style.display = 'none';
                }

                // Always fetch fresh categories for the dropdown
                const categorySelect = document.getElementById('edit_category_id');
                if (!categorySelect) {
                    console.error('Edit category select element not found!');
                    return;
                }

                // Show loading in the dropdown
                categorySelect.innerHTML = '<option value="">Loading categories...</option>';

                // Make API call using XHR for better compatibility
                const xhr = new XMLHttpRequest();
                xhr.open('GET', '<?php echo e(config('services.auth_api.base_url')); ?>/api/admin/article-category', true);
                xhr.setRequestHeader('Authorization', `Bearer ${getAuthToken()}`);
                xhr.setRequestHeader('Accept', 'application/json');

                xhr.onload = function() {
                    if (xhr.status >= 200 && xhr.status < 300) {
                        try {
                            const data = JSON.parse(xhr.responseText);
                            const fetchedCategories = Array.isArray(data) ? data : (data.data || data);

                            // Update global categories
                            categories = fetchedCategories;

                            console.log('Fresh categories loaded for edit form:', categories);

                            // Update dropdown directly with HTML for maximum compatibility
                            categorySelect.innerHTML = '<option value="">Pilih Kategori</option>';

                            // First add direct HTML
                            categories.forEach(cat => {
                                const selected = cat.id == article.category_id ? ' selected' : '';
                                categorySelect.innerHTML +=
                                    `<option value="${cat.id}"${selected}>${cat.name}</option>`;
                            });

                            console.log('Categories added to dropdown, selected category_id:', article.category_id);
                        } catch (error) {
                            console.error('Error processing categories:', error);
                            categorySelect.innerHTML = '<option value="">Error processing categories</option>';
                        }
                    } else {
                        console.error('Failed to load categories:', xhr.status);
                        categorySelect.innerHTML = '<option value="">Error loading categories</option>';
                    }
                };

                xhr.onerror = function() {
                    console.error('Network error when loading categories');
                    categorySelect.innerHTML = '<option value="">Network error</option>';
                };

                xhr.send();

                // Initialize character counter for edit form
                setupCharacterCounter('edit_body', 'editBodyCounter', 5000);

                // Display the modal
                document.getElementById('editNewsModal').style.display = 'block';

            } catch (error) {
                console.error('Error fetching article details:', error);
                showAlert('Error: ' + error.message, 'error');
            }
        }

        function closeEditModal() {
            document.getElementById('editNewsModal').style.display = 'none';
        }

        // Handle add form submission
        document.getElementById('newsForm').addEventListener('submit', async function(e) {
            e.preventDefault();

            try {
                // Get admin's site_id
                const adminSiteId = getAdminSiteId();
                if (!adminSiteId) {
                    showAlert('Site ID admin tidak ditemukan. Silakan login ulang.', 'error');
                    return;
                }

                // Validation
                const title = document.getElementById('title').value;
                const body = document.getElementById('body').value;

                if (title.length < 10 || title.length > 255) {
                    showAlert('Judul harus 10-255 karakter', 'error');
                    return;
                }

                if (body.length < 100 || body.length > 5000) {
                    showAlert('Isi berita harus 100-5000 karakter', 'error');
                    return;
                }

                const formData = new FormData();
                formData.append('title', title);
                formData.append('body', body);
                formData.append('category_id', document.getElementById('category_id').value);
                formData.append('site_id', adminSiteId); // Tambahkan site_id dari admin yang login
                formData.append('is_inherited', document.getElementById('is_inherited').value);

                // Add site_id from admin session
                const siteId = getAdminSiteId();
                if (!siteId) {
                    throw new Error('Site ID admin tidak ditemukan. Silakan login ulang.');
                }
                formData.append('site_id', siteId);

                // Add image file
                const imageFile = document.getElementById('article').files[0];
                if (imageFile) {
                    formData.append('article_image', imageFile);
                }

                await apiCall('api/admin/article/', 'POST', formData);

                showAlert('Berita berhasil ditambahkan!', 'success');
                toggleAddForm();
                loadNews();

            } catch (error) {
                console.error('Error adding news:', error);
                showAlert('Error: ' + error.message, 'error');
            }
        });

        // Handle edit form submission
        document.getElementById('editNewsForm').addEventListener('submit', async function(e) {
            e.preventDefault();

            try {
                // Get admin's site_id
                const adminSiteId = getAdminSiteId();
                if (!adminSiteId) {
                    showAlert('Site ID admin tidak ditemukan. Silakan login ulang.', 'error');
                    return;
                }

                // Validation
                const title = document.getElementById('edit_title').value;
                const body = document.getElementById('edit_body').value;
                const articleId = document.getElementById('edit_article_id').value;

                if (title.length < 10 || title.length > 255) {
                    showAlert('Judul harus 10-255 karakter', 'error');
                    return;
                }

                if (body.length < 100 || body.length > 5000) {
                    showAlert('Isi berita harus 100-5000 karakter', 'error');
                    return;
                }

                const formData = new FormData();
                formData.append('title', title);
                formData.append('body', body);
                formData.append('category_id', document.getElementById('edit_category_id').value);
                formData.append('is_inherited', document.getElementById('edit_is_inherited').value);

                // Add site_id from admin session
                const siteId = getAdminSiteId();
                if (!siteId) {
                    throw new Error('Site ID admin tidak ditemukan. Silakan login ulang.');
                }
                formData.append('site_id', siteId);

                // Add image file only if a new one was selected
                const imageFile = document.getElementById('edit_article').files[0];
                if (imageFile) {
                    formData.append('article_image', imageFile);
                }

                await apiCall(`api/admin/article/${articleId}`, 'PUT', formData);

                showAlert('Berita berhasil diperbarui!', 'success');
                closeEditModal();
                loadNews();

            } catch (error) {
                console.error('Error updating news:', error);
                showAlert('Error: ' + error.message, 'error');
            }
        });

        // Sidebar dropdown logic
        const kelolaAdminLink = document.getElementById('kelola-admin-link');
        if (kelolaAdminLink) {
            kelolaAdminLink.addEventListener('click', function(e) {
                e.preventDefault();
                var dropdown = document.getElementById('kelola-admin-dropdown');
                if (dropdown) {
                    dropdown.style.display = dropdown.style.display === 'block' ? 'none' : 'block';
                }
            });
        }

        // Function to populate category dropdown manually
        function populateCategoryDropdown() {
            console.log('=== POPULATE CATEGORY DROPDOWN ===');
            const categorySelect = document.getElementById('category_id');
            console.log('Found category select element:', categorySelect);

            if (!categorySelect) {
                console.log('Category select not found, form probably not visible. Retrying in 100ms...');
                setTimeout(populateCategoryDropdown, 100);
                return;
            }

            console.log('Categories available:', categories.length);
            console.log('Manually populating dropdown with categories:', categories);
            populateDropdown(categorySelect);
        }

        // Close modal when clicking outside
        window.onclick = function(event) {
            if (event.target === document.getElementById('editNewsModal')) {
                closeEditModal();
            }
        };

        // Initialize page
        // Tab Switching Logic
        function switchTab(tabName) {
            // Hide all tabs
            document.getElementById('articlesTab').style.display = 'none';
            document.getElementById('categoriesTab').style.display = 'none';

            // Remove active class from all tab buttons
            document.getElementById('articlesTabBtn').classList.remove('active');
            document.getElementById('categoriesTabBtn').classList.remove('active');

            // Show selected tab and activate button
            document.getElementById(`${tabName}Tab`).style.display = 'block';
            document.getElementById(`${tabName}TabBtn`).classList.add('active');

            // Load content based on tab
            if (tabName === 'categories' && document.getElementById('categoryListContainer').innerHTML.includes(
                    'loading')) {
                loadCategoriesData();
            }
        }

        // Reload categories and update all dropdowns
        async function reloadCategories() {
            try {
                const refreshBtn = document.getElementById('refreshCategoriesBtn');
                if (refreshBtn) {
                    refreshBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Memuat...';
                    refreshBtn.disabled = true;
                }

                console.log('Reloading categories...');

                // Make a fresh API call to get categories
                const response = await fetch('<?php echo e(config('services.auth_api.base_url')); ?>/api/admin/article-category', {
                    headers: {
                        'Authorization': `Bearer ${getAuthToken()}`,
                        'Accept': 'application/json'
                    }
                });

                if (response.status === 401) {
                    if (window.handleSessionExpired) window.handleSessionExpired();
                    return;
                }

                if (!response.ok) {
                    throw new Error(`HTTP Error: ${response.status}`);
                }

                const data = await response.json();
                console.log('Categories reloaded successfully:', data);

                // Update the global categories array
                categories = Array.isArray(data) ? data : (data.data || data);

                // Update all category dropdowns
                populateAllCategoryDropdowns();

                showAlert('Kategori berhasil dimuat ulang!', 'success');

                // Log the categories for debugging
                console.log('Available categories after reload:');
                categories.forEach(cat => {
                    console.log(`- ${cat.name} (ID: ${cat.id})`);
                });

                if (refreshBtn) {
                    refreshBtn.innerHTML = '<i class="fas fa-sync-alt"></i> Refresh Kategori';
                    refreshBtn.disabled = false;
                }
            } catch (error) {
                console.error('Error reloading categories:', error);
                showAlert('Gagal memuat ulang kategori: ' + error.message, 'error');

                const refreshBtn = document.getElementById('refreshCategoriesBtn');
                if (refreshBtn) {
                    refreshBtn.innerHTML = '<i class="fas fa-sync-alt"></i> Refresh Kategori';
                    refreshBtn.disabled = false;
                }
            }
        }

        // Category Management Functions
        function openAddCategoryModal() {
            // Reset form
            document.getElementById('categoryForm').reset();
            document.getElementById('category_id').value = '';
            document.getElementById('categoryModalTitle').textContent = 'Tambah Kategori Baru';

            // Initialize character counter
            setupCharacterCounter('category_description', 'categoryDescCounter', 500);

            // Show modal
            document.getElementById('categoryFormModal').style.display = 'block';
        }

        function openEditCategoryModal(categoryId) {
            const category = categories.find(c => c.id == categoryId);
            if (!category) return;

            document.getElementById('categoryModalTitle').textContent = 'Edit Kategori';
            document.getElementById('category_id').value = category.id;
            document.getElementById('category_name').value = category.name || '';
            document.getElementById('category_description').value = category.description || '';

            // Initialize character counter
            setupCharacterCounter('category_description', 'categoryDescCounter', 500);

            // Show modal
            document.getElementById('categoryFormModal').style.display = 'block';
        }

        function closeCategoryModal() {
            document.getElementById('categoryFormModal').style.display = 'none';
        }

        async function loadCategoriesData() {
            try {
                await loadCategories(); // This reuses our existing function to fetch categories
                renderCategoriesList();
            } catch (error) {
                console.error('Error loading categories data:', error);
                document.getElementById('categoryListContainer').innerHTML =
                    `<div class="loading" style="color: #dc2626;">
                        <i class="fas fa-exclamation-triangle"></i> Error: ${error.message}
                    </div>`;
            }
        }

        function renderCategoriesList() {
            const container = document.getElementById('categoryListContainer');

            if (!categories || categories.length === 0) {
                container.innerHTML = `
                    <div class="loading">
                        <i class="fas fa-info-circle"></i> Belum ada kategori yang tersedia.
                    </div>`;
                return;
            }

            const tableHTML = `
                <table class="news-table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Nama Kategori</th>
                            <th>Deskripsi</th>
                            <th>Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
                        ${categories.map(category => `
                                                <tr>
                                                    <td>${category.id}</td>
                                                    <td><strong>${category.name}</strong></td>
                                                    <td>${category.description || '-'}</td>
                                                    <td style="display: flex; gap: 8px;">
                                                        <button class="btn-primary" style="padding: 8px 16px;" onclick="openEditCategoryModal(${category.id})">
                                                            <i class="fas fa-edit"></i> Edit
                                                        </button>
                                                        <button class="btn-danger" onclick="deleteCategory(${category.id})">
                                                            <i class="fas fa-trash"></i>
                                                        </button>
                                                    </td>
                                                </tr>
                                            `).join('')}
                    </tbody>
                </table>`;

            container.innerHTML = tableHTML;
        }

        async function deleteCategory(categoryId) {
            if (!confirm(
                    'Apakah Anda yakin ingin menghapus kategori ini? Artikel yang menggunakan kategori ini mungkin akan terdampak.'
                )) {
                return;
            }

            try {
                await apiCall(`api/admin/article-category/${categoryId}`, 'DELETE');
                showAlert('Kategori berhasil dihapus!', 'success');
                loadCategoriesData(); // Refresh the category list
            } catch (error) {
                console.error('Error deleting category:', error);
                showAlert('Error: ' + error.message, 'error');
            }
        }

        // Handle category form submission
        document.getElementById('categoryForm').addEventListener('submit', async function(e) {
            e.preventDefault();

            try {
                const categoryId = document.getElementById('category_id').value;
                const isEdit = categoryId !== '';

                const data = {
                    name: document.getElementById('category_name').value,
                    description: document.getElementById('category_description').value
                };

                if (isEdit) {
                    await apiCall(`api/admin/article-category/${categoryId}`, 'PUT', data);
                    showAlert('Kategori berhasil diperbarui!', 'success');
                } else {
                    await apiCall('api/admin/article-category', 'POST', data);
                    showAlert('Kategori berhasil ditambahkan!', 'success');
                }

                closeCategoryModal();
                loadCategoriesData(); // Refresh the category list
                loadCategories(); // Refresh categories for dropdowns

            } catch (error) {
                console.error('Error saving category:', error);
                showAlert('Error: ' + error.message, 'error');
            }
        });

        // Close category modal when clicking outside
        window.addEventListener('click', function(event) {
            if (event.target === document.getElementById('categoryFormModal')) {
                closeCategoryModal();
            }
        });

        // Function to ensure categories are loaded when clicking on a dropdown
        function ensureCategoriesLoaded(selectElement) {
            // Check if the dropdown already has categories (more than just the default option)
            if (selectElement.options.length <= 1) {
                console.log('Category dropdown clicked but empty, populating now...');

                // If we already have categories in memory, use them
                if (categories.length > 0) {
                    console.log('Using in-memory categories to populate dropdown');

                    // Clear existing options except the first one
                    while (selectElement.options.length > 1) {
                        selectElement.remove(1);
                    }

                    // Add each category as an option
                    categories.forEach(category => {
                        const option = document.createElement('option');
                        option.value = category.id;
                        option.textContent = category.name;
                        selectElement.appendChild(option);
                        console.log(`Added option: ${category.name} (ID: ${category.id})`);
                    });

                    console.log('Dropdown populated with', categories.length, 'categories');
                } else {
                    // We don't have categories in memory, need to load them
                    console.log('No categories in memory, fetching from API...');
                    selectElement.innerHTML = '<option value="">Loading...</option>';

                    // Fetch categories from API
                    fetch('<?php echo e(config('services.auth_api.base_url')); ?>/api/admin/article-category', {
                            headers: {
                                'Authorization': `Bearer ${getAuthToken()}`,
                                'Accept': 'application/json'
                            }
                        })
                        .then(response => {
                            if (!response.ok) throw new Error('Failed to fetch categories');
                            return response.json();
                        })
                        .then(data => {
                            // Process the data and update the global categories array
                            let fetchedCategories = Array.isArray(data) ? data : (data.data || data);
                            categories = fetchedCategories;

                            // Clear the dropdown
                            selectElement.innerHTML = '<option value="">Pilih Kategori</option>';

                            // Add each category to the dropdown
                            categories.forEach(category => {
                                if (category && category.id && category.name) {
                                    const option = document.createElement('option');
                                    option.value = category.id;
                                    option.textContent = category.name;
                                    selectElement.appendChild(option);
                                    console.log(
                                        `Added category to dropdown: ${category.name} (ID: ${category.id})`);
                                }
                            });

                            console.log('Dropdown populated with', categories.length, 'categories');
                        })
                        .catch(error => {
                            console.error('Error fetching categories:', error);
                            selectElement.innerHTML = '<option value="">Error loading categories</option>';
                        });
                }
            } else {
                console.log('Category dropdown already has options:', selectElement.options.length - 1);
            }
        }

        // Function to load categories and then toggle the form
        async function loadCategoriesAndToggleForm() {
            try {
                const addButton = document.querySelector('.btn-primary[onclick="loadCategoriesAndToggleForm()"]');
                if (addButton) {
                    addButton.disabled = true;
                    addButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Memuat...';
                }

                console.log('Loading categories before opening form...');

                // Make a fresh API call to get categories
                const response = await fetch('<?php echo e(config('services.auth_api.base_url')); ?>/api/admin/article-category', {
                    headers: {
                        'Authorization': `Bearer ${getAuthToken()}`,
                        'Accept': 'application/json'
                    }
                });

                if (response.status === 401) {
                    if (window.handleSessionExpired) window.handleSessionExpired();
                    return;
                }

                if (!response.ok) {
                    throw new Error(`HTTP Error: ${response.status}`);
                }

                const data = await response.json();
                console.log('Categories loaded successfully:', data);

                // Update the global categories array
                categories = Array.isArray(data) ? data : (data.data || data);

                // Now that we have categories, open the form
                toggleAddForm();

                if (addButton) {
                    addButton.disabled = false;
                    addButton.innerHTML = '<i class="fas fa-plus"></i> Tambah Berita';
                }
            } catch (error) {
                console.error('Error loading categories:', error);
                showAlert('Gagal memuat kategori: ' + error.message, 'error');

                const addButton = document.querySelector('.btn-primary[onclick="loadCategoriesAndToggleForm()"]');
                if (addButton) {
                    addButton.disabled = false;
                    addButton.innerHTML = '<i class="fas fa-plus"></i> Tambah Berita';
                }
            }
        }

        // Direct update function for category dropdowns - to be called after any API success
        function updateCategoryDropdowns(categoriesData) {
            const dropdowns = [
                document.getElementById('category_id'),
                document.getElementById('edit_category_id')
            ];

            // Store the updated categories
            categories = categoriesData;

            // Update all dropdowns that exist
            dropdowns.forEach(dropdown => {
                if (dropdown) {
                    // Clear existing options except the first "Select Category" option
                    dropdown.innerHTML = '<option value="">Pilih Kategori</option>';

                    // Add the categories
                    categoriesData.forEach(category => {
                        const option = document.createElement('option');
                        option.value = category.id;
                        option.textContent = category.name;
                        dropdown.appendChild(option);
                    });

                    console.log(`Updated dropdown ${dropdown.id} with ${categoriesData.length} categories`);
                }
            });
        }

        // Prevent nice-select initialization on category dropdowns
        function preventNiceSelect() {
            // Remove nice-select if already initialized
            const categoryDropdowns = ['category_id', 'edit_category_id'];
            categoryDropdowns.forEach(id => {
                const select = document.getElementById(id);
                if (select) {
                    const niceSelectContainer = select.nextElementSibling;
                    if (niceSelectContainer && niceSelectContainer.classList.contains('nice-select')) {
                        niceSelectContainer.remove();
                    }
                    // Remove nice-select class if present
                    select.classList.remove('nice-select');
                    // Make sure the original select is visible and styled
                    select.style.display = 'block';
                    select.style.opacity = '1';
                    select.style.visibility = 'visible';
                }
            });

            // Override jQuery nice-select initialization for category dropdowns
            if (window.jQuery) {
                const originalNiceSelect = $.fn.niceSelect;
                $.fn.niceSelect = function() {
                    if (this.is('#category_id, #edit_category_id')) {
                        return this; // Skip nice-select for category dropdowns
                    }
                    return originalNiceSelect.apply(this, arguments);
                };
            }
        }

        document.addEventListener('DOMContentLoaded', function() {
            adminSiteId = getAdminSiteId();
            console.log('Admin Site ID:', adminSiteId);

            // Call preventNiceSelect after a short delay to ensure nice-select is loaded
            setTimeout(preventNiceSelect, 100);

            // Setup character counter for body field
            setupCharacterCounter('body', 'bodyCounter', 5000);

            // Get the category select elements
            const mainCategorySelect = document.getElementById('category_id');
            const editCategorySelect = document.getElementById('edit_category_id');

            // Initialize with loading message
            if (mainCategorySelect) mainCategorySelect.innerHTML =
                '<option value="">Loading categories...</option>';
            if (editCategorySelect) editCategorySelect.innerHTML =
                '<option value="">Loading categories...</option>';

            console.log('Initializing page and loading categories...');

            // Make API call using XHR for better compatibility
            const xhr = new XMLHttpRequest();
            xhr.open('GET', '<?php echo e(config('services.auth_api.base_url')); ?>/api/admin/article-category', true);
            xhr.setRequestHeader('Authorization', `Bearer ${getAuthToken()}`);
            xhr.setRequestHeader('Accept', 'application/json');

            xhr.onload = function() {
                if (xhr.status >= 200 && xhr.status < 300) {
                    try {
                        const data = JSON.parse(xhr.responseText);
                        const fetchedCategories = Array.isArray(data) ? data : (data.data || data);

                        if (fetchedCategories && fetchedCategories.length > 0) {
                            // Update global categories variable
                            categories = fetchedCategories;

                            console.log('Categories loaded successfully:', categories.length);
                            console.log('Available categories:');
                            categories.forEach(cat => {
                                console.log(`- ${cat.name} (ID: ${cat.id})`);
                            });

                            // Update the dropdown HTML directly for maximum compatibility
                            if (mainCategorySelect) {
                                mainCategorySelect.innerHTML = '<option value="">Pilih Kategori</option>';
                                categories.forEach(cat => {
                                    mainCategorySelect.innerHTML +=
                                        `<option value="${cat.id}">${cat.name}</option>`;
                                });
                                console.log('Main category dropdown populated with', categories.length,
                                    'items');
                            }

                            if (editCategorySelect) {
                                editCategorySelect.innerHTML = '<option value="">Pilih Kategori</option>';
                                categories.forEach(cat => {
                                    editCategorySelect.innerHTML +=
                                        `<option value="${cat.id}">${cat.name}</option>`;
                                });
                                console.log('Edit category dropdown populated with', categories.length,
                                    'items');
                            }

                            // Add onclick handlers to ensure dropdowns work
                            if (mainCategorySelect) {
                                mainCategorySelect.onclick = function() {
                                    console.log('Main category dropdown clicked, verifying options');
                                    if (mainCategorySelect.options.length <= 1) {
                                        console.log('Repopulating main dropdown...');
                                        mainCategorySelect.innerHTML =
                                            '<option value="">Pilih Kategori</option>';
                                        categories.forEach(cat => {
                                            mainCategorySelect.innerHTML +=
                                                `<option value="${cat.id}">${cat.name}</option>`;
                                        });
                                    }
                                };
                            }

                            if (editCategorySelect) {
                                editCategorySelect.onclick = function() {
                                    console.log('Edit category dropdown clicked, verifying options');
                                    if (editCategorySelect.options.length <= 1) {
                                        console.log('Repopulating edit dropdown...');
                                        editCategorySelect.innerHTML =
                                            '<option value="">Pilih Kategori</option>';
                                        categories.forEach(cat => {
                                            editCategorySelect.innerHTML +=
                                                `<option value="${cat.id}">${cat.name}</option>`;
                                        });
                                    }
                                };
                            }
                        } else {
                            console.warn('No categories found in API response');
                            if (mainCategorySelect) mainCategorySelect.innerHTML =
                                '<option value="">No categories available</option>';
                            if (editCategorySelect) editCategorySelect.innerHTML =
                                '<option value="">No categories available</option>';
                        }
                    } catch (error) {
                        console.error('Error processing categories:', error);
                        if (mainCategorySelect) mainCategorySelect.innerHTML =
                            '<option value="">Error processing categories</option>';
                        if (editCategorySelect) editCategorySelect.innerHTML =
                            '<option value="">Error processing categories</option>';
                    }
                } else {
                    console.error('Failed to load categories:', xhr.status);
                    if (mainCategorySelect) mainCategorySelect.innerHTML =
                        '<option value="">Error loading categories</option>';
                    if (editCategorySelect) editCategorySelect.innerHTML =
                        '<option value="">Error loading categories</option>';
                }
            };

            xhr.onerror = function() {
                console.error('Network error when loading categories');
                if (mainCategorySelect) mainCategorySelect.innerHTML =
                    '<option value="">Network error</option>';
                if (editCategorySelect) editCategorySelect.innerHTML =
                    '<option value="">Network error</option>';
            };

            xhr.send();

            // Load news
            loadNews();

            // Initialize tabs
            switchTab('articles');
        });
    </script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.layoutadmin', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH D:\laravel\krs-jawa3-template\daerah\resources\views/admin/beritaAdmin.blade.php ENDPATH**/ ?>