// ── Two-Factor Authentication — PROJECT CONFIGURATION ───────────────
// This page is admin configuration ONLY: choose which methods your app's
// users may turn on (authenticator / email / SMS) and, for email & SMS, which
// column of the users table holds the address/number. It does NOT enrol the
// console admin's own device — enrolment happens per-user inside the built app,
// where each user picks ONE of the enabled methods.

let currentUser = { id: null, role: null, is_admin: false };
let userTableColumns = [];
let cfg = {
    remember_machine: false,
    methods: {
        totp: { enabled: false },
        email: { enabled: false, email_field: 'email', message: 'Your verification code is: {code}' },
        sms: { enabled: false, phone_field: 'phone', message: 'Your code: {code}' }
    }
};

function esc(str) {
    if (str === undefined || str === null) return '';
    return String(str).replace(/[&<>"]/g, m => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[m]));
}
function firstScalar(v, def) {
    while (Array.isArray(v)) v = v.length ? v[v.length - 1] : def;
    return v === undefined || v === null ? def : v;
}

async function renderTwoFactor() {
    const container = document.getElementById('securityPageContainer');
    if (!window.securitySettings?.db_auth_enabled) {
        if (container) container.innerHTML = '<div class="alert alert-warning">Database authentication is not enabled. Turn it on in the Settings tab first.</div>';
        return;
    }
    container.innerHTML = '<div class="text-center py-5"><div class="spinner-border"></div></div>';
    try {
        const userData = await (await fetch(`${baseUrl}/project/${projectSlug}/security/current-user`)).json();
        if (userData.success) currentUser = userData.user;

        const settingsData = await (await fetch(`${baseUrl}/project/${projectSlug}/security/2fa/settings`)).json();
        if (settingsData.success) mergeSettings(settingsData.settings);

        const usersTable = window.securitySettings?.users_table || 'users';
        const colData = await (await fetch(`${baseUrl}/project/${projectSlug}/security/columns`, {
            method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ table: usersTable })
        })).json();
        userTableColumns = (colData.success && Array.isArray(colData.columns)) ? colData.columns : [];
    } catch (e) {
        console.error(e);
        container.innerHTML = '<div class="alert alert-danger">Failed to load 2FA settings.</div>';
        return;
    }
    renderUI();
}

function mergeSettings(s) {
    const m = s.methods || {};
    cfg.remember_machine = !!firstScalar(s.remember_machine, false);
    cfg.methods.totp.enabled = !!firstScalar(m.totp?.enabled, false);
    cfg.methods.email.enabled = !!firstScalar(m.email?.enabled, false);
    cfg.methods.email.email_field = String(firstScalar(m.email?.email_field, 'email') || 'email');
    cfg.methods.email.message = String(firstScalar(m.email?.message, cfg.methods.email.message));
    cfg.methods.sms.enabled = !!firstScalar(m.sms?.enabled, false);
    cfg.methods.sms.phone_field = String(firstScalar(m.sms?.phone_field, 'phone') || 'phone');
    cfg.methods.sms.message = String(firstScalar(m.sms?.message, cfg.methods.sms.message));
}

function fieldSelect(id, selected) {
    const opts = ['<option value="">— select a column —</option>']
        .concat(userTableColumns.map(c => `<option value="${esc(c)}" ${c === selected ? 'selected' : ''}>${esc(c)}</option>`));
    return `<select id="${id}" class="tfa-field">${opts.join('')}</select>`;
}

function methodCard(key, icon, title, desc, enabled, extra) {
    return `
    <div class="tfa-card ${enabled ? 'is-on' : ''}" data-card="${key}">
        <div class="tfa-card-head">
            <div class="tfa-card-title"><i class="bi ${icon}"></i> ${esc(title)}</div>
            <label class="tfa-switch"><input type="checkbox" class="tfa-toggle" data-method="${key}" ${enabled ? 'checked' : ''}><span></span></label>
        </div>
        <p class="tfa-card-desc">${esc(desc)}</p>
        <div class="tfa-card-extra" ${enabled ? '' : 'hidden'}>${extra || ''}</div>
    </div>`;
}

