<?php
/**
 * ============================================
 * FLOWBOT DCI v3.0 - DASHBOARD
 * ============================================
 * Clean, professional dashboard page
 */
declare(strict_types=1);

// Variables from controller (with safe defaults)
$baseUrl = rtrim(dirname($_SERVER['SCRIPT_NAME']), '/\\');
$pageTitle = 'Dashboard';
$currentPage = 'dashboard';

// Stats with safe defaults (cast to numeric to handle string values from database)
$stats = $stats ?? [];
$active = (int)($stats['active'] ?? 0);
$completed = (int)($stats['completed'] ?? 0);
$failed = (int)($stats['failed'] ?? 0);
$today = (int)($stats['today'] ?? 0);
$totalUrls = (int)($stats['total_urls'] ?? 0);
$successRate = (float)($stats['success_rate'] ?? 0);
$avgTime = (float)($stats['avg_processing_time'] ?? 0);

// Other data
$activeProcesses = $activeProcesses ?? [];
$recentActivity = $recentActivity ?? [];
$history = $history ?? ['items' => [], 'total' => 0];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= htmlspecialchars($pageTitle) ?> - Flowb0t DCI v3.0</title>
    <link rel="icon" type="image/svg+xml" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'><rect width='32' height='32' rx='8' fill='%233B82F6'/><path d='M8 10h16M8 16h12M8 22h8' stroke='white' stroke-width='2.5' stroke-linecap='round'/></svg>">
    <link rel="stylesheet" href="<?= $baseUrl ?>/assets/css/v3-styles.css?v=<?= time() ?>">
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js"></script>
</head>
<body>
    <!-- Navigation -->
    <nav class="main-nav">
        <div class="nav-container">
            <div class="nav-brand">
                <a href="<?= $baseUrl ?>/" class="brand-link">
                    <span class="brand-logo">
                        <svg viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <rect width="32" height="32" rx="8" fill="url(#brand-gradient)"/>
                            <path d="M8 10h16M8 16h12M8 22h8" stroke="white" stroke-width="2.5" stroke-linecap="round"/>
                            <circle cx="24" cy="22" r="4" fill="#10B981"/>
                            <defs>
                                <linearGradient id="brand-gradient" x1="0" y1="0" x2="32" y2="32">
                                    <stop stop-color="#3B82F6"/>
                                    <stop offset="1" stop-color="#8B5CF6"/>
                                </linearGradient>
                            </defs>
                        </svg>
                    </span>
                    <span class="brand-text">Flowb0t DCI</span>
                    <span class="brand-version">v3.0</span>
                </a>
            </div>

            <div class="nav-main">
                <a href="<?= $baseUrl ?>/" class="nav-link active">
                    <svg class="nav-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <rect x="3" y="3" width="7" height="7" rx="1"/>
                        <rect x="14" y="3" width="7" height="7" rx="1"/>
                        <rect x="3" y="14" width="7" height="7" rx="1"/>
                        <rect x="14" y="14" width="7" height="7" rx="1"/>
                    </svg>
                    <span>Dashboard</span>
                </a>
                <a href="<?= $baseUrl ?>/new" class="nav-link">
                    <svg class="nav-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <circle cx="12" cy="12" r="9"/>
                        <line x1="12" y1="8" x2="12" y2="16"/>
                        <line x1="8" y1="12" x2="16" y2="12"/>
                    </svg>
                    <span>New Process</span>
                </a>
                <a href="/flowb0t.com/v2/views/crawler-ultimate.php" class="nav-link">
                    <svg class="nav-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <circle cx="11" cy="11" r="8"/>
                        <line x1="21" y1="21" x2="16.65" y2="16.65"/>
                    </svg>
                    <span>Crawler</span>
                </a>
                <a href="<?= $baseUrl ?>/history" class="nav-link">
                    <svg class="nav-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <circle cx="12" cy="12" r="9"/>
                        <polyline points="12,7 12,12 16,14"/>
                    </svg>
                    <span>History</span>
                </a>
            </div>

            <div class="nav-right">
                <a href="<?= $baseUrl ?>/new" class="btn btn-primary btn-sm">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16">
                        <line x1="12" y1="5" x2="12" y2="19"/>
                        <line x1="5" y1="12" x2="19" y2="12"/>
                    </svg>
                    New
                </a>
            </div>
        </div>
    </nav>

    <!-- Main Content -->
    <main class="main-content">
        <!-- Page Header -->
        <div class="page-header">
            <h1 class="page-title">Control Center</h1>
            <p class="page-subtitle">Monitor and manage all URL processing operations</p>
        </div>

        <!-- Stats Grid -->
        <div class="stats-grid">
            <!-- Active Processes -->
            <div class="stat-card stat-card-active">
                <div class="stat-icon">
                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <circle cx="12" cy="12" r="10"/>
                        <polyline points="12 6 12 12 16 14"/>
                    </svg>
                </div>
                <div class="stat-content">
                    <span class="stat-value" id="stat-active"><?= number_format($active) ?></span>
                    <span class="stat-label">Active Processes
                        <?php if ($active > 0): ?>
                        <span class="live-indicator live-sm" title="Auto-updating">
                            <span class="live-dot"></span>
                        </span>
                        <?php endif; ?>
                    </span>
                </div>
            </div>

            <!-- Completed -->
            <div class="stat-card stat-card-success">
                <div class="stat-icon">
                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/>
                        <polyline points="22 4 12 14.01 9 11.01"/>
                    </svg>
                </div>
                <div class="stat-content">
                    <span class="stat-value" id="stat-completed"><?= number_format($completed) ?></span>
                    <span class="stat-label">Completed</span>
                    <div class="stat-trend positive" id="stat-today">+<?= number_format($today) ?> today</div>
                </div>
            </div>

            <!-- Failed -->
            <div class="stat-card stat-card-error">
                <div class="stat-icon">
                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <circle cx="12" cy="12" r="10"/>
                        <line x1="15" y1="9" x2="9" y2="15"/>
                        <line x1="9" y1="9" x2="15" y2="15"/>
                    </svg>
                </div>
                <div class="stat-content">
                    <span class="stat-value"><?= number_format($failed) ?></span>
                    <span class="stat-label">Failed</span>
                </div>
            </div>

            <!-- Total URLs -->
            <div class="stat-card stat-card-total">
                <div class="stat-icon">
                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/>
                        <path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/>
                    </svg>
                </div>
                <div class="stat-content">
                    <span class="stat-value"><?= number_format($totalUrls) ?></span>
                    <span class="stat-label">Total URLs</span>
                    <div class="stat-trend"><?= number_format($successRate, 1) ?>% success rate</div>
                </div>
            </div>
        </div>

        <!-- Dashboard Grid -->
        <div class="dashboard-grid">
            <!-- Main Column -->
            <div class="dashboard-main">
                <!-- Active Processes -->
                <div class="section">
                    <div class="section-header">
                        <h2 class="section-title">
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/>
                            </svg>
                            Active Processes
                        </h2>
                    </div>
                    <div class="section-body">
                        <?php if (empty($activeProcesses)): ?>
                        <div class="empty-state">
                            <svg class="empty-state-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
                                <circle cx="12" cy="12" r="10"/>
                                <path d="M8 12h8M12 8v8"/>
                            </svg>
                            <p class="empty-state-title">No Active Processes</p>
                            <p class="empty-state-text">Start a new process to see it here.</p>
                            <a href="<?= $baseUrl ?>/new" class="btn btn-primary">Start New Process</a>
                        </div>
                        <?php else: ?>
                        <div id="active-processes-list">
                        <?php foreach ($activeProcesses as $process): ?>
                        <div class="card mb-md process-card" data-process-id="<?= htmlspecialchars($process['id']) ?>">
                            <div class="flex justify-between items-center mb-sm">
                                <a href="<?= $baseUrl ?>/process/<?= htmlspecialchars($process['id']) ?>">
                                    <strong>#<?= htmlspecialchars(substr($process['id'], 0, 8)) ?></strong>
                                </a>
                                <span class="badge badge-info" data-field="status"><?= htmlspecialchars($process['status'] ?? 'running') ?></span>
                            </div>
                            <div class="progress mb-sm">
                                <div class="progress-fill" data-field="progress" style="width: <?= $process['progress_percent'] ?? 0 ?>%"></div>
                            </div>
                            <div class="flex justify-between text-muted" style="font-size: 0.8125rem;">
                                <span data-field="urls"><?= number_format((int)($process['processed_urls'] ?? 0)) ?>/<?= number_format((int)($process['total_urls'] ?? 0)) ?> URLs</span>
                                <span data-field="phase">Phase <?= $process['phase'] ?? 0 ?>/4</span>
                            </div>
                        </div>
                        <?php endforeach; ?>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Process History -->
                <div class="section">
                    <div class="section-header">
                        <h2 class="section-title">
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <circle cx="12" cy="12" r="10"/>
                                <polyline points="12,6 12,12 16,14"/>
                            </svg>
                            Process History
                        </h2>
                        <a href="<?= $baseUrl ?>/history" class="btn btn-ghost btn-sm">View All</a>
                    </div>
                    <div class="table-container">
                        <?php if (empty($history['items'])): ?>
                        <div class="empty-state">
                            <p class="empty-state-title">No History Yet</p>
                            <p class="empty-state-text">Completed processes will appear here.</p>
                        </div>
                        <?php else: ?>
                        <table>
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>URLs</th>
                                    <th>Status</th>
                                    <th>Date</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach (array_slice($history['items'], 0, 5) as $item): ?>
                                <tr>
                                    <td>#<?= htmlspecialchars(substr($item['id'], 0, 8)) ?></td>
                                    <td><?= number_format((int)($item['total_urls'] ?? 0)) ?></td>
                                    <td>
                                        <span class="badge badge-<?= $item['status'] === 'completed' ? 'success' : 'error' ?>">
                                            <?= htmlspecialchars($item['status'] ?? 'unknown') ?>
                                        </span>
                                    </td>
                                    <td><?= date('M j, Y', strtotime($item['created_at'] ?? 'now')) ?></td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

                <!-- Charts Section -->
                <div class="section">
                    <div class="section-header">
                        <h2 class="section-title">
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <line x1="18" y1="20" x2="18" y2="10"/>
                                <line x1="12" y1="20" x2="12" y2="4"/>
                                <line x1="6" y1="20" x2="6" y2="14"/>
                            </svg>
                            Analytics Overview
                        </h2>
                    </div>
                    <div class="section-body">
                        <div class="grid-2col gap-lg">
                            <!-- Status Distribution Chart -->
                            <div class="card">
                                <div class="card-body">
                                    <h4 class="text-sm font-medium mb-sm text-muted">Process Status Distribution</h4>
                                    <div style="height: 180px; position: relative;">
                                        <canvas id="statusChart"></canvas>
                                    </div>
                                </div>
                            </div>

                            <!-- Weekly Activity Chart -->
                            <div class="card">
                                <div class="card-body">
                                    <h4 class="text-sm font-medium mb-sm text-muted">URLs Processed (7 days)</h4>
                                    <div style="height: 180px; position: relative;">
                                        <canvas id="weeklyChart"></canvas>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Sidebar -->
            <div class="dashboard-sidebar">
                <!-- Recent Activity -->
                <div class="section">
                    <div class="section-header">
                        <h2 class="section-title">
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <path d="M22 12h-4l-3 9L9 3l-3 9H2"/>
                            </svg>
                            Recent Activity
                        </h2>
                    </div>
                    <div class="section-body">
                        <?php if (empty($recentActivity)): ?>
                        <p class="text-muted text-center">No recent activity</p>
                        <?php else: ?>
                        <ul class="activity-list">
                            <?php foreach (array_slice($recentActivity, 0, 5) as $activity): ?>
                            <li class="activity-item">
                                <div class="activity-icon <?= $activity['severity'] ?? 'info' ?>">
                                    <?= ($activity['severity'] ?? 'info') === 'error' ? '!' : '✓' ?>
                                </div>
                                <div class="activity-content">
                                    <p class="activity-text"><?= htmlspecialchars($activity['message'] ?? '') ?></p>
                                    <span class="activity-time"><?= date('H:i', strtotime($activity['created_at'] ?? 'now')) ?></span>
                                </div>
                            </li>
                            <?php endforeach; ?>
                        </ul>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Performance -->
                <div class="section">
                    <div class="section-header">
                        <h2 class="section-title">
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <line x1="18" y1="20" x2="18" y2="10"/>
                                <line x1="12" y1="20" x2="12" y2="4"/>
                                <line x1="6" y1="20" x2="6" y2="14"/>
                            </svg>
                            Performance
                        </h2>
                    </div>
                    <div class="section-body">
                        <div class="perf-stats">
                            <div class="perf-stat">
                                <span class="perf-label">Success Rate (7 days)</span>
                                <span class="perf-value"><?= number_format($successRate, 1) ?>%</span>
                            </div>
                            <div class="perf-bar">
                                <div class="perf-bar-fill" style="width: <?= min(100, $successRate) ?>%"></div>
                            </div>

                            <div class="perf-stat mt-md">
                                <span class="perf-label">Avg Time/URL</span>
                                <span class="perf-value"><?= number_format($avgTime, 1) ?>s</span>
                            </div>

                            <div class="perf-stat">
                                <span class="perf-label">Total Processed</span>
                                <span class="perf-value"><?= number_format($totalUrls) ?></span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </main>

    <!-- Toast Container -->
    <div id="toastContainer" class="toast-container"></div>

    <script src="<?= $baseUrl ?>/assets/js/app.js?v=<?= time() ?>"></script>
    <script src="<?= $baseUrl ?>/assets/js/realtime.js?v=<?= time() ?>"></script>
    <script>
    // ============================================
    // DASHBOARD AUTO-REFRESH
    // ============================================
    const REFRESH_INTERVAL = 3000;
    let hasActiveProcesses = <?= $active > 0 ? 'true' : 'false' ?>;
    let refreshTimer = null;

    async function refreshDashboard() {
        try {
            // Fetch stats
            const statsResponse = await fetch('<?= $baseUrl ?>/api/v1/dashboard/stats');
            if (statsResponse.ok) {
                const statsData = await statsResponse.json();
                if (statsData.success) {
                    updateStats(statsData.data);
                }
            }

            // Fetch active processes
            const activeResponse = await fetch('<?= $baseUrl ?>/api/v1/dashboard/active');
            if (activeResponse.ok) {
                const activeData = await activeResponse.json();
                if (activeData.success) {
                    updateActiveProcesses(activeData.data);
                }
            }

        } catch (error) {
            console.error('Dashboard refresh error:', error);
        }

        // Continue refreshing if there are active processes
        if (hasActiveProcesses) {
            refreshTimer = setTimeout(refreshDashboard, REFRESH_INTERVAL);
        }
    }

    function updateStats(stats) {
        const activeEl = document.getElementById('stat-active');
        const completedEl = document.getElementById('stat-completed');
        const todayEl = document.getElementById('stat-today');

        if (activeEl) {
            const newActive = Number(stats.active || 0);
            if (activeEl.textContent !== newActive.toLocaleString()) {
                activeEl.textContent = newActive.toLocaleString();
                flashElement(activeEl);
            }
            hasActiveProcesses = newActive > 0;
        }

        if (completedEl) {
            const newCompleted = Number(stats.completed || 0);
            if (completedEl.textContent !== newCompleted.toLocaleString()) {
                completedEl.textContent = newCompleted.toLocaleString();
                flashElement(completedEl);
            }
        }

        if (todayEl) {
            const newToday = '+' + Number(stats.today || 0).toLocaleString() + ' today';
            if (todayEl.textContent !== newToday) {
                todayEl.textContent = newToday;
            }
        }
    }

    function updateActiveProcesses(processes) {
        const container = document.getElementById('active-processes-list');
        if (!container || !processes) return;

        processes.forEach(process => {
            const card = container.querySelector(`[data-process-id="${process.id}"]`);
            if (card) {
                // Update progress bar
                const progressBar = card.querySelector('[data-field="progress"]');
                if (progressBar) {
                    const newWidth = (process.progress_percent || 0) + '%';
                    if (progressBar.style.width !== newWidth) {
                        progressBar.style.width = newWidth;
                    }
                }

                // Update URLs text
                const urlsEl = card.querySelector('[data-field="urls"]');
                if (urlsEl) {
                    const processed = Number(process.processed_urls || 0).toLocaleString();
                    const total = Number(process.total_urls || 0).toLocaleString();
                    const newText = `${processed}/${total} URLs`;
                    if (urlsEl.textContent !== newText) {
                        urlsEl.textContent = newText;
                        flashElement(urlsEl);
                    }
                }

                // Update phase
                const phaseEl = card.querySelector('[data-field="phase"]');
                if (phaseEl) {
                    const newPhase = `Phase ${process.phase || 0}/4`;
                    if (phaseEl.textContent !== newPhase) {
                        phaseEl.textContent = newPhase;
                    }
                }

                // Update status
                const statusEl = card.querySelector('[data-field="status"]');
                if (statusEl && process.status) {
                    const newStatus = process.status.charAt(0).toUpperCase() + process.status.slice(1);
                    if (statusEl.textContent !== newStatus) {
                        statusEl.textContent = newStatus;
                        flashElement(statusEl);
                    }
                }
            }
        });
    }

    function flashElement(el) {
        el.classList.add('flash-update');
        setTimeout(() => el.classList.remove('flash-update'), 500);
    }

    // Start auto-refresh if there are active processes
    if (hasActiveProcesses) {
        refreshTimer = setTimeout(refreshDashboard, REFRESH_INTERVAL);
    }

    // Cleanup on page unload
    window.addEventListener('beforeunload', () => {
        if (refreshTimer) clearTimeout(refreshTimer);
    });

    // ============================================
    // DASHBOARD CHARTS
    // ============================================
    let weeklyChart = null;

    document.addEventListener('DOMContentLoaded', function() {
        // Chart.js default configuration
        Chart.defaults.color = 'rgba(255, 255, 255, 0.7)';
        Chart.defaults.borderColor = 'rgba(255, 255, 255, 0.1)';

        // Status Distribution Pie Chart
        const statusCtx = document.getElementById('statusChart');
        if (statusCtx) {
            new Chart(statusCtx, {
                type: 'doughnut',
                data: {
                    labels: ['Active', 'Completed', 'Failed'],
                    datasets: [{
                        data: [<?= $active ?>, <?= $completed ?>, <?= $failed ?>],
                        backgroundColor: [
                            'rgba(59, 130, 246, 0.8)',   // Blue - active
                            'rgba(16, 185, 129, 0.8)',  // Green - completed
                            'rgba(239, 68, 68, 0.8)'    // Red - failed
                        ],
                        borderColor: [
                            'rgba(59, 130, 246, 1)',
                            'rgba(16, 185, 129, 1)',
                            'rgba(239, 68, 68, 1)'
                        ],
                        borderWidth: 2
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    cutout: '60%',
                    plugins: {
                        legend: {
                            position: 'bottom',
                            labels: {
                                padding: 15,
                                usePointStyle: true,
                                pointStyle: 'circle',
                                font: { size: 11 }
                            }
                        }
                    }
                }
            });
        }

        // Weekly Activity Line Chart - Initialize and load real data
        initWeeklyChart();
        loadChartData();
    });

    function initWeeklyChart() {
        const weeklyCtx = document.getElementById('weeklyChart');
        if (!weeklyCtx) return;

        // Generate last 7 days labels
        const labels = [];
        for (let i = 6; i >= 0; i--) {
            const date = new Date();
            date.setDate(date.getDate() - i);
            labels.push(date.toLocaleDateString('en', { weekday: 'short' }));
        }

        weeklyChart = new Chart(weeklyCtx, {
            type: 'line',
            data: {
                labels: labels,
                datasets: [{
                    label: 'URLs Processed',
                    data: [0, 0, 0, 0, 0, 0, 0], // Initial - will be updated with real data
                    fill: true,
                    borderColor: 'rgba(59, 130, 246, 1)',
                    backgroundColor: 'rgba(59, 130, 246, 0.1)',
                    borderWidth: 2,
                    tension: 0.4,
                    pointBackgroundColor: 'rgba(59, 130, 246, 1)',
                    pointBorderColor: '#fff',
                    pointBorderWidth: 2,
                    pointRadius: 4,
                    pointHoverRadius: 6
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: true,
                        grid: {
                            color: 'rgba(255, 255, 255, 0.05)'
                        },
                        ticks: {
                            font: { size: 10 }
                        }
                    },
                    x: {
                        grid: {
                            display: false
                        },
                        ticks: {
                            font: { size: 10 }
                        }
                    }
                },
                plugins: {
                    legend: {
                        display: false
                    }
                }
            }
        });
    }

    async function loadChartData() {
        try {
            const response = await fetch('<?= $baseUrl ?>/api/v1/dashboard/charts?period=7d');
            if (!response.ok) throw new Error('Failed to fetch chart data');

            const result = await response.json();
            if (!result.success || !result.data) return;

            const dailyStats = result.data.daily_stats || [];

            // Build data map from API response (date -> total URLs)
            const dataMap = {};
            dailyStats.forEach(stat => {
                const date = stat.date;
                dataMap[date] = parseInt(stat.total) || 0;
            });

            // Generate data for last 7 days in order
            const chartData = [];
            for (let i = 6; i >= 0; i--) {
                const date = new Date();
                date.setDate(date.getDate() - i);
                const dateStr = date.toISOString().split('T')[0]; // YYYY-MM-DD
                chartData.push(dataMap[dateStr] || 0);
            }

            // Update chart with real data
            if (weeklyChart) {
                weeklyChart.data.datasets[0].data = chartData;
                weeklyChart.update('none'); // Update without animation for smooth transition
            }

        } catch (error) {
            console.error('Error loading chart data:', error);
            // Chart stays functional with zeros on error
        }
    }
    </script>
</body>
</html>
