<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>


<!-- Places Content Fragment -->
<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="pagination-controls">
        <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-content(page=${currentPage - 1})}"
                    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-content(page=${currentPage + 1})}"
                    hx-target="#places-management"
                    hx-swap="innerHTML"
                    th:text="#{form.next}">Next</button>
        </div>
    </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">
                <form th:id="'place-form-' + ${place.id()}"  autocomplete="off"
                      th:attr="hx-post=@{/settings/places/{id}/update(id=${place.id()}, page=${currentPage})}"
                      hx-target="#places-management"
                      hx-swap="innerHTML">
                    <div class="form-group">
                        <label th:for="'name-' + ${place.id()}" th:text="#{places.name.label}">Name</label>
                        <input type="text" th:id="'name-' + ${place.id()}" name="name" th:value="${place.name()}" required>
                    </div>
                    <div class="form-group">
                        <label th:for="'address-' + ${place.id()}" th:text="#{places.address.label}">Address</label>
                        <input type="text" th:id="'address-' + ${place.id()}" name="address" th:value="${place.address()}" th:placeholder="#{places.address.placeholder}">
                    </div>
                    <div class="form-group">
                        <label th:for="'type-' + ${place.id()}" th:text="#{places.category.label}">Category</label>
                        <select th:id="'type-' + ${place.id()}" name="type" class="form-select">
                            <option th:each="placeType : ${placeTypes}" 
                                    th:value="${placeType.name()}" 
                                    th:selected="${placeType == place.type()}"
                                    th:text="#{${placeType.messageKey}}">Place Type</option>
                        </select>
                    </div>
                    <div class="place-info">
                        <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="submit" class="btn" th:text="#{form.update}">Update</button>
                        <button type="button" 
                                class="btn btn-secondary"
                                th:attr="hx-post=@{/settings/places/{id}/geocode(id=${place.id()}, page=${currentPage})}, hx-confirm=#{places.geocode.confirm}"
                                hx-target="#places-management"
                                hx-swap="innerHTML"
                                th:text="#{places.geocode.button}">Geocode</button>
                        <button type="button" 
                                class="btn btn-secondary"
                                th:attr="hx-get=@{/settings/places/{id}/geocoding-response(id=${place.id()}, page=${currentPage})}"
                                hx-target="#places-management"
                                hx-swap="innerHTML"
                                th:text="#{places.geocoding.response.button}">View Geocoding</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <p th:if="${isEmpty}" th:text="#{places.no.places}">No significant places found.</p>
</div>

<!-- Queue Stats Content Fragment -->
<div th:fragment="queue-stats-content">
    <h2 th:text="#{jobs.title}">Job Status</h2>

    <div class="queue-status">
        <div class="queue-card" th:each="queue : ${queueStats}">
            <div class="queue-name" th:text="${queue.name()}">Queue Name</div>
            <div class="queue-count" th:text="${queue.count()}">0</div>
            <div class="queue-time" th:text="#{jobs.estimated.time(${queue.estimatedTime()})}">Est. processing time: 0 min</div>
            <div class="progress-bar">
                <div class="progress-fill" th:style="'width:' + ${queue.rate()} + '%'"></div>
            </div>
        </div>
    </div>

    <div style="margin-top: 20px;">
        <button class="btn" 
                hx-get="/settings/queue-stats-content" 
                hx-target="#job-status" 
                hx-swap="innerHTML"
                th:text="#{jobs.refresh}">Refresh Status</button>
    </div>
</div>