function renderUI() {
    const c = document.getElementById('securityPageContainer');
    const m = cfg.methods;
    const emailExtra = `<label class="tfa-lbl">User email field</label>${fieldSelect('tfaEmailField', m.email.email_field)}
        <label class="tfa-lbl tfa-mt">Message (use <code>{code}</code>)</label><input id="tfaEmailMsg" class="tfa-input" value="${esc(m.email.message)}" placeholder="Your verification code is: {code}">`;
    const smsExtra = `<label class="tfa-lbl">User phone field</label>${fieldSelect('tfaPhoneField', m.sms.phone_field)}
        <label class="tfa-lbl tfa-mt">Message (use <code>{code}</code>)</label><input id="tfaSmsMsg" class="tfa-input" value="${esc(m.sms.message)}" placeholder="Your code: {code}">`;

    c.innerHTML = `
    <div class="tfa-wrap">
        <p class="tfa-intro">Choose which second-factor methods your app&rsquo;s users may use. Each user turns on <strong>one</strong> of the enabled methods from their own account. Nothing here signs <em>you</em> in — it only decides what&rsquo;s available.</p>
        <div class="tfa-grid">
            ${methodCard('totp', 'bi-phone', 'Authenticator app', 'Time-based codes from Google Authenticator, Authy, Microsoft Authenticator, 1Password, etc.', m.totp.enabled, '<p class="tfa-note"><i class="bi bi-info-circle"></i> No configuration needed — users scan a QR code in the app.</p>')}
            ${methodCard('email', 'bi-envelope', 'Email', 'A one-time code is emailed to the user when they sign in.', m.email.enabled, emailExtra)}
            ${methodCard('sms', 'bi-chat-dots', 'SMS', 'A one-time code is texted to the user when they sign in.', m.sms.enabled, smsExtra)}
        </div>
        <label class="tfa-remember"><input type="checkbox" id="tfaRemember" ${cfg.remember_machine ? 'checked' : ''}> Allow &ldquo;Remember this device&rdquo; (skip 2FA for 30 days)</label>
        <span class="tfa-status" id="tfaStatus"></span>
    </div>`;

    c.querySelectorAll('.tfa-toggle').forEach(t => t.addEventListener('change', onToggle));
    ['tfaEmailField', 'tfaEmailMsg', 'tfaPhoneField', 'tfaSmsMsg', 'tfaRemember'].forEach(id => {
        const el = document.getElementById(id);
        if (el) el.addEventListener('change', collectAndSave);
    });
}

function onToggle(e) {
    const card = e.target.closest('.tfa-card');
    if (card) {
        card.classList.toggle('is-on', e.target.checked);
        const extra = card.querySelector('.tfa-card-extra');
        if (extra) extra.hidden = !e.target.checked;
    }
    collectAndSave();
}

function collect() {
    const val = id => (document.getElementById(id)?.value ?? '');
    const on = method => !!document.querySelector(`.tfa-toggle[data-method="${method}"]`)?.checked;
    return {
        remember_machine: !!document.getElementById('tfaRemember')?.checked,
        methods: {
            totp: { enabled: on('totp') },
            email: { enabled: on('email'), email_field: val('tfaEmailField') || 'email', message: val('tfaEmailMsg') || 'Your verification code is: {code}' },
            sms: { enabled: on('sms'), phone_field: val('tfaPhoneField') || 'phone', message: val('tfaSmsMsg') || 'Your code: {code}' }
        }
    };
}

async function collectAndSave() {
    const settings = collect();
    const status = document.getElementById('tfaStatus');
    if (status) { status.textContent = 'Saving…'; status.className = 'tfa-status'; }
    try {
        const data = await (await fetch(`${baseUrl}/project/${projectSlug}/security/2fa/settings`, {
            method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ settings })
        })).json();
        if (data.success) {
            if (status) { status.textContent = 'Saved'; status.className = 'tfa-status is-ok'; setTimeout(() => { if (status) status.textContent = ''; }, 1800); }
        } else if (status) { status.textContent = data.message || 'Save failed'; status.className = 'tfa-status is-err'; }
    } catch (e) {
        if (status) { status.textContent = 'Network error'; status.className = 'tfa-status is-err'; }
    }
}

window.renderTwoFactor = renderTwoFactor;
