// ── Login security (Settings → Login) ───────────────────────────────────────
// This page owns how the sign-in flow BEHAVES. How it LOOKS belongs to
// Designer → Common Pages → Login, which has the template gallery and the full
// auth_form editor. Keeping the two apart is deliberate: an earlier version of
// this page duplicated the Designer's appearance controls and silently
// overrode the template the developer had chosen.

const SECLOGIN_DEFAULTS = {
    lockout_enabled: true,
    max_attempts: 5,
    attempt_window: 15,
    lockout_minutes: 15,
    ip_max_attempts: 20,
    guest_only: true,
    register_max: 5,
    register_window: 60,
    forgot_max: 5,
    forgot_window: 60,
    remember_days: 30,
    generic_errors: true
};

// Mirrors the Designer's own gallery (modules/Designer/Views/app/panels.js).
const SECLOGIN_TEMPLATES = {
    aurora:    { name: 'Aurora Split', note: 'Bold product story', icon: 'bi-stars' },
    halo:      { name: 'Glass Halo', note: 'Immersive and focused', icon: 'bi-circle-half' },
    executive: { name: 'Executive', note: 'Clean enterprise SSO', icon: 'bi-buildings' },
    verdant:   { name: 'Verdant Glass', note: 'Scenic frosted focus', icon: 'bi-tree' }
};

