// ── Core State & Helpers ──────────────────────────────────────────────
window.currentSecurityPage = 'settings-database';
window.securitySettings = null;
window.securityData = { users: [], groups: [] };
window.isPageUnloading = false;

const securityPageMeta = {
    'settings-database': { label: 'Settings / Database', title: 'Authentication database', description: 'Connect user accounts and identity fields to your project data.', icon: 'database-check' },
    'settings-login': { label: 'Settings / Login', title: 'Login security', description: 'Brute-force lockout, abuse throttles and disclosure rules for the sign-in flow. Appearance lives in the Designer.', icon: 'shield-lock' },
    'settings-registration': { label: 'Settings / Registration', title: 'Registration & passwords', description: 'Control account creation, password policy, recovery, and notifications.', icon: 'person-plus' },
    'settings-emails': { label: 'Settings / Email Templates', title: 'Account emails', description: 'The messages your app sends for sign-up, approval and password recovery.', icon: 'envelope-paper' },
    'settings-social': { label: 'Settings / Social Login', title: 'Social login providers', description: 'Google, Microsoft, Apple, Facebook, GitHub and LinkedIn sign-in for the generated Login and Register pages.', icon: 'person-badge' },
    users: { label: 'Users & Groups / Users', title: 'User accounts', description: 'Review, create, update, and organize application users.', icon: 'people' },
    groups: { label: 'Users & Groups / Groups', title: 'Security groups', description: 'Create reusable roles that make access control easier to maintain.', icon: 'people-fill' },
    permissions: { label: 'Permissions / Access matrix', title: 'Table & page permissions', description: 'Grant the least access each group needs across records and pages.', icon: 'key' },
    twofactor: { label: 'Authentication / Two-factor', title: 'Two-factor authentication', description: 'Strengthen sign-in with authenticator, email, or SMS verification.', icon: 'shield-lock' },
    advanced: { label: 'Advanced / Row security', title: 'Row-level security', description: 'Limit which records each group can see or change using ownership rules.', icon: 'diagram-3' },
    encryption: { label: 'Advanced / Encryption', title: 'Field encryption', description: 'Protect sensitive values at rest while keeping project behavior explicit.', icon: 'lock' },
    audit: { label: 'Audit & Locking / Activity', title: 'Audit log', description: 'Trace security-sensitive activity with searchable operational history.', icon: 'journal-text' },
    locks: { label: 'Audit & Locking / Records', title: 'Record locks', description: 'Inspect and release locks that protect concurrent record editing.', icon: 'lock-fill' },
    session: { label: 'Session Control / Runtime', title: 'Sessions & single sign-on', description: 'Manage timeout policy, concurrent access, active sessions, and SSO.', icon: 'clock-history' }
};

function updateSecurityChrome(page = window.currentSecurityPage) {
    const meta = securityPageMeta[page] || securityPageMeta['settings-database'];
    const label = document.getElementById('selectedPageLabel');
    const title = document.getElementById('selectedPageTitle');
    const description = document.getElementById('selectedPageDescription');
    const icon = document.getElementById('selectedPageIcon');
    if (label) label.textContent = meta.label;
    if (title) title.textContent = meta.title;
    if (description) description.textContent = meta.description;
    if (icon) icon.innerHTML = `<i class="bi bi-${meta.icon}"></i>`;

    const auth = document.getElementById('securityAuthState');
    if (auth) {
        const enabled = Boolean(window.securitySettings?.db_auth_enabled);
        auth.classList.toggle('is-enabled', enabled);
        auth.innerHTML = `<i class="bi bi-circle-fill"></i> ${enabled ? 'Database auth enabled' : 'Built-in admin mode'}`;
    }
}