<!-- Integrations Content Fragment -->
<div th:fragment="integrations-content">
    <h2 th:text="#{integrations.title}">App Integrations</h2>
    
    <div th:if="${!hasToken}" style="background-color: #fff3cd; border: 1px solid #ffeaa7; border-radius: 4px; padding: 15px; margin-bottom: 20px; color: #856404;">
        <strong>⚠️ No API Token Available</strong><br>
        <span th:text="#{integrations.no.token.warning}">You need to create an API token first in the "API Tokens" tab before setting up app integrations.</span>
    </div>
    
    <!-- Data Ingestion Collapsible Section -->
    <div>
        <details th:attr="open=${openSection == 'data-ingestion' ? 'open' : null}">
            <summary>
                <i class="lni lni-phone"></i> <span th:text="#{integrations.data.ingestion.title}">Data Ingestion</span>
            </summary>
            <div style="padding: 15px;">
                <p th:text="#{integrations.data.ingestion.description}" style="margin-bottom: 20px; color: var(--color-text-white);">Configure mobile apps to automatically send location data to Reitti</p>

                <div class="integration-section" style="margin-bottom: 30px;">
                    <h3 th:text="#{integrations.gpslogger.title}">📱 GPSLogger Setup</h3>
                    <p th:text="#{integrations.gpslogger.description}">GPSLogger is a free Android app that can automatically log your location and send it to Reitti.</p>

                    <div class="setup-steps">
                        <h4 th:text="#{integrations.setup.instructions}">Setup Instructions:</h4>
                        <ol>
                            <li>Download GPSLogger from the Google Play Store</li>
                            <li>Open GPSLogger and go to <strong>Logging details → Log to custom URL</strong></li>
                            <li>Enable "Log to custom URL"</li>
                            <li th:if="${hasToken}">Set the URL to: <code th:text="${serverUrl + '/api/v1/ingest/owntracks?token=' + firstToken}">https://your-domain.com/api/v1/location-data</code></li>
                            <li th:unless="${hasToken}">Set the URL to: <code th:text="${serverUrl + '/api/v1/ingest/owntracks?token=<YOUR TOKEN>'}">https://your-domain.com/api/v1/location-data</code></li>
                            <li>Set HTTP Method to <strong>POST</strong></li>
                            <li>Set HTTP Body to: <code>{
                                "_type" : "location",
                                "t": "u",
                                "acc": "%ACC",
                                "alt": "%ALT",
                                "batt": "%BATT",
                                "bs": "%ISCHARGING",
                                "lat": "%LAT",
                                "lon": "%LON",
                                "tst": "%TIMESTAMP",
                                "vel": "%SPD"
                                }</code></li>
                            <li>Set HTTP header to: <code>Content-Type: application/json</code></li>
                            <li>Start logging!</li>
                        </ol>
                    </div>
                </div>

                <div class="integration-section">
                    <h3 th:text="#{integrations.owntracks.title}">🗺️ OwnTracks Setup</h3>
                    <p th:text="#{integrations.owntracks.description}">OwnTracks is a privacy-focused location tracking app available for iOS and Android.</p>

                    <div class="setup-steps">
                        <h4 th:text="#{integrations.setup.instructions}">Setup Instructions:</h4>
                        <ol>
                            <li>Download OwnTracks from the App Store or Google Play Store</li>
                            <li>Open OwnTracks and go to <strong>Settings → Connection</strong></li>
                            <li>Set Mode to <strong>HTTP</strong></li>
                            <li th:if="${hasToken}">Set the Endpoint to: <code th:text="${serverUrl + '/api/v1/ingest/owntracks?token=' + firstToken}">https://your-domain.com/api/v1/location-data</code></li>
                            <li th:unless="${hasToken}">Set the Endpoint to: <code th:text="${serverUrl + '/api/v1/ingest/owntracks?token=<YOUR TOKEN>'}">https://your-domain.com/api/v1/location-data</code></li>
                            <li>Disable <strong>Authentication</strong> (we use the token in the URL instead)</li>
                            <li>Configure tracking settings as desired</li>
                            <li>On the map view, set tracking mode to "Movement"</li>
                            <li>The app will automatically start sending location updates</li>
                        </ol>
                    </div>
                </div>
            </div>
        </details>
        <details th:attr="open=${openSection == 'external-data-stores' ? 'open' : null}">
            <summary>
                <i class="lni lni-database-2"></i> <span th:text="#{integrations.data-stores.title}">External Data Stores</span>
            </summary>
            <div style="padding: 15px;">
                <p th:text="#{integrations.data-stores.description}" style="margin-bottom: 20px; color: var(--color-text-white);">Configure Reitti to connect to external data storage like OwnTracks Recorder.</p>

                <div class="integration-section">
                    <h3 th:text="#{integrations.owntracks.recorder.title}">📊 OwnTracks Recorder Integration</h3>
                    <p th:text="#{integrations.owntracks.recorder.description}">Connect to an OwnTracks Recorder instance to fetch location data from specific users and devices.</p>

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

                    <form hx-post="/settings/owntracks-recorder-integration" hx-target="#integrations" hx-swap="innerHTML" class="owntracks-recorder-form" style="margin-top: 20px;" autocomplete="off">
                        <div class="form-group">
                            <label for="recorderBaseUrl" th:text="#{integrations.owntracks.recorder.base.url}">Base URL</label>
                            <input type="url"
                                   id="recorderBaseUrl"
                                   name="baseUrl"
                                   required
                                   autocomplete="off"
                                   th:placeholder="#{integrations.owntracks.recorder.base.url.placeholder}"
                                   th:value="${ownTracksRecorderIntegration?.baseUrl}">
                        </div>

                        <div class="form-group">
                            <label for="recorderUsername" th:text="#{integrations.owntracks.recorder.username}">Username</label>
                            <input type="text"
                                   id="recorderUsername"
                                   name="username"
                                   required
                                   autocomplete="off"
                                   th:placeholder="#{integrations.owntracks.recorder.username.placeholder}"
                                   th:value="${ownTracksRecorderIntegration?.username}">
                        </div>

                        <div class="form-group">
                            <label for="recorderDeviceId" th:text="#{integrations.owntracks.recorder.device.id}">Device ID</label>
                            <input type="text"
                                   id="recorderDeviceId"
                                   name="deviceId"
                                   required
                                   autocomplete="off"
                                   th:placeholder="#{integrations.owntracks.recorder.device.id.placeholder}"
                                   th:value="${ownTracksRecorderIntegration?.deviceId}">
                        </div>

                        <div class="form-group">
                            <label>
                                <input type="checkbox"
                                       name="enabled"
                                       value="true"
                                       th:checked="${ownTracksRecorderIntegration?.enabled}">
                                <span th:text="#{integrations.owntracks.recorder.enabled}">Enable Integration</span>
                            </label>
                        </div>

                        <div style="display: flex; gap: 10px; margin-top: 20px;">
                            <button type="submit" class="btn" th:text="#{integrations.owntracks.recorder.save}">Save Configuration</button>
                            <button type="button"
                                    class="btn"
                                    id="test-recorder-connection-btn"
                                    th:text="#{integrations.owntracks.recorder.test.connection}">Test Connection</button>
                            <button type="button"
                                    class="btn"
                                    id="load-historical-btn"
                                    th:attr="hx-post=@{/settings/owntracks-recorder-integration/load-historical}, hx-confirm=#{integrations.owntracks.recorder.load.historical.confirm}, disabled=${!hasRecorderIntegration}"
                                    hx-target="#integrations"
                                    hx-swap="innerHTML"
                                    th:text="#{integrations.owntracks.recorder.load.historical}">Load Historical Data</button>
                        </div>
                    </form>

                    <div id="recorder-connection-test-result" style="margin-top: 10px;"></div>

                    <script>
                        document.getElementById('test-recorder-connection-btn').addEventListener('click', function() {
                            const baseUrl = document.getElementById('recorderBaseUrl').value;
                            const username = document.getElementById('recorderUsername').value;
                            const deviceId = document.getElementById('recorderDeviceId').value;
                            const resultDiv = document.getElementById('recorder-connection-test-result');

                            if (!baseUrl || !username || !deviceId) {
                                resultDiv.innerHTML = '<div class="alert alert-warning" style="display: block;">Please fill in Base URL, Username, and Device ID</div>';
                                return;
                            }

                            // Show loading state
                            resultDiv.innerHTML = '<div style="color: var(--color-text-white);">Testing connection...</div>';

                            // Make AJAX request to test connection
                            fetch('/settings/owntracks-recorder-integration/test', {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/x-www-form-urlencoded',
                                },
                                body: new URLSearchParams({
                                    baseUrl: baseUrl,
                                    username: username,
                                    deviceId: deviceId
                                })
                            })
                                .then(response => response.json())
                                .then(data => {
                                    if (data.success) {
                                        resultDiv.innerHTML = '<div class="alert alert-success" style="display: block;">' + data.message + '</div>';
                                    } else {
                                        resultDiv.innerHTML = '<div class="alert alert-danger" style="display: block;">' + data.message + '</div>';
                                    }
                                })
                                .catch(error => {
                                    resultDiv.innerHTML = '<div class="alert alert-danger" style="display: block;">Connection test failed: ' + error.message + '</div>';
                                });
                        });

                        // Add loading indicator for Load Historical Data button
                        document.addEventListener('htmx:beforeRequest', function(evt) {
                            if (evt.detail.elt.id === 'load-historical-btn') {
                                evt.detail.elt.innerHTML = '<span style="display: inline-flex; align-items: center; gap: 8px;"><span style="width: 16px; height: 16px; border: 2px solid #ffffff; border-top: 2px solid transparent; border-radius: 50%; animation: spin 1s linear infinite;"></span>Loading Historical Data...</span>';
                                evt.detail.elt.disabled = true;
                            }
                        });

                        // Add CSS for spinner animation
                        if (!document.querySelector('#spinner-styles')) {
                            const style = document.createElement('style');
                            style.id = 'spinner-styles';
                            style.textContent = `
                                @keyframes spin {
                                    0% { transform: rotate(0deg); }
                                    100% { transform: rotate(360deg); }
                                }
                            `;
                            document.head.appendChild(style);
                        }
                    </script>
                </div>
            </div>
        </details>
        <details th:attr="open=${openSection == 'photos' ? 'open' : null}">
            <summary>
                <i class="lni lni-photos"></i> <span th:text="#{integrations.photos.title}">Photos</span>
            </summary>
            <div id="photos-section" hx-get="/settings/photos-content" hx-trigger="load" hx-swap="innerHTML" style="padding: 15px;">
                <!-- Photos content will be loaded here -->
            </div>
        </details>
        <details th:attr="open=${openSection == 'shared-instances' ? 'open' : null}">
            <summary>
                <i class="lni lni-network"></i> <span th:text="#{integrations.shared.instances.title}">Shared Instances</span>
            </summary>
            <div id="shared-instances-section" hx-get="/settings/shared-instances-content" hx-trigger="load" hx-swap="innerHTML" style="padding: 15px;">
                <!-- Shared instances content will be loaded here -->
            </div>
        </details>
    </div>

