<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PiAware - Statistiques</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="/static/css/style.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        .stats-wrapper { margin: 2rem auto; width: 90%; max-width: 1200px; padding: 2rem; overflow-y: auto;}
        .charts-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(450px, 1fr)); gap: 2rem; margin-top: 2rem; }
        .chart-card { background: rgba(0,0,0,0.2); padding: 1.5rem; border-radius: 12px; border: 1px solid var(--glass-border); }
        .chart-container { position: relative; height: 350px; width: 100%; margin-top: 1rem; }
        .back-link { color: var(--text-muted); text-decoration: none; font-size: 0.9rem; transition: color 0.2s;}
        .back-link:hover { color: var(--accent); }
    </style>
</head>
<body style="min-height: 100vh;">
    <div class="stats-wrapper glass-panel">
        <header style="padding: 0; justify-content: space-between; display: flex; align-items: flex-end;">
            <div>
                <a href="/" class="back-link">&larr; Retour au Radar</a>
                <h1 style="margin-top: 1rem;">Analytique & <span class="accent">Statistiques</span></h1>
            </div>
            <div class="controls" style="padding:0; justify-content:flex-end;">
                <label class="toggle"><input type="checkbox" id="toggle-metric"> Système Métrique</label>
            </div>
        </header>
        
        <div class="charts-grid">
            <div class="chart-card">
                <h3 style="text-align: center; font-weight: 400; font-size: 1.1rem; color: #f8fafc;">Activité de Survol (7 derniers jours)</h3>
                <div class="chart-container">
                    <canvas id="activityChart"></canvas>
                </div>
            </div>
            
            <div class="chart-card">
                <h3 style="text-align: center; font-weight: 400; font-size: 1.1rem; color: #f8fafc;">Répartition des Altitudes Max</h3>
                <div class="chart-container">
                    <canvas id="altitudeChart"></canvas>
                </div>
            </div>

            <div class="chart-card">
                <h3 style="text-align: center; font-weight: 400; font-size: 1.1rem; color: #f8fafc;">Top 5 des Compagnies Aériennes</h3>
                <div class="chart-container">
                    <canvas id="airlineChart"></canvas>
                </div>
            </div>

            <div class="chart-card">
                <h3 style="text-align: center; font-weight: 400; font-size: 1.1rem; color: #f8fafc;">Portée de Détection Antenne</h3>
                <div class="chart-container">
                    <canvas id="distanceChart"></canvas>
                </div>
            </div>
        </div>
        
        <h2 style="margin-top: 4rem; margin-bottom: 1.5rem; font-weight: 400; text-align: center; color: #f8fafc;">Succès Déverrouillés 🏆</h2>
        <div id="achievements-container" style="display: flex; gap: 1rem; flex-wrap: wrap; justify-content: center;">
            <p style="color: var(--text-muted); font-style: italic;">Recherche de vos succès...</p>
        </div>
    </div>
    
    <script>
        // Set default Chart.js theme to fit dark mode
        Chart.defaults.color = '#94a3b8';
        Chart.defaults.font.family = "'Inter', sans-serif";
        
        let useMetric = localStorage.getItem('useMetric') === 'true';
        document.getElementById('toggle-metric').checked = useMetric;
        
        let altitudeChartInstance = null;
        let distanceChartInstance = null;
        let airlineChartInstance = null;
        let chartDataCache = null;
 
        document.getElementById('toggle-metric').addEventListener('change', (e) => {
            useMetric = e.target.checked;
            localStorage.setItem('useMetric', useMetric);
            if (chartDataCache) {
                renderAltitudeChart(chartDataCache.altitudes);
                renderDistanceChart(chartDataCache.distances);
                renderAchievements(chartDataCache.achievements);
            }
        });
 
        function formatAchievementValue(value, unit_type) {
            if (useMetric) {
                if (unit_type === 'ft') return Math.round(value * 0.3048).toLocaleString() + ' m';
                if (unit_type === 'kt') return Math.round(value * 1.852).toLocaleString() + ' km/h';
                if (unit_type === 'km') return value.toFixed(1) + ' km';
            } else {
                if (unit_type === 'ft') return Math.round(value).toLocaleString() + ' ft';
                if (unit_type === 'kt') return Math.round(value).toLocaleString() + ' kt';
                if (unit_type === 'km') return (value / 1.852).toFixed(1) + ' NM';
            }
            return value;
        }
 
        function renderAltitudeChart(altitudesData) {
            let labels = Object.keys(altitudesData);
            if (useMetric) {
                const replacements = {
                    "< 10k ft": "< 3 000 m",
                    "10k-20k ft": "3 000 - 6 000 m",
                    "20k-30k ft": "6 000 - 9 000 m",
                    "> 30k ft": "> 9 000 m"
                };
                labels = labels.map(l => replacements[l] || l);
            }
 
            if (altitudeChartInstance) {
                altitudeChartInstance.data.labels = labels;
                altitudeChartInstance.update();
            } else {
                const ctxAlt = document.getElementById('altitudeChart');
                altitudeChartInstance = new Chart(ctxAlt, {
                    type: 'doughnut',
                    data: {
                        labels: labels,
                        datasets: [{
                            data: Object.values(altitudesData),
                            backgroundColor: ['#10b981', '#f59e0b', '#3b82f6', '#8b5cf6'],
                            borderColor: 'transparent',
                            hoverOffset: 4
                        }]
                    },
                    options: { 
                        responsive: true, 
                        maintainAspectRatio: false,
                        cutout: '65%',
                        plugins: {
                            legend: { position: 'bottom' }
                        }
                    }
                });
            }
        }

        function renderDistanceChart(distancesData) {
            let labels = Object.keys(distancesData);
            if (!useMetric) {
                const replacements = {
                    "< 50 km": "< 27 NM",
                    "50-150 km": "27 - 80 NM",
                    "150-250 km": "80 - 135 NM",
                    "> 250 km": "> 135 NM"
                };
                labels = labels.map(l => replacements[l] || l);
            }

            if (distanceChartInstance) {
                distanceChartInstance.data.labels = labels;
                distanceChartInstance.update();
            } else {
                const ctxDist = document.getElementById('distanceChart');
                distanceChartInstance = new Chart(ctxDist, {
                    type: 'doughnut',
                    data: {
                        labels: labels,
                        datasets: [{
                            data: Object.values(distancesData),
                            backgroundColor: ['#06b6d4', '#0284c7', '#2563eb', '#1d4ed8'],
                            borderColor: 'transparent',
                            hoverOffset: 4
                        }]
                    },
                    options: { 
                        responsive: true, 
                        maintainAspectRatio: false,
                        cutout: '65%',
                        plugins: {
                            legend: { position: 'bottom' }
                        }
                    }
                });
            }
        }

        function renderAirlineChart(airlinesData) {
            const labels = Object.keys(airlinesData);
            const values = Object.values(airlinesData);

            if (airlineChartInstance) {
                airlineChartInstance.data.labels = labels;
                airlineChartInstance.data.datasets[0].data = values;
                airlineChartInstance.update();
            } else {
                const ctxAir = document.getElementById('airlineChart');
                airlineChartInstance = new Chart(ctxAir, {
                    type: 'bar',
                    data: {
                        labels: labels,
                        datasets: [{
                            label: 'Vols',
                            data: values,
                            backgroundColor: '#a855f7',
                            borderColor: 'transparent',
                            borderWidth: 1,
                            borderRadius: 6
                        }]
                    },
                    options: {
                        indexAxis: 'y',
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: { display: false }
                        },
                        scales: {
                            x: { grid: { color: 'rgba(255,255,255,0.05)' }, beginAtZero: true },
                            y: { grid: { display: false } }
                        }
                    }
                });
            }
        }
 
        function renderAchievements(achievements) {
            const achContainer = document.getElementById('achievements-container');
            if (!achievements || achievements.length === 0) {
                achContainer.innerHTML = '<p style="color: var(--text-muted);">Continuez à tracker des avions pour débloquer vos premiers succès !</p>';
                return;
            }
            
            achContainer.innerHTML = '';
            achievements.forEach(a => {
                const valDisplay = formatAchievementValue(a.value, a.unit);
                const dateObj = new Date(a.date);
                const dateStr = dateObj.toLocaleDateString() + ' à ' + dateObj.toLocaleTimeString();
                const cardId = 'ach-' + a.id;
                
                achContainer.innerHTML += `
                    <div id="${cardId}" style="background: rgba(0,0,0,0.2); padding: 1.5rem; border-radius: 12px; border: 1px solid var(--glass-border); text-align: center; min-width: 250px; flex: 1; max-width: 320px;">
                        <div style="font-size: 3rem; margin-bottom: 0.5rem; filter: drop-shadow(0 0 10px rgba(255,255,255,0.2));">${a.icon}</div>
                        <h4 style="color: var(--accent); margin-bottom: 0.5rem; font-size: 1.1rem;">${a.title}</h4>
                        <div style="font-size: 1.25rem; font-weight: bold; margin-bottom: 0.5rem;">${valDisplay}</div>
                        <div style="font-size: 0.8rem; color: var(--text-muted); line-height: 1.4;">
                            ${a.callsign !== 'N/A' ? a.callsign : 'Inconnu'} (${a.hex})<br>
                            ${dateStr}
                        </div>
                        <div class="photo-container" style="margin-top: 1rem; min-height: 20px;">
                            <span style="font-size: 0.75rem; color: gray;">Recherche d'image...</span>
                        </div>
                    </div>
                `;
                
                fetch('/api/details/' + a.hex).then(r => r.json()).then(details => {
                    const c = document.getElementById(cardId);
                    if (!c) return;
                    const pc = c.querySelector('.photo-container');
                    let html = '';
                    if (details.type) {
                        html += `<div style="font-size: 0.85rem; font-weight: 600; margin-bottom: 0.5rem; color: var(--text-muted);">${details.type}</div>`;
                    }
                    if (details.photo) {
                        html += `<img src="${details.photo}" style="width: 100%; border-radius: 6px; border: 1px solid rgba(255,255,255,0.1);">`;
                    } else {
                        html += `<div style="font-size: 0.75rem; color: gray; font-style: italic;">Pas de photo dispo</div>`;
                    }
                    pc.innerHTML = html;
                }).catch(() => {
                    const c = document.getElementById(cardId);
                    if (c) c.querySelector('.photo-container').innerHTML = '';
                });
            });
        }
 
        fetch('/api/charts').then(r => r.json()).then(data => {
            chartDataCache = data;
            
            const ctxAct = document.getElementById('activityChart');
            new Chart(ctxAct, {
                type: 'line',
                data: {
                    labels: Object.keys(data.activity),
                    datasets: [{
                        label: 'Vols uniques détectés',
                        data: Object.values(data.activity),
                        borderColor: '#38bdf8',
                        backgroundColor: 'rgba(56, 189, 248, 0.15)',
                        fill: true,
                        tension: 0.4,
                        borderWidth: 2,
                        pointBackgroundColor: '#38bdf8',
                        pointRadius: 4
                    }]
                },
                options: { 
                    responsive: true, 
                    maintainAspectRatio: false,
                    plugins: { legend: { display: false } },
                    scales: {
                        y: { grid: { color: 'rgba(255,255,255,0.05)' }, beginAtZero: true },
                        x: { grid: { display: false } }
                    }
                }
            });
 
            renderAltitudeChart(data.altitudes);
            renderDistanceChart(data.distances);
            renderAirlineChart(data.airlines);
            renderAchievements(data.achievements);
            
        }).catch(err => console.error("API Error", err));
    </script>
</body>
</html>