async function loadSecurityPage(page) {
    window.currentSecurityPage = page;
    updateSecurityChrome(page);
    const container = document.getElementById('securityPageContainer');
    container.innerHTML = '<div class="text-center py-5"><div class="spinner-border"></div></div>';

    // Check if page requires database authentication
    const authRequiredPages = ['settings-login', 'settings-registration', 'settings-emails', 'users', 'groups', 'permissions', 'twofactor', 'advanced', 'audit', 'locks', 'encryption', 'session'];
    if (authRequiredPages.includes(page) && (!window.securitySettings?.db_auth_enabled)) {
        container.innerHTML = '<div class="alert alert-warning">Database authentication is not enabled. Please enable it in the Settings tab first.</div>';
        return;
    }

    if (page === 'settings-database') await renderDatabaseSettings();
    else if (page === 'settings-login') await renderLoginFormSettings();
    else if (page === 'settings-registration') await renderRegistrationSettings();
    else if (page === 'settings-emails') await renderAuthEmailSettings();
    else if (page === 'settings-social') await renderSocialAuthSettings();
    else if (page === 'users') await renderUsers();
    else if (page === 'groups') await renderGroups();
    else if (page === 'permissions') await renderPermissions();
    else if (page === 'twofactor') await renderTwoFactor();
    else if (page === 'advanced') await renderAdvanced();
    else if (page === 'audit') await renderAudit();
    else if (page === 'locks') await renderLocks();
    else if (page === 'encryption') await renderEncryption();
    else if (page === 'session') await renderSession();
    else container.innerHTML = '<div class="alert alert-warning">Page coming soon</div>';
}

// Stub functions for future tabs
async function renderLoginFormSettings() {
    const container = document.getElementById('securityPageContainer');
    // Superseded by renderLoginFormSettings() in login-appearance.js.
    container.innerHTML = '';
}
async function renderRegistrationSettings() {
    // This will be replaced by the actual implementation from registration.js
    const container = document.getElementById('securityPageContainer');
    container.innerHTML = `<div class="card shadow-sm"><div class="card-header">Registration & Passwords</div><div class="card-body"><div class="alert alert-info">Settings will appear once you enable database authentication.</div></div></div>`;
}
async function renderTwoFactor() {
    const container = document.getElementById('securityPageContainer');
    container.innerHTML = `<div class="card shadow-sm"><div class="card-header">Two-Factor Authentication</div><div class="card-body"><div class="alert alert-info">Coming soon...</div></div></div>`;
}
async function renderAdvanced() {
    const container = document.getElementById('securityPageContainer');
    container.innerHTML = `<div class="card shadow-sm"><div class="card-header">Advanced Security (Row‑Level)</div><div class="card-body"><div class="alert alert-info">Coming soon...</div></div></div>`;
}
async function renderAudit() {
    const container = document.getElementById('securityPageContainer');
    container.innerHTML = `<div class="card shadow-sm"><div class="card-header">Audit Log</div><div class="card-body"><div class="alert alert-info">Coming soon...</div></div></div>`;
}
async function renderLocks() {
    const container = document.getElementById('securityPageContainer');
    container.innerHTML = `<div class="card shadow-sm"><div class="card-header">Record Locks</div><div class="card-body"><div class="alert alert-info">Coming soon...</div></div></div>`;
}
async function renderEncryption() {
    const container = document.getElementById('securityPageContainer');
    container.innerHTML = `<div class="card shadow-sm"><div class="card-header">Field Encryption</div><div class="card-body"><div class="alert alert-info">Coming soon...</div></div></div>`;
}
async function renderSession() {
    const container = document.getElementById('securityPageContainer');
    container.innerHTML = `<div class="card shadow-sm"><div class="card-header">Session Control</div><div class="card-body"><div class="alert alert-info">Coming soon...</div></div></div>`;
}

function escapeHtml(str) {
    if (!str) return '';
    return str.replace(/[&<>]/g, function (m) {
        if (m === '&') return '&amp;';
        if (m === '<') return '&lt;';
        if (m === '>') return '&gt;';
        return m;
    });
}

window.loadSecurityPage = loadSecurityPage;
window.escapeHtml = escapeHtml;
window.updateSecurityChrome = updateSecurityChrome;
