<!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="#{page.title}">Reitti - Your Location Timeline</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/date-picker.css">
    <link rel="stylesheet" href="/css/main.css">
    <link rel="stylesheet" href="/css/lineicons.css">
    <link rel="stylesheet" href="/css/photo-client.css">
    <script src="/js/HumanizeDuration.js"></script>
    <script src="/js/horizontal-date-picker.js"></script>
    <script src="/js/timeline-scroll-indicator.js"></script>
    <script src="/js/photo-client.js"></script>
    <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://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>
<div id="map"></div>

<!-- Settings Overlay -->
<div id="settings-overlay" class="settings-overlay">
    <div class="settings-content">
        <span class="close-settings">&times;</span>

        <div class="settings-nav">
            <div class="settings-nav-item" data-target="job-status" th:text="#{settings.job.status}">Job Status</div>
            <div class="settings-nav-item" data-target="file-upload" th:text="#{settings.import.data}">Import Data</div>
            <div class="settings-nav-item active" data-target="api-tokens" th:text="#{settings.api.tokens}">API Tokens</div>
            <div class="settings-nav-item" data-target="user-management" th:text="#{settings.user.management}">User Management</div>
            <div class="settings-nav-item" data-target="places-management" th:text="#{settings.places}">Places</div>
            <div class="settings-nav-item" data-target="geocode-services" th:text="#{settings.geocoding}">Geocoding</div>
            <div class="settings-nav-item" data-target="manage-data" th:if="${dataManagementEnabled}" th:text="#{settings.manage.data}">Manage Data</div>
            <div class="settings-nav-item" data-target="language-settings" th:text="#{language.select}">Select Language</div>
            <div class="settings-nav-item" data-target="integrations" hx-get="/settings/integrations-content" hx-target="#integrations" th:text="#{settings.integrations}">Integrations</div>
            <div class="settings-nav-item" data-target="about-section" th:text="#{settings.about}">About</div>
        </div>

        <!-- API Tokens Section -->
        <div id="api-tokens" class="settings-section active" hx-get="/settings/api-tokens-content"
             hx-trigger="revealed, every 30s">
            <div class="htmx-indicator">Loading tokens...</div>
        </div>

        <!-- User Management Section -->
        <div id="user-management" class="settings-section" hx-get="/settings/users-content" hx-trigger="revealed">
            <div class="htmx-indicator">Loading users...</div>
        </div>

        <!-- Places Management Section -->
        <div id="places-management" class="settings-section">
            <div class="htmx-indicator">Loading places...</div>
        </div>

        <!-- Geocoding Services Section -->
        <div id="geocode-services" class="settings-section">
            <div class="htmx-indicator">Loading geocoding services...</div>
        </div>

        <!-- Integrations Section -->
        <div id="integrations" class="settings-section">
            <div class="htmx-indicator">Loading integrations...</div>
        </div>

        <!-- Manage Data Section -->
        <div th:if="${dataManagementEnabled}" id="manage-data" class="settings-section">
            <div class="htmx-indicator">Loading data management...</div>
        </div>

        <!-- Job Status Section -->
        <div id="job-status" class="settings-section" hx-get="/settings/queue-stats-content"
             hx-trigger="revealed, every 5s">
            <div class="htmx-indicator">Loading queue stats...</div>
        </div>

        <!-- File Upload Section -->
        <div id="file-upload" class="settings-section">
            <div class="htmx-indicator">Loading file upload options...</div>
        </div>

        <!-- Language Settings Section -->
        <div id="language-settings" class="settings-section" hx-get="/settings/language-content">
            <div class="htmx-indicator">Loading language options...</div>
        </div>

        <!-- About Section -->
        <div id="about-section" class="settings-section">
            <div class="htmx-indicator">Loading about information...</div>
        </div>

        <script>
            // Function to initialize maps for place cards
            function initPlaceMaps() {

                document.querySelectorAll('.place-map').forEach(mapElement => {
                    const lat = parseFloat(mapElement.dataset.lat);
                    const lng = parseFloat(mapElement.dataset.lng);
                    const placeMap = L.map(mapElement, {
                        zoomControl: false,
                        attributionControl: false,
                        dragging: false,
                        scrollWheelZoom: false
                    })

                    L.tileLayer('https://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png', {
                        maxZoom: 19,
                        attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, Tiles style by <a href="https://www.hotosm.org/" target="_blank">Humanitarian OpenStreetMap Team</a> hosted by <a href="https://openstreetmap.fr/" target="_blank">OpenStreetMap France</a>'
                    }).addTo(placeMap);

                    if (!isNaN(lat) && !isNaN(lng)) {
                        placeMap.setView([lat, lng], 14);


                        L.circleMarker([lat, lng], {
                            radius: 8,
                            fillColor: '#4a89dc',
                            color: '#fff',
                            weight: 1,
                            opacity: 1,
                            fillOpacity: 0.8
                        }).addTo(placeMap);
                        placeMap.invalidateSize();
                    }
                });
            }

            document.body.addEventListener('htmx:afterSwap', function (event) {
                if (event.detail.target.id === 'places-management' ||
                    event.detail.target.closest('#places-management')) {
                    initPlaceMaps();
                }

                // Handle form resets after successful submission
                if (event.detail.target.id === 'user-management' ||
                    event.detail.target.closest('#user-management')) {
                    // Find and reset any forms in the user management section
                    const forms = event.detail.target.querySelectorAll('form');
                    forms.forEach(form => {
                        form.reset();
                    });
                }
            });
        </script>
    </div>