</div>

<!-- Photos Content Fragment -->
<div th:fragment="photos-content">
    <p th:text="#{integrations.photos.description}" style="margin-bottom: 20px; color: var(--color-text-white);">Configure photo management integration with Immich</p>
    
    <div th:if="${successMessage}" class="alert alert-success" style="display: block;">
        <span th:text="${successMessage}">Configuration saved successfully</span>
    </div>
    <div th:if="${errorMessage}" class="alert alert-danger" style="display: block;">
        <span th:text="${errorMessage}">Error message</span>
    </div>
    
    <div class="integration-section">
        <h3 th:text="#{integrations.immich.title}">🖼️ Immich Integration</h3>
        <p th:text="#{integrations.immich.description}">Immich is a self-hosted photo and video backup solution. Connect your Immich instance to show photos taken at specific locations and dates on your timeline map.</p>
        
        <form hx-post="/settings/immich-integration" hx-target="#photos-section" hx-swap="innerHTML" class="immich-form" style="margin-top: 20px;" autocomplete="off" >
            <div class="form-group">
                <label for="serverUrl" th:text="#{integrations.immich.server.url}">Server URL</label>
                <input type="url" 
                       id="serverUrl" 
                       name="serverUrl" 
                       required
                       autocomplete="off"
                       th:placeholder="#{integrations.immich.server.url.placeholder}"
                       th:value="${hasIntegration ? immichIntegration.serverUrl : ''}">
            </div>
            
            <div class="form-group">
                <label for="apiToken" th:text="#{integrations.immich.api.token}">API Token</label>
                <input type="password" 
                       id="apiToken" 
                       name="apiToken" 
                       required
                       autocomplete="new-password"
                       th:placeholder="#{integrations.immich.api.token.placeholder}"
                       th:value="${hasIntegration ? immichIntegration.apiToken : ''}">
            </div>
            
            <div class="form-group">
                <label>
                    <input type="checkbox" 
                           name="enabled" 
                           value="true"
                           th:checked="${hasIntegration && immichIntegration.enabled}">
                    <span th:text="#{integrations.immich.enabled}">Enable Integration</span>
                </label>
            </div>
            
            <div style="display: flex; gap: 10px; margin-top: 20px;">
                <button type="submit" class="btn" th:text="#{integrations.immich.save}">Save Configuration</button>
                <button type="button" 
                        class="btn" 
                        id="test-connection-btn"
                        th:text="#{integrations.immich.test.connection}">Test Connection</button>
            </div>
        </form>
        
        <div id="connection-test-result" style="margin-top: 10px;"></div>
        
        <script>
            document.getElementById('test-connection-btn').addEventListener('click', function() {
                const serverUrl = document.getElementById('serverUrl').value;
                const apiToken = document.getElementById('apiToken').value;
                const resultDiv = document.getElementById('connection-test-result');
                
                if (!serverUrl || !apiToken) {
                    resultDiv.innerHTML = '<div class="alert alert-warning" style="display: block;">Please fill in both Server URL and API Token</div>';
                    return;
                }
                
                // Show loading state
                resultDiv.innerHTML = '<div style="color: var(--color-text-white);">Testing connection...</div>';
                
                // Make AJAX request to test connection
                fetch('/settings/immich-integration/test', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: new URLSearchParams({
                        serverUrl: serverUrl,
                        apiToken: apiToken
                    })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        resultDiv.innerHTML = '<div class="alert alert-success" style="display: block;">' + data.message + '</div>';
                    } else {
                        resultDiv.innerHTML = '<div class="alert alert-danger" style="display: block;">' + data.message + '</div>';
                    }
                })
                .catch(error => {
                    resultDiv.innerHTML = '<div class="alert alert-danger" style="display: block;">Connection test failed: ' + error.message + '</div>';
                });
            });
        </script>
    </div>
