// ── Auto‑Save & Central Save for Security Module ─────────────────────
let securityAutoSaveTimer = null;
let securityAutoSavePage = null;

function securityAutoSave() {
    if (window.isPageUnloading) return;
    if (securityAutoSaveTimer) clearTimeout(securityAutoSaveTimer);
    // Remember which page armed the timer. Without this, editing page A and
    // navigating to page B within the delay makes the timer save PAGE B from
    // page B's freshly-rendered DOM — which is how a settings page could
    // silently overwrite itself with its own defaults.
    securityAutoSavePage = window.currentSecurityPage;
    securityAutoSaveTimer = setTimeout(() => {
        if (window.currentSecurityPage !== securityAutoSavePage) return;
        saveCurrentSecurityPage();
    }, 600);
}

function saveCurrentSecurityPage() {
    if (window.isPageUnloading) return;
    const page = window.currentSecurityPage;
    if (!page) return;

    // Map page to its save function
    const saveMap = {
        'settings-database': () => {
            const btn = document.getElementById('btnSaveSettings');
            if (btn) btn.click();
        },
        'settings-registration': () => {
            const btn = document.getElementById('btnSaveRegSettings');
            if (btn) btn.click();
        },
        'settings-login': () => {
            const btn = document.getElementById('btnSaveLoginAppearance');
            if (btn) btn.click();
        },
        'settings-social': () => {
            document.getElementById('btnSaveSocialAuth')?.click();
        },
        'twofactor': () => {
            if (typeof saveAllSettings === 'function') saveAllSettings();
        },
        'permissions': () => {
            // Save both table and page permissions
            const tableBtn = document.getElementById('saveTablePerms');
            const pageBtn = document.getElementById('savePagePerms');
            if (tableBtn) tableBtn.click();
            if (pageBtn) pageBtn.click();
        },
        'session': () => {
            const btn = document.getElementById('saveAllSessionSettings');
            if (btn) btn.click();
        },
        'advanced': () => {
            document.getElementById('saveRlsRules')?.click();
        },
        'encryption': () => {
            document.getElementById('saveEncryptionSettings')?.click();
        },
        // Other pages (users, groups, audit, locks) have manual save only
    };
    if (saveMap[page]) saveMap[page]();
}

// Attach auto‑save listeners to all input/select/checkbox inside a container
function attachAutoSaveListeners(container) {
    if (!container) return;
    const elements = container.querySelectorAll('input, select, textarea');
    elements.forEach(el => {
        // Remove previous listener to avoid duplicates
        el.removeEventListener('change', securityAutoSave);
        el.removeEventListener('input', securityAutoSave);
        // Add event (change for most, input for text fields)
        el.addEventListener('change', securityAutoSave);
        if (el.tagName === 'INPUT' && (el.type === 'text' || el.type === 'password' || el.type === 'email' || el.type === 'number')) {
            el.addEventListener('input', securityAutoSave);
        }
    });
}

// ── Unload beacon ───────────────────────────────────────────────────────────
// Pages OPT IN by registering a provider; nothing is sent otherwise.
//
// This used to rebuild each page's payload by reading hard-coded element ids
// (allowRegistration, passwordMinLength, …). When a page was redesigned those
// ids disappeared, every getter returned null, and the beacon quietly saved
// "everything off, min_length 6" on the way out — silently wiping the user's
// settings just because they navigated away. A payload must come from the page
// that owns it, or not at all.
const securityBeaconProviders = {};

/**
 * @param {string} page   the securityPage id, e.g. 'settings-registration'
 * @param {() => ({endpoint: string, settings: object}|null)} provider
 *        Return null to send nothing (e.g. when there are no unsaved edits).
 */
function registerSecurityBeacon(page, provider) {
    securityBeaconProviders[page] = provider;
}

function securitySendBeacon() {
    const page = window.currentSecurityPage;
    const provider = page && securityBeaconProviders[page];
    if (typeof provider !== 'function') return;
    let payload = null;
    try { payload = provider(); } catch (e) { return; }
    if (!payload || !payload.endpoint || !payload.settings) return;
    navigator.sendBeacon(
        `${baseUrl}/project/${projectSlug}/security/${payload.endpoint}`,
        JSON.stringify({ settings: payload.settings })
    );
}

window.addEventListener('pagehide', () => {
    window.isPageUnloading = true;
    securitySendBeacon();
});
window.addEventListener('beforeunload', () => {
    window.isPageUnloading = true;
    securitySendBeacon();
});

// Expose auto‑save trigger to other scripts
window.securityAutoSave = securityAutoSave;
window.attachAutoSaveListeners = attachAutoSaveListeners;

// ── Central Save Button (toolbar) ─────────────────────────────────────
// Delegates to the current page's own Save button (saveCurrentSecurityPage),
// so it can never build a stale payload out of element ids that have moved.
document.addEventListener('projectSave', (e) => {
    if (e.detail.module !== 'security') return;
    saveCurrentSecurityPage();
});


window.registerSecurityBeacon = registerSecurityBeacon;
