{% extends "base.html" %}

{% block title %}Admin Dashboard{% endblock %}
{% block page_id %}dashboard{% endblock %}
{% block page_title %}Dashboard{% endblock %}
{% block eyebrow %}Overview{% endblock %}

{% block head %}
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        /* Clickable stat cards */
        .stat-card.clickable {
            cursor: pointer;
            transition: all 0.3s ease;
        }
        .stat-card.clickable:hover {
            transform: translateY(-6px);
            box-shadow: 0 20px 40px rgba(44, 125, 160, 0.15);
            border-color: rgba(44, 125, 160, 0.3);
        }
        .stat-card.clickable.warning:hover {
            box-shadow: 0 20px 40px rgba(239, 68, 68, 0.15);
            border-color: rgba(239, 68, 68, 0.3);
        }
        .stat-card.clickable.warning strong { color: #ef4444; }

        /* Dashboard layout */
        .dashboard-layout {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 16px;
        }

        /* Day-wise cards — same style as stat cards above */
        .daywise-grid {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 16px;
        }

        .daywise-card {
            background: #ffffff;
            border-radius: 16px;
            border: 1px solid #e2e8f0;
            padding: 20px 24px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
            transition: all 0.25s ease;
        }

        .daywise-card:hover {
            transform: translateY(-4px);
            box-shadow: 0 8px 24px rgba(44,125,160,0.12);
            border-color: #bfdbfe;
        }

        .daywise-card-label {
            display: block;
            font-size: 11px;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 0.6px;
            color: #64748b;
            margin-bottom: 8px;
        }

        .daywise-card-count {
            display: block;
            font-size: 36px;
            font-weight: 800;
            color: #0f172a;
            line-height: 1;
            margin-bottom: 6px;
        }

        .daywise-card-date {
            font-size: 12px;
            color: #94a3b8;
            margin-bottom: 12px;
            display: block;
        }

        .daywise-mini-stats {
            display: flex;
            gap: 12px;
            border-top: 1px solid #f1f5f9;
            padding-top: 10px;
            margin-top: 4px;
        }

        .daywise-mini-stat {
            font-size: 12px;
            color: #64748b;
        }

        .daywise-mini-stat strong {
            font-weight: 700;
            color: #0f172a;
        }

        .daywise-mini-stat.sent strong { color: #16a34a; }
        .daywise-mini-stat.remaining strong { color: #ea580c; }

        @media (max-width: 1100px) {
            .dashboard-layout { grid-template-columns: 1fr; }
            .daywise-grid { grid-template-columns: repeat(2, 1fr); }
        }
        @media (max-width: 640px) {
            .daywise-grid { grid-template-columns: 1fr 1fr; }
            .dash-modal-content { max-width: 100%; max-height: 90vh; }
        }
        @media (max-width: 420px) {
            .daywise-grid { grid-template-columns: 1fr; }
        }
        .dash-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;
        }
        .dash-modal.active { display: flex; }

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

        .dash-modal-header {
            padding: 16px 20px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            flex-shrink: 0;
            background: linear-gradient(135deg, #0f2b3d 0%, #1b5e7a 100%);
            border-radius: 18px 18px 0 0;
        }
        .dash-modal-header h3 { margin: 0; color: #ffffff !important; font-size: 16px; font-weight: 700; }
        .dash-modal-close {
            background: rgba(255,255,255,0.15);
            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;
            transition: background 0.2s;
        }
        .dash-modal-close:hover { background: rgba(255,255,255,0.3); }

        /* Email tabs */
        .em-tab-bar {
            display: flex;
            background: #f8fafc;
            border-bottom: 1px solid #e2e8f0;
            flex-shrink: 0;
        }
        .em-tab {
            flex: 1; padding: 14px 8px;
            border: none; background: transparent;
            cursor: pointer;
            display: flex; flex-direction: column; align-items: center; gap: 3px;
            border-bottom: 3px solid transparent;
            margin-bottom: -1px;
            transition: all 0.2s;
        }
        .em-tab:hover { background: #f0f7ff; }
        .em-tab.active { border-bottom-color: #2c7da0; background: #fff; }
        .em-tab.tab-sent.active { border-bottom-color: #16a34a; }
        .em-tab.tab-remaining.active { border-bottom-color: #ea580c; }
        .em-tab-count { font-size: 28px; font-weight: 800; color: #0f172a; line-height: 1; }
        .em-tab.active .em-tab-count { color: #2c7da0; }
        .em-tab.tab-sent.active .em-tab-count { color: #16a34a; }
        .em-tab.tab-remaining.active .em-tab-count { color: #ea580c; }
        .em-tab-label { font-size: 12px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px; color: #64748b; }

        /* Modal table */
        .dash-modal-body { padding: 0; overflow-y: auto; flex: 1; min-height: 300px; }
        .em-table { width: 100%; border-collapse: collapse; font-size: 14px; }
        .em-table th { background: #f1f5f9; padding: 13px 20px; text-align: left; font-weight: 700; font-size: 12px; text-transform: uppercase; letter-spacing: 0.5px; color: #475569; border-bottom: 2px solid #e2e8f0; position: sticky; top: 0; }
        .em-table td { padding: 14px 20px; border-bottom: 1px solid #f1f5f9; vertical-align: middle; }
        .em-table tbody tr:hover { background: #f8fafc; }
        .em-table tbody tr:last-child td { border-bottom: none; }
        .em-name { font-weight: 700; color: #0f172a; font-size: 14px; }
        .em-email { font-size: 13px; color: #64748b; margin-top: 2px; }
        .em-time { font-size: 12px; color: #94a3b8; }
        .em-badge { display: inline-block; padding: 4px 12px; border-radius: 20px; font-size: 12px; font-weight: 700; }
        .em-badge-sent { background: #dcfce7; color: #15803d; }
        .em-badge-pending { background: #ffedd5; color: #ea580c; }
        .em-empty { text-align: center; padding: 40px; color: #94a3b8; font-size: 14px; }

        /* Responsive */
        @media (max-width: 1100px) {
            .dashboard-layout { grid-template-columns: 1fr; }
            .day-events-grid { grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); }
        }
        @media (max-width: 640px) {
            .day-events-grid { grid-template-columns: 1fr; }
            .dash-modal-content { max-width: 100%; max-height: 90vh; }
        }
    </style>
{% endblock %}

{% block content %}
    <section class="hero-panel glass-card">
        <div>
            <p class="hero-kicker">Live metrics</p>
            <h2>{{ event_data.event_name if event_data else "No Event Configured" }}</h2>
            <p class="hero-copy">{{ event_data.event_subtitle if event_data else "Please configure event details in Event Config" }}</p>
        </div>
        <div class="hero-assets">
            {% if site_assets.logo %}
                <img src="{{ site_assets.logo.image_path }}" alt="Logo">
            {% endif %}
        </div>
    </section>

    <!-- Stat Cards -->
    <section class="stats-grid">
        <article class="stat-card glass-card">
            <span>Total Registered Users</span>
            <strong>{{ stats.total_visitors }}</strong>
        </article>
        <article class="stat-card glass-card">
            <span>Face Registered Users</span>
            <strong>{{ stats.total_registered_users }}</strong>
        </article>
        <article class="stat-card glass-card clickable warning" onclick="openRemainingModal()">
            <span>Remaining Registrations</span>
            <strong>{{ stats.total_visitors - stats.total_registered_users }}</strong>
            <p style="font-size:12px;color:#94a3b8;margin-top:4px;">Click to view list</p>
        </article>
        <article class="stat-card glass-card clickable" onclick="openEmailStatsModal()">
            <span>Total Emails Sent</span>
            <strong>{{ stats.total_emails_sent }}</strong>
            <p style="font-size:12px;color:#94a3b8;margin-top:4px;">Click to view details</p>
        </article>
    </section>

    <!-- Day-wise Email Stat Cards (same row style as above) -->
    <section class="stats-grid" id="daywiseCards" style="display:none;">
        <!-- filled by JS -->
    </section>

    <!-- Chart + Assets -->
    <section class="dashboard-layout">
        <article class="glass-card panel-card">
            <div class="panel-header">
                <div>
                    <p class="eyebrow">Last 7 days</p>
                    <h3>Face Registered Users</h3>
                </div>
            </div>
            <canvas id="dashboardChart" data-chart='{{ chart_data|tojson }}'></canvas>
        </article>

        <article class="glass-card panel-card">
            <div class="panel-header">
                <div>
                    <p class="eyebrow">Assets</p>
                    <h3>Current public visuals</h3>
                </div>
            </div>
            <div class="asset-preview-grid">
                <div class="mini-asset">
                    <span>Logo</span>
                    {% if site_assets.logo %}<img src="{{ site_assets.logo.image_path }}" alt="Logo">{% else %}<div class="mini-asset empty">No logo</div>{% endif %}
                </div>
                <div class="mini-asset">
                    <span>Header</span>
                    {% if site_assets.header %}<img src="{{ site_assets.header.image_path }}" alt="Header">{% else %}<div class="mini-asset empty">No header</div>{% endif %}
                </div>
                <div class="mini-asset">
                    <span>Footer</span>
                    {% if site_assets.footer %}<img src="{{ site_assets.footer.image_path }}" alt="Footer">{% else %}<div class="mini-asset empty">No footer</div>{% endif %}
                </div>
            </div>
        </article>
    </section>

    <!-- REMAINING USERS MODAL -->
    <div id="remainingModal" class="dash-modal">
        <div class="dash-modal-content">
            <div class="dash-modal-header">
                <h3>📋 Remaining Registrations</h3>
                <button class="dash-modal-close" onclick="closeModal('remainingModal')">&times;</button>
            </div>
            <div class="dash-modal-body">
                <table class="em-table">
                    <thead>
                        <tr><th>Name</th><th>Email</th><th>Mobile</th></tr>
                    </thead>
                    <tbody id="remainingTableBody">
                        <tr><td colspan="3" class="em-empty">Loading...</td></tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- EMAIL STATS MODAL -->
    <div id="emailStatsModal" class="dash-modal">
        <div class="dash-modal-content">
            <div class="dash-modal-header">
                <h3>📧 Email Delivery Details</h3>
                <button class="dash-modal-close" onclick="closeModal('emailStatsModal')">&times;</button>
            </div>
            <div class="em-tab-bar">
                <button class="em-tab active" id="tabTotal" onclick="switchTab('total')">
                    <span class="em-tab-count" id="emCountTotal">—</span>
                    <span class="em-tab-label">Total</span>
                </button>
                <button class="em-tab tab-sent" id="tabSent" onclick="switchTab('sent')">
                    <span class="em-tab-count" id="emCountSent">—</span>
                    <span class="em-tab-label">Sent</span>
                </button>
                <button class="em-tab tab-remaining" id="tabRemaining" onclick="switchTab('remaining')">
                    <span class="em-tab-count" id="emCountRemaining">—</span>
                    <span class="em-tab-label">Remaining</span>
                </button>
            </div>
            <div class="dash-modal-body" id="emModalBody">
                <div class="em-empty">Loading...</div>
            </div>
        </div>
    </div>
{% endblock %}

{% block scripts %}
<script>
    // ── Chart ────────────────────────────────────────────────────────────────
    function initChart() {
        const el = document.getElementById('dashboardChart');
        if (!el) return;
        const data = JSON.parse(el.getAttribute('data-chart'));
        new Chart(el.getContext('2d'), {
            type: 'line',
            data: {
                labels: data.map(d => d.label),
                datasets: [{
                    label: 'Face Registrations',
                    data: data.map(d => d.value),
                    borderColor: '#2c7da0',
                    backgroundColor: 'rgba(44,125,160,0.1)',
                    borderWidth: 2, fill: true, tension: 0.4,
                    pointRadius: 4, pointBackgroundColor: '#2c7da0',
                    pointBorderColor: '#ffffff', pointBorderWidth: 2,
                }]
            },
            options: {
                responsive: true, maintainAspectRatio: true,
                plugins: { legend: { display: false } },
                scales: {
                    y: { beginAtZero: true, ticks: { stepSize: 1 }, grid: { color: 'rgba(0,0,0,0.05)' } },
                    x: { grid: { display: false } }
                }
            }
        });
    }

    // ── Modal helpers ─────────────────────────────────────────────────────────
    function closeModal(id) {
        document.getElementById(id).classList.remove('active');
    }
    document.querySelectorAll('.dash-modal').forEach(m => {
        m.addEventListener('click', e => { if (e.target === m) m.classList.remove('active'); });
    });

    // ── Remaining Registrations Modal ─────────────────────────────────────────
    async function openRemainingModal() {
        document.getElementById('remainingModal').classList.add('active');
        const tbody = document.getElementById('remainingTableBody');
        tbody.innerHTML = '<tr><td colspan="3" class="em-empty">Loading...</td></tr>';
        try {
            const res = await fetch('/admin/api/remaining-visitors');
            const json = await res.json();
            const visitors = json.data || json;          // handle both {data:[]} and plain []
            if (!visitors.length) {
                tbody.innerHTML = '<tr><td colspan="3" class="em-empty">✅ All visitors completed registration</td></tr>';
            } else {
                tbody.innerHTML = visitors.map(v => `
                    <tr>
                        <td><div class="em-name">${v.name}</div></td>
                        <td><div class="em-email">${v.email || '-'}</div></td>
                        <td>${v.mobile_number || '-'}</td>
                    </tr>`).join('');
            }
        } catch (e) {
            tbody.innerHTML = '<tr><td colspan="3" class="em-empty" style="color:#ef4444;">Failed to load data.</td></tr>';
        }
    }

    // ── Email Stats Modal ────────────────────────────────────────────────────
    let emailStats = null;

    async function openEmailStatsModal() {
        document.getElementById('emailStatsModal').classList.add('active');
        document.getElementById('emModalBody').innerHTML = '<div class="em-empty">Loading...</div>';
        if (!emailStats) {
            try {
                const res = await fetch('/admin/api/emails/stats');
                emailStats = await res.json();
                (emailStats.sent || []).forEach(r => {
                    if (r.last_sent_at) r._fmt = new Date(r.last_sent_at).toLocaleString();
                });
            } catch (e) {
                document.getElementById('emModalBody').innerHTML = '<div class="em-empty" style="color:#ef4444;">Failed to load data.</div>';
                return;
            }
        }
        const d = emailStats;
        document.getElementById('emCountTotal').textContent = (d.sent||[]).length + (d.remaining||[]).length;
        document.getElementById('emCountSent').textContent = (d.sent||[]).length;
        document.getElementById('emCountRemaining').textContent = (d.remaining||[]).length;
        switchTab('total');
    }

    function switchTab(tab) {
        ['total','sent','remaining'].forEach(t => {
            document.getElementById('tab' + t[0].toUpperCase() + t.slice(1)).classList.remove('active');
        });
        document.getElementById('tab' + tab[0].toUpperCase() + tab.slice(1)).classList.add('active');

        const d = emailStats;
        const body = document.getElementById('emModalBody');

        if (tab === 'total') {
            const rows = [
                ...(d.sent||[]).map(u=>({...u,status:'sent'})),
                ...(d.remaining||[]).map(u=>({...u,status:'pending'}))
            ];
            body.innerHTML = rows.length ? `
                <table class="em-table">
                    <thead><tr><th>Name</th><th>Email</th><th>Status</th><th>Images</th></tr></thead>
                    <tbody>${rows.map(u=>`
                        <tr>
                            <td><div class="em-name">${u.name}</div></td>
                            <td><div class="em-email">${u.email||'-'}</div></td>
                            <td><span class="em-badge ${u.status==='sent'?'em-badge-sent':'em-badge-pending'}">${u.status==='sent'?'Sent':'Pending'}</span></td>
                            <td>${u.images_sent||u.matched_images||'-'}</td>
                        </tr>`).join('')}
                    </tbody>
                </table>` : '<div class="em-empty">No data yet.</div>';

        } else if (tab === 'sent') {
            const rows = d.sent || [];
            body.innerHTML = rows.length ? `
                <table class="em-table">
                    <thead><tr><th>Name</th><th>Email</th><th>Images</th><th>Last Sent</th></tr></thead>
                    <tbody>${rows.map(u=>`
                        <tr>
                            <td><div class="em-name">${u.name}</div></td>
                            <td><div class="em-email">${u.email||'-'}</div></td>
                            <td>${u.images_sent}</td>
                            <td><div class="em-time">${u._fmt||'-'}</div></td>
                        </tr>`).join('')}
                    </tbody>
                </table>` : '<div class="em-empty">No emails sent yet.</div>';

        } else if (tab === 'remaining') {
            const rows = d.remaining || [];
            body.innerHTML = rows.length ? `
                <table class="em-table">
                    <thead><tr><th>Name</th><th>Email</th><th>Matched Images</th><th>Reason</th></tr></thead>
                    <tbody>${rows.map(u=>`
                        <tr>
                            <td><div class="em-name">${u.name}</div></td>
                            <td><div class="em-email">${u.email||'-'}</div></td>
                            <td>${u.matched_images}</td>
                            <td><span class="em-badge em-badge-pending">Not triggered yet</span></td>
                        </tr>`).join('')}
                    </tbody>
                </table>` : '<div class="em-empty">✅ All emails delivered!</div>';
        }
    }

    // ── Day-wise Cards ────────────────────────────────────────────────────────
    async function loadDaywiseCards() {
        const container = document.getElementById('daywiseCards');
        if (!container) return;

        try {
            const res = await fetch('/admin/api/daywise-email-stats');
            const data = await res.json();

            if (!data.days || data.days.length === 0) {
                container.style.display = 'none';
                return;
            }

            const total = data.total_matched_users || 0;

            container.innerHTML = data.days.map(day => {
                const sent = day.users_reached || 0;       // users who received email on this day
                const remaining = Math.max(0, total - sent); // users who didn't get email on this day

                return `
                <article class="stat-card glass-card">
                    <span>Day ${day.day_num} &nbsp;·&nbsp; ${day.date}</span>
                    <div style="display:grid;grid-template-columns:repeat(3,1fr);gap:8px;margin-top:14px;">
                        <div>
                            <div style="font-size:1.8rem;font-weight:800;color:#0b2b38;line-height:1;">${total}</div>
                            <div style="font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:0.05em;color:#64748b;margin-top:4px;">Total</div>
                        </div>
                        <div>
                            <div style="font-size:1.8rem;font-weight:800;color:#16a34a;line-height:1;">${sent}</div>
                            <div style="font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:0.05em;color:#64748b;margin-top:4px;">Sent</div>
                        </div>
                        <div>
                            <div style="font-size:1.8rem;font-weight:800;color:#ea580c;line-height:1;">${remaining}</div>
                            <div style="font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:0.05em;color:#64748b;margin-top:4px;">Remaining</div>
                        </div>
                    </div>
                </article>`;
            }).join('');

            container.style.display = 'grid';

        } catch (e) {
            console.error('Daywise cards error:', e);
            container.style.display = 'none';
        }
    }

    window.onload = () => {
        initChart();
        loadDaywiseCards();
    };
</script>
{% endblock %}