</div>

<!-- Manage Data Content Fragment -->
<div th:fragment="manage-data-content">
    <h2 th:text="#{data.title}">Manage Data</h2>
    
    <div th:if="${successMessage}" class="alert alert-success" style="display: block;">
        <span th:text="${successMessage}">Processing started successfully</span>
    </div>
    <div th:if="${errorMessage}" class="alert alert-danger" style="display: block;">
        <span th:text="${errorMessage}">Error message</span>
    </div>
    
    <div class="settings-card">
        <h3 th:text="#{data.about.title}">About Data Processing</h3>
        <p th:text="#{data.about.description}">This section allows you to manually trigger data processing operations. These operations normally run automatically on a schedule, but you can trigger them manually here if needed.</p>
        <p><strong th:text="#{data.about.warning}">Warning: Manual processing may take some time depending on the amount of data to process.</strong> </p>
    </div>
    
    <div class="settings-card">
        <div class="action-card">
            <h3 th:text="#{data.process.visits.title}">Process Visits and Trips</h3>
            <p th:text="#{data.process.visits.description}">Manually trigger the processing of raw location data into visits and trips. This will analyze unprocessed location points and create meaningful visits and trips from them.</p>
            <button class="btn" 
                    hx-post="/settings/manage-data/process-visits-trips" 
                    hx-target="#manage-data" 
                    hx-swap="innerHTML"
                    th:attr="hx-confirm=#{data.process.visits.confirm}"
                    th:text="#{data.process.visits.button}">
                Start Processing
            </button>
        </div>

        <div class="action-card" style="margin-top: 15px;">
            <h3 th:text="#{data.clear.reprocess.title}">Clear and Reprocess All Data</h3>
            <p th:text="#{data.clear.reprocess.description}">Clear all processed data (visits, trips, processed visits) while preserving significant places and raw location points. Raw location points will be marked as unprocessed, and the processing pipeline will be triggered automatically.</p>
            <div style="background-color: #fff3cd; border: 1px solid #ffeaa7; border-radius: 4px; padding: 10px; margin: 10px 0; color: #856404;">
                <strong>⚠️ Warning:</strong> <span th:text="#{data.clear.reprocess.warning}">This action will permanently delete all visits, trips, and processed visits. This cannot be undone.</span>
            </div>
            <button class="btn btn-danger" 
                    hx-post="/settings/manage-data/clear-and-reprocess" 
                    hx-target="#manage-data" 
                    hx-swap="innerHTML"
                    th:attr="hx-confirm=#{data.clear.reprocess.confirm}"
                    th:text="#{data.clear.reprocess.button}">
                Clear and Reprocess
            </button>
        </div>

        <div class="action-card" style="margin-top: 15px;">
            <h3 th:text="#{data.remove.all.title}">Remove All Data</h3>
            <p th:text="#{data.remove.all.description}">Remove all data except significant places. This will permanently delete all raw location points, visits, trips, and processed visits while preserving your significant places.</p>
            <div style="background-color: #f8d7da; border: 1px solid #f5c6cb; border-radius: 4px; padding: 10px; margin: 10px 0; color: #721c24;">
                <strong>⚠️ Danger:</strong> <span th:text="#{data.remove.all.warning}">This action will permanently delete ALL location data except significant places. This cannot be undone.</span>
            </div>
            <button class="btn btn-danger" 
                    hx-post="/settings/manage-data/remove-all-data" 
                    hx-target="#manage-data" 
                    hx-swap="innerHTML"
                    th:attr="hx-confirm=#{data.remove.all.confirm}"
                    th:text="#{data.remove.all.button}">
                Remove All Data
            </button>
        </div>

    </div>
</div>

