// ── Email Tab ──────────────────────────────────────────────────────────
const emailPresets = {
    gmail: { host: 'smtp.gmail.com', port: 587, encryption: 'tls', help: 'Use an App Password. Enable 2‑Step Verification, then generate one at myaccount.google.com/apppasswords.' },
    outlook: { host: 'smtp-mail.outlook.com', port: 587, encryption: 'tls', help: 'Outlook requires OAuth 2.0. App passwords may not be available for all accounts.' },
    yahoo: { host: 'smtp.mail.yahoo.com', port: 465, encryption: 'ssl', help: 'Enable 2‑Step Verification, then generate an App Password under "External connections".' },
    custom: { host: '', port: 587, encryption: 'tls', help: 'Enter your own SMTP server details.' },
};

function applyEmailPreset() {
    const provider = document.getElementById('emailProvider').value;
    const p = emailPresets[provider] || emailPresets.custom;
    document.getElementById('emailHost').value = p.host;
    document.getElementById('emailPort').value = p.port;
    document.getElementById('emailEncryption').value = p.encryption;
    document.getElementById('emailHelp').textContent = p.help;
}

function populateEmailTab() {
    const cfg = currentConfig.email || {};
    document.getElementById('emailProvider').value = cfg.provider || 'gmail';
    document.getElementById('emailHost').value = cfg.host || '';
    document.getElementById('emailPort').value = cfg.port || 587;
    document.getElementById('emailEncryption').value = cfg.encryption || 'tls';
    document.getElementById('emailUser').value = cfg.username || '';
    document.getElementById('emailPass').value = cfg.password || '';
    document.getElementById('emailFrom').value = cfg.fromAddress || '';
    document.getElementById('emailFromName').value = cfg.fromName || '';
    applyEmailPreset();
}

// Collect current email settings as a plain object
function getCurrentEmailData() {
    return {
        provider: document.getElementById('emailProvider')?.value || '',
        host: document.getElementById('emailHost')?.value || '',
        port: document.getElementById('emailPort')?.value || 587,
        encryption: document.getElementById('emailEncryption')?.value || 'tls',
        username: document.getElementById('emailUser')?.value || '',
        password: document.getElementById('emailPass')?.value || '',
        fromAddress: document.getElementById('emailFrom')?.value || '',
        fromName: document.getElementById('emailFromName')?.value || ''
    };
}

// Save on page hide (navigation, refresh, close) using sendBeacon
window.addEventListener('pagehide', () => {
    const emailData = getCurrentEmailData();
    if (Object.keys(emailData).length) {
        navigator.sendBeacon(
            `${baseUrl}/project/${projectSlug}/misc/save`,
            JSON.stringify({ section: 'email', data: emailData })
        );
    }
});

document.addEventListener('DOMContentLoaded', () => {
    document.getElementById('emailProvider')?.addEventListener('change', () => {
        applyEmailPreset();
        saveSection('email');
    });
    document.querySelectorAll('#emailPane input, #emailPane select').forEach(el => {
        if (el.id !== 'emailProvider') el.addEventListener('change', () => saveSection('email'));
    });

    // Toggle Password visibility
    document.getElementById('btnToggleEmailPass')?.addEventListener('click', () => {
        const input = document.getElementById('emailPass');
        const icon = document.getElementById('btnToggleEmailPass').querySelector('i');
        if (input.type === 'password') { input.type = 'text'; icon.className = 'bi bi-eye-slash'; }
        else { input.type = 'password'; icon.className = 'bi bi-eye'; }
    });

    // Test Email button
    document.getElementById('btnTestEmail')?.addEventListener('click', async () => {
        const to = await pp.dialog.prompt('Send test email to:', 'your@email.com');
        if (!to) return;
        const settings = getCurrentEmailData();
        if (!settings.host) { pp.dialog.alert('Missing Host', 'Please enter the SMTP host before testing.', 'warning'); return; }
        Swal.fire({ title: 'Sending test email…', text: 'Please wait while we verify your configuration.', allowOutsideClick: false, didOpen: () => Swal.showLoading() });
        try {
            const res = await fetch(`${baseUrl}/project/${projectSlug}/misc/test-email`, {
                method: 'POST', headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ to, settings })
            });
            const data = await res.json();
            Swal.close();
            if (data.success) pp.dialog.toast('success', 'Test email sent successfully!');
            else pp.dialog.alert('Failed', data.message, 'error');
        } catch (err) { Swal.close(); pp.dialog.toast('error', 'Network error.'); }
    });
});