{% extends "base.html" %}

{% block title %}Admin Email Resend{% endblock %}
{% block page_id %}emails{% endblock %}
{% block page_title %}New Emails{% endblock %}
{% block eyebrow %}Delivery{% endblock %}

{% block content %}
    {% with messages = get_flashed_messages(with_categories=true) %}
        {% if messages %}
            <div class="flash-container">
                {% for category, message in messages %}
                    <div class="flash {{ category }}">
                        {{ message }}
                        <button class="flash-close" onclick="this.parentElement.remove()">&times;</button>
                    </div>
                {% endfor %}
            </div>
        {% endif %}
    {% endwith %}



    <!-- Resend Section -->
    <section class="content-grid">
        <article class="glass-card panel-card">
            <div class="panel-header">
                <div>
                    <p class="eyebrow">Step 1</p>
                    <h3>Fetch existing user</h3>
                </div>
            </div>

            <div class="field-group">
                <label class="field-label" for="oldEmail">Name / Email / Mobile *</label>
                <div class="input-with-button">
                    <div class="input-wrapper">
                        <input id="oldEmail" type="text" placeholder="Type name, email or mobile number" autocomplete="off">
                        <div id="emailSuggestions" class="suggestions-container"></div>
                    </div>
                    <button class="primary-btn" id="fetchUserButton" type="button">Fetch</button>
                </div>
            </div>

            <div id="emailUserCard" class="user-card hidden">
                <div class="user-card-media">
                    <img id="emailUserImage" alt="User preview">
                </div>
                <div class="user-card-body">
                    <strong id="emailUserName">-</strong>
                    <span id="emailUserExistingEmail">-</span>
                    <span id="emailUserPhone">-</span>
                </div>
            </div>
        </article>

        <article class="glass-card panel-card">
            <div class="panel-header">
                <div>
                    <p class="eyebrow">Step 2</p>
                    <h3>Send gallery to New email</h3>
                </div>
            </div>

            <div class="field-group">
                <label class="field-label" for="newEmail">Email address *</label>
                <div class="input-with-button">
                    <input id="newEmail" type="email" placeholder="Enter email address">
                    <button class="primary-btn" id="sendEmailButton" type="button">Send</button>
                </div>
            </div>
            <p class="field-hint">Reuses existing gallery email flow. Images are not duplicated.</p>

            <!-- Response Card -->
            <div id="emailResponseCard" style="display:none; margin-top:16px;">
                <div id="emailResponseInner" class="email-response-card">
                    <!-- filled by JS -->
                </div>
            </div>
        </article>
    </section>

    <!-- EMAIL STATS MODAL -->
    <div id="emailStatsModal" class="em-modal">
        <div class="em-modal-content">
            <div class="em-modal-header" id="emModalHeader">
                <h3 id="emModalTitle">Email Stats</h3>
                <button class="em-modal-close" onclick="closeEmailModal()">&times;</button>
            </div>
            <div class="em-modal-stats-bar" id="emModalStatsBar"></div>
            <div class="em-modal-body" id="emModalBody">
                <div class="em-loading">Loading...</div>
            </div>
        </div>
    </div>
{% endblock %}

{% block head %}
<style>
    /* Flash */
    .flash-container { position: fixed; top: 20px; right: 20px; z-index: 9999; max-width: 400px; }
    .flash { padding: 14px 20px; border-radius: 10px; margin-bottom: 12px; color: #fff; font-weight: 500; font-size: 14px; box-shadow: 0 4px 12px rgba(0,0,0,0.2); animation: slideIn 0.3s ease; display: flex; align-items: center; justify-content: space-between; }
    .flash.error { background: linear-gradient(135deg, #dc2626, #b91c1c); }
    .flash.success { background: linear-gradient(135deg, #16a34a, #15803d); }
    .flash-close { background: transparent; border: none; color: #fff; font-size: 20px; cursor: pointer; margin-left: 12px; padding: 0; }
    @keyframes slideIn { from { opacity:0; transform:translateX(20px); } to { opacity:1; transform:translateX(0); } }

    /* Email Stats Grid */
    .email-stats-grid {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 16px;
        margin-bottom: 20px;
    }

    .email-stat-card {
        background: #ffffff;
        border-radius: 16px;
        border: 1.5px solid #e2e8f0;
        padding: 20px;
        display: flex;
        align-items: center;
        gap: 16px;
        cursor: pointer;
        transition: all 0.25s ease;
        box-shadow: 0 2px 8px rgba(0,0,0,0.05);
    }

    .email-stat-card:hover {
        transform: translateY(-4px);
        box-shadow: 0 8px 24px rgba(0,0,0,0.1);
    }

    .total-card { border-color: #bfdbfe; }
    .total-card:hover { border-color: #7dd3fc; background: #f0f7ff; }
    .sent-card { border-color: #bbf7d0; }
    .sent-card:hover { border-color: #86efac; background: #f0fdf4; }
    .remaining-card { border-color: #fed7aa; }
    .remaining-card:hover { border-color: #fdba74; background: #fff7ed; }

    .email-stat-icon { font-size: 32px; flex-shrink: 0; }

    .email-stat-body { flex: 1; }
    .email-stat-label { display: block; font-size: 12px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px; color: #64748b; margin-bottom: 4px; }
    .email-stat-value { display: block; font-size: 32px; font-weight: 800; color: #0f172a; line-height: 1; margin-bottom: 4px; }
    .email-stat-sub { font-size: 12px; color: #94a3b8; margin: 0; }

    /* Input with button row */
    .input-with-button { display: flex; gap: 12px; align-items: flex-end; }
    .input-wrapper { flex: 1; position: relative; }
    .input-with-button input { width: 100% !important; }
    .input-with-button .primary-btn { flex-shrink: 0; min-width: 90px; padding: 12px 20px !important; margin: 0 !important; }

    /* Input styling */
    .field-group input {
        background: #ffffff !important;
        color: #0f172a !important;
        border: 1.5px solid #cbd5e1 !important;
        width: 100% !important;
        padding: 12px 16px !important;
        border-radius: 12px !important;
        font-size: 14px !important;
        box-sizing: border-box !important;
    }
    .field-group input::placeholder { color: #94a3b8 !important; }
    .field-group input:focus { outline: none; border-color: #2c7da0 !important; box-shadow: 0 0 0 3px rgba(44,125,160,0.1); }
    .field-label { color: #475569 !important; font-size: 13px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 8px; display: block; }
    .field-hint { color: #475569 !important; font-size: 13px; margin-top: 8px; }
    #emailResponse { background: #f1f5f9 !important; color: #0f172a !important; border: 1px solid #e2e8f0 !important; }
    #emailUserImage { width: 100%; height: 110px; object-fit: cover; border-radius: 12px; }
    .user-card-media { display: flex; align-items: center; justify-content: center; }
    .field-group { position: relative; margin-bottom: 16px; }

    /* Predictive Suggestions */
    .suggestions-container {
        position: absolute; top: 100%; left: 0; right: 0;
        background: #ffffff; border: 1.5px solid #cbd5e1;
        border-top: none; border-radius: 0 0 12px 12px;
        max-height: 300px; overflow-y: auto;
        display: none; z-index: 100;
        box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        padding: 8px 0;
    }
    .suggestions-container.active { display: block; }
    .suggestion-item { padding: 10px 12px; cursor: pointer; margin: 4px 8px; border-radius: 10px; background: #f8fafc; display: flex; flex-direction: column; gap: 4px; border: 1px solid transparent; transition: all 0.15s; }
    .suggestion-item:hover { background: #f0f7ff; border-color: #cbd5e1; }
    .suggestion-name { font-weight: 700; font-size: 14px; color: #0f172a; }
    .suggestion-contact { font-size: 12px; color: #64748b; display: flex; gap: 6px; }
    .suggestion-no-results { padding: 16px; color: #94a3b8; text-align: center; font-size: 13px; }

    /* Email Stats Modal */
    .em-modal {
        display: none; position: fixed; inset: 0;
        background: rgba(15,23,42,0.65); backdrop-filter: blur(6px);
        z-index: 1000; align-items: center; justify-content: center; padding: 16px;
    }
    .em-modal.active { display: flex; }

    .em-modal-content {
        background: #ffffff; border-radius: 18px; width: 100%; max-width: 640px;
        max-height: 85vh; overflow: hidden; display: flex; flex-direction: column;
        box-shadow: 0 25px 60px rgba(0,0,0,0.25);
        animation: emIn 0.2s ease;
    }
    @keyframes emIn { from { opacity:0; transform:translateY(-16px) scale(0.97); } to { opacity:1; transform:translateY(0) scale(1); } }

    .em-modal-header {
        padding: 16px 20px; display: flex; align-items: center; justify-content: space-between; flex-shrink: 0;
    }
    .em-modal-header.total { background: linear-gradient(135deg, #1e3a5f, #2c7da0); }
    .em-modal-header.sent { background: linear-gradient(135deg, #14532d, #16a34a); }
    .em-modal-header.remaining { background: linear-gradient(135deg, #7c2d12, #ea580c); }

    .em-modal-header h3 { margin: 0; color: #ffffff !important; font-size: 16px; font-weight: 700; }

    .em-modal-close {
        background: rgba(255,255,255,0.2); border: 1.5px solid rgba(255,255,255,0.3);
        color: #ffffff; width: 32px; height: 32px; border-radius: 8px;
        cursor: pointer; font-size: 18px; display: flex; align-items: center; justify-content: center; padding: 0;
    }
    .em-modal-close:hover { background: rgba(255,255,255,0.35); }

    .em-modal-stats-bar {
        display: flex; gap: 0; background: #f8fafc;
        border-bottom: 1px solid #e2e8f0; flex-shrink: 0;
    }
    .em-stats-pill {
        flex: 1; text-align: center; padding: 12px 8px;
        border-right: 1px solid #e2e8f0;
        font-size: 13px;
    }
    .em-stats-pill:last-child { border-right: none; }
    .em-stats-pill strong { display: block; font-size: 22px; font-weight: 800; color: #0f172a; }
    .em-stats-pill span { color: #64748b; font-size: 11px; text-transform: uppercase; letter-spacing: 0.5px; }

    .em-modal-body { padding: 16px; overflow-y: auto; flex: 1; }

    .em-loading { text-align: center; color: #94a3b8; padding: 30px; }

    /* Modal table */
    .em-table { width: 100%; border-collapse: collapse; font-size: 13px; }
    .em-table th { background: #f1f5f9; padding: 10px 12px; text-align: left; font-weight: 700; font-size: 11px; text-transform: uppercase; letter-spacing: 0.5px; color: #475569; border-bottom: 2px solid #e2e8f0; }
    .em-table td { padding: 12px; color: #0f172a; border-bottom: 1px solid #f1f5f9; vertical-align: top; }
    .em-table tbody tr:hover { background: #f8fafc; }
    .em-table tbody tr:last-child td { border-bottom: none; }
    .em-badge { display: inline-block; padding: 2px 8px; border-radius: 20px; font-size: 11px; font-weight: 700; }
    .em-badge-sent { background: #dcfce7; color: #15803d; }
    .em-badge-pending { background: #ffedd5; color: #ea580c; }
    .em-name { font-weight: 600; color: #0f172a; }
    .em-email { font-size: 12px; color: #64748b; }
    .em-time { font-size: 11px; color: #94a3b8; }

    @media (max-width: 768px) {
        .email-stats-grid { grid-template-columns: 1fr; }
        .email-stat-card { padding: 16px; }
        .email-stat-value { font-size: 26px; }
        .em-modal-content { max-width: 100%; max-height: 90vh; }
        .input-with-button { flex-wrap: wrap; }
        .input-with-button .primary-btn { width: 100%; }
    }

    /* ===== EMAIL RESPONSE CARD ===== */
    .email-response-card {
        border-radius: 14px;
        padding: 16px 18px;
        display: flex;
        flex-direction: column;
        gap: 12px;
        animation: cardSlideIn 0.3s ease;
    }
    @keyframes cardSlideIn {
        from { opacity: 0; transform: translateY(8px); }
        to   { opacity: 1; transform: translateY(0); }
    }
    .email-response-card.success {
        background: linear-gradient(135deg, #f0fdf4, #dcfce7);
        border: 1.5px solid #86efac;
    }
    .email-response-card.error {
        background: linear-gradient(135deg, #fef2f2, #fee2e2);
        border: 1.5px solid #fca5a5;
    }
    .response-card-header { display: flex; align-items: center; gap: 10px; }
    .response-card-icon { font-size: 22px; flex-shrink: 0; }
    .response-card-title { font-size: 15px; font-weight: 700; color: #0f172a; }
    .response-card-subtitle { font-size: 12px; font-weight: 500; margin-top: 2px; }
    .success .response-card-subtitle { color: #15803d; }
    .error   .response-card-subtitle { color: #b91c1c; }
    .response-card-rows {
        display: flex; flex-direction: column; gap: 6px;
        border-top: 1px solid rgba(0,0,0,0.07); padding-top: 10px;
    }
    .response-card-row { display: flex; align-items: center; justify-content: space-between; }
    .response-card-key { color: #64748b; font-weight: 600; text-transform: uppercase; letter-spacing: 0.4px; font-size: 11px; }
    .response-card-val { color: #0f172a; font-weight: 600; font-size: 13px; }
    .response-card-badge { display: inline-block; padding: 2px 10px; border-radius: 20px; font-size: 11px; font-weight: 700; }
    .badge-resend { background: #fef9c3; color: #854d0e; }
    .badge-new    { background: #dbeafe; color: #1e40af; }
</style>
{% endblock %}

{% block scripts %}
<script>
    // ── Stats Cards ──────────────────────────────────────────────────────────
    let statsData = null;

    async function loadEmailStats() {
        try {
            const res = await fetch('/admin/api/emails/stats');
            const data = await res.json();
            statsData = data;

            document.getElementById('statTotal').textContent = data.total_users_with_matches;
            document.getElementById('statSent').textContent = data.sent.length;
            document.getElementById('statRemaining').textContent = data.remaining.length;
        } catch (e) {
            console.error('Failed to load email stats:', e);
        }
    }

    function openEmailModal(type) {
        if (!statsData) {
            loadEmailStats().then(() => renderModal(type));
        } else {
            renderModal(type);
        }
        document.getElementById('emailStatsModal').classList.add('active');
    }

    function closeEmailModal() {
        document.getElementById('emailStatsModal').classList.remove('active');
    }

    function renderModal(type) {
        const header = document.getElementById('emModalHeader');
        const title = document.getElementById('emModalTitle');
        const statsBar = document.getElementById('emModalStatsBar');
        const body = document.getElementById('emModalBody');

        header.className = 'em-modal-header ' + type;

        if (type === 'total') {
            title.textContent = '📧 Total Emails';
            statsBar.innerHTML = `
                <div class="em-stats-pill"><strong>${statsData.total_users_with_matches}</strong><span>Total Users</span></div>
                <div class="em-stats-pill"><strong>${statsData.sent.length}</strong><span>Sent</span></div>
                <div class="em-stats-pill"><strong>${statsData.remaining.length}</strong><span>Remaining</span></div>
            `;
            body.innerHTML = `
                <table class="em-table">
                    <thead>
                        <tr>
                            <th>User</th>
                            <th>Status</th>
                            <th>Images</th>
                        </tr>
                    </thead>
                    <tbody>
                        ${statsData.sent.map(u => `
                            <tr>
                                <td><div class="em-name">${u.name}</div><div class="em-email">${u.email || '-'}</div></td>
                                <td><span class="em-badge em-badge-sent">Sent</span></td>
                                <td>${u.images_sent}</td>
                            </tr>
                        `).join('')}
                        ${statsData.remaining.map(u => `
                            <tr>
                                <td><div class="em-name">${u.name}</div><div class="em-email">${u.email || '-'}</div></td>
                                <td><span class="em-badge em-badge-pending">Pending</span></td>
                                <td>${u.matched_images}</td>
                            </tr>
                        `).join('')}
                        ${statsData.sent.length === 0 && statsData.remaining.length === 0 ? '<tr><td colspan="3" style="text-align:center;color:#94a3b8;">No data yet</td></tr>' : ''}
                    </tbody>
                </table>
            `;
        } else if (type === 'sent') {
            title.textContent = '✅ Sent Emails';
            statsBar.innerHTML = `
                <div class="em-stats-pill"><strong>${statsData.sent.length}</strong><span>Users Reached</span></div>
                <div class="em-stats-pill"><strong>${statsData.total_emails_sent}</strong><span>Total Deliveries</span></div>
            `;
            body.innerHTML = statsData.sent.length === 0
                ? '<div class="em-loading">No emails sent yet.</div>'
                : `
                    <table class="em-table">
                        <thead>
                            <tr><th>User</th><th>Images Sent</th><th>Last Sent</th></tr>
                        </thead>
                        <tbody>
                            ${statsData.sent.map(u => `
                                <tr>
                                    <td><div class="em-name">${u.name}</div><div class="em-email">${u.email || '-'}</div></td>
                                    <td>${u.images_sent}</td>
                                    <td><div class="em-time">${u.last_sent_at ? new Date(u.last_sent_at).toLocaleString() : '-'}</div></td>
                                </tr>
                            `).join('')}
                        </tbody>
                    </table>
                `;
        } else if (type === 'remaining') {
            title.textContent = '⏳ Remaining';
            statsBar.innerHTML = `
                <div class="em-stats-pill"><strong>${statsData.remaining.length}</strong><span>Users Pending</span></div>
                <div class="em-stats-pill"><strong>${statsData.total_users_with_matches - statsData.sent.length}</strong><span>Not Delivered</span></div>
            `;
            body.innerHTML = statsData.remaining.length === 0
                ? '<div class="em-loading">All emails have been sent! ✅</div>'
                : `
                    <table class="em-table">
                        <thead>
                            <tr><th>User</th><th>Matched Images</th><th>Reason</th></tr>
                        </thead>
                        <tbody>
                            ${statsData.remaining.map(u => `
                                <tr>
                                    <td><div class="em-name">${u.name}</div><div class="em-email">${u.email || '-'}</div></td>
                                    <td>${u.matched_images}</td>
                                    <td><span class="em-badge em-badge-pending">Email not triggered yet</span></td>
                                </tr>
                            `).join('')}
                        </tbody>
                    </table>
                `;
        }
    }

    // ── Predictive Search ────────────────────────────────────────────────────
    const oldEmailInput = document.getElementById('oldEmail');
    const suggestionsContainer = document.getElementById('emailSuggestions');

    function debounce(func, wait) {
        let timeout;
        return function(...args) { clearTimeout(timeout); timeout = setTimeout(() => func(...args), wait); };
    }

    async function fetchEmailSuggestions(query) {
        if (query.length < 2) { suggestionsContainer.classList.remove('active'); return; }
        try {
            const res = await fetch(`/admin/api/emails/suggestions?q=${encodeURIComponent(query)}`);
            const data = await res.json();
            showSuggestions(data.suggestions || []);
        } catch (e) { console.error(e); }
    }

    function showSuggestions(suggestions) {
        suggestionsContainer.innerHTML = '';
        if (suggestions.length === 0) {
            suggestionsContainer.innerHTML = '<div class="suggestion-no-results">No results found</div>';
        } else {
            suggestions.forEach(s => {
                const div = document.createElement('div');
                div.className = 'suggestion-item';
                div.innerHTML = `
                    <div class="suggestion-name">${s.name}</div>
                    <div class="suggestion-contact">
                        <span>${s.email}</span>
                        ${s.phone ? `<span>| ${s.phone}</span>` : ''}
                    </div>`;
                div.onclick = () => { oldEmailInput.value = s.email; suggestionsContainer.classList.remove('active'); };
                suggestionsContainer.appendChild(div);
            });
        }
        suggestionsContainer.classList.add('active');
    }

    const debouncedSearch = debounce(fetchEmailSuggestions, 300);
    oldEmailInput.addEventListener('input', e => { e.target.value.length >= 2 ? debouncedSearch(e.target.value.trim()) : suggestionsContainer.classList.remove('active'); });
    document.addEventListener('click', e => { if (e.target !== oldEmailInput && !suggestionsContainer.contains(e.target)) suggestionsContainer.classList.remove('active'); });

    // ── Fetch User ────────────────────────────────────────────────────────────
    document.getElementById('fetchUserButton').addEventListener('click', async () => {
        const email = oldEmailInput.value.trim().toLowerCase();
        if (!email) { showFlash('error', 'Please enter an email or name'); return; }
        document.getElementById('fetchUserButton').disabled = true;
        document.getElementById('fetchUserButton').textContent = '...';
        try {
            const res = await fetch(`/admin/api/emails/user-lookup?old_email=${encodeURIComponent(email)}`);
            const data = await res.json();
            if (!res.ok) { showFlash('error', data.error || 'User not found'); return; }
            document.getElementById('emailUserImage').src = data.user.s3_image_url || data.user.image_url || '';
            document.getElementById('emailUserName').textContent = data.user.name || '-';
            document.getElementById('emailUserExistingEmail').textContent = data.user.email || '-';
            document.getElementById('emailUserPhone').textContent = data.user.phone || '-';
            document.getElementById('emailUserCard').classList.remove('hidden');
            suggestionsContainer.classList.remove('active');
            document.getElementById('newEmail').focus();
        } catch (e) { showFlash('error', e.message); }
        finally { document.getElementById('fetchUserButton').disabled = false; document.getElementById('fetchUserButton').textContent = 'Fetch'; }
    });

    // ── Send Email ────────────────────────────────────────────────────────────
    document.getElementById('sendEmailButton').addEventListener('click', async () => {
        const oldEmail = oldEmailInput.value.trim().toLowerCase();
        const newEmail = document.getElementById('newEmail').value.trim().toLowerCase();
        if (!oldEmail) { showFlash('error', 'Please fetch a user first'); return; }
        if (!newEmail) { showFlash('error', 'Please enter an email address'); return; }
        const btn = document.getElementById('sendEmailButton');
        btn.disabled = true; btn.textContent = 'Sending...';
        try {
            const res = await fetch('/admin/api/emails/send', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ old_email: oldEmail, new_email: newEmail })
            });
            const data = await res.json();
            if (!res.ok) {
                showFlash('error', data.error || 'Failed to send email');
                showResponseCard('error', data);
            } else {
                showResponseCard('success', data);
                document.getElementById('newEmail').value = '';
                await loadEmailStats();
            }
        } catch (e) { showFlash('error', e.message); }
        finally { btn.disabled = false; btn.textContent = 'Send'; }
    });

    // ── Response Card ─────────────────────────────────────────────────────────
    function showResponseCard(type, data) {
        const card = document.getElementById('emailResponseCard');
        const inner = document.getElementById('emailResponseInner');

        if (type === 'success') {
            const isResend = data.is_resend;
            inner.className = 'email-response-card success';
            inner.innerHTML = `
                <div class="response-card-header">
                    <span class="response-card-icon">✅</span>
                    <div>
                        <div class="response-card-title">${isResend ? 'Email Resent' : 'Email Sent Successfully'}</div>
                        <div class="response-card-subtitle">${data.message}</div>
                    </div>
                </div>
                <div class="response-card-rows">
                    <div class="response-card-row">
                        <span class="response-card-key">From</span>
                        <span class="response-card-val">${data.old_email}</span>
                    </div>
                    <div class="response-card-row">
                        <span class="response-card-key">Sent To</span>
                        <span class="response-card-val">${data.new_email}</span>
                    </div>
                    <div class="response-card-row">
                        <span class="response-card-key">Images Logged</span>
                        <span class="response-card-val">${data.logged_images ?? 0}</span>
                    </div>
                    <div class="response-card-row">
                        <span class="response-card-key">Type</span>
                        <span class="response-card-badge ${isResend ? 'badge-resend' : 'badge-new'}">${isResend ? 'Resend' : 'New Send'}</span>
                    </div>
                </div>`;
        } else {
            inner.className = 'email-response-card error';
            inner.innerHTML = `
                <div class="response-card-header">
                    <span class="response-card-icon">❌</span>
                    <div>
                        <div class="response-card-title">Failed to Send</div>
                        <div class="response-card-subtitle">${data.error || 'An unexpected error occurred'}</div>
                    </div>
                </div>`;
        }
        card.style.display = 'block';
    }

    // ── Flash ─────────────────────────────────────────────────────────────────
    function showFlash(category, message) {
        const flash = document.createElement('div');
        flash.className = `flash ${category}`;
        flash.innerHTML = `${message} <button class="flash-close" onclick="this.parentElement.remove()">&times;</button>`;
        (document.querySelector('.flash-container') || document.body).appendChild(flash);
        setTimeout(() => { if (flash.parentElement) flash.remove(); }, 5000);
    }

    // ── Modal backdrop ────────────────────────────────────────────────────────
    document.getElementById('emailStatsModal').addEventListener('click', function(e) {
        if (e.target === this) closeEmailModal();
    });

    // Enter key
    oldEmailInput.addEventListener('keypress', e => { if (e.key === 'Enter') document.getElementById('fetchUserButton').click(); });
    document.getElementById('newEmail').addEventListener('keypress', e => { if (e.key === 'Enter') document.getElementById('sendEmailButton').click(); });

    // Load stats on page load
    window.onload = loadEmailStats;
</script>
{% endblock %}