<!-- Geocode Services Content Fragment -->
<div th:fragment="geocode-services-content">
    <h2 th:text="#{geocoding.title}">Geocoding Services</h2>
    
    <div th:if="${successMessage}" class="alert alert-success" style="display: block;">
        <span th:text="${successMessage}">Service created successfully</span>
    </div>
    <div th:if="${errorMessage}" class="alert alert-danger" style="display: block;">
        <span th:text="${errorMessage}">Error message</span>
    </div>
    <div class="settings-card">
        <h4 th:text="#{geocoding.about.title}">About Geocoding Services</h4>
        <p th:text="#{geocoding.about.description}">Geocoding services convert coordinates to addresses for your significant places. You can add multiple services and the system will use them randomly to distribute the load.</p>
        <p th:text="#{geocoding.about.format}">Make sure that the geocoding service answers with GeoJson. This is the only supported response.</p>
        <p><strong th:text="#{geocoding.url.placeholders}">URL Template placeholders:</strong></p>
        <ul>
            <li><code>{lat}</code> - <span th:text="#{geocoding.placeholder.lat}">Will be replaced with latitude</span></li>
            <li><code>{lng}</code> - <span th:text="#{geocoding.placeholder.lng}">Will be replaced with longitude</span></li>
        </ul>
        <p><strong th:text="#{geocoding.example}">Example:</strong> <code>https://nominatim.openstreetmap.org/reverse?format=json&lat={lat}&lon={lng}&zoom=18&addressdetails=1</code></p>
    </div>
    <div class="settings-card">
        <h3 th:text="#{geocoding.available.services}">Available Services</h3>
        <div th:if="${geocodeServices.isEmpty()}">
            <p th:text="#{geocoding.no.services}">No geocoding services configured.</p>
        </div>

        <table th:if="${!geocodeServices.isEmpty()}">
            <thead>
            <tr>
                <th th:text="#{geocoding.table.name}">Name</th>
                <th th:text="#{geocoding.table.url}">URL Template</th>
                <th th:text="#{geocoding.table.status}">Status</th>
                <th th:text="#{geocoding.table.errors}">Errors</th>
                <th th:text="#{geocoding.table.last.used}">Last Used</th>
                <th th:text="#{geocoding.table.actions}">Actions</th>
            </tr>
            </thead>
            <tbody>
            <tr th:each="service : ${geocodeServices}">
                <td th:text="${service.name}"></td>
                <td style="max-width: 300px; word-break: break-all; font-family: monospace;"
                    th:text="${service.urlTemplate}"></td>
                <td>
                    <span th:if="${service.enabled}"><i class="lni lni-check"></i> <span
                            th:text="#{geocoding.status.enabled}">Enabled</span></span>
                    <span th:if="${!service.enabled}" style="color: red;"><i class="lni lni-xmark"></i> <span
                            th:text="#{geocoding.status.disabled}">Disabled</span></span>
                </td>
                <td>
                    <span th:text="${service.errorCount + '/' + maxErrors}"></span>
                    <span th:if="${service.errorCount >= maxErrors}" th:text="#{geocoding.auto.disabled}"> (Auto-disabled)</span>
                </td>
                <td th:text="${service.lastUsed != null ? #temporals.format(service.lastUsed, 'yyyy-MM-dd HH:mm') : #messages.msg('geocoding.never.used')}"></td>
                <td>
                    <button class="btn"
                            th:attr="hx-post=@{/settings/geocode-services/{id}/toggle(id=${service.id})}"
                            hx-target="#geocode-services"
                            hx-swap="innerHTML"
                            th:text="${service.enabled ? #messages.msg('geocoding.disable') : #messages.msg('geocoding.enable')}">
                        Toggle
                    </button>

                    <button th:if="${service.errorCount > 0}"
                            class="btn"
                            th:attr="hx-post=@{/settings/geocode-services/{id}/reset-errors(id=${service.id})}"
                            hx-target="#geocode-services"
                            hx-swap="innerHTML"
                            th:text="#{geocoding.reset.errors}">Reset Errors
                    </button>

                    <button class="btn btn-danger"
                            th:attr="hx-post=@{/settings/geocode-services/{id}/delete(id=${service.id})}, hx-confirm=#{geocoding.delete.confirm}"
                            hx-target="#geocode-services"
                            hx-swap="innerHTML"
                            th:text="#{form.delete}">Delete
                    </button>
                </td>
            </tr>
            </tbody>
        </table>
    </div>
    <div class="settings-card">
        <form hx-post="/settings/geocode-services" hx-target="#geocode-services" hx-swap="innerHTML" class="geocode-service-form" style="margin-bottom: 20px;">
            <h3 th:text="#{geocoding.add.title}">Add New Geocoding Service</h3>
            <div class="form-group">
                <label for="serviceName" th:text="#{geocoding.service.name}">Service Name</label>
                <input type="text" id="serviceName" name="name" required placeholder="e.g., My Custom Geocoder">
            </div>
            <div class="form-group">
                <label for="serviceUrl" th:text="#{geocoding.service.url}">URL Template</label>
                <input type="text" id="serviceUrl" name="urlTemplate" required placeholder="https://api.example.com/reverse?lat={lat}&lon={lng}&format=json">
            </div>
            <button type="submit" class="btn" th:text="#{form.create}">Add Service</button>
        </form>

    </div>

    <div class="settings-card">
        <h3 th:text="#{geocoding.execution.title}">Geocoding Execution</h3>
        <p th:text="#{geocoding.execution.description}">Manually trigger geocoding operations for your significant places</p>

        <div class="action-card">
            <h4 th:text="#{geocoding.run.title}">Run Geocoding</h4>
            <p th:text="#{geocoding.run.description}">Process all significant places that haven't been geocoded yet</p>
            <button class="btn"
                    hx-post="/settings/geocode-services/run-geocoding"
                    hx-target="#geocode-services"
                    hx-swap="innerHTML"
                    th:attr="hx-confirm=#{geocoding.run.confirm}"
                    th:text="#{geocoding.run.button}">
                Start Geocoding
            </button>
        </div>
        <div class="action-card">
            <h4 th:text="#{geocoding.clear.title}">Clear and Re-geocode All</h4>
            <p th:text="#{geocoding.clear.description}">Clear all existing geocoding data and re-process all significant places</p>
            <div style="background-color: #fff3cd; border: 1px solid #ffeaa7; border-radius: 4px; padding: 10px; margin: 10px 0; color: #856404;">
                <strong>⚠️ Warning:</strong> <span th:text="#{geocoding.clear.warning}">This will clear all existing address information and re-geocode all places</span>
            </div>
            <button class="btn btn-danger"
                    hx-post="/settings/geocode-services/clear-and-rerun"
                    hx-target="#geocode-services"
                    hx-swap="innerHTML"
                    th:attr="hx-confirm=#{geocoding.clear.confirm}"
                    th:text="#{geocoding.clear.button}">
                Clear and Re-geocode
            </button>
        </div>
    </div>

