document.addEventListener("DOMContentLoaded", async function () {
    const navbarPlaceholder = document.getElementById("navbar-placeholder");
    if (navbarPlaceholder) {
        let data = await fetch("navbar.html")
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! Status: ${response.status} while fetching navbar.html`);
                }
                return response.text();
            })
        navbarPlaceholder.innerHTML = data;

        // Determine which navigation link to highlight
        let actualPageName = window.location.pathname.split("/").pop() || "index.html";
        let pageToHighlight = actualPageName;

        // Mappings from detail pages to their main navigation item's filename
        const pageGroupMappings = {
            // About section
            "about-us-detail.html": "about.html",
            "our-team.html": "about.html",
            "our-philosophy.html": "about.html",
            "a-to-z.html": "about.html",
            // Services section
            "consultation-info.html": "services.html",
            "detox-program.html": "services.html",
            "beyond74-program.html": "services.html",
            "health-awareness-course.html": "services.html",
            "introduction-talks.html": "services.html",
            "1yr-training-course.html": "services.html",
            "dhanwantari-yog-training.html": "services.html",
            // Resources section
            "all-video-resources.html": "resources.html",
            "all-audio-resources.html": "resources.html",
            // Testimonials section
            "all-written-testimonials.html": "testimonials.html",
            "all-video-testimonials.html": "testimonials.html"
        };

        if (pageGroupMappings[actualPageName]) {
            pageToHighlight = pageGroupMappings[actualPageName];
        }

        actualPageName = actualPageName.replace(/\.html/, '');
        pageToHighlight = pageToHighlight.replace(/\.html/, '');

        let moreLinks = await fetch('/api/nav-items.json').then(response => response.json());
        moreLinks.items.forEach(link => {
            const linkItem = document.createElement('li');
            linkItem.classList.add('nav-item');
            let el = document.createElement('a');
            el.href = `${link.name}.html`;
            el.classList.add('nav-link');
            el.textContent = link.text;
            el.classList.add('nav-item');
            linkItem.appendChild(el);
            navbarPlaceholder.querySelector('.navbar-links').appendChild(linkItem);
        });

        try {
            let verify = await fetch('/api/admin/verify').then(response => response.json());
            if (verify.isAdmin) {
                const adminLink = document.createElement('li');
                adminLink.classList.add('nav-item');
                adminLink.innerHTML = `<a class="nav-link" href="/new-page.html">New Page</a>`;
                navbarPlaceholder.querySelector('.navbar-links').appendChild(adminLink);

                // Backup Button
                const backupListItem = document.createElement('li');
                backupListItem.classList.add('nav-item');
                backupListItem.innerHTML = `<a class="nav-link" href="#">Backup</a>`;
                backupListItem.querySelector('a').addEventListener('click', async (e) => {
                    e.preventDefault();
                    const link = e.target;
                    if (link.dataset.loading === 'true') return;

                    const confirmMsg = "Are you sure? This will backup:\n- content/ (Site Text & Structure)\n- public/photos/ (All Images)\n- public/audio/ (All Audio)\n- consent_audit.log (DPDP Consent Logs)\n\nThis may take a minute for large files.";
                    if (!confirm(confirmMsg)) return;

                    const originalText = link.textContent;
                    link.innerHTML = 'Download in process... <span class="nav-spinner"></span>';
                    link.dataset.loading = 'true';
                    link.style.opacity = '0.5';
                    link.style.cursor = 'not-allowed';

                    try {
                        const response = await fetch('/api/admin/download-content');
                        if (response.ok) {
                            const blob = await response.blob();
                            const url = window.URL.createObjectURL(blob);
                            const a = document.createElement('a');
                            a.href = url;
                            const now = new Date();
                            const timestamp = `${String(now.getDate()).padStart(2, '0')}-${String(now.getMonth() + 1).padStart(2, '0')}-${now.getFullYear()}`;
                            a.download = `sfwebsite_backup_${timestamp}.zip`;
                            document.body.appendChild(a);
                            a.click();
                            a.remove();
                            window.URL.revokeObjectURL(url);
                            alert('Content backup downloaded successfully!');
                        } else {
                            alert('Failed to download backup.');
                        }
                    } catch (error) {
                        console.error('Backup error:', error);
                        alert('Error downloading backup.');
                    } finally {
                        link.innerHTML = originalText;
                        delete link.dataset.loading;
                        link.style.opacity = '1';
                        link.style.cursor = 'pointer';
                    }
                });
                navbarPlaceholder.querySelector('.navbar-links').appendChild(backupListItem);

                // Logout Button
                const logoutListItem = document.createElement('li');
                logoutListItem.innerHTML = `<a href="#">Logout</a>`;
                logoutListItem.querySelector('a').addEventListener('click', async (event) => {
                    event.preventDefault();
                    try {
                        await fetch('/api/admin/logout', { method: 'POST' });
                    } catch (err) {
                        console.error('Logout error:', err);
                    }
                    window.location.href = '/admin-login.html';
                });
                navbarPlaceholder.querySelector('.navbar-links').appendChild(logoutListItem);
            }
        } catch (error) {
            console.error('Navbar admin verification failed:', error);
        }

        const navLinks = navbarPlaceholder.querySelectorAll(".navbar-links a");
        navLinks.forEach(link => {
            let linkPage = link.getAttribute("href").split("/").pop();
            linkPage = linkPage.replace(/\.html/, '');
            if (linkPage === pageToHighlight) {
                link.parentElement.classList.add("active");
            }
        });

    } else {
        console.error('Error: The div with id="navbar-placeholder" was not found in the HTML document.');
    }
});