<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard - Simple Analytics</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: #0f0f0f;
            color: #e0e0e0;
        }
        .sidebar {
            position: fixed;
            left: 0; top: 0; bottom: 0;
            width: 260px;
            background: #1a1a1a;
            border-right: 1px solid #2a2a2a;
            padding: 24px 0;
            overflow-y: auto;
        }
        .sidebar h2 {
            font-size: 18px;
            padding: 0 24px 16px;
            color: #fff;
            border-bottom: 1px solid #333;
            margin-bottom: 12px;
        }
        .domain-item {
            padding: 10px 24px;
            cursor: pointer;
            font-size: 14px;
            color: #aaa;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .domain-item:hover { background: #252525; color: #fff; }
        .domain-item.active { background: #252525; color: #4a9eff; }
        .domain-item .count { font-size: 12px; color: #666; }
        .domain-item.active .count { color: #4a9eff; }
        .main {
            margin-left: 260px;
            padding: 32px;
        }
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 32px;
        }
        .header h1 { font-size: 24px; color: #fff; }
        .date-picker {
            display: flex;
            gap: 8px;
        }
        .date-btn {
            padding: 8px 16px;
            background: #1a1a1a;
            border: 1px solid #333;
            border-radius: 6px;
            color: #aaa;
            cursor: pointer;
            font-size: 13px;
        }
        .date-btn:hover { border-color: #4a9eff; color: #fff; }
        .date-btn.active { background: #4a9eff; color: #fff; border-color: #4a9eff; }
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 16px;
            margin-bottom: 32px;
        }
        .stat-card {
            background: #1a1a1a;
            border: 1px solid #2a2a2a;
            border-radius: 12px;
            padding: 24px;
        }
        .stat-card .label {
            font-size: 13px;
            color: #888;
            margin-bottom: 8px;
        }
        .stat-card .value {
            font-size: 32px;
            font-weight: 700;
            color: #fff;
        }
        .chart-container {
            background: #1a1a1a;
            border: 1px solid #2a2a2a;
            border-radius: 12px;
            padding: 24px;
            margin-bottom: 24px;
        }
        .chart-container h3 {
            font-size: 16px;
            margin-bottom: 16px;
            color: #fff;
        }
        .chart-container canvas {
            height: 250px;
        }
        .data-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 24px;
        }
        .data-table {
            background: #1a1a1a;
            border: 1px solid #2a2a2a;
            border-radius: 12px;
            padding: 24px;
        }
        .data-table h3 {
            font-size: 16px;
            margin-bottom: 16px;
            color: #fff;
        }
        .data-table table {
            width: 100%;
            border-collapse: collapse;
        }
        .data-table td {
            padding: 8px 0;
            font-size: 14px;
            border-bottom: 1px solid #2a2a2a;
        }
        .data-table td:first-child { color: #ccc; }
        .data-table td:last-child {
            text-align: right;
            color: #4a9eff;
            font-weight: 600;
        }
        .data-table tr:last-child td { border-bottom: none; }
        .script-box {
            background: #1a1a1a;
            border: 1px solid #2a2a2a;
            border-radius: 12px;
            padding: 24px;
            margin-top: 24px;
        }
        .script-box h3 { font-size: 16px; margin-bottom: 16px; color: #fff; }
        .script-box code {
            display: block;
            background: #0f0f0f;
            padding: 16px;
            border-radius: 8px;
            font-family: 'Monaco', 'Consolas', monospace;
            font-size: 13px;
            color: #4a9eff;
            word-break: break-all;
        }
        .logout {
            padding: 12px 24px;
            color: #888;
            font-size: 13px;
            cursor: pointer;
            border-top: 1px solid #333;
            margin-top: 16px;
        }
        .logout:hover { color: #ff6b6b; }
        @media (max-width: 768px) {
            .sidebar { display: none; }
            .main { margin-left: 0; }
            .stats-grid { grid-template-columns: 1fr; }
            .data-grid { grid-template-columns: 1fr; }
        }
    </style>
</head>
<body>
    <div class="sidebar">
        <h2>📊 Domains</h2>
        <div id="domain-list"></div>
        <div class="logout" onclick="document.cookie='auth=; path=/; max-age=0';window.location='/login'">
            Sign Out
        </div>
    </div>

    <div class="main">
        <div class="header">
            <h1 id="dashboard-title">All Domains</h1>
            <div class="date-picker">
                <button class="date-btn" data-days="7" onclick="setDays(7)">7 days</button>
                <button class="date-btn active" data-days="30" onclick="setDays(30)">30 days</button>
                <button class="date-btn" data-days="90" onclick="setDays(90)">90 days</button>
                <button class="date-btn" data-days="365" onclick="setDays(365)">1 year</button>
            </div>
        </div>

        <div class="stats-grid">
            <div class="stat-card">
                <div class="label">Total Visits</div>
                <div class="value" id="total-visits">-</div>
            </div>
            <div class="stat-card">
                <div class="label">Unique Visitors</div>
                <div class="value" id="unique-visitors">-</div>
            </div>
            <div class="stat-card">
                <div class="label">Avg Daily</div>
                <div class="value" id="avg-daily">-</div>
            </div>
        </div>

        <div class="chart-container">
            <h3>Visits Over Time</h3>
            <canvas id="visits-chart"></canvas>
        </div>

        <div class="data-grid">
            <div class="data-table">
                <h3>Top Pages</h3>
                <table id="pages-table"><tr><td colspan="2">Loading...</td></tr></table>
            </div>
            <div class="data-table">
                <h3>Top Referrers</h3>
                <table id="referrers-table"><tr><td colspan="2">Loading...</td></tr></table>
            </div>
            <div class="data-table">
                <h3>Browsers</h3>
                <table id="browsers-table"><tr><td colspan="2">Loading...</td></tr></table>
            </div>
            <div class="data-table">
                <h3>Devices</h3>
                <table id="devices-table"><tr><td colspan="2">Loading...</td></tr></table>
            </div>
        </div>

        <div class="script-box">
            <h3>Install on Your Site</h3>
            <code id="install-script">Loading...</code>
        </div>
    </div>

    <script>
        let currentDays = 30;
        let currentDomain = null;
        let visitsChart = null;

        async function loadDomains() {
            const res = await fetch('/api/domains');
            const domains = await res.json();
            const list = document.getElementById('domain-list');
            list.innerHTML = domains.map(d => `
                <div class="domain-item ${d.domain === (currentDomain || '') ? 'active' : ''}"
                     onclick="selectDomain('${d.domain.replace(/'/g, "\\'")}')">
                    <span>${d.domain}</span>
                    <span class="count">${d.total_visits || 0}</span>
                </div>
            `).join('');
        }

        function selectDomain(domain) {
            currentDomain = domain;
            loadDomains();
            loadStats();
        }

        function setDays(days) {
            currentDays = days;
            document.querySelectorAll('.date-btn').forEach(b => {
                b.classList.toggle('active', parseInt(b.dataset.days) === days);
            });
            loadStats();
        }

        async function loadStats() {
            const params = new URLSearchParams({ days: currentDays });
            if (currentDomain) params.set('domain', currentDomain);

            const res = await fetch(`/api/stats?${params}`);
            const data = await res.json();

            document.getElementById('dashboard-title').textContent =
                currentDomain || 'All Domains';
            document.getElementById('total-visits').textContent =
                data.total_visits.toLocaleString();
            document.getElementById('unique-visitors').textContent =
                data.unique_visitors.toLocaleString();
            document.getElementById('avg-daily').textContent =
                Math.round(data.total_visits / currentDays).toLocaleString();

            // Update chart
            updateChart(data.daily);

            // Update tables
            updateTable('pages-table', data.pages, 'page', (v) => {
                try { return new URL(v).pathname.split('/')[1] || '/'; }
                catch { return v; }
            });
            updateTable('referrers-table', data.referrers, 'referrer', (v) => {
                try { return new URL(v).hostname; }
                catch { return v; }
            });
            updateTable('browsers-table', data.browsers, 'browser');
            updateTable('devices-table', data.devices, 'device');

            // Update install script
            const host = window.location.host;
            document.getElementById('install-script').textContent =
                `<script src="https://${host}/beacon.js"><\/script>`;
        }

        function updateTable(id, rows, labelKey, transform = null) {
            const table = document.getElementById(id);
            if (rows.length === 0) {
                table.innerHTML = '<tr><td colspan="2">No data yet</td></tr>';
                return;
            }
            table.innerHTML = rows.map(r => {
                const label = transform ? transform(r[labelKey]) : r[labelKey];
                return `<tr><td>${label}</td><td>${r.cnt}</td></tr>`;
            }).join('');
        }

        function updateChart(dailyData) {
            const ctx = document.getElementById('visits-chart').getContext('2d');

            if (visitsChart) visitsChart.destroy();

            const labels = dailyData.map(d => d.day);
            const values = dailyData.map(d => d.cnt);

            visitsChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: labels,
                    datasets: [{
                        label: 'Visits',
                        data: values,
                        borderColor: '#4a9eff',
                        backgroundColor: 'rgba(74, 158, 255, 0.1)',
                        fill: true,
                        tension: 0.3,
                        pointRadius: 2,
                        pointHoverRadius: 5,
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: { display: false },
                        tooltip: {
                            backgroundColor: '#1a1a1a',
                            borderColor: '#333',
                            borderWidth: 1,
                            titleColor: '#fff',
                            bodyColor: '#ccc',
                        }
                    },
                    scales: {
                        x: {
                            grid: { color: 'rgba(255,255,255,0.05)' },
                            ticks: { color: '#666', maxTicksLimit: 10 }
                        },
                        y: {
                            grid: { color: 'rgba(255,255,255,0.05)' },
                            ticks: { color: '#666' },
                            beginAtZero: true
                        }
                    }
                }
            });
        }

        // Initial load
        loadDomains();
        loadStats();
    </script>
</body>
</html>