</div>

<!-- About Content Fragment -->
<div th:fragment="about-content">
    <h2 th:text="#{about.title}">About Application</h2>
    <div class="settings-card">
        <p>
            <strong th:text="#{about.app.version}">Application Version:</strong>
            <span th:text="${buildVersion}">N/A</span>
        </p>
        <p>
            <strong th:text="#{about.git.commit.details}">Commit Details:</strong>
            <span th:text="${gitCommitDetails}">N/A</span>
        </p>
        <p>
            <strong th:text="#{about.build.time}">Build Time:</strong>
            <span th:text="${buildTime}">N/A</span>
        </p>
    </div>
</div>

<!-- Shared Instances Content Fragment -->
<div th:fragment="shared-instances-content">
    <p th:text="#{integrations.shared.instances.description}" style="margin-bottom: 20px; color: var(--color-text-white);">Connect to other Reitti instances to share location data with friends, family, or colleagues. This allows you to view their location data alongside yours on the timeline map.</p>
    
    <div th:if="${successMessage}" class="alert alert-success" style="display: block;">
        <span th:text="${successMessage}">Configuration saved successfully</span>
    </div>
    <div th:if="${errorMessage}" class="alert alert-danger" style="display: block;">
        <span th:text="${errorMessage}">Error message</span>
    </div>
    
    <div class="integration-section">
        <h3 th:text="#{integrations.reitti.title}">🌐 Reitti Instance Integration</h3>
        <p th:text="#{integrations.reitti.description}">Connect to a local or remote Reitti instance to access another user's location data.</p>
        
        <div class="settings-card" th:if="${reittiIntegrations.isEmpty()}">
            <p th:text="#{integrations.reitti.no.integrations}">No Reitti integrations configured.</p>
        </div>

        <div class="settings-card" th:if="${!reittiIntegrations.isEmpty()}">
            <table>
                <thead>
                <tr>
                    <th th:text="#{integrations.reitti.table.url}">Instance URL</th>
                    <th th:text="#{integrations.reitti.table.enabled}">Enabled</th>
                    <th th:text="#{integrations.reitti.table.status}">Status</th>
                    <th th:text="#{integrations.reitti.table.last.used}">Last Used</th>
                    <th th:text="#{integrations.reitti.table.color}">Color</th>
                    <th th:text="#{integrations.reitti.table.actions}">Actions</th>
                </tr>
                </thead>
                <tbody>
                <tr th:each="integration : ${reittiIntegrations}">
                    <td th:text="${integration.url}"></td>
                    <td>
                        <span th:if="${integration.enabled}">
                            <i class="lni lni-check"></i> <span th:text="#{integrations.reitti.status.enabled}">Enabled</span>
                        </span>
                        <span th:if="${!integration.enabled}" style="color: orange;">
                            <i class="lni lni-xmark"></i> <span th:text="#{integrations.reitti.status.disabled}">Disabled</span>
                        </span>
                    </td>
                    <td>
                        <span>
                            <span th:text="#{'integrations.reitti.status.' + ${integration.status} + '.name'}">ACTIVE</span>
                        </span>
                    </td>
                    <td th:text="${integration.lastUsed.isPresent() ? #temporals.format(integration.lastUsed.get(), 'yyyy-MM-dd HH:mm') : #messages.msg('integrations.reitti.never.used')}"></td>
                    <td>
                        <div style="display: flex; align-items: center; gap: 8px;">
                            <div th:style="'width: 20px; height: 20px; border-radius: 50%; background-color: ' + ${integration.color ?: '#3498db'} + '; border: 2px solid #fff; box-shadow: 0 1px 3px rgba(0,0,0,0.3);'"></div>
                            <span th:text="${integration.color ?: '#3498db'}" style="font-family: monospace; font-size: 0.9em;"></span>
                        </div>
                    </td>
                    <td>
                        <button class="btn"
                                th:attr="hx-get=@{/settings/reitti-integrations/{id}/info(id=${integration.id})}"
                                hx-target="#reitti-info-display"
                                hx-swap="innerHTML"
                                th:text="#{integrations.reitti.info}">Info
                        </button>
                        <button class="btn"
                                th:attr="onclick='editReittiIntegration(' + ${integration.id} + ', \'' + ${integration.url} + '\', \'' + ${integration.token} + '\', \'' + ${integration.color} + '\', ' + ${integration.enabled} + ', ' + ${integration.version} + ')'"
                                th:text="#{form.edit}">Edit
                        </button>
                        <button class="btn"
                                th:attr="hx-post=@{/settings/reitti-integrations/{id}/toggle(id=${integration.id})}"
                                hx-target="#shared-instances-section"
                                hx-swap="innerHTML"
                                th:text="${integration.enabled ? #messages.msg('integrations.reitti.disable') : #messages.msg('integrations.reitti.enable')}">
                            Toggle
                        </button>
                        <button class="btn btn-danger"
                                th:attr="hx-post=@{/settings/reitti-integrations/{id}/delete(id=${integration.id})}, hx-confirm=#{integrations.reitti.delete.confirm}"
                                hx-target="#shared-instances-section"
                                hx-swap="innerHTML"
                                th:text="#{form.delete}">Delete
                        </button>
                    </td>
                </tr>
                </tbody>
            </table>
            <!-- Info Display Area -->
            <div id="reitti-info-display" style="margin-top: 20px;">
                <!-- Remote instance info will be displayed here -->
            </div>
        </div>
        
        <div class="settings-card">
            <form id="reitti-integration-form" hx-post="/settings/reitti-integrations" hx-target="#shared-instances-section" hx-swap="innerHTML" class="reitti-integration-form" style="margin-top: 20px;" autocomplete="off">
                <h4 id="form-title" th:text="#{integrations.reitti.add.title}">Add New Reitti Integration</h4>
                
                <input type="hidden" id="integrationId" name="id" value="">
                <input type="hidden" id="integrationVersion" name="version" value="">
                
                <div class="form-group">
                    <label for="reittiUrl" th:text="#{integrations.reitti.url}">Instance URL</label>
                    <input type="url" 
                           id="reittiUrl" 
                           name="url" 
                           required
                           autocomplete="off"
                           th:placeholder="#{integrations.reitti.url.placeholder}">
                </div>
                
                <div class="form-group">
                    <label for="reittiToken" th:text="#{integrations.reitti.token}">API Token</label>
                    <input type="text"
                           id="reittiToken" 
                           name="remote_token"
                           required
                           autocomplete="new-password"
                           th:placeholder="#{integrations.reitti.token.placeholder}">
                </div>
                
                <div class="form-group">
                    <label for="reittiColor" th:text="#{integrations.reitti.color}">Color</label>
                    <div style="display: flex; align-items: center; gap: 10px;">
                        <input type="color" 
                               id="reittiColor" 
                               name="color" 
                               value="#3498db"
                               style="width: 50px; height: 40px; border: none; border-radius: 4px; cursor: pointer; padding: 2px;">
                        <span style="color: var(--color-text-white); font-size: 0.9em;" th:text="#{integrations.reitti.color.description}">Choose a color to identify this integration on the map</span>
                    </div>
                </div>
                
                <div class="form-group">
                    <label>
                        <input type="checkbox" 
                               id="reittiEnabled"
                               name="enabled" 
                               value="true"
                               checked>
                        <span th:text="#{integrations.reitti.enabled}">Enable Integration</span>
                    </label>
                </div>
                
                <div style="display: flex; gap: 10px; margin-top: 20px;">
                    <button type="submit" id="submit-btn" class="btn" th:text="#{integrations.reitti.save}">Save Configuration</button>
                    <button type="button" 
                            class="btn" 
                            id="test-reitti-connection-btn"
                            th:text="#{integrations.reitti.test.connection}">Test Connection</button>
                    <button type="button" 
                            class="btn btn-secondary" 
                            id="cancel-edit-btn"
                            style="display: none;"
                            onclick="cancelEdit()"
                            th:text="#{form.cancel}">Cancel</button>
                </div>
            </form>
            
            <div id="reitti-connection-test-result" style="margin-top: 10px;"></div>
        </div>
    </div>

    <script>
        function editReittiIntegration(id, url, token, color, enabled, version) {
            // Update form title
            document.getElementById('form-title').textContent = 'Edit Reitti Integration';

            // Set form action to update
            const form = document.getElementById('reitti-integration-form');
            form.setAttribute('hx-post', '/settings/reitti-integrations/' + id + '/update');

            // Tell HTMX to process the form again after changing attributes
            htmx.process(form);

            // Fill form fields
            document.getElementById('integrationId').value = id;
            document.getElementById('integrationVersion').value = version;
            document.getElementById('reittiUrl').value = url;
            document.getElementById('reittiToken').value = token;
            document.getElementById('reittiColor').value = color;
            document.getElementById('reittiEnabled').checked = enabled;

            // Update button text and show cancel button
            document.getElementById('submit-btn').textContent = 'Update Configuration';
            document.getElementById('cancel-edit-btn').style.display = 'inline-block';

            // Clear any previous test results
            document.getElementById('reitti-connection-test-result').innerHTML = '';

            // Scroll to form
            form.scrollIntoView({ behavior: 'smooth' });
        }

        function cancelEdit() {
            // Reset form title
            document.getElementById('form-title').textContent = 'Add New Reitti Integration';

            // Reset form action to create
            const form = document.getElementById('reitti-integration-form');
            form.setAttribute('hx-post', '/settings/reitti-integrations');

            // Tell HTMX to process the form again after changing attributes
            htmx.process(form);

            // Clear form fields
            document.getElementById('integrationId').value = '';
            document.getElementById('integrationVersion').value = '';
            document.getElementById('reittiUrl').value = '';
            document.getElementById('reittiToken').value = '';
            document.getElementById('reittiColor').value = '#3498db';
            document.getElementById('reittiEnabled').checked = true;

            // Reset button text and hide cancel button
            document.getElementById('submit-btn').textContent = 'Save Configuration';
            document.getElementById('cancel-edit-btn').style.display = 'none';

            // Clear any previous test results
            document.getElementById('reitti-connection-test-result').innerHTML = '';
        }

        document.getElementById('test-reitti-connection-btn').addEventListener('click', function() {
            const url = document.getElementById('reittiUrl').value;
            const token = document.getElementById('reittiToken').value;
            const resultDiv = document.getElementById('reitti-connection-test-result');

            if (!url || !token) {
                resultDiv.innerHTML = '<div class="alert alert-warning" style="display: block;">Please fill in both Instance URL and API Token</div>';
                return;
            }

            // Show loading state
            resultDiv.innerHTML = '<div style="color: var(--color-text-white);">Testing connection...</div>';

            // Make AJAX request to test connection
            fetch('/settings/reitti-integrations/test', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({
                    url: url,
                    foreign_token: token
                })
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        resultDiv.innerHTML = '<div class="alert alert-success" style="display: block;">' + data.message + '</div>';
                    } else {
                        resultDiv.innerHTML = '<div class="alert alert-danger" style="display: block;">' + data.message + '</div>';
                    }
                })
                .catch(error => {
                    resultDiv.innerHTML = '<div class="alert alert-danger" style="display: block;">Connection test failed: ' + error.message + '</div>';
                });
        });
    </script>
