<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title th:text="#{statistics.page.title}">Statistics - Reitti</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=" crossorigin=""/>
    <link rel="stylesheet" href="/css/main.css">
    <link rel="stylesheet" href="/css/lineicons.css">
    <link href="https://fonts.googleapis.com/css2?family=Fraunces:ital,opsz,wght@0,9..144,100..900;1,9..144,100..900&display=swap" rel="stylesheet">
    <script src="https://unpkg.com/htmx.org@1.9.12"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js" integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo=" crossorigin=""></script>
    <script src="/js/TileLayer.Grayscale.js"></script>
</head>
<body class="background-dark">
<div id="statistics-panel"></div>

<div class="timeline">
    <span class="timeline-header">
        <a href="/" class="nav-link" th:title="#{nav.timeline}"><i class="lni lni-route-1"></i></a>
        <form th:action="@{/logout}" method="post" >
            <button type="submit" class="nav-link" style="font-size: 1.4rem;" th:title="#{nav.logout.tooltip}"><i
                    class="lni lni-exit"></i>
            </button>
        </form>
    </span>

    <div class="timeline-container">
        <div id="years-navigation" 
             hx-get="/statistics/years-navigation" 
             hx-trigger="load">
            <div class="photo-modal-loading-spinner htmx-indicator" th:text="#{timeline.loading}">Loading...</div>
        </div>
    </div>
