<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Podcast Pile - Admin Dashboard</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background: #f5f5f5;
            color: #333;
            line-height: 1.6;
        }

        .container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 20px;
        }

        header {
            background: #2c3e50;
            color: white;
            padding: 20px 0;
            margin-bottom: 30px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        header h1 {
            font-size: 28px;
            font-weight: 600;
        }

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

        .stat-card {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            transition: transform 0.2s;
        }

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

        .stat-card h3 {
            font-size: 14px;
            color: #666;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            margin-bottom: 10px;
        }

        .stat-card .value {
            font-size: 36px;
            font-weight: 700;
            color: #2c3e50;
        }

        .stat-card.pending .value { color: #f39c12; }
        .stat-card.processing .value { color: #3498db; }
        .stat-card.completed .value { color: #27ae60; }
        .stat-card.failed .value { color: #e74c3c; }

        .jobs-section {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        .jobs-section h2 {
            margin-bottom: 20px;
            color: #2c3e50;
            font-size: 22px;
        }

        .jobs-table {
            width: 100%;
            border-collapse: collapse;
        }

        .jobs-table th {
            background: #ecf0f1;
            padding: 12px;
            text-align: left;
            font-weight: 600;
            color: #2c3e50;
            border-bottom: 2px solid #bdc3c7;
        }

        .jobs-table td {
            padding: 12px;
            border-bottom: 1px solid #ecf0f1;
        }

        .jobs-table tr:hover {
            background: #f8f9fa;
        }

        .status-badge {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 600;
            text-transform: uppercase;
        }

        .status-pending { background: #fff3cd; color: #856404; }
        .status-assigned { background: #d1ecf1; color: #0c5460; }
        .status-processing { background: #cce5ff; color: #004085; }
        .status-completed { background: #d4edda; color: #155724; }
        .status-failed { background: #f8d7da; color: #721c24; }
        .status-expired { background: #e2e3e5; color: #383d41; }

        .url-cell {
            max-width: 400px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

        .timestamp {
            color: #666;
            font-size: 14px;
        }

        .refresh-notice {
            text-align: center;
            color: #666;
            margin-top: 20px;
            font-size: 14px;
        }

        .worker-count {
            background: #3498db;
            color: white;
            padding: 4px 12px;
            border-radius: 12px;
            font-size: 14px;
            font-weight: 600;
        }

        .charts-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .chart-container {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            position: relative;
            height: 350px;
        }

        .chart-container h3 {
            margin-bottom: 15px;
            color: #2c3e50;
            font-size: 18px;
        }

        .chart-canvas-wrapper {
            position: relative;
            height: calc(100% - 45px);
        }
    </style>
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
    <script>
        let charts = {};

        async function loadChartData() {
            try {
                const response = await fetch('/api/charts/data');
                const data = await response.json();
                updateCharts(data);
            } catch (error) {
                console.error('Error loading chart data:', error);
            }
        }

        function updateCharts(data) {
            // Throughput chart
            if (charts.throughput) {
                charts.throughput.data.labels = data.throughput.labels;
                charts.throughput.data.datasets[0].data = data.throughput.data;
                charts.throughput.update('none');
            }

            // Worker performance chart
            if (charts.workers) {
                charts.workers.data.labels = data.workers.labels;
                charts.workers.data.datasets[0].data = data.workers.data;
                charts.workers.update('none');
            }

            // Processing times chart
            if (charts.processingTimes) {
                charts.processingTimes.data.labels = data.processing_times.labels;
                charts.processingTimes.data.datasets[0].data = data.processing_times.data;
                charts.processingTimes.update('none');
            }

            // Status distribution chart
            if (charts.statusDist) {
                charts.statusDist.data.labels = Object.keys(data.status_distribution);
                charts.statusDist.data.datasets[0].data = Object.values(data.status_distribution);
                charts.statusDist.update('none');
            }

            // Update avg time display
            const avgTimeEl = document.getElementById('avg-processing-time');
            if (avgTimeEl) {
                avgTimeEl.textContent = data.avg_processing_time + ' min';
            }
        }

        function initCharts() {
            // Throughput chart
            const throughputCtx = document.getElementById('throughputChart');
            if (throughputCtx) {
                charts.throughput = new Chart(throughputCtx, {
                    type: 'line',
                    data: {
                        labels: [],
                        datasets: [{
                            label: 'Jobs Completed',
                            data: [],
                            borderColor: '#3498db',
                            backgroundColor: 'rgba(52, 152, 219, 0.1)',
                            tension: 0.4,
                            fill: true
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: { display: false }
                        },
                        scales: {
                            y: {
                                beginAtZero: true,
                                ticks: { stepSize: 1 }
                            }
                        }
                    }
                });
            }

            // Worker performance chart
            const workersCtx = document.getElementById('workersChart');
            if (workersCtx) {
                charts.workers = new Chart(workersCtx, {
                    type: 'bar',
                    data: {
                        labels: [],
                        datasets: [{
                            label: 'Jobs Completed',
                            data: [],
                            backgroundColor: '#27ae60'
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: { display: false }
                        },
                        scales: {
                            y: {
                                beginAtZero: true,
                                ticks: { stepSize: 1 }
                            }
                        }
                    }
                });
            }

            // Processing times chart
            const processingCtx = document.getElementById('processingTimesChart');
            if (processingCtx) {
                charts.processingTimes = new Chart(processingCtx, {
                    type: 'line',
                    data: {
                        labels: [],
                        datasets: [{
                            label: 'Processing Time (min)',
                            data: [],
                            borderColor: '#f39c12',
                            backgroundColor: 'rgba(243, 156, 18, 0.1)',
                            tension: 0.4
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: { display: false }
                        },
                        scales: {
                            y: {
                                beginAtZero: true
                            }
                        }
                    }
                });
            }

            // Status distribution chart
            const statusCtx = document.getElementById('statusDistChart');
            if (statusCtx) {
                charts.statusDist = new Chart(statusCtx, {
                    type: 'doughnut',
                    data: {
                        labels: [],
                        datasets: [{
                            data: [],
                            backgroundColor: [
                                '#f39c12', // pending
                                '#3498db', // assigned
                                '#2980b9', // processing
                                '#27ae60', // completed
                                '#e74c3c', // failed
                                '#95a5a6'  // expired
                            ]
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                position: 'right'
                            }
                        }
                    }
                });
            }

            loadChartData();
        }

        // Auto-refresh every 5 seconds
        setInterval(() => {
            loadChartData();
            setTimeout(() => location.reload(), 5000);
        }, 10000);

        // Initialize charts when page loads
        window.addEventListener('load', initCharts);
    </script>
</head>
<body>
    <header>
        <div class="container">
            <h1>Podcast Pile Admin Dashboard</h1>
        </div>
    </header>

    <div class="container">
        <div class="stats-grid">
            <div class="stat-card">
                <h3>Total Jobs</h3>
                <div class="value">{{ stats.total }}</div>
            </div>
            <div class="stat-card pending">
                <h3>Pending</h3>
                <div class="value">{{ stats.pending }}</div>
            </div>
            <div class="stat-card processing">
                <h3>Processing</h3>
                <div class="value">{{ stats.assigned + stats.processing }}</div>
            </div>
            <div class="stat-card completed">
                <h3>Completed</h3>
                <div class="value">{{ stats.completed }}</div>
            </div>
            <div class="stat-card failed">
                <h3>Failed</h3>
                <div class="value">{{ stats.failed }}</div>
            </div>
            <div class="stat-card">
                <h3>Expired</h3>
                <div class="value">{{ stats.expired }}</div>
            </div>
            <div class="stat-card">
                <h3>Active Workers</h3>
                <div class="value">{{ active_workers }}</div>
            </div>
            <div class="stat-card">
                <h3>Avg Processing Time</h3>
                <div class="value" id="avg-processing-time">0 min</div>
            </div>
        </div>

        <div class="charts-grid">
            <div class="chart-container">
                <h3>Throughput (Last 24 Hours)</h3>
                <div class="chart-canvas-wrapper">
                    <canvas id="throughputChart"></canvas>
                </div>
            </div>
            <div class="chart-container">
                <h3>Worker Performance</h3>
                <div class="chart-canvas-wrapper">
                    <canvas id="workersChart"></canvas>
                </div>
            </div>
            <div class="chart-container">
                <h3>Processing Times (Last 20 Jobs)</h3>
                <div class="chart-canvas-wrapper">
                    <canvas id="processingTimesChart"></canvas>
                </div>
            </div>
            <div class="chart-container">
                <h3>Status Distribution</h3>
                <div class="chart-canvas-wrapper">
                    <canvas id="statusDistChart"></canvas>
                </div>
            </div>
        </div>

        <div class="jobs-section">
            <h2>Recent Jobs <a href="/jobs" style="font-size: 14px; font-weight: normal; color: #3498db; text-decoration: none; margin-left: 10px;">View All &rarr;</a></h2>
            <table class="jobs-table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Episode URL</th>
                        <th>Status</th>
                        <th>Worker</th>
                        <th>Worker IP</th>
                        <th>Created</th>
                        <th>Completed</th>
                    </tr>
                </thead>
                <tbody>
                    {% for job in recent_jobs %}
                    <tr>
                        <td><strong><a href="/jobs/{{ job.id }}" style="color: #3498db; text-decoration: none;">#{{ job.id }}</a></strong></td>
                        <td class="url-cell" title="{{ job.episode_url }}">{{ job.episode_url }}</td>
                        <td>
                            <span class="status-badge status-{{ job.status.value }}">
                                {{ job.status.value }}
                            </span>
                        </td>
                        <td>{{ job.worker_id or '-' }}</td>
                        <td>{{ job.worker_ip or '-' }}</td>
                        <td class="timestamp">{{ job.created_at.strftime('%Y-%m-%d %H:%M:%S') }}</td>
                        <td class="timestamp">
                            {{ job.completed_at.strftime('%Y-%m-%d %H:%M:%S') if job.completed_at else '-' }}
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
            <div class="refresh-notice">
                Auto-refreshing every 5 seconds...
            </div>
        </div>
    </div>
</body>
</html>