</div>

<!-- Reitti Info Content Fragment -->
<div th:fragment="reitti-info-content">
    <div class="settings-card">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
            <h4 style="margin: 0; color: var(--color-accent);" th:text="#{integrations.reitti.info.title}">Remote Instance Information</h4>
            <button class="btn btn-secondary" 
                    hx-get="/settings/shared-instances-content" 
                    hx-target="#shared-instances-section" 
                    hx-swap="innerHTML"
                    th:text="#{form.close}">Close</button>
        </div>
        
        <div th:if="${errorMessage}" class="alert alert-danger" style="display: block;">
            <span th:text="${errorMessage}">Error fetching information</span>
        </div>
        
        <div th:if="${remoteInfo}" style="color: var(--color-text-white);">
            <div th:if="${remoteInfo.serverInfo()}" style="margin-bottom: 20px;">
                <h5 style="margin: 0 0 10px 0; color: var(--color-accent);">🖥️ Server Information</h5>
                <div style="background-color: rgba(255,255,255,0.1); padding: 15px; border-radius: 4px;">
                    <div><strong>Name:</strong> <span th:text="${remoteInfo.serverInfo().name() ?: 'N/A'}">N/A</span></div>
                    <div><strong>Version:</strong> <span th:text="${remoteInfo.serverInfo().version() ?: 'N/A'}">N/A</span></div>
                    <div><strong>System Time:</strong> <span th:text="${remoteInfo.serverInfo().systemTime() ?: 'N/A'}">N/A</span></div>
                </div>
            </div>
            
            <div th:if="${remoteInfo.userInfo()}" style="margin-bottom: 20px;">
                <h5 style="margin: 0 0 10px 0; color: var(--color-accent);">👤 User Information</h5>
                <div style="background-color: rgba(255,255,255,0.1); padding: 15px; border-radius: 4px;">
                    <div><strong>Username:</strong> <span th:text="${remoteInfo.userInfo().username() ?: 'N/A'}">N/A</span></div>
                    <div><strong>Display Name:</strong> <span th:text="${remoteInfo.userInfo().displayName() ?: 'N/A'}">N/A</span></div>
                    <div><strong>User ID:</strong> <span th:text="${remoteInfo.userInfo().id() ?: 'N/A'}">N/A</span></div>
                    <div><strong>Version:</strong> <span th:text="${remoteInfo.userInfo().version() ?: 'N/A'}">N/A</span></div>
                </div>
            </div>
            
            <div style="padding: 10px; background-color: rgba(0,255,0,0.1); border-radius: 4px; border-left: 4px solid #00ff00;">
                <strong>✅ Connection successful!</strong> You can access this user's location data.
            </div>
        </div>
    </div>
