// ── Auth email templates (Settings → Email Templates) ───────────────────────
// Master/detail over core/Auth/AuthEmails: the catalogue and the shipped
// defaults live there, so this page never hard-codes template content and the
// generated app sends exactly what the preview shows.

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

    let templates = {}, appName = 'App', activeKey = null;
    // Unsaved edits, kept per template so switching away and back does not lose them.
    const drafts = {};

    try {
        const res = await fetch(`${baseUrl}/project/${projectSlug}/security/auth-emails`);
        const data = await res.json();
        if (!data.success) throw new Error(data.message || 'Unable to load templates.');
        templates = data.templates || {};
        appName = data.app_name || 'App';
    } catch (e) {
        container.innerHTML = `<div class="secdb-empty"><i class="bi bi-exclamation-triangle"></i>
            <strong>Could not load email templates</strong><span>${escapeHtml(e.message)}</span></div>`;
        return;
    }
    window.updateSecurityChrome?.('settings-emails');
    activeKey = Object.keys(templates)[0];

    container.innerHTML = `
        <div class="secdb" style="gap:12px">
            <div class="secdb-master is-on">
                <span class="secdb-master-icon"><i class="bi bi-envelope-paper"></i></span>
                <div class="secdb-master-copy">
                    <strong>Account emails</strong>
                    <p>Every message the generated app sends during sign-up, approval and password recovery.
                       Edit the content, switch one off, or restore the original at any time.</p>
                </div>
                <div class="secdb-summary" id="secmailCount"></div>
            </div>
            <div class="secmail">
                <div class="secmail-list" id="secmailList"></div>
                <div class="secmail-editor" id="secmailEditor"></div>
            </div>
        </div>`;

    const listEl = document.getElementById('secmailList');
    const editorEl = document.getElementById('secmailEditor');

    const draftOf = key => drafts[key] || {
        subject: templates[key].subject,
        body: templates[key].body
    };
    const isDirty = key => {
        const d = drafts[key];
        return !!d && (d.subject !== templates[key].subject || d.body !== templates[key].body);
    };

    function renderList() {
        const on = Object.values(templates).filter(t => t.enabled).length;
        document.getElementById('secmailCount').innerHTML =
            `<span class="secdb-pill is-ok"><i class="bi bi-toggle-on"></i> ${on} of ${Object.keys(templates).length} active</span>`;

        listEl.innerHTML = Object.entries(templates).map(([key, t]) => `
            <button type="button" class="secmail-item ${key === activeKey ? 'is-active' : ''} ${t.enabled ? '' : 'is-off'}"
                    data-key="${key}">
                <span class="secmail-dot"></span>
                <span class="secmail-item-copy">
                    <strong>${escapeHtml(t.label)}</strong>
                    <span>to ${t.to === 'admin' ? 'administrator' : 'user'}</span>
                </span>
                ${t.customized || isDirty(key) ? '<span class="secmail-edited">edited</span>' : ''}
            </button>`).join('');

        listEl.querySelectorAll('.secmail-item').forEach(b =>
            b.addEventListener('click', () => { activeKey = b.dataset.key; renderList(); renderEditor(); }));
    }

    function renderEditor() {
        const t = templates[activeKey];
        const d = draftOf(activeKey);
        editorEl.innerHTML = `
            <div class="secdb-panel">
                <div class="secdb-panel-head">
                    <i class="bi bi-pencil-square"></i>
                    <div><h6>${escapeHtml(t.label)}</h6><small>${escapeHtml(t.hint)}</small></div>
                    <div class="secdb-panel-head-actions">
                        <label class="secdb-switch form-switch" style="gap:6px" title="Switch this email on or off">
                            <span class="secdb-switch-state" id="secmailState">${t.enabled ? 'On' : 'Off'}</span>
                            <input class="form-check-input" type="checkbox" role="switch" id="secmailEnabled" ${t.enabled ? 'checked' : ''}>
                        </label>
                    </div>
                </div>
                <div class="secdb-panel-body secdb" style="gap:10px">
                    <div class="secdb-field">
                        <label class="secdb-label" for="secmailSubject">Subject</label>
                        <input class="form-control form-control-sm" id="secmailSubject" value="${escapeHtml(d.subject)}">
                    </div>
                    <div class="secdb-field">
                        <label class="secdb-label" for="secmailBody">Body (HTML)</label>
                        <textarea class="secmail-code" id="secmailBody" spellcheck="false">${escapeHtml(d.body)}</textarea>
                    </div>
                    <div class="secdb-field">
                        <span class="secdb-label">Placeholders — click to insert</span>
                        <div class="secmail-vars">
                            ${t.vars.map(v => `<button type="button" class="secmail-var" data-var="${escapeHtml(v)}">${escapeHtml(v)}</button>`).join('')}
                        </div>
                    </div>
                    <div class="secmail-toolbar">
                        <span class="secdb-label">Live preview — sample data, branded shell</span>
                        <button type="button" class="btn btn-sm btn-outline-secondary" id="secmailReset"
                                title="Discard your changes and restore the original wording">
                            <i class="bi bi-arrow-counterclockwise"></i> Reset to default
                        </button>
                        <button type="button" class="btn btn-primary btn-sm" id="secmailSave">
                            <i class="bi bi-save me-1"></i> Save template
                        </button>
                    </div>
                    <div class="secmail-preview"><iframe id="secmailFrame" title="Email preview"></iframe></div>
                    <div class="secdb-summary" id="secmailNote"></div>
                </div>
            </div>`;

        const subjectEl = document.getElementById('secmailSubject');
        const bodyEl = document.getElementById('secmailBody');

        const stash = () => { drafts[activeKey] = { subject: subjectEl.value, body: bodyEl.value }; };
        let timer = null;
        const schedulePreview = () => { clearTimeout(timer); timer = setTimeout(paint, 250); };

        [subjectEl, bodyEl].forEach(el => el.addEventListener('input', () => {
            stash(); renderList(); schedulePreview();
        }));

        editorEl.querySelectorAll('.secmail-var').forEach(btn => btn.addEventListener('click', () => {
            // Insert at the caret so a placeholder lands where the author is typing.
            const target = document.activeElement === subjectEl ? subjectEl : bodyEl;
            const v = btn.dataset.var;
            const s = target.selectionStart ?? target.value.length;
            const e = target.selectionEnd ?? s;
            target.value = target.value.slice(0, s) + v + target.value.slice(e);
            target.focus();
            target.setSelectionRange(s + v.length, s + v.length);
            stash(); renderList(); schedulePreview();
        }));

        document.getElementById('secmailEnabled').addEventListener('change', async function () {
            const enabled = this.checked;
            document.getElementById('secmailState').textContent = enabled ? 'On' : 'Off';
            try {
                const res = await fetch(`${baseUrl}/project/${projectSlug}/security/auth-emails/toggle`, {
                    method: 'POST', headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ key: activeKey, enabled })
                });
                const data = await res.json();
                if (!data.success) throw new Error(data.message || 'Could not update.');
                templates[activeKey].enabled = data.enabled;
                renderList();
                pp.dialog.toast('success', `“${templates[activeKey].label}” ${data.enabled ? 'will be sent' : 'will not be sent'}.`);
            } catch (e) { pp.dialog.toast('error', e.message); }
        });

        document.getElementById('secmailSave').addEventListener('click', async () => {
            try {
                const res = await fetch(`${baseUrl}/project/${projectSlug}/security/auth-emails`, {
                    method: 'POST', headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ key: activeKey, subject: subjectEl.value, body: bodyEl.value })
                });
                const data = await res.json();
                if (!data.success) throw new Error(data.message || 'Could not save.');
                templates[activeKey] = data.template;
                delete drafts[activeKey];
                renderList(); renderEditor();
                pp.dialog.toast('success', 'Template saved. Rebuild to publish it.');
            } catch (e) { pp.dialog.toast('error', e.message); }
        });

        document.getElementById('secmailReset').addEventListener('click', async () => {
            const ok = await Swal.fire({
                title: `Reset “${templates[activeKey].label}”?`,
                text: 'The subject and body return to the wording PPPHP ships. Your on/off switch is kept.',
                icon: 'warning', showCancelButton: true,
                confirmButtonText: 'Reset to default', cancelButtonText: 'Keep my version'
            });
            if (!ok.isConfirmed) return;
            try {
                const res = await fetch(`${baseUrl}/project/${projectSlug}/security/auth-emails/reset`, {
                    method: 'POST', headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ key: activeKey })
                });
                const data = await res.json();
                if (!data.success) throw new Error(data.message || 'Could not reset.');
                templates[activeKey] = data.template;
                delete drafts[activeKey];
                renderList(); renderEditor();
                pp.dialog.toast('success', data.message);
            } catch (e) { pp.dialog.toast('error', e.message); }
        });

        function paint() {
            const q = new URLSearchParams({
                key: activeKey, subject: subjectEl.value, body: bodyEl.value
            });
            document.getElementById('secmailFrame').src =
                `${baseUrl}/project/${projectSlug}/security/auth-emails/preview?${q}`;
            const note = document.getElementById('secmailNote');
            if (note) {
                note.innerHTML = isDirty(activeKey)
                    ? '<span class="secdb-pill is-warn"><i class="bi bi-pencil"></i> Unsaved changes — the preview is live, the app still sends the saved version</span>'
                    : (templates[activeKey].customized
                        ? '<span class="secdb-pill"><i class="bi bi-check2"></i> Saved · edited from the default</span>'
                        : '<span class="secdb-pill is-ok"><i class="bi bi-check2"></i> Using the shipped default</span>');
            }
        }
        paint();
    }

    renderList();
    renderEditor();
    // No auto-save: email content is edited deliberately and saved per template.
}

window.renderAuthEmailSettings = renderAuthEmailSettings;
