<!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="#{settings.title}">Settings - Reitti</title>
    <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/leaflet.js"></script>
    <script src="/js/TileLayer.Grayscale.js"></script>
</head>
<body class="settings-page">
    <div class="settings-container">
        <!-- Settings navigation sidebar -->
        <div class="settings-nav">
            <div class="timeline-header">
                <a th:href="@{/}"><img class="logo" th:src="@{/img/logo.png}" alt="reitti logo" title="reitti" src="/img/logo.png"></a>
                <a href="/" class="nav-link" th:title="#{nav.timeline}"><i class="lni lni-route-1"></i></a>
                <a href="/statistics" class="nav-link" th:title="#{nav.statistics}"><i class="lni lni-bar-chart-4"></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>
            <a href="/settings?section=job-status" 
               class="settings-nav-item" 
               th:classappend="${activeSection == 'job-status'} ? 'active' : ''"
               th:text="#{settings.job.status}">Job Status</a>
            
            <a href="/settings?section=file-upload" 
               class="settings-nav-item"
               th:classappend="${activeSection == 'file-upload'} ? 'active' : ''"
               th:text="#{settings.import.data}">Import Data</a>

            <a href="/settings?section=export-data"
               class="settings-nav-item"
               th:classappend="${activeSection == 'export-data'} ? 'active' : ''"
               th:text="#{export.title}">Export Data</a>

            <a href="/settings?section=api-tokens" 
               class="settings-nav-item"
               th:classappend="${activeSection == 'api-tokens'} ? 'active' : ''"
               th:text="#{settings.api.tokens}">API Tokens</a>

            <a href="/settings?section=user-management"
               class="settings-nav-item"
               th:classappend="${activeSection == 'user-management'} ? 'active' : ''"
               th:text="#{settings.user.management}">User Management</a>
            
            <a href="/settings?section=places-management" 
               class="settings-nav-item"
               th:classappend="${activeSection == 'places-management'} ? 'active' : ''"
               th:text="#{settings.places}">Places</a>
            
            <a href="/settings?section=geocode-services" 
               class="settings-nav-item"
               th:classappend="${activeSection == 'geocode-services'} ? 'active' : ''"
               th:text="#{settings.geocoding}">Geocoding</a>
            
            <a href="/settings?section=manage-data" 
               th:if="${dataManagementEnabled}"
               class="settings-nav-item"
               th:classappend="${activeSection == 'manage-data'} ? 'active' : ''"
               th:text="#{settings.manage.data}">Manage Data</a>
            
            <a href="/settings?section=integrations" 
               class="settings-nav-item"
               th:classappend="${activeSection == 'integrations'} ? 'active' : ''"
               th:text="#{settings.integrations}">Integrations</a>

            <a href="/settings?section=about-section" 
               class="settings-nav-item"
               th:classappend="${activeSection == 'about-section'} ? 'active' : ''"
               th:text="#{settings.about}">About</a>
        </div>

        <!-- Settings content area -->
        <div class="settings-content-area">
            <!-- API Tokens Section -->
            <div th:if="${activeSection == 'api-tokens'}" id="api-tokens" class="settings-section active">
                <div th:replace="~{fragments/api-tokens :: api-tokens-content}"></div>
            </div>

            <!-- User Management Section -->
            <div th:if="${activeSection == 'user-management'}" id="user-management" class="settings-section active">
                <div th:replace="~{fragments/user-management :: ${isAdmin ? 'users-list' : 'user-form-page'}}"></div>
            </div>

            <!-- Places Management Section -->
            <div th:if="${activeSection == 'places-management'}" id="places-management" class="settings-section active">
                <div th:replace="~{fragments/settings :: places-content}"></div>
            </div>

            <!-- Geocoding Services Section -->
            <div th:if="${activeSection == 'geocode-services'}" id="geocode-services" class="settings-section active">
                <div th:replace="~{fragments/settings :: geocode-services-content}"></div>
            </div>

            <!-- Integrations Section -->
            <div th:if="${activeSection == 'integrations'}" id="integrations" class="settings-section active">
                <div th:replace="~{fragments/settings :: integrations-content}"></div>
            </div>

            <!-- Manage Data Section -->
            <div th:if="${dataManagementEnabled && activeSection == 'manage-data'}" id="manage-data" class="settings-section active">
                <div th:replace="~{fragments/settings :: manage-data-content}"></div>
            </div>

            <!-- Job Status Section -->
            <div th:if="${activeSection == 'job-status'}" id="job-status" class="settings-section active">
                <div th:replace="~{fragments/settings :: queue-stats-content}"></div>
            </div>

            <!-- File Upload Section -->
            <div th:if="${activeSection == 'file-upload'}" id="file-upload" class="settings-section active"
                 hx-get="/import/file-upload-content" hx-trigger="load once">
                <div class="htmx-indicator">Loading file upload options...</div>
            </div>

            <!-- Export Data Section -->
            <div th:if="${activeSection == 'export-data'}" id="export-data" class="settings-section active">
                <div th:replace="~{fragments/export-data :: export-data-content}"></div>
            </div>

            <!-- About Section -->
            <div th:if="${activeSection == 'about-section'}" id="about-section" class="settings-section active">
                <div th:replace="~{fragments/settings :: about-content}"></div>
            </div>
        </div>
    </div>

    <script th:inline="javascript">
        window.userSettings = /*[[${userSettings}]]*/ {}

        function removeCurrentAvatar() {
            // Hide the current avatar preview
            const avatarPreview = document.querySelector('.current-avatar');
            if (avatarPreview) {
                avatarPreview.style.display = 'none';
            }

            // Clear the file input
            const fileInput = document.getElementById('avatar');
            if (fileInput) {
                fileInput.value = '';
            }

            // Set the remove flag
            const removeFlag = document.getElementById('removeAvatarFlag');
            if (removeFlag) {
                removeFlag.value = 'true';
            }

            // Hide the remove button
            const avatarActions = document.querySelector('.avatar-actions');
            if (avatarActions) {
                avatarActions.style.display = 'none';
            }
        }

        function initPlaceMaps() {
            document.querySelectorAll('.place-map:not(.leaflet-container)').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
                })
                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(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:afterSettle', function (event) {
            if (event.detail.target.id === 'places-management' ||
                event.detail.target.closest('#places-management')) {
                initPlaceMaps();
            }
        });

        // Navigation is now handled server-side via URL parameters

        document.addEventListener('DOMContentLoaded', function() {
            // Function to disable all upload buttons and show spinners
            function disableAllUploads() {
                const uploadButtons = document.querySelectorAll('.upload-btn');
                const spinners = document.querySelectorAll('.spinner');

                uploadButtons.forEach(button => {
                    button.disabled = true;
                    button.style.display = 'none';
                });

                spinners.forEach(spinner => {
                    spinner.style.display = 'flex';
                });
            }
            initPlaceMaps();
            if (document.querySelector('#homeLocationMap')) {
                setTimeout(initializeHomeLocationMap, 100);
            }
            // Function to enable all upload buttons and hide spinners
            function enableAllUploads() {
                const uploadButtons = document.querySelectorAll('.upload-btn');
                const spinners = document.querySelectorAll('.spinner');

                uploadButtons.forEach(button => {
                    button.disabled = false;
                    button.style.display = 'inline-block';
                });

                spinners.forEach(spinner => {
                    spinner.style.display = 'none';
                });
            }

            // Listen for HTMX request start events on actual file upload forms only
            document.body.addEventListener('htmx:beforeRequest', function(evt) {
                const form = evt.target;
                if (form && form.id && typeof form.id === 'string' && form.id.includes('upload-form') && !form.id.includes('integration')) {
                    disableAllUploads();
                }
            });

            // Listen for HTMX request completion events on actual file upload forms only
            document.body.addEventListener('htmx:afterRequest', function(evt) {
                const form = evt.target;
                if (form && form.id && typeof form.id === 'string' && form.id.includes('upload-form') && !form.id.includes('integration')) {
                    enableAllUploads();
                }
            });

            // Handle progress events
            document.body.addEventListener('htmx:xhr:progress', function(evt) {
                const form = evt.target;
                if (form.id && typeof form.id === 'string' ) {
                    const progressId = form.id.replace('-upload-form', '').replace('-', '-');
                    const progressElement = document.getElementById('progress-' + progressId);
                    if (progressElement) {
                        progressElement.setAttribute('value', evt.detail.loaded/evt.detail.total * 100);
                        progressElement.style.display = 'block';
                    }
                }
            });
        });

        // Home location map functionality
        let homeLocationMap;
        let homeLocationMarker;

        function initializeHomeLocationMap() {
            if (typeof L === 'undefined') {
                console.error('Leaflet is not loaded');
                return;
            }
            const tilesUrl = window.userSettings.tiles.service;
            const tilesAttribution = window.userSettings.tiles.attribution;
            const tileLayer = window.userSettings.preferColoredMap ? L.tileLayer : L.tileLayer.grayscale;

            // Initialize map
            homeLocationMap = L.map('homeLocationMap').setView([60.1699, 24.9384], 10)
            // Add tile layer
            tileLayer(tilesUrl, {
                attribution: tilesAttribution
            }).addTo(homeLocationMap);

            // Get current home location from form inputs
            const latInput = document.getElementById('homeLatitude');
            const lngInput = document.getElementById('homeLongitude');
            
            if (latInput && latInput.value && lngInput && lngInput.value) {
                const lat = parseFloat(latInput.value);
                const lng = parseFloat(lngInput.value);
                
                if (!isNaN(lat) && !isNaN(lng)) {
                    homeLocationMap.setView([lat, lng], 13);
                    // Create marker
                    homeLocationMarker = L.circleMarker([lat, lng], {
                        radius: 15,
                        fillColor: '#ff6c00',
                        color: '#fff',
                        weight: 1,
                        opacity: 1,
                        fillOpacity: 0.8,
                        draggable: true
                    }).addTo(homeLocationMap);

                    homeLocationMarker.on('dragend', function(e) {
                        const position = e.target.getLatLng();
                        updateCoordinateInputs(position.lat, position.lng);
                    });
                }
            }
            
            // Add click event to map
            homeLocationMap.on('click', function(e) {
                const lat = e.latlng.lat;
                const lng = e.latlng.lng;
                
                if (homeLocationMarker) {
                    homeLocationMap.removeLayer(homeLocationMarker);
                }

                homeLocationMarker = L.circleMarker([lat, lng], {
                    radius: 15,
                    fillColor: '#ff6c00',
                    color: '#fff',
                    weight: 1,
                    opacity: 1,
                    fillOpacity: 0.8,
                    draggable: true
                }).addTo(homeLocationMap);
                updateCoordinateInputs(lat, lng);
                
                homeLocationMarker.on('dragend', function(e) {
                    const position = e.target.getLatLng();
                    updateCoordinateInputs(position.lat, position.lng);
                });
            });
        }

        function updateCoordinateInputs(lat, lng) {
            const latInput = document.getElementById('homeLatitude');
            const lngInput = document.getElementById('homeLongitude');
            if (latInput && lngInput) {
                latInput.value = lat.toFixed(6);
                lngInput.value = lng.toFixed(6);
            }
        }

        window.updateMapMarker = function() {
            if (!homeLocationMap) return;
            
            const latInput = document.getElementById('homeLatitude');
            const lngInput = document.getElementById('homeLongitude');
            
            if (!latInput || !lngInput) return;
            
            const lat = parseFloat(latInput.value);
            const lng = parseFloat(lngInput.value);
            
            if (!isNaN(lat) && !isNaN(lng) && lat >= -90 && lat <= 90 && lng >= -180 && lng <= 180) {
                if (homeLocationMarker) {
                    homeLocationMap.removeLayer(homeLocationMarker);
                }

                homeLocationMarker = L.circleMarker([lat, lng], {
                    radius: 15,
                    fillColor: '#ff6c00',
                    color: '#fff',
                    weight: 1,
                    opacity: 1,
                    fillOpacity: 0.8,
                    draggable: true
                }).addTo(homeLocationMap);
                homeLocationMap.setView([lat, lng], 13);
                
                homeLocationMarker.on('dragend', function(e) {
                    const position = e.target.getLatLng();
                    updateCoordinateInputs(position.lat, position.lng);
                });
            } else if (homeLocationMarker) {
                homeLocationMap.removeLayer(homeLocationMarker);
                homeLocationMarker = null;
            }
        }

        window.clearHomeLocation = function() {
            const latInput = document.getElementById('homeLatitude');
            const lngInput = document.getElementById('homeLongitude');
            
            if (latInput) latInput.value = '';
            if (lngInput) lngInput.value = '';
            
            if (homeLocationMarker && homeLocationMap) {
                homeLocationMap.removeLayer(homeLocationMarker);
                homeLocationMarker = null;
            }
        }

        // Initialize home location map when user management section loads
        document.body.addEventListener('htmx:afterSettle', function(evt) {
            if (evt.detail.target.querySelector && evt.detail.target.querySelector('#homeLocationMap')) {
                setTimeout(initializeHomeLocationMap, 100);
            }
        });
    </script>

</body>
</html>
