// ── Initialization & Event Listeners ────────────────────────────────
document.addEventListener('DOMContentLoaded', async () => {
    // Preload settings
    try {
        const res = await fetch(`${baseUrl}/project/${projectSlug}/security/settings`);
        const data = await res.json();
        if (data.success) window.securitySettings = data.settings;
    } catch (e) { console.error(e); }
    updateSecurityChrome();

    // Use event delegation on the sidebar container (handles dynamically loaded accordion content)
    document.getElementById('securityAccordion')?.addEventListener('click', (e) => {
        const link = e.target.closest('.nav-link');
        if (!link) return;
        e.preventDefault();
        const page = link.dataset.page;
        if (!page) return;
        // Update active state
        document.querySelectorAll('#securityAccordion .nav-link').forEach(l => l.classList.remove('active'));
        link.classList.add('active');
        loadSecurityPage(page);
        document.getElementById('securitySidebar')?.classList.remove('is-mobile-open');
        document.getElementById('btnToggleSecurityNav')?.setAttribute('aria-expanded', 'false');
    });

    const navSearch = document.getElementById('securityNavSearch');
    const navClear = document.getElementById('clearSecurityNavSearch');
    const navCount = document.getElementById('securityNavResultCount');
    const filterSecurityNav = () => {
        const term = (navSearch?.value || '').trim().toLowerCase();
        let visible = 0;
        document.querySelectorAll('#securityAccordion .nav-item').forEach(item => {
            const matches = !term || item.textContent.toLowerCase().includes(term);
            item.hidden = !matches;
            if (matches) visible += 1;
        });
        document.querySelectorAll('#securityAccordion .accordion-item').forEach(section => {
            const hasVisible = Boolean(section.querySelector('.nav-item:not([hidden])'));
            section.hidden = !hasVisible;
            if (term && hasVisible) section.querySelector('.accordion-collapse')?.classList.add('show');
        });
        if (navCount) navCount.textContent = `${visible} ${visible === 1 ? 'setting' : 'settings'}`;
        navClear?.classList.toggle('is-visible', Boolean(term));
    };
    navSearch?.addEventListener('input', filterSecurityNav);
    navClear?.addEventListener('click', () => {
        navSearch.value = '';
        filterSecurityNav();
        navSearch.focus();
    });

    document.getElementById('btnToggleSecurityNav')?.addEventListener('click', function () {
        const sidebar = document.getElementById('securitySidebar');
        const expanded = !sidebar?.classList.contains('is-mobile-open');
        sidebar?.classList.toggle('is-mobile-open', expanded);
        this.setAttribute('aria-expanded', String(expanded));
    });

    // Load default page (Database Settings)
    loadSecurityPage('settings-database');
    document.querySelector('#securityAccordion .nav-link[data-page="settings-database"]')?.classList.add('active');

    // Central Save button – triggers auto‑save and dispatches projectSave event
    document.getElementById('btnSaveSecurity')?.addEventListener('click', () => {
        // Dispatch projectSave event for the global collector (if any module is listening)
        const event = new CustomEvent('projectSave', {
            detail: { module: 'security' }
        });
        document.dispatchEvent(event);
        // Perform immediate save of the current page
        if (typeof saveCurrentSecurityPage === 'function') saveCurrentSecurityPage();
        pp.dialog.toast('success', 'Security settings saved.');
    });
});