</div>

<!-- Geocoding Response Content Fragment -->
<div th:fragment="geocoding-response-content">
    <h2 th:text="#{places.geocoding.response.title(${place.name()})}">Geocoding Response for Place</h2>

    <div style="margin-bottom: 20px;">
        <button class="btn" 
                th:attr="hx-get=@{/settings/places-content(page=${currentPage})}"
                hx-target="#places-management"
                hx-swap="innerHTML"
                th:text="#{places.geocoding.response.back}">Back to Places</button>
    </div>

    <div class="settings-card">
        <h3 th:text="${place.name()}">Place Name</h3>
        <p><strong th:text="#{places.address.label}">Address:</strong> <span th:text="${place.address() ?: #messages.msg('places.address.not.available')}">Address</span></p>
        <p><strong th:text="#{places.coordinates.label}">Coordinates:</strong> <span th:text="${place.latitude() + ', ' + place.longitude()}">Coordinates</span></p>
    </div>

    <div th:if="${!geocodingResponses.isEmpty()}" class="settings-card">
        <h3>Geocoding Responses</h3>
        <div style="margin-bottom: 30px; padding-bottom: 20px; border-bottom: 1px solid rgba(255,255,255,0.2);">
            <table>
                <thead>
                <tr>
                    <th th:text="#{places.geocoding.response.provider}">Provider</th>
                    <th th:text="#{places.geocoding.response.status}">Status</th>
                    <th th:text="#{places.geocoding.response.fetched.at}">Fetched At</th>
                    <th th:text="#{places.geocoding.response.error.details}">Error Details</th>
                    <th th:text="#{places.geocoding.response.raw.data}">Raw Data</th>
                </tr>
                </thead>
                <tbody>
                <tr th:each="response, iterStat : ${geocodingResponses}">
                    <td th:text="${response.providerName}">Provider Name</td>
                    <td th:text="${response.status}">Status</td>
                    <td th:text="${#temporals.format(response.fetchedAt, 'yyyy-MM-dd HH:mm:ss')}">Fetched At</td>
                    <td><span  th:if="${response.errorDetails}" th:text="${response.errorDetails}">Error Details</span></td>
                    <td>
                        <pre style="background-color: rgba(255,255,255,0.1); padding: 15px; border-radius: 4px; overflow-x: auto; white-space: pre-wrap; word-wrap: break-word; max-height: 300px; overflow-y: auto;"
                             th:text="${response.rawData}"></pre>
                    </td>
                </tr>
                </tbody>
            </table>
        </div>
    </div>

    <div th:if="${geocodingResponses.isEmpty()}" class="settings-card">
        <p th:text="#{places.geocoding.response.no.data}">No geocoding response available for this place</p>
    </div>
</div>

<script>
// Avatar selection JavaScript
document.addEventListener('DOMContentLoaded', function() {
    // Clear file input when default avatar is selected
    document.addEventListener('change', function(e) {
        if (e.target.name === 'defaultAvatar') {
            const fileInput = document.getElementById('avatar');
            if (fileInput) {
                fileInput.value = '';
            }
        }
    });

    // Clear default avatar selection when file is selected
    const avatarFileInput = document.getElementById('avatar');
    if (avatarFileInput) {
        avatarFileInput.addEventListener('change', function() {
            if (this.files.length > 0) {
                document.querySelectorAll('input[name="defaultAvatar"]').forEach(radio => {
                    radio.checked = false;
                });
            }
        });
    }
});
</script>

</body>
</html>