</div>


<div class="timeline">
    <span class="timeline-header">
        <a href="/statistics" class="nav-link" th:title="#{nav.statistics}"><i class="lni lni-bar-chart-4"></i></a>
        <a href="#" id="settings-button" class="nav-link"><i class="lni lni-gear-1" th:title="#{nav.settings.tooltip}"></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="loading-indicator" style="display: none;" th:text="#{timeline.loading}">Loading...</div>
        <!-- Timeline entries will be loaded here -->
    </div>
</div>

<!-- Horizontal date picker will be initialized here -->
<div id="horizontal-date-picker-container"></div>

<script th:inline="javascript">
    // Locale object for JavaScript
    window.locale = {
        loading: /*[[#{timeline.loading}]]*/ 'Loading...',
        noData: /*[[#{timeline.no.data}]]*/ 'No timeline data available for this date.',
        duration: /*[[#{timeline.duration}]]*/ 'Duration',
        distance: /*[[#{timeline.distance}]]*/ 'Distance',
        trip: /*[[#{timeline.trip}]]*/ 'Trip',
        transportWalking: /*[[#{timeline.transport.walking}]]*/ 'by foot',
        transportCycling: /*[[#{timeline.transport.cycling}]]*/ 'by bike',
        transportDriving: /*[[#{timeline.transport.driving}]]*/ 'by car',
        today: /*[[#{datepicker.today}]]*/ 'Today',
        days: [
            /*[[#{datepicker.days.sun}]]*/ 'Sun',
            /*[[#{datepicker.days.mon}]]*/ 'Mon',
            /*[[#{datepicker.days.tue}]]*/ 'Tue',
            /*[[#{datepicker.days.wed}]]*/ 'Wed',
            /*[[#{datepicker.days.thu}]]*/ 'Thu',
            /*[[#{datepicker.days.fri}]]*/ 'Fri',
            /*[[#{datepicker.days.sat}]]*/ 'Sat'
        ],
        months: [
            /*[[#{datepicker.months.jan}]]*/ 'Jan',
            /*[[#{datepicker.months.feb}]]*/ 'Feb',
            /*[[#{datepicker.months.mar}]]*/ 'Mar',
            /*[[#{datepicker.months.apr}]]*/ 'Apr',
            /*[[#{datepicker.months.may}]]*/ 'May',
            /*[[#{datepicker.months.jun}]]*/ 'Jun',
            /*[[#{datepicker.months.jul}]]*/ 'Jul',
            /*[[#{datepicker.months.aug}]]*/ 'Aug',
            /*[[#{datepicker.months.sep}]]*/ 'Sep',
            /*[[#{datepicker.months.oct}]]*/ 'Oct',
            /*[[#{datepicker.months.nov}]]*/ 'Nov',
            /*[[#{datepicker.months.dec}]]*/ 'Dec'
        ]
    };
    
    // Set locale for HumanizeDuration
    const currentLocale = /*[[${#locale.language}]]*/ 'en';

    document.addEventListener('DOMContentLoaded', function () {
        // Settings overlay functionality
        const settingsButton = document.getElementById('settings-button');
        const settingsOverlay = document.getElementById('settings-overlay');
        const closeSettings = document.querySelector('.close-settings');

        // Open settings overlay
        settingsButton.addEventListener('click', function (e) {
            e.preventDefault();
            settingsOverlay.style.display = 'block';

            // For places tab, we need to check if it's active and load content
            const placesSection = document.getElementById('places-management');
            
            if (placesSection.classList.contains('active')) {
                // If places tab is active, load its content
                placesSection.setAttribute('hx-get', '/settings/places-content?page=0');
                placesSection.setAttribute('hx-trigger', 'load');
                htmx.process(placesSection);
            }
            
        });

        // Close settings overlay
        closeSettings.addEventListener('click', function () {
            settingsOverlay.style.display = 'none';
        });

        // Close when clicking outside the content
        window.addEventListener('click', function (event) {
            if (event.target === settingsOverlay) {
                settingsOverlay.style.display = 'none';
            }
        });

        // Tab navigation in settings with htmx
        const navItems = document.querySelectorAll('.settings-nav-item');
        const sections = document.querySelectorAll('.settings-section');

        navItems.forEach(item => {
            item.addEventListener('click', function () {
                const target = this.getAttribute('data-target');

                // Update active nav item
                navItems.forEach(nav => nav.classList.remove('active'));
                this.classList.add('active');

                // Show target section
                sections.forEach(section => {
                    section.classList.remove('active');
                    if (section.id === target) {
                        section.classList.add('active');
                        
                        // If this is the places tab, load its content if not already loaded
                        if (target === 'places-management' && !section.hasAttribute('hx-triggered')) {
                            section.setAttribute('hx-get', '/settings/places-content?page=0');
                            section.setAttribute('hx-trigger', 'load');
                            section.setAttribute('hx-triggered', 'true');
                            htmx.process(section);
                        }
                        
                        // If this is the file upload tab, load its content if not already loaded
                        if (target === 'file-upload' && !section.hasAttribute('hx-triggered')) {
                            section.setAttribute('hx-get', '/settings/file-upload-content');
                            section.setAttribute('hx-trigger', 'load once');
                            section.setAttribute('hx-triggered', 'true');
                            htmx.process(section);
                        }

                        // If this is the geocoding tab, load its content if not already loaded
                        if (target === 'geocode-services' && !section.hasAttribute('hx-triggered')) {
                            section.setAttribute('hx-get', '/settings/geocode-services-content');
                            section.setAttribute('hx-trigger', 'load once');
                            section.setAttribute('hx-triggered', 'true');
                            htmx.process(section);
                        }

                        // If this is the manage data tab, load its content if not already loaded
                        if (target === 'manage-data' && !section.hasAttribute('hx-triggered')) {
                            section.setAttribute('hx-get', '/settings/manage-data-content');
                            section.setAttribute('hx-trigger', 'load once');
                            section.setAttribute('hx-triggered', 'true');
                            htmx.process(section);
                        }
                        // If this is the about tab, load its content if not already loaded
                        if (target === 'about-section' && !section.hasAttribute('hx-triggered')) {
                            section.setAttribute('hx-get', '/settings/about-content');
                            section.setAttribute('hx-trigger', 'load once');
                            section.setAttribute('hx-triggered', 'true');
                            htmx.process(section);
                        }
                        // If this is the language data tab, load its content if not already loaded
                        if (target === 'language-settings' && !section.hasAttribute('hx-triggered')) {
                            section.setAttribute('hx-get', '/settings/language-content');
                            section.setAttribute('hx-trigger', 'load once');
                            section.setAttribute('hx-triggered', 'true');
                            htmx.process(section);
                        }
                    }
                });
            });
        });


        // Check if date is in URL parameters
        const urlParams = new URLSearchParams(window.location.search);
        let initialDate;

        if (urlParams.has('date')) {
            initialDate = urlParams.get('date');
            // Validate date format (YYYY-MM-DD)
            if (!/^\d{4}-\d{2}-\d{2}$/.test(initialDate)) {
                initialDate = null;
            }
        }

        // Set date picker to URL date or today's date
        const today = new Date();
        const formattedDate = initialDate || today.toISOString().split('T')[0]; // YYYY-MM-DD format

        // Function to update URL with date parameter
        function updateUrlWithDate(date) {
            const url = new URL(window.location);
            url.searchParams.set('date', date);
            window.history.pushState({}, '', url);
        }

        // Initialize the map
        const map = L.map('map').setView([60.1699, 24.9384], 12); // Helsinki coordinates as default
        L.tileLayer.grayscale('https://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png', {
            maxZoom: 19,
            attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, Tiles style by <a href="https://www.hotosm.org/" target="_blank">Humanitarian OpenStreetMap Team</a> hosted by <a href="https://openstreetmap.fr/" target="_blank">OpenStreetMap France</a>'
        }).addTo(map);

        // Add scale control
        L.control.scale({
            imperial: false,
            metric: true
        }).addTo(map);

        // Initialize photo client
        const photoClient = new PhotoClient(map);
        
        // Listen for map move/zoom events to update photo markers
        map.on('moveend zoomend', () => {
            photoClient.onMapMoveEnd();
        });

        // Function to load timeline data
        function loadTimelineData(date) {
            const loadingIndicator = document.getElementById('loading-indicator');
            loadingIndicator.style.display = 'block';

            // Cleanup existing scroll indicator
            if (window.timelineScrollIndicator) {
                window.timelineScrollIndicator.cleanup();
                window.timelineScrollIndicator = null;
            }

            // Load photos for the selected date
            photoClient.updatePhotosForDate(date);

            // Fetch both timeline data and raw location points
            Promise.all([
                fetch(`/api/timeline?selectedDate=${date}`).then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.json();
                }),
                fetch(`/api/v1/raw-location-points?date=${date}`).then(response => {
                    if (!response.ok) {
                        // If endpoint doesn't exist or returns error, just return empty array
                        console.warn('Could not fetch raw location points');
                        return { points: [] };
                    }
                    return response.json();
                }).catch(error => {
                    console.warn('Error fetching raw location points:', error);
                    return { points: [] };
                })
            ])
            .then(([timelineData, rawPointsData]) => {
                updateTimeline(timelineData, rawPointsData);
                loadingIndicator.style.display = 'none';
                
                // Initialize scroll indicator after timeline is updated
                window.timelineScrollIndicator = new TimelineScrollIndicator();
                window.timelineScrollIndicator.init();
            })
            .catch(error => {
                console.error('Error fetching data:', error);
                loadingIndicator.style.display = 'none';
            });
        }

        const selectedPath = L.polyline([], {
            color: '#ff984f',
            weight: 6,
            opacity: 1,
            lineJoin: 'round',
            lineCap: 'round'
        });

        // Create a polyline for raw location points
        const rawPointsPath = L.polyline([], {
            color: '#f1ba63',  // Purple color for raw points
            weight: 6,
            opacity: 0.9,
            lineJoin: 'round',
            lineCap: 'round'
        });

        // Function to update the timeline with fetched data
        function updateTimeline(data, rawPointsData) {
            const timelineContainer = document.querySelector('.timeline-container');
            const loadingIndicator = document.getElementById('loading-indicator');
            timelineContainer.innerHTML = '';
            timelineContainer.appendChild(loadingIndicator);

            // Clear existing markers and paths
            map.eachLayer(layer => {
                if (!layer._url) {
                    map.removeLayer(layer);
                }
            });

            if (!data || !data.entries || data.entries.length === 0) {
                const noDataMsg = document.createElement('div');
                noDataMsg.className = 'timeline-entry';
                noDataMsg.textContent = window.locale.noData;
                timelineContainer.appendChild(noDataMsg);
                return;
            }

            const bounds = L.latLngBounds();
            // Store the original bounds for deselection
            window.originalBounds = L.latLngBounds();

            let hasValidCoords = false;

            // Group places by coordinates to avoid duplicate markers
            const placeGroups = new Map();

            // Create timeline entries
            data.entries.forEach(entry => {
                const entryElement = document.createElement('div');
                entryElement.className = `timeline-entry ${entry.type.toLowerCase()}`;
                entryElement.dataset.id = entry.id;

                // Set coordinates based on entry type
                if (entry.type === 'VISIT' && entry.place) {
                    entryElement.dataset.lat = entry.place.latitude;
                    entryElement.dataset.lng = entry.place.longitude;
                } else if (entry.type === 'TRIP') {
                    // For trips, use start place coordinates
                    if (entry.startPlace) {
                        entryElement.dataset.lat = entry.startPlace.latitude;
                        entryElement.dataset.lng = entry.startPlace.longitude;
                    }

                    // If trip has path data, add it
                    if (entry.path) {
                        entryElement.dataset.path = JSON.stringify(entry.path);
                    }
                }

                // Create time element
                const timeElement = document.createElement('div');
                timeElement.className = 'entry-time';
                const startTime = new Date(entry.startTime);
                const endTime = new Date(entry.endTime);
                
                // Get the selected date from the URL or use today
                const urlParams = new URLSearchParams(window.location.search);
                let selectedDateStr = urlParams.get('date');
                const selectedDate = selectedDateStr ? new Date(selectedDateStr) : new Date();
                selectedDate.setHours(0, 0, 0, 0); // Set to beginning of day
                
                // Format start time
                let startTimeStr = startTime.toLocaleTimeString([], {
                    hour: '2-digit',
                    minute: '2-digit',
                    hour12: false
                });
                
                // If start time is not on the selected day, add day and month
                if (startTime.getDate() !== selectedDate.getDate() || 
                    startTime.getMonth() !== selectedDate.getMonth() || 
                    startTime.getFullYear() !== selectedDate.getFullYear()) {
                    startTimeStr = startTime.toLocaleDateString([], {
                        day: 'numeric',
                        month: 'short'
                    }) + ' ' + startTimeStr;
                }
                
                // Format end time
                let endTimeStr = endTime.toLocaleTimeString([], {
                    hour: '2-digit',
                    minute: '2-digit',
                    hour12: false
                });
                
                // If end time is not on the selected day, add day and month
                if (endTime.getDate() !== selectedDate.getDate() || 
                    endTime.getMonth() !== selectedDate.getMonth() || 
                    endTime.getFullYear() !== selectedDate.getFullYear()) {
                    endTimeStr = endTime.toLocaleDateString([], {
                        day: 'numeric',
                        month: 'short'
                    }) + ' ' + endTimeStr;
                }
                
                timeElement.textContent = `${startTimeStr} - ${endTimeStr}`;

                // Calculate duration
                const durationMs = endTime - startTime;
                const durationText = humanizeDuration(durationMs, {
                    units: ["h", "m"], 
                    round: true,
                    language: currentLocale
                });

                const durationElement = document.createElement('span');
                durationElement.className = 'entry-duration';
                durationElement.textContent = `${window.locale.duration}: ${durationText}`;

                // Create description element
                const descElement = document.createElement('div');
                descElement.className = 'entry-description';

                if (entry.type === 'VISIT') {
                    descElement.textContent = entry.place ? entry.place.name || 'Unknown Place' : 'Unknown Place';
                } else if (entry.type === 'TRIP') {
                    descElement.textContent = window.locale.trip;
                    if (entry.distanceMeters) {
                        const distanceKm = (entry.distanceMeters / 1000).toFixed(1);
                        durationElement.textContent = `${window.locale.distance}: ${distanceKm} km `;
                    }

                    if (entry.transportMode) {
                        switch (entry.transportMode) {
                            case 'WALKING':
                                durationElement.textContent += entry.distanceMeters ? ` ${window.locale.transportWalking}` : ` ${window.locale.transportWalking}`;
                                break;
                            case 'CYCLING':
                                durationElement.textContent += entry.distanceMeters ? ` ${window.locale.transportCycling}` : ` ${window.locale.transportCycling}`;
                                break;
                            case 'DRIVING':
                                durationElement.textContent += entry.distanceMeters ? ` ${window.locale.transportDriving}` : ` ${window.locale.transportDriving}`;
                                break;
                        }

                    }
                }

                // Add elements to entry
                entryElement.appendChild(descElement);
                entryElement.appendChild(durationElement);
                entryElement.appendChild(timeElement);

                // Add entry to timeline
                timelineContainer.appendChild(entryElement);

                // Group places by coordinates for visits
                const lat = parseFloat(entryElement.dataset.lat);
                const lng = parseFloat(entryElement.dataset.lng);

                if (!isNaN(lat) && !isNaN(lng) && entry.type === 'VISIT') {
                    const coordKey = `${lat.toFixed(6)},${lng.toFixed(6)}`;
                    
                    if (!placeGroups.has(coordKey)) {
                        placeGroups.set(coordKey, {
                            lat: lat,
                            lng: lng,
                            totalDurationMs: 0,
                            visits: [],
                            place: entry.place
                        });
                    }
                    
                    const group = placeGroups.get(coordKey);
                    const durationMs = new Date(entry.endTime) - new Date(entry.startTime);
                    group.totalDurationMs += durationMs;
                    group.visits.push(entry);
                    
                    bounds.extend([lat, lng]);
                    window.originalBounds.extend([lat, lng]);
                    hasValidCoords = true;
                }

            });

            // Add raw location points if available
            if (rawPointsData && rawPointsData.points && rawPointsData.points.length > 0) {
                const rawPointsCoords = rawPointsData.points.map(point => [point.latitude, point.longitude]);

                rawPointsPath.remove();
                // Add the raw points polyline to the map
                rawPointsPath.setLatLngs(rawPointsCoords);
                rawPointsPath.addTo(map);

                // Extend bounds with raw points
                const rawPointsBounds = L.latLngBounds(rawPointsCoords);
                if (rawPointsBounds.isValid()) {
                    bounds.extend(rawPointsBounds);
                    window.originalBounds.extend(rawPointsBounds);
                    hasValidCoords = true;
                }
            }

            // Draw markers for grouped places
            placeGroups.forEach((group, coordKey) => {
                const { lat, lng, totalDurationMs, visits, place } = group;
                
                // Calculate radius using logarithmic scale to prevent extreme differences
                // Base radius of 15m, with logarithmic scaling for duration
                const durationHours = totalDurationMs / (1000 * 60 * 60);
                const baseRadius = 15;
                const maxRadius = 100;
                const minRadius = 15;
                
                // Use logarithmic scale: log(1 + duration) to smooth out differences
                const logScale = Math.log(1 + durationHours) / Math.log(1 + 24); // Normalize to 24 hours
                const radius = Math.min(maxRadius, Math.max(minRadius, baseRadius + (logScale * (maxRadius - baseRadius))));

                // Create marker
                const marker = L.circleMarker([lat, lng], {
                    radius: 5,
                    fillColor: '#ff6c00',
                    color: '#fff',
                    weight: 1,
                    opacity: 1,
                    fillOpacity: 0.8
                }).addTo(map);

                // Create circle with calculated radius
                const circle = L.circle([lat, lng], {
                    color: '#dcae4a',
                    fillColor: '#ff984f',
                    fillOpacity: 0.1,
                    radius: radius
                }).addTo(map);

                const totalDurationText = humanizeDuration(totalDurationMs, {units: ["h", "m"], round: true});
                const visitCount = visits.length;
                const visitText = visitCount === 1 ? 'visit' : 'visits';
                
                let tooltip = L.tooltip([lat, lng], {
                    content: `<div style="font-size: 1.4rem; color: wheat">${place.name}</div>
                             <div>Address:<br />${place.address}</div>
                             <div style="margin-top: 4px; font-weight: bold;">
                                 ${visitCount} ${visitText} - Total: ${totalDurationText}
                             </div>`,
                    className: 'visit-popup', 
                    permanent: false
                });

                circle.bindTooltip(tooltip);
            });

            // Fit map to bounds if we have valid coordinates
            if (hasValidCoords) {
                map.fitBounds(bounds, {
                    padding: [50, 50],
                    maxZoom: 16
                });
            }
        }

        // Handle clicks on timeline entries
        document.querySelector('.timeline-container').addEventListener('click', function (event) {
            const entry = event.target.closest('.timeline-entry');
            if (!entry) return;
            
            // Check if this entry is already active (deselection case)
            const isCurrentlyActive = entry.classList.contains('active');
            
            // Remove active class from all entries
            document.querySelectorAll('.timeline-container .timeline-entry')
                .forEach(e => e.classList.remove('active'));
            
            // Remove any selected path
            selectedPath.remove();
            
            if (isCurrentlyActive) {
                // Deselection: zoom back to original bounds showing all data
                if (window.originalBounds && window.originalBounds.isValid()) {
                    map.flyToBounds(window.originalBounds, {
                        padding: [50, 50],
                        maxZoom: 16
                    });
                }
            } else {
                // Selection: zoom to specific entry
                entry.classList.add('active');
                const newBounds = L.latLngBounds();

                const lat = parseFloat(entry.dataset.lat);
                const lng = parseFloat(entry.dataset.lng);

                if (entry.dataset.path) {
                    const pathData = JSON.parse(entry.dataset.path);
                    const latlngs = pathData.map(coord => [coord.latitude, coord.longitude]);
                    latlngs.forEach(latlng => {
                        newBounds.extend(latlng);
                    });
                    selectedPath.setLatLngs(latlngs);
                    selectedPath.addTo(map);
                }
                    
                if (!isNaN(lat) && !isNaN(lng)) {
                    newBounds.extend([lat, lng]);
                }
                    
                if (newBounds.isValid()) {
                    map.flyToBounds(newBounds, {
                        padding: [50, 50],
                        maxZoom: 16
                    });
                }
            }
        });

        loadTimelineData(formattedDate);

        // Parse the initial date properly to ensure correct date picker initialization
        let dateToUse = new Date();
        if (initialDate) {
            // Parse the date from URL parameter (YYYY-MM-DD format)
            const [year, month, day] = initialDate.split('-').map(Number);
            // Note: month is 0-indexed in JavaScript Date
            dateToUse = new Date(year, month - 1, day);
        }

        // Initialize horizontal date picker
        new HorizontalDatePicker({
            container: document.getElementById('horizontal-date-picker-container'),
            selectedDate: dateToUse,
            autoSelectOnScroll: true, // Enable auto-select on scroll
            showNavButtons: false, // Show navigation buttons
            daysToShow: 21, // Show more days
            showMonthRow: true, // Enable month selection row
            showYearRow: true, // Enable year selection row
            yearsToShow: 5, // Show 5 years in the year row
            allowFutureDates: false, // Disable selection of future dates
            showTodayButton: true, // Show the Today button
            // No min/max date for infinite scrolling
            onDateSelect: (date, formattedDate) => {
                // Update URL
                updateUrlWithDate(formattedDate);

                // Load timeline data
                loadTimelineData(formattedDate);
            },
            onDateDeselect: () => {
                // Clear photos when no date is selected
                photoClient.clearPhotos();
            }
        });
    });
</script>
</body>
</html>