async function renderLoginFormSettings() {
    const container = document.getElementById('securityPageContainer');
    let cfg = { ...SECLOGIN_DEFAULTS };
    let design = { template: '', title: '', subtitle: '', social: [], designed: false };

    try {
        const res = await fetch(`${baseUrl}/project/${projectSlug}/security/login-security`);
        const data = await res.json();
        if (data.success) {
            cfg = { ...SECLOGIN_DEFAULTS, ...(data.settings || {}) };
            design = { ...design, ...(data.design || {}) };
        }
    } catch (e) { console.error(e); }
    window.updateSecurityChrome?.('settings-login');

    const tpl = SECLOGIN_TEMPLATES[design.template] || null;

    const toggle = (key, title, hint) => `
        <div class="seclg-row">
            <div class="seclg-row-copy"><strong>${title}</strong><span>${hint}</span></div>
            <div class="form-check form-switch m-0">
                <input class="form-check-input" type="checkbox" role="switch" data-cfg="${key}" ${cfg[key] ? 'checked' : ''}>
            </div>
        </div>`;

    const num = (key, title, hint, min, max, suffix) => `
        <div class="seclg-row">
            <div class="seclg-row-copy"><strong>${title}</strong><span>${hint}</span></div>
            <div class="seclg-range" style="max-width:160px">
                <input type="number" class="form-control form-control-sm" min="${min}" max="${max}"
                       value="${cfg[key]}" data-cfg="${key}">
                <output style="min-width:auto">${suffix}</output>
            </div>
        </div>`;

    container.innerHTML = `
        <div class="secdb" style="gap:12px">
            <div class="secdb-master ${cfg.lockout_enabled ? 'is-on' : ''}" id="seclgMaster">
                <span class="secdb-master-icon"><i class="bi bi-shield-lock"></i></span>
                <div class="secdb-master-copy">
                    <strong>Brute-force protection</strong>
                    <p>Lock an account after repeated failed sign-ins, and throttle sign-up and password-reset abuse.</p>
                </div>
                <label class="secdb-switch form-switch" for="seclgLockout">
                    <span class="secdb-switch-state" id="seclgState">${cfg.lockout_enabled ? 'On' : 'Off'}</span>
                    <input class="form-check-input" type="checkbox" role="switch" id="seclgLockout"
                           data-cfg="lockout_enabled" ${cfg.lockout_enabled ? 'checked' : ''}>
                </label>
            </div>

            <div class="secdb-panel">
                <div class="secdb-panel-head"><i class="bi bi-palette"></i>
                    <div><h6>Appearance</h6><small>Owned by the Designer, not this page</small></div>
                    <div class="secdb-panel-head-actions">
                        <a class="btn btn-sm btn-outline-secondary"
                           href="${baseUrl}/project/${projectSlug}/designer">
                            <i class="bi bi-pencil-square"></i> Open in Designer
                        </a>
                    </div>
                </div>
                <div class="secdb-panel-body">
                    ${design.designed ? `
                        <div class="secdb-map-item is-set" style="max-width:none">
                            <div class="secdb-map-head">
                                <i class="bi ${tpl ? tpl.icon : 'bi-window'}"></i>
                                <strong>${escapeHtml(tpl ? tpl.name : (design.template || 'Custom design'))}</strong>
                                <span class="secdb-tag is-opt">Active template</span>
                            </div>
                            <div class="secdb-summary" style="margin-top:2px">
                                ${design.title ? `<span class="secdb-pill"><i class="bi bi-type"></i> ${escapeHtml(design.title)}</span>` : ''}
                                ${design.social.length ? `<span class="secdb-pill"><i class="bi bi-box-arrow-in-right"></i> ${design.social.length} social provider${design.social.length > 1 ? 's' : ''}</span>` : ''}
                                <span class="secdb-pill"><i class="bi bi-info-circle"></i> Templates, colours and copy live in the Designer</span>
                            </div>
                        </div>` : `
                        <div class="secdb-empty" style="padding:16px">
                            <i class="bi bi-window"></i>
                            <strong>No Login page designed yet</strong>
                            <span>Open the Designer to pick one of the four sign-in templates.</span>
                        </div>`}
                </div>
            </div>

            <div class="secdb-panel">
                <div class="secdb-panel-head"><i class="bi bi-lock"></i>
                    <div><h6>Failed sign-ins</h6><small>Password-guessing defence</small></div></div>
                <div class="secdb-panel-body" style="padding-block:6px">
                    ${num('max_attempts', 'Attempts before lockout', 'Failures allowed per account', 1, 100, 'tries')}
                    ${num('attempt_window', 'Counting window', 'Failures are counted over this period', 1, 1440, 'min')}
                    ${num('lockout_minutes', 'Lockout duration', 'Measured from the last failure', 1, 1440, 'min')}
                    ${num('ip_max_attempts', 'Per-IP ceiling', 'Failures from one address across all accounts', 1, 1000, 'tries')}
                </div>
            </div>

            <div class="secdb-panel">
                <div class="secdb-panel-head"><i class="bi bi-speedometer2"></i>
                    <div><h6>Abuse throttles</h6><small>Per IP address</small></div></div>
                <div class="secdb-panel-body" style="padding-block:6px">
                    ${num('register_max', 'Sign-ups allowed', '0 disables this throttle', 0, 1000, 'max')}
                    ${num('register_window', 'Sign-up window', 'Period the sign-ups are counted over', 1, 1440, 'min')}
                    ${num('forgot_max', 'Reset requests allowed', '0 disables this throttle', 0, 1000, 'max')}
                    ${num('forgot_window', 'Reset window', 'Period the requests are counted over', 1, 1440, 'min')}
                </div>
            </div>

            <div class="secdb-panel">
                <div class="secdb-panel-head"><i class="bi bi-person-check"></i>
                    <div><h6>Sessions &amp; disclosure</h6><small>Behaviour of the auth pages</small></div></div>
                <div class="secdb-panel-body" style="padding-block:6px">
                    ${toggle('guest_only', 'Redirect signed-in users', 'Sends them home instead of showing sign-in again')}
                    ${toggle('generic_errors', 'Hide whether an account exists', 'Same wording for unknown and real accounts')}
                    ${num('remember_days', '“Remember me” lifetime', 'How long the cookie stays valid', 1, 365, 'days')}
                </div>
            </div>

            <div class="secdb-panel">
                <div class="secdb-panel-head"><i class="bi bi-key"></i>
                    <div><h6>Password rules</h6><small>Applied to sign-up and password reset</small></div>
                    <div class="secdb-panel-head-actions">
                        <button type="button" class="btn btn-sm btn-outline-secondary" id="seclgGoReg">
                            <i class="bi bi-sliders"></i> Registration &amp; Passwords
                        </button>
                    </div>
                </div>
                <div class="secdb-panel-body">
                    <div class="secdb-summary">
                        <span class="secdb-pill"><i class="bi bi-info-circle"></i> Length and complexity are set on the Registration &amp; Passwords page and are now enforced by the generated app</span>
                    </div>
                </div>
            </div>

            <div class="secdb-foot">
                <div class="secdb-summary" id="seclgSummary"></div>
                <button class="btn btn-primary btn-sm" id="btnSaveLoginAppearance"><i class="bi bi-save me-1"></i> Save settings</button>
            </div>
        </div>
    `;

    function refresh() {
        const on = !!cfg.lockout_enabled;
        document.getElementById('seclgMaster').classList.toggle('is-on', on);
        document.getElementById('seclgState').textContent = on ? 'On' : 'Off';
        const s = document.getElementById('seclgSummary');
        if (s) {
            s.innerHTML = on
                ? `<span class="secdb-pill is-ok"><i class="bi bi-shield-check"></i> Locks for ${cfg.lockout_minutes} min after ${cfg.max_attempts} failures in ${cfg.attempt_window} min</span>`
                : `<span class="secdb-pill is-warn"><i class="bi bi-shield-exclamation"></i> Accounts can be guessed without limit</span>`;
        }
    }

    container.querySelectorAll('[data-cfg]').forEach(el => {
        const key = el.getAttribute('data-cfg');
        el.addEventListener(el.type === 'checkbox' ? 'change' : 'input', () => {
            cfg[key] = el.type === 'checkbox' ? el.checked : (parseInt(el.value, 10) || 0);
            refresh();
        });
    });

    document.getElementById('seclgGoReg')?.addEventListener('click', () => {
        document.querySelector('.security-sidebar .nav-link[data-page="settings-registration"]')?.click();
    });

    document.getElementById('btnSaveLoginAppearance').addEventListener('click', async () => {
        try {
            const res = await fetch(`${baseUrl}/project/${projectSlug}/security/login-security`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ settings: cfg })
            });
            const data = await res.json();
            if (!data.success) return pp.dialog.alert('Error', data.message || 'Could not save.', 'error');
            cfg = { ...cfg, ...(data.settings || {}) };   // the server clamps the values
            refresh();
            pp.dialog.toast('success', 'Login security saved. Rebuild to publish it.');
        } catch (e) { pp.dialog.toast('error', 'Network error'); }
    });

    refresh();
    // No auto-save: these are security limits, changed deliberately.
}

window.renderLoginFormSettings = renderLoginFormSettings;
