<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Error Log - MySQL to Sheets Sync</title>
    <style>
        :root {
            --primary: #2563eb;
            --primary-hover: #1d4ed8;
            --success: #16a34a;
            --error: #dc2626;
            --warning: #ca8a04;
            --bg: #f8fafc;
            --card-bg: #ffffff;
            --border: #e2e8f0;
            --text: #1e293b;
            --text-muted: #64748b;
        }

        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: var(--bg);
            color: var(--text);
            line-height: 1.5;
            padding: 2rem;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
        }

        header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 2rem;
        }

        h1 {
            font-size: 1.5rem;
            font-weight: 600;
        }

        .nav-links {
            display: flex;
            gap: 1rem;
        }

        .nav-links a {
            color: var(--primary);
            text-decoration: none;
            font-size: 0.875rem;
        }

        .nav-links a:hover {
            text-decoration: underline;
        }

        .version {
            color: var(--text-muted);
            font-size: 0.875rem;
        }

        .card {
            background: var(--card-bg);
            border: 1px solid var(--border);
            border-radius: 0.5rem;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
        }

        .card h2 {
            font-size: 1.125rem;
            font-weight: 600;
            margin-bottom: 1rem;
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1rem;
            margin-bottom: 1.5rem;
        }

        .stat-card {
            background: var(--card-bg);
            border: 1px solid var(--border);
            border-radius: 0.5rem;
            padding: 1rem;
            text-align: center;
        }

        .stat-card .value {
            font-size: 2rem;
            font-weight: 700;
            color: var(--error);
        }

        .stat-card .label {
            font-size: 0.875rem;
            color: var(--text-muted);
        }

        .filters {
            display: flex;
            gap: 1rem;
            margin-bottom: 1rem;
            flex-wrap: wrap;
        }

        .filters select, .filters input {
            padding: 0.5rem;
            border: 1px solid var(--border);
            border-radius: 0.375rem;
            font-size: 0.875rem;
        }

        .btn {
            display: inline-block;
            padding: 0.5rem 1rem;
            background: var(--primary);
            color: white;
            border: none;
            border-radius: 0.375rem;
            font-size: 0.875rem;
            cursor: pointer;
            text-decoration: none;
        }

        .btn:hover {
            background: var(--primary-hover);
        }

        .btn-secondary {
            background: var(--card-bg);
            color: var(--text);
            border: 1px solid var(--border);
        }

        .btn-secondary:hover {
            background: var(--bg);
        }

        table {
            width: 100%;
            border-collapse: collapse;
            font-size: 0.875rem;
        }

        th, td {
            padding: 0.75rem;
            text-align: left;
            border-bottom: 1px solid var(--border);
        }

        th {
            font-weight: 600;
            background: var(--bg);
        }

        .badge {
            display: inline-block;
            padding: 0.125rem 0.5rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 500;
        }

        .badge-error {
            background: #fef2f2;
            color: var(--error);
        }

        .badge-transient {
            background: #fefce8;
            color: var(--warning);
        }

        .badge-permanent {
            background: #fef2f2;
            color: var(--error);
        }

        .badge-config {
            background: #eff6ff;
            color: var(--primary);
        }

        .badge-permission {
            background: #faf5ff;
            color: #7c3aed;
        }

        .badge-quota {
            background: #fff7ed;
            color: #c2410c;
        }

        .error-details {
            display: none;
            background: var(--bg);
            padding: 1rem;
            margin-top: 0.5rem;
            border-radius: 0.375rem;
        }

        .error-details.show {
            display: block;
        }

        .error-row {
            cursor: pointer;
        }

        .error-row:hover {
            background: var(--bg);
        }

        .remediation {
            background: #f0fdf4;
            border-left: 3px solid var(--success);
            padding: 0.75rem;
            margin-top: 0.5rem;
            font-size: 0.875rem;
        }

        .empty-state {
            text-align: center;
            padding: 3rem;
            color: var(--text-muted);
        }

        .loading {
            text-align: center;
            padding: 2rem;
            color: var(--text-muted);
        }

        .code {
            font-family: monospace;
            background: var(--bg);
            padding: 0.125rem 0.375rem;
            border-radius: 0.25rem;
            font-size: 0.8125rem;
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <div>
                <h1>Error Log</h1>
                <span class="version">v{{ version }}</span>
            </div>
            <div class="nav-links">
                <a href="/">Dashboard</a>
                <a href="/health">Health</a>
                <a href="/schedules">Schedules</a>
            </div>
        </header>

        <div class="stats-grid" id="stats-grid">
            <div class="stat-card">
                <div class="value" id="total-errors">-</div>
                <div class="label">Errors (24h)</div>
            </div>
            <div class="stat-card">
                <div class="value" id="transient-errors">-</div>
                <div class="label">Transient</div>
            </div>
            <div class="stat-card">
                <div class="value" id="permanent-errors">-</div>
                <div class="label">Permanent</div>
            </div>
            <div class="stat-card">
                <div class="value" id="top-error">-</div>
                <div class="label">Top Error Code</div>
            </div>
        </div>

        <div class="card">
            <h2>Error Log</h2>

            <div class="filters">
                <select id="filter-category">
                    <option value="">All Categories</option>
                    <option value="transient">Transient</option>
                    <option value="permanent">Permanent</option>
                    <option value="config">Configuration</option>
                    <option value="permission">Permission</option>
                    <option value="quota">Quota</option>
                </select>
                <select id="filter-hours">
                    <option value="1">Last 1 hour</option>
                    <option value="6">Last 6 hours</option>
                    <option value="24" selected>Last 24 hours</option>
                    <option value="168">Last 7 days</option>
                </select>
                <button class="btn btn-secondary" onclick="loadErrors()">Refresh</button>
            </div>

            <div id="errors-loading" class="loading">Loading errors...</div>
            <div id="errors-empty" class="empty-state" style="display: none;">
                No errors in the selected time period.
            </div>

            <table id="errors-table" style="display: none;">
                <thead>
                    <tr>
                        <th>Time</th>
                        <th>Error Code</th>
                        <th>Category</th>
                        <th>Message</th>
                    </tr>
                </thead>
                <tbody id="errors-body">
                </tbody>
            </table>
        </div>
    </div>

    <script>
        let errorsData = [];

        async function loadStats() {
            try {
                const response = await fetch('/api/errors/stats');
                const data = await response.json();

                document.getElementById('total-errors').textContent = data.total_errors_24h || 0;
                document.getElementById('transient-errors').textContent =
                    data.errors_by_category?.transient || 0;
                document.getElementById('permanent-errors').textContent =
                    data.errors_by_category?.permanent || 0;

                if (data.top_error_codes && data.top_error_codes.length > 0) {
                    document.getElementById('top-error').textContent =
                        data.top_error_codes[0].code;
                } else {
                    document.getElementById('top-error').textContent = '-';
                }
            } catch (error) {
                console.error('Failed to load stats:', error);
            }
        }

        async function loadErrors() {
            const category = document.getElementById('filter-category').value;
            const hours = document.getElementById('filter-hours').value;

            document.getElementById('errors-loading').style.display = 'block';
            document.getElementById('errors-table').style.display = 'none';
            document.getElementById('errors-empty').style.display = 'none';

            try {
                let url = `/api/errors?hours=${hours}`;
                if (category) {
                    url += `&category=${category}`;
                }

                const response = await fetch(url);
                const data = await response.json();
                errorsData = data.errors || [];

                document.getElementById('errors-loading').style.display = 'none';

                if (errorsData.length === 0) {
                    document.getElementById('errors-empty').style.display = 'block';
                    return;
                }

                document.getElementById('errors-table').style.display = 'table';
                renderErrors();
            } catch (error) {
                console.error('Failed to load errors:', error);
                document.getElementById('errors-loading').textContent = 'Failed to load errors';
            }
        }

        function renderErrors() {
            const tbody = document.getElementById('errors-body');
            tbody.innerHTML = '';

            errorsData.forEach((error, index) => {
                const tr = document.createElement('tr');
                tr.className = 'error-row';
                tr.onclick = () => toggleDetails(index);

                const timestamp = new Date(error.timestamp).toLocaleString();
                const categoryClass = getCategoryClass(error.error_category);

                tr.innerHTML = `
                    <td>${timestamp}</td>
                    <td><span class="code">${error.error_code || '-'}</span></td>
                    <td><span class="badge ${categoryClass}">${error.error_category || '-'}</span></td>
                    <td>${escapeHtml(error.message || 'Unknown error')}</td>
                `;
                tbody.appendChild(tr);

                // Details row
                const detailsRow = document.createElement('tr');
                detailsRow.id = `details-${index}`;
                detailsRow.innerHTML = `
                    <td colspan="4">
                        <div class="error-details" id="details-content-${index}">
                            <strong>Sheet:</strong> ${error.sheet_id || '-'} / ${error.worksheet || '-'}<br>
                            <strong>Error Code:</strong> ${error.error_code || '-'}<br>
                            ${error.remediation ? `<div class="remediation"><strong>Remediation:</strong> ${escapeHtml(error.remediation)}</div>` : ''}
                        </div>
                    </td>
                `;
                tbody.appendChild(detailsRow);
            });
        }

        function toggleDetails(index) {
            const details = document.getElementById(`details-content-${index}`);
            details.classList.toggle('show');
        }

        function getCategoryClass(category) {
            switch (category) {
                case 'transient': return 'badge-transient';
                case 'permanent': return 'badge-permanent';
                case 'config': return 'badge-config';
                case 'permission': return 'badge-permission';
                case 'quota': return 'badge-quota';
                default: return 'badge-error';
            }
        }

        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }

        // Initial load
        loadStats();
        loadErrors();

        // Event listeners for filters
        document.getElementById('filter-category').addEventListener('change', loadErrors);
        document.getElementById('filter-hours').addEventListener('change', loadErrors);
    </script>
</body>
</html>