</div>
<script>

    function shouldTrigger(element) {
        return !element.classList.contains('active');
    }
    function initializePlaceMaps() {
        const mapContainers = document.querySelectorAll('.place-map:not([data-map-initialized])');
        mapContainers.forEach((container, index) => {
            container.setAttribute('data-map-initialized', 'true');

            const lat = parseFloat(container.getAttribute('data-lat')) || 53.8;
            const lng = parseFloat(container.getAttribute('data-lng')) || 10.7;

            const map = L.map(container, {
                center: [lat, lng],
                zoom: 15,
                zoomControl: false,
                attributionControl: false,
                dragging: false,
                touchZoom: false,
                doubleClickZoom: false,
                scrollWheelZoom: false,
                boxZoom: false,
                keyboard: false
            });

            L.tileLayer.grayscale('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                attribution: ''
            }).addTo(map);

            setTimeout(() => {
                map.invalidateSize();
            }, 100);
        });
    }

    function renderCharts() {
        // Find all statistics content containers that haven't been processed yet
        Chart.defaults.color = '#ffffff';
        Chart.defaults.font.family = 'Fraunces';
        const statisticsContainers = document.querySelectorAll('.statistics-content:not([data-charts-initialized])');

        statisticsContainers.forEach(container => {
            container.setAttribute('data-charts-initialized', 'true');

            const statisticsType = container.getAttribute('data-statistics-type');
            const year = container.getAttribute('data-year');
            const month = container.getAttribute('data-month');
            const transportStatsAttr = container.getAttribute('data-transport-stats');
            const breakdownTransportAttr = container.getAttribute('data-breakdown-transport');

            // Parse transport stats data
            let transportStats = [];
            if (transportStatsAttr && transportStatsAttr !== '[]') {
                try {
                    transportStats = JSON.parse(transportStatsAttr);
                } catch (e) {
                    console.error('Error parsing transport stats:', e);
                }
            }

            // Parse breakdown transport data
            let breakdownTransportData = [];
            if (breakdownTransportAttr && breakdownTransportAttr !== '[]') {
                try {
                    breakdownTransportData = JSON.parse(breakdownTransportAttr);
                } catch (e) {
                    console.error('Error parsing breakdown transport data:', e);
                }
            }

            // Transport mode colors
            const transportColors = {
                'DRIVING': '#FF6384',
                'WALKING': '#36A2EB',
                'CYCLING': '#FFCE56',
                'public_transport': '#4BC0C0',
                'unknown': '#FF9F40'
            };

            // Render pie chart for transport distribution
            if (transportStats.length > 0) {
                let chartId;
                if (statisticsType === 'overall') {
                    chartId = 'transportPieChart_overall';
                } else if (statisticsType === 'year') {
                    chartId = `transportPieChart_${year}`;
                } else if (statisticsType === 'month') {
                    chartId = `transportPieChart_${year}_${month}`;
                }

                const pieCanvas = document.getElementById(chartId);
                if (pieCanvas) {
                    const ctx = pieCanvas.getContext('2d');
                    new Chart(ctx, {
                        type: 'pie',
                        data: {
                            labels: transportStats.map(stat => stat.transportMode),
                            datasets: [{
                                data: transportStats.map(stat => stat.totalDistanceKm),
                                backgroundColor: transportStats.map(stat => transportColors[stat.transportMode] || '#999999')
                            }]
                        },
                        options: {
                            responsive: true,
                            maintainAspectRatio: false,
                            plugins: {
                                legend: {
                                    position: 'bottom'
                                }
                            }
                        }
                    });
                }
            }

            // Render breakdown chart for year view (monthly breakdown)
            if (statisticsType === 'year' && breakdownTransportData.length > 0) {
                const monthlyCanvas = document.getElementById(`monthlyTransportChart_${year}`);
                if (monthlyCanvas) {
                    const ctx = monthlyCanvas.getContext('2d');

                    // Group data by transport mode
                    const transportModes = [...new Set(transportStats.map(item => item.transportMode))];
                    const months = [...new Set(breakdownTransportData.map(item => item.monthName))].sort((a, b) => a - b);

                    const datasets = transportModes.map(mode => ({
                        label: mode,
                        data: months.map(month => {
                            const item = breakdownTransportData.filter(d => d.monthName === month).map(d => d.transportStats);
                            if (item.length === 0) {
                                return 0;
                            } else {
                                let byTransportMode = item[0].find(i => i.transportMode === mode);
                                return byTransportMode ? byTransportMode.totalDistanceKm : 0;
                            }
                        }),
                        backgroundColor: transportColors[mode] || '#999999'
                    }));

                    new Chart(ctx, {
                        type: 'bar',
                        data: {
                            labels: months,
                            datasets: datasets
                        },
                        options: {
                            responsive: true,
                            maintainAspectRatio: false,
                            scales: {
                                x: {
                                    stacked: true
                                },
                                y: {
                                    stacked: true,
                                    title: {
                                        display: true,
                                        text: 'km'
                                    }
                                }
                            }
                        }
                    });
                }
            }
        });

        // Handle month content containers separately
        const monthContainers = document.querySelectorAll('.month-content:not([data-charts-initialized])');

        monthContainers.forEach(container => {
            container.setAttribute('data-charts-initialized', 'true');

            const year = container.getAttribute('data-year');
            const month = container.getAttribute('data-month');
            const transportStatsAttr = container.getAttribute('data-transport-stats');
            const breakdownTransportAttr = container.getAttribute('data-breakdown-transport');

            // Parse transport stats data
            let transportStats = [];
            if (transportStatsAttr && transportStatsAttr !== '[]') {
                try {
                    transportStats = JSON.parse(transportStatsAttr);
                } catch (e) {
                    console.error('Error parsing transport stats:', e);
                }
            }

            // Parse breakdown transport data
            let breakdownTransportData = [];
            if (breakdownTransportAttr && breakdownTransportAttr !== '[]') {
                try {
                    breakdownTransportData = JSON.parse(breakdownTransportAttr);
                } catch (e) {
                    console.error('Error parsing breakdown transport data:', e);
                }
            }

            // Transport mode colors
            const transportColors = {
                'DRIVING': '#FF6384',
                'WALKING': '#36A2EB',
                'CYCLING': '#FFCE56',
                'public_transport': '#4BC0C0',
                'unknown': '#FF9F40'
            };

            // Render pie chart for month transport distribution
            if (transportStats.length > 0) {
                const pieCanvas = document.getElementById(`monthTransportPieChart_${year}_${month}`);
                if (pieCanvas) {
                    const ctx = pieCanvas.getContext('2d');
                    new Chart(ctx, {
                        type: 'pie',
                        data: {
                            labels: transportStats.map(stat => stat.transportMode),
                            datasets: [{
                                data: transportStats.map(stat => stat.totalDistanceKm),
                                backgroundColor: transportStats.map(stat => transportColors[stat.transportMode] || '#cd0808')
                            }]
                        },
                        options: {
                            responsive: true,
                            maintainAspectRatio: false,
                            plugins: {
                                legend: {
                                    position: 'bottom'
                                }
                            }
                        }
                    });
                }
            }

            // Render breakdown chart for month view (daily breakdown)
            if (breakdownTransportData.length > 0) {
                const dailyCanvas = document.getElementById(`monthDailyTransportChart_${year}_${month}`);
                if (dailyCanvas) {
                    const ctx = dailyCanvas.getContext('2d');

                    // Group data by transport mode
                    const transportModes = [...new Set(transportStats.map(item => item.transportMode))];
                    const days = [...new Set(breakdownTransportData.map(item => item.dayOfMonth))].sort((a, b) => a - b);

                    const datasets = transportModes.map(mode => ({
                        label: mode,
                        data: days.map(day => {
                            const item = breakdownTransportData.filter(d => d.dayOfMonth === day).map(d => d.transportStats);
                            if (item.length === 0) {
                                return 0;
                            } else {
                                let byTransportMode = item[0].find(i => i.transportMode === mode);
                                return byTransportMode ? byTransportMode.totalDistanceKm : 0;
                            }
                        }),
                        backgroundColor: transportColors[mode] || '#f10808'
                    }));

                    new Chart(ctx, {

                        type: 'bar',
                        data: {
                            labels: days,
                            datasets: datasets
                        },
                        options: {
                            plugins: {
                                legend: {
                                    display: true
                                }
                            },
                            responsive: true,
                            maintainAspectRatio: false,
                            scales: {
                                x: {
                                    stacked: true,
                                    title: {
                                        display: true,
                                        text: 'Day'
                                    }
                                },
                                y: {
                                    stacked: true,
                                    title: {
                                        display: true,
                                        text: 'km'
                                    }
                                }
                            }
                        }
                    });
                }
            }
        });

    }

</script>
</body>
</html>
