<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.w3.org/1999/xhtml">
<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="icon" th:href="@{/img/logo.svg}">
    <link rel="apple-touch-icon" th:href="@{/img/logo.svg}">
    <link rel="shortcut icon" type="image/x-icon" th:href="@{/img/logo.svg}">
    <link rel="stylesheet" href="/css/leaflet.css">
    <link rel="stylesheet" href="/css/main.css">
    <link rel="stylesheet" href="/css/lineicons.css">
    <script src="/js/htmx.min.js"></script>
    <script src="/js/chart.js"></script>
    <script src="/js/leaflet.js"></script>
    <script src="/js/TileLayer.Grayscale.js"></script>
</head>
<body class="background-dark">
<div id="statistics-panel"></div>
<div class="navigation-container" th:replace="~{fragments/main-navigation :: main-navigation('statistics')}"></div>

<div class="timeline">
    <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 th:inline="javascript">
    window.userSettings = /*[[${userSettings}]]*/ {}

    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
            });

            const tilesUrl = window.userSettings.tiles.service;

            const tileLayer = window.userSettings.preferColoredMap ? L.tileLayer : L.tileLayer.grayscale;
            tileLayer(tilesUrl, {
                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';
        
        // Helper function to convert km to miles if needed
        function convertDistance(km) {
            if (window.userSettings && window.userSettings.unitSystem === 'IMPERIAL') {
                return km * 0.621371; // Convert km to miles
            }
            return km;
        }
        
        // Helper function to get distance unit label
        function getDistanceUnit() {
            if (window.userSettings && window.userSettings.unitSystem === 'IMPERIAL') {
                return 'miles';
            }
            return 'km';
        }
        
        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',
                'TRANSIT': '#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 => convertDistance(stat.totalDistanceKm)),
                                backgroundColor: transportStats.map(stat => transportColors[stat.transportMode] || '#999999')
                            }]
                        },
                        options: {
                            responsive: true,
                            maintainAspectRatio: false,
                            plugins: {
                                legend: {
                                    position: 'bottom'
                                },
                                tooltip: {
                                    callbacks: {
                                        label: function(context) {
                                            return context.label + ': ' + context.parsed.toFixed(1) + ' ' + getDistanceUnit();
                                        }
                                    }
                                }
                            }
                        }
                    });
                }
            }

            // 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 ? convertDistance(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: getDistanceUnit()
                                    }
                                }
                            }
                        }
                    });
                }
            }
        });

        // 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',
                'TRANSIT': '#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 => convertDistance(stat.totalDistanceKm)),
                                backgroundColor: transportStats.map(stat => transportColors[stat.transportMode] || '#cd0808')
                            }]
                        },
                        options: {
                            responsive: true,
                            maintainAspectRatio: false,
                            plugins: {
                                legend: {
                                    position: 'bottom'
                                },
                                tooltip: {
                                    callbacks: {
                                        label: function(context) {
                                            return context.label + ': ' + context.parsed.toFixed(1) + ' ' + getDistanceUnit();
                                        }
                                    }
                                }
                            }
                        }
                    });
                }
            }

            // 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 ? convertDistance(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,
                                    type: 'logarithmic',
                                    title: {
                                        display: true,
                                        text: getDistanceUnit()
                                    }
                                }
                            }
                        }
                    });
                }
            }
        });

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