
// Refactored app.js with Event Delegation and AJAX
document.addEventListener('DOMContentLoaded', function () {
    const pdfModalEl = document.getElementById('panggilanPdfModal');
    let pdfModal, pdfFrame, pdfFallback, pdfLoader, pdfError, pdfErrorBtn;

    // Initialize PDF references if modal exists
    if (pdfModalEl) {
        pdfModal = new bootstrap.Modal(pdfModalEl);
        pdfFrame = document.getElementById('panggilanPdfFrame');
        pdfFallback = document.getElementById('panggilanPdfFallback');
        pdfLoader = document.getElementById('pdfLoader');
        pdfError = document.getElementById('pdfError');
        pdfErrorBtn = document.getElementById('pdfErrorBtn');

        // Cleanup on close
        pdfModalEl.addEventListener('hidden.bs.modal', function () {
            pdfFrame.src = '';
            pdfLoader.classList.add('d-none');
            pdfError.classList.add('d-none');
        });
    }

    // Event Delegation for PDF Buttons (Handles dynamic content)
    document.addEventListener('click', function (e) {
        const btn = e.target.closest('.btn-view-file');

        if (btn && pdfModalEl) {
            e.preventDefault();
            const previewUrl = btn.getAttribute('data-preview-url');
            const originalUrl = btn.getAttribute('data-original-url');

            // UI Reset
            pdfFrame.src = 'about:blank';
            pdfFrame.classList.add('d-none');
            pdfLoader.classList.remove('d-none');
            pdfError.classList.add('d-none');

            // Fallback links
            pdfFallback.href = originalUrl;
            pdfErrorBtn.href = originalUrl;

            // Load iframe
            pdfFrame.onload = function () {
                pdfLoader.classList.add('d-none');
                pdfFrame.classList.remove('d-none');
            };

            pdfFrame.onerror = function () {
                showErrorState();
            };

            // Timeout fallback
            setTimeout(() => {
                if (!pdfLoader.classList.contains('d-none')) {
                    console.warn('PDF Load Timeout');
                }
            }, 10000);

            pdfFrame.src = previewUrl;
            pdfModal.show();
        }
    });

    function showErrorState() {
        pdfLoader.classList.add('d-none');
        pdfFrame.classList.add('d-none');
        pdfError.classList.remove('d-none');
    }

    // AJAX Year Switching
    const yearLinks = document.querySelectorAll('.panggilan-year-link');
    const contentContainer = document.getElementById('panggilanAccordion');
    // Primary selector for title
    const titleContainer = document.querySelector('.page-header h2');

    if (yearLinks.length > 0 && contentContainer) {
        yearLinks.forEach(link => {
            link.addEventListener('click', function (e) {
                e.preventDefault();
                const url = this.href;

                // Active State Update
                yearLinks.forEach(l => l.classList.remove('active'));
                this.classList.add('active');

                // UI Loading State
                contentContainer.style.opacity = '0.5';
                contentContainer.style.pointerEvents = 'none';

                fetch(url)
                    .then(response => response.text())
                    .then(html => {
                        const parser = new DOMParser();
                        const doc = parser.parseFromString(html, 'text/html');

                        const newContent = doc.getElementById('panggilanAccordion');
                        // Try both selectors for title
                        const newTitle = doc.querySelector('.page-header h2') || doc.getElementById('panggilan-title');

                        if (newContent) {
                            contentContainer.innerHTML = newContent.innerHTML;
                        }

                        // Update ID-based title if it exists, otherwise class-based
                        const safeTitleContainer = document.getElementById('panggilan-title') || titleContainer;
                        if (newTitle && safeTitleContainer) {
                            safeTitleContainer.innerHTML = newTitle.innerHTML;
                        }

                        // Update URL
                        window.history.pushState({}, '', url);

                        // Reset UI State
                        contentContainer.style.opacity = '1';
                        contentContainer.style.pointerEvents = 'auto';
                    })
                    .catch(error => {
                        console.error('Error loading year:', error);
                        // Fallback: reload page
                        window.location.href = url;
                    });
            });
        });
    }
});
