<!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="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/leaflet.js"></script>
    <script src="/js/TileLayer.Grayscale.js"></script>
    <script src="/js/util.js"></script>
</head>
<body class="settings-page">
<div class="settings-container">
    <div th:replace="~{fragments/settings-navigation :: settings-nav(${activeSection}, ${dataManagementEnabled}, ${isAdmin})}"></div>
    <div class="settings-content-area">
        <div id="places-management" class="settings-section active">
            <div th:fragment="places-content">
                <h2 th:text="#{places.title}">Significant Places</h2>

                <div th:if="${successMessage}" class="alert alert-success" style="display: block;">
                    <span th:text="${successMessage}">Success message</span>
                </div>
                <div th:if="${errorMessage}" class="alert alert-danger" style="display: block;">
                    <span th:text="${errorMessage}">Error message</span>
                </div>

                <div class="search-container" style="margin-bottom: 20px;">
                    <input type="text" id="search-input" name="search" th:value="${search}" placeholder="Search places..." style="width: 100%; padding: 10px; border: 1px solid #ccc; border-radius: 4px;" hx-get="/settings/places/places-content" hx-target="#places-management" hx-swap="innerHTML" hx-trigger="input changed delay:300ms" hx-vals='{"page": 0}' />
                </div>

                <div class="places-grid" th:if="${!isEmpty}">
                    <div class="place-stats-card" th:each="place : ${places}">
                        <div class="place-map-container">
                            <div class="place-map" th:id="'map-' + ${place.id()}" th:data-lat="${place.latitude()}" th:data-lng="${place.longitude()}" ></div>
                        </div>
                        <div class="place-details text-align-left">
                            <div class="place-info">
                                <div><strong th:text="#{places.name.label}">Name:</strong> <span th:text="${place.name()}"></span></div>
                                <div><strong th:text="#{places.address.label}">Address:</strong> <span th:text="${place.address() ?: #messages.msg('places.address.not.available')}"></span></div>
                                <div><strong th:text="#{places.category.label}">Category:</strong> <span th:text="#{${place.type().messageKey}}"></span></div>
                                <div><strong th:text="#{places.coordinates.label}">Coordinates:</strong> <span th:text="${place.latitude() + ', ' + place.longitude()}"></span></div>
                            </div>
                            <div style="display: flex; gap: 10px; margin-top: 10px;">
                                <button type="button"
                                        class="btn btn-block"
                                        th:attr="hx-get=@{/settings/places/{id}/edit(id=${place.id()}, page=${currentPage}, search=${search})}"
                                        hx-target="#places-management"
                                        hx-swap="innerHTML"
                                        th:text="#{places.edit.button}">Edit</button>
                            </div>
                        </div>
                    </div>
                </div>
                <p th:if="${isEmpty}" th:text="#{places.no.places}">No significant places found.</p>

                <div class="pagination-controls" style="text-align: right;">
                    <span th:text="#{places.page.info(${currentPage + 1}, ${totalPages})}">Page 1 of 1</span>
                    <div class="pagination-buttons">
                        <button th:if="${currentPage > 0}"
                                class="btn"
                                th:attr="hx-get=@{/settings/places/places-content(page=${currentPage - 1}, search=${search})}"
                                hx-target="#places-management"
                                hx-swap="innerHTML"
                                th:text="#{form.previous}">Previous</button>
                        <button th:if="${currentPage < totalPages - 1}"
                                class="btn"
                                th:attr="hx-get=@{/settings/places/places-content(page=${currentPage + 1}, search=${search})}"
                                hx-target="#places-management"
                                hx-swap="innerHTML"
                                th:text="#{form.next}">Next</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

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

    document.addEventListener('DOMContentLoaded', function () {
        initPlaceMaps();
    })


    function initPlaceMaps() {
        // Initialize read-only place maps
        document.querySelectorAll('.place-map:not(.leaflet-container)').forEach(mapElement => {
            if (mapElement.id.startsWith('edit-map-')) {
                return; // Skip edit maps, they're handled separately
            }
            
            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();
            }
        });

        // Initialize interactive edit maps
        document.querySelectorAll('.place-map[id^="edit-map-"]:not(.leaflet-container)').forEach(mapElement => {
            const lat = parseFloat(mapElement.dataset.lat);
            const lng = parseFloat(mapElement.dataset.lng);
            const placeMap = L.map(mapElement, {
                zoomControl: true,
                attributionControl: true,
                dragging: true,
                scrollWheelZoom: true
            })
            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], 16);

                L.circleMarker([lat, lng], {
                    radius: 10,
                    fillColor: '#4a89dc',
                    color: '#fff',
                    weight: 2,
                    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();
        }
    });
</script>
<script th:inline="javascript">
    window.userSettings = /*[[${userSettings}]]*/ {}
</script>
</body>
</html>
