<!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="stylesheet" href="/css/leaflet.css">
    <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">
    <link rel="stylesheet" href="/css/inline-edit.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>
    <script src="/js/htmx.min.js"></script>
    <script src="/js/leaflet.js"></script>
    <script src="/js/TileLayer.Grayscale.js"></script>
    <script src="/js/leaflet.geodesic.2.7.2.js"></script>
</head>
<body>
<div id="message-container">
    <div id="sse-message"></div>
</div>
<div id="map"></div>

<!-- Auto-update overlay -->
<div id="auto-update-overlay" class="auto-update-overlay">
    <button class="overlay-button exit-button" onclick="disableAutoUpdate()" title="Exit Auto Update">
        <i class="lni lni-pause"></i>
    </button>
    <button class="overlay-button fullscreen-button" onclick="toggleFullscreen()" title="Toggle Fullscreen">
        <i class="lni lni-arrow-all-direction"></i>
    </button>
    <div class="date" id="auto-update-date"></div>
    <div class="time" id="auto-update-time"></div>
</div>

<div class="timeline">
    <div class="timeline-header">
        <span><img class="logo" th:src="@{/img/logo.png}" alt="reitti logo" title="reitti" src="/img/logo.png"></span>
        <a href="/statistics" class="nav-link" th:title="#{nav.statistics}"><i class="lni lni-bar-chart-4"></i></a>
        <a href="/settings" class="nav-link" th:title="#{nav.settings.tooltip}"><i class="lni lni-gear-1"></i></a>
        <a type="button" class="nav-link" id="auto-update-btn" onclick="toggleAutoUpdate()" title="Auto Update"><i class="lni lni-play"></i></a>
        <a type="button" class="nav-link" onclick="toggleFullscreen()" title="Toggle Fullscreen"><i class="lni lni-arrow-all-direction"></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>
    </div>
    <div class="timeline-container" 
         hx-get="/timeline/content"
         hx-trigger="load, dateChanged from:body"
         hx-vals='js:{"date": getSelectedDate(), "timezone": getUserTimezone()}'
         hx-indicator="#loading-indicator">
        <div id="loading-indicator" class="timeline-entry" th:text="#{timeline.loading}">Loading...</div>
    </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 = {
        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'
        ],
        sse: {
            error: /*[[#{sse.error.connection-lost}]]*/ 'Connection to server lost! Will reconnect ...',
        },
        autoupdate: {
          latestLocation:  /*[[#{map.auto-update.latest-location}]]*/ 'Latest location',
        }
    };

    window.userSettings = /*[[${userSettings}]]*/ {}

    const messagesDiv = document.getElementById('sse-message');    let autoUpdateMode = false;
    let autoUpdateTimer = null;
    let autoUpdateTimeInterval = null;
    let eventSource = null;
    let reloadTimeoutId = null;
    let pendingEvents = [];

    // Initialize the map
    const map = L.map('map', {zoomControl: false, attributionControl: false}).setView([window.userSettings.homeLatitude, window.userSettings.homeLongitude], 12);

    function getSelectedDate() {
        const urlParams = new URLSearchParams(window.location.search);
        if (urlParams.has('date')) {
            return urlParams.get('date');
        } else if (window.userSettings.newestData) {
            return window.userSettings.newestData.split('T')[0];
        } else {
            return new Date().toISOString().split('T')[0];
        }
    }
    // Helper function for HTMX to get user timezone
    function getUserTimezone() {
        return Intl.DateTimeFormat().resolvedOptions().timeZone;
    }

    function selectUser(userHeader) {
        // Remove active class from all user headers
        document.querySelectorAll('.user-header').forEach(header => {
            header.classList.remove('active');
        });

        // Add active class to clicked user header
        userHeader.classList.add('active');

        // Get the user ID from the clicked header
        const userId = userHeader.getAttribute('data-user-id');

        // Hide all user timeline sections
        document.querySelectorAll('.user-timeline-section').forEach(section => {
            section.classList.remove('active');
        });

        // Show the corresponding user timeline section
        const targetSection = document.querySelector(`.user-timeline-section[data-user-id="${userId}"]`);
        if (targetSection) {
            targetSection.classList.add('active');
        }
    }

    const fitToBoundsConfig = {
        paddingTopLeft: [100,0],
        paddingBottomRight: [100, 300],
        zoomSnap: 0.1
    };

    let pulsatingMarkers = [];

    document.addEventListener('DOMContentLoaded', function () {
        // 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;
            }
        }

        if (!initialDate && window.userSettings.newestData) {
            initialDate = window.userSettings.newestData.split('T')[0]
        }

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


        const tilesUrl = window.userSettings.tiles.service;
        const tilesAttribution = window.userSettings.tiles.attribution;

        const tileLayer = window.userSettings.preferColoredMap ? L.tileLayer : L.tileLayer.grayscale;
        tileLayer(tilesUrl, {
            maxZoom: 19,
            attribution:  tilesAttribution
        }).addTo(map);
        L.control.attribution({position: 'topright'}).addAttribution(tilesAttribution)
            .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 loadTimelineData(date) {
            // Load photos for the selected date
            photoClient.updatePhotosForDate(date, getUserTimezone());
            // Remove pulsating markers when loading new data
            removePulsatingMarkers();
            // Get raw location points URL from timeline container
            const timelineContainer = document.querySelectorAll('.user-timeline-section');
            for (const path of rawPointPaths) {
                path.remove();
            }

            for (const element of timelineContainer) {
                const rawLocationPointsUrl = element?.dataset.rawLocationPointsUrl;
                const color = element?.dataset.baseColor;
                if (rawLocationPointsUrl) {
                    // Fetch raw location points for map display
                    fetch(rawLocationPointsUrl).then(response => {
                        if (!response.ok) {
                            console.warn('Could not fetch raw location points');
                            return { points: [] };
                        }
                        return response.json();
                    }).then(rawPointsData => {
                        updateMapWithRawPoints(rawPointsData, color);
                    }).then(() => {
                        window.originalBounds = bounds;
                        map.fitBounds(bounds, fitToBoundsConfig)
                    }).catch(error => {
                        console.warn('Error fetching raw location points:', error);
                    });
                }
            }


        }

        // Function to update map with raw location points
        function updateMapWithRawPoints(rawPointsData, color) {
            const rawPointsPath = L.geodesic([], {
                color: color == null ? '#f1ba63' : color,
                weight: 6,
                opacity: 0.9,
                lineJoin: 'round',
                lineCap: 'round',
                steps: 2
            });

            if (rawPointsData && rawPointsData.points && rawPointsData.points.length > 0) {
                const rawPointsCoords = rawPointsData.points.map(point => [point.latitude, point.longitude]);
                bounds.extend(rawPointsCoords)
                rawPointsPath.setLatLngs(rawPointsCoords);
                rawPointsPath.addTo(map);
                rawPointPaths.push(rawPointsPath)
                
                // Add pulsating marker for the latest point if in auto-update mode and today is selected
                if (autoUpdateMode && isSelectedDateToday() && rawPointsData.points.length > 0) {
                    const latestPoint = rawPointsData.points[rawPointsData.points.length - 1];
                    addPulsatingMarker(latestPoint.latitude, latestPoint.longitude, color);
                }
            }
        }

        const selectedPath = L.geodesic([], {
            color: '#ff984f',
            weight: 6,
            opacity: 1,
            lineJoin: 'round',
            lineCap: 'round',
            steps: 2

        });

        const rawPointPaths = [];

        // Add HTMX event handlers for timeline updates
        document.body.addEventListener('htmx:afterSwap', function(event) {
            if (event.detail.target.classList.contains('timeline-container')) {
                // Timeline content has been updated, update map markers
                bounds = L.latLngBounds()
                loadTimelineData(getSelectedDate())
                updateMapFromTimeline();
                // Initialize scroll indicator after timeline is updated
                if (window.timelineScrollIndicator) {
                    window.timelineScrollIndicator.cleanup();
                }
                window.timelineScrollIndicator = new TimelineScrollIndicator();
                window.timelineScrollIndicator.init();
            }
        });
        let bounds = L.latLngBounds();
        // Function to update map markers from timeline entries
        function updateMapFromTimeline() {
            // Clear existing markers and paths (except tile layer)
            map.eachLayer(layer => {
                if (!layer._url) {
                    map.removeLayer(layer);
                }
            });


            window.originalBounds = L.latLngBounds();
            let hasValidCoords = false;

            // Group places by coordinates to avoid duplicate markers

            let timelineUserSections = document.querySelectorAll('.user-timeline-section ');

            for (const timelineUserSection of timelineUserSections) {
                const color = timelineUserSection?.dataset.baseColor;
                const timelineEntries = timelineUserSection.querySelectorAll('.timeline-entry[data-lat][data-lng]');

                const placeGroups = new Map();

                timelineEntries.forEach(entryElement => {
                    const lat = parseFloat(entryElement.dataset.lat);
                    const lng = parseFloat(entryElement.dataset.lng);

                    if (!isNaN(lat) && !isNaN(lng) && entryElement.classList.contains('visit')) {
                        const coordKey = `${lat.toFixed(6)},${lng.toFixed(6)}`;

                        if (!placeGroups.has(coordKey)) {
                            // Extract place name from the timeline entry
                            const placeNameElement = entryElement.querySelector('.place-name');
                            const placeName = placeNameElement ? placeNameElement.textContent : 'Unknown Place';

                            placeGroups.set(coordKey, {
                                lat: lat,
                                lng: lng,
                                totalDurationMs: 0,
                                visits: [],
                                place: { name: placeName, address: '' }
                            });
                        }

                        const group = placeGroups.get(coordKey);
                        // Calculate duration from time range text
                        const durationElement = entryElement.querySelector('.entry-duration');
                        if (durationElement) {
                            const durationText = durationElement.textContent;
                            const durationMs = parseDurationText(durationText);
                            group.totalDurationMs += durationMs;
                        }
                        group.visits.push({ id: entryElement.dataset.id });

                        bounds.extend([lat, lng]);
                        hasValidCoords = true;
                    }


                    // Draw markers for grouped places
                    placeGroups.forEach((group) => {
                        const { lat, lng, totalDurationMs, visits, place } = group;

                        // Calculate radius using logarithmic scale
                        const durationHours = totalDurationMs / (1000 * 60 * 60);
                        const baseRadius = 15;
                        const maxRadius = 100;
                        const minRadius = 15;

                        const logScale = Math.log(1 + durationHours) / Math.log(1 + 24);
                        const radius = Math.min(maxRadius, Math.max(minRadius, baseRadius + (logScale * (maxRadius - baseRadius))));

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

                        // Create circle with calculated radius
                        const circle = L.circle([lat, lng], {
                            color: color ? 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 style="margin-top: 4px; font-weight: bold;">
                                 ${visitCount} ${visitText} - Total: ${totalDurationText}
                             </div>`,
                            className: 'visit-popup',
                            permanent: false
                        });

                        bounds.extend([lat, lng])

                        circle.bindTooltip(tooltip);
                    });
                });

            }
        }

        // Helper function to parse duration text (simple implementation)
        function parseDurationText(durationText) {
            // Extract numbers followed by 'h' or 'm'
            const hours = (durationText.match(/(\d+)h/) || [0, 0])[1];
            const minutes = (durationText.match(/(\d+)m/) || [0, 0])[1];
            return (parseInt(hours) * 60 + parseInt(minutes)) * 60 * 1000; // Convert to milliseconds
        }

        // Handle clicks on timeline entries
        document.querySelector('.timeline-container').addEventListener('click', function (event) {
            const entry = event.target.closest('.timeline-entry');
            if (!entry) return;

            const editingElement = event.target.closest('.editing');
            if (editingElement || event.target.classList.contains('edit-icon')) {
                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, fitToBoundsConfig);
                }
            } 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, fitToBoundsConfig);
                }
            }
        });

        // Load initial timeline data via HTMX (will be triggered by the hx-trigger="load")
        // Also load photos and raw points for the initial date
        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
        window.horizontalDatePicker = new HorizontalDatePicker({
            container: document.getElementById('horizontal-date-picker-container'),
            selectedDate: dateToUse,
            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, isManualSelected) => {
                // Update URL
                updateUrlWithDate(formattedDate);
                // Trigger HTMX reload of timeline
                document.body.dispatchEvent(new CustomEvent('dateChanged'));
                if (isManualSelected) {
                    disableAutoUpdate();
                }
            }
        });
    });


    function toggleAutoUpdate() {
        const btn = document.getElementById('auto-update-btn');
        const icon = btn.querySelector('i');
        
        if (!autoUpdateMode) {
            // Enable auto-update mode
            autoUpdateMode = true;
            icon.className = 'lni lni-pause';
            btn.title = 'Pause Auto Update';
            
            // Hide timeline and date picker smoothly
            hideUIElements();
            
            // Show auto-update overlay
            showAutoUpdateOverlay();
            
            // Update the date picker to today
            if (window.horizontalDatePicker) {
                window.horizontalDatePicker.setDate(new Date());
            }

            // Start the timer to check for date changes every 30 seconds
            startAutoUpdateTimer();

            eventSource = new EventSource('/events'); // Connect to your SSE endpoint

            eventSource.onopen = function() {
                console.log('SSE connection opened.');
                messagesDiv.classList.remove('active')
            };

            // Listen for events with the name "message"
            eventSource.addEventListener('message', function(event) {
                console.log('Received message event:', event.data);
            });


            eventSource.onerror = function(error) {
                console.error('EventSource failed:', error);
                messagesDiv.innerHTML = `<p><strong>${window.locale.sse.error}</strong></p>`;
                messagesDiv.classList.add('active')
            };

            eventSource.onmessage = function(event) {
                console.log('Received generic event:', event.data);
                
                // Parse the event data
                try {
                    const eventData = JSON.parse(event.data);
                    
                    // Check if the event has a date field and it matches today
                    if (eventData.date) {
                        const today = new Date().toISOString().split('T')[0]; // YYYY-MM-DD format
                        const eventDate = eventData.date;
                        
                        // If event date matches today and we're in auto-update mode, schedule reload
                        if (eventDate === today && autoUpdateMode) {
                            console.log('Auto-update: Scheduling timeline reload due to SSE event for today');
                            scheduleTimelineReload(eventData);
                        }
                    }
                } catch (error) {
                    console.warn('Could not parse SSE event data:', error);
                }
            };

        } else {
            // Disable auto-update mode
            disableAutoUpdate();
        }
    }

    function disableAutoUpdate() {
        autoUpdateMode = false;
        
        // Clear the timer
        if (autoUpdateTimer) {
            clearInterval(autoUpdateTimer);
            autoUpdateTimer = null;
        }
        
        // Clear time update interval
        if (autoUpdateTimeInterval) {
            clearInterval(autoUpdateTimeInterval);
            autoUpdateTimeInterval = null;
        }
        
        // Clear any pending reload timeout
        if (reloadTimeoutId) {
            clearTimeout(reloadTimeoutId);
            reloadTimeoutId = null;
        }
        
        // Clear pending events
        pendingEvents = [];
        
        if (eventSource) {
            eventSource.close();
            eventSource = null;
        }
        
        // Remove pulsating markers when auto-update is disabled
        removePulsatingMarkers();
        
        // Hide auto-update overlay
        hideAutoUpdateOverlay();
        
        // Show timeline and date picker again
        showUIElements();
        
        const btn = document.getElementById('auto-update-btn');
        const icon = btn.querySelector('i');
        icon.className = 'lni lni-play';
        btn.title = 'Auto Update';
    }

    function startAutoUpdateTimer() {
        // Check every 30 seconds if we need to switch to today's date
        autoUpdateTimer = setInterval(() => {
            if (!autoUpdateMode) {
                return; // Exit if auto-update mode was disabled
            }
            
            const today = new Date();
            const todayString = today.toISOString().split('T')[0]; // YYYY-MM-DD format
            const currentSelectedDate = getSelectedDate();
            
            // If the selected date is not today, switch to today
            if (currentSelectedDate !== todayString) {
                console.log('Auto-update: Switching to today\'s date');
                if (window.horizontalDatePicker) {
                    window.horizontalDatePicker.setDate(today);
                }
            }
        }, 30000); // 30 seconds
    }

    function isSelectedDateToday() {
        const today = new Date().toISOString().split('T')[0];
        const selectedDate = getSelectedDate();
        return selectedDate === today;
    }

    function addPulsatingMarker(lat, lng, color) {
        // Create new pulsating marker
        const cssIcon = L.divIcon({
            // Specify a class name we can refer to in CSS.
            className: 'css-icon',
            html: `<div style="border-color: ${color || '#606060'}" class="gps_ring"></div>`
            ,iconSize: [22,22]
        });

        const pulsatingMarker = L.marker([lat, lng], {icon: cssIcon}).addTo(map);

        // Add tooltip
        pulsatingMarker.bindTooltip(window.locale.autoupdate.latestLocation, {
            permanent: false,
            direction: 'top'
        });

        // Store the marker for cleanup later
        pulsatingMarkers.push(pulsatingMarker);
    }

    function removePulsatingMarkers() {
        pulsatingMarkers.forEach(marker => {
            if (marker) {
                map.removeLayer(marker);
            }
        });
        pulsatingMarkers = [];
    }

    function scheduleTimelineReload(eventData) {
        // Add event to pending events
        pendingEvents.push(eventData);
        
        // Clear existing timeout if any
        if (reloadTimeoutId) {
            clearTimeout(reloadTimeoutId);
        }
        
        // Schedule reload after 5 seconds of idle time
        reloadTimeoutId = setTimeout(() => {
            debugger
            if (autoUpdateMode && pendingEvents.length > 0) {
                console.log(`Auto-update: Reloading timeline data after ${pendingEvents.length} accumulated events`);
                document.body.dispatchEvent(new CustomEvent('dateChanged'));
                // Clear pending events
                pendingEvents = [];
            }
            reloadTimeoutId = null;
        }, 5000); // 5 seconds
    }

    function hideUIElements() {
        const timeline = document.querySelector('.timeline');
        const datePicker = document.getElementById('horizontal-date-picker-container');
        
        timeline.classList.add('hidden');
        datePicker.classList.add('hidden');
    }

    function showUIElements() {
        const timeline = document.querySelector('.timeline');
        const datePicker = document.getElementById('horizontal-date-picker-container');
        
        timeline.classList.remove('hidden');
        datePicker.classList.remove('hidden');
    }

    function showAutoUpdateOverlay() {
        const overlay = document.getElementById('auto-update-overlay');
        
        // Update initial time
        updateAutoUpdateTime();
        
        // Show overlay
        overlay.classList.add('visible');
        
        // Start updating time every second
        autoUpdateTimeInterval = setInterval(updateAutoUpdateTime, 1000);
    }

    function hideAutoUpdateOverlay() {
        const overlay = document.getElementById('auto-update-overlay');
        overlay.classList.remove('visible');
    }

    function updateAutoUpdateTime() {
        const now = new Date();
        const dateElement = document.getElementById('auto-update-date');
        const timeElement = document.getElementById('auto-update-time');
        
        // Use browser locale for date formatting
        const dateOptions = { 
            weekday: 'long', 
            year: 'numeric', 
            month: 'long', 
            day: 'numeric' 
        };
        const formattedDate = now.toLocaleDateString(navigator.language, dateOptions);
        
        // Use browser locale for time formatting
        const timeOptions = { 
            hour: '2-digit', 
            minute: '2-digit',
            hour12: false
        };
        const formattedTime = now.toLocaleTimeString(navigator.language, timeOptions);
        
        dateElement.textContent = formattedDate;
        timeElement.textContent = formattedTime;
    }

    function toggleFullscreen() {
        if (!document.fullscreenElement) {
            document.documentElement.requestFullscreen().catch(err => {
                console.log(`Error attempting to enable fullscreen: ${err.message}`);
            });
        } else {
            document.exitFullscreen();
        }
    }
</script>
</body>
</html>
