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

<!-- API Tokens Content Fragment -->
<div th:fragment="api-tokens-content">
    <h2 th:text="#{tokens.title}">API Tokens</h2>

    <div th:if="${successMessage}" class="alert alert-success" style="display: block;">
        <span th:text="${successMessage}">Token created 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/tokens" hx-target="#api-tokens" hx-swap="innerHTML" class="token-form" style="margin-bottom: 20px;">
        <div class="form-group">
            <label for="tokenName" th:text="#{tokens.name.label}">Token Name</label>
            <input type="text" id="tokenName" name="name" required th:placeholder="#{tokens.name.placeholder}">
        </div>
        <button type="submit" class="btn" th:text="#{form.create}">Create New Token</button>
    </form>

    <div th:if="${tokens.isEmpty()}">
        <p th:text="#{tokens.no.tokens}">No API tokens found. Create one to get started.</p>
    </div>
    
    <table th:if="${!tokens.isEmpty()}">
        <thead>
            <tr>
                <th th:text="#{tokens.table.name}">Name</th>
                <th th:text="#{tokens.table.token}">Token</th>
                <th th:text="#{tokens.table.created}">Created</th>
                <th th:text="#{tokens.table.last.used}">Last Used</th>
                <th th:text="#{tokens.table.actions}">Actions</th>
            </tr>
        </thead>
        <tbody>
            <tr th:each="token : ${tokens}">
                <td th:text="${token.name}"></td>
                <td th:text="${token.token}"></td>
                <td th:text="${#temporals.format(token.createdAt, 'yyyy-MM-dd HH:mm')}"></td>
                <td th:text="${token.lastUsedAt != null ? #temporals.format(token.lastUsedAt, 'yyyy-MM-dd HH:mm') : 'Never'}"></td>
                <td>
                    <button class="btn btn-danger" 
                            th:attr="hx-post=@{/settings/tokens/{id}/delete(id=${token.id})}, hx-confirm=#{tokens.delete.confirm}"
                            hx-target="#api-tokens"
                            hx-swap="innerHTML"
                            th:text="#{form.delete}">Delete</button>
                </td>
            </tr>
        </tbody>
    </table>
</div>

<!-- Users Content Fragment -->
<div th:fragment="users-content">
    <h2 th:text="#{users.title}">User Management</h2>

    <div th:if="${successMessage}" class="alert alert-success" style="display: block;">
        <span th:text="${successMessage}">User created successfully</span>
    </div>
    <div th:if="${errorMessage}" class="alert alert-danger" style="display: block;">
        <span th:text="${errorMessage}">Error message</span>
    </div>
    <div th:if="${requireRelogin}" class="alert alert-warning" style="display: block;">
        <span>Your username has changed to <strong th:text="${newUsername}"></strong>. You will need to log out and log in again with your new username.</span>
    </div>

    <h3 th:text="#{users.existing}">Existing Users</h3>
    <div th:if="${users.isEmpty()}">
        <p th:text="#{users.no.users}">No users found.</p>
    </div>
    
    <table th:if="${!users.isEmpty()}">
        <thead>
            <tr>
                <th th:text="#{users.table.username}">Username</th>
                <th th:text="#{users.table.display.name}">Display Name</th>
                <th th:text="#{users.table.actions}">Actions</th>
            </tr>
        </thead>
        <tbody>
            <tr th:each="user : ${users}" th:attr="data-user-id=${user.id}" class="user-row">
                <td th:text="${user.username}" th:attr="data-username=${user.username}"></td>
                <td th:text="${user.displayName}" th:attr="data-display-name=${user.displayName}"></td>
                <td>
                    <span th:if="${user.username == currentUsername}" th:text="#{users.current.user}">(Current User)</span>
                    <button th:if="${user.username != currentUsername}" 
                            class="btn btn-danger"
                            th:attr="hx-post=@{/settings/users/{id}/delete(id=${user.id})}, hx-confirm=#{users.delete.confirm}"
                            hx-target="#user-management"
                            hx-swap="innerHTML"
                            th:text="#{form.delete}">Delete</button>
                    <button class="btn"
                            th:attr="hx-get=@{/settings/user-form(userId=${user.id}, username=${user.username}, displayName=${user.displayName})}"
                            hx-target="#user-form-container"
                            th:text="#{form.update}">Edit</button>
                </td>
            </tr>
        </tbody>
    </table>

    <div id="user-form-container" style="margin-top: 30px;">
        <div hx-get="/settings/user-form" hx-trigger="load" hx-target="#user-form-container"></div>
    </div>
</div>

<!-- User Form Fragment -->
<div th:fragment="user-form">
    <form hx-target="#user-management" hx-swap="innerHTML" class="user-form" autocomplete="off" 
          th:attr="hx-post=${userId != null ? '/settings/users/update' : '/settings/users'}">
        <input type="hidden" name="userId" th:value="${userId}">
        <h3 th:text="${userId != null ? #messages.msg('users.update.title') : #messages.msg('users.add.title')}">Add New User</h3>
        <div class="form-group">
            <label for="username" th:text="#{users.username.label}">Username</label>
            <input type="text" id="username" name="username" required th:placeholder="#{users.username.placeholder}" autocomplete="off" 
                   th:value="${username}">
        </div>
        <div class="form-group">
            <label for="displayName" th:text="#{users.display.name.label}">Display Name</label>
            <input type="text" id="displayName" name="displayName" required th:placeholder="#{users.display.name.placeholder}" autocomplete="off"
                   th:value="${displayName}">
        </div>
        <div class="form-group">
            <label for="password" th:text="#{users.password.label}">Password</label>
            <input type="password" id="password" name="password" th:required="${userId == null}" th:placeholder="#{users.password.placeholder}" autocomplete="new-password">
            <small th:if="${userId != null}" th:text="#{users.password.keep.current}">Leave empty to keep current password</small>
        </div>
        <div style="display: flex; gap: 10px;">
            <button type="submit" class="btn" th:text="${userId != null ? #messages.msg('form.update') : #messages.msg('form.create')}">Create User</button>
            <button type="button" class="btn" th:if="${userId != null}" 
                    hx-get="/settings/user-form" hx-target="#user-form-container" th:text="#{form.cancel}">Cancel</button>
        </div>
    </form>
</div>

<!-- Places Content Fragment -->
<div th:fragment="places-content">
    <h2 th:text="#{places.title}">Significant Places</h2>

    <div id="place-message" class="alert" style="display: none;"></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()})}"
                      hx-swap="none">
                    <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="place-info">
                        <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.category() ?: #messages.msg('places.category.not.categorized')}"></span></div>
                        <div><strong th:text="#{places.coordinates.label}">Coordinates:</strong> <span th:text="${place.latitude() + ', ' + place.longitude()}"></span></div>
                    </div>
                    <button type="submit" class="btn" th:text="#{form.update}">Update</button>
                </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>

<!-- File Upload Content Fragment -->
<div th:fragment="file-upload-content">
    <h2 th:text="#{upload.title}">Import Location Data</h2>
    
    <div th:if="${uploadSuccessMessage}" class="alert alert-success" style="display: block;">
        <span th:text="${uploadSuccessMessage}">File uploaded successfully</span>
    </div>
    <div th:if="${uploadErrorMessage}" class="alert alert-danger" style="display: block;">
        <span th:text="${uploadErrorMessage}">Error message</span>
    </div>
    
    <div class="upload-options">
        <div class="upload-option">
            <h3 th:text="#{upload.gpx.title}">GPX Files</h3>
            <p class="description" th:text="#{upload.gpx.description}">
                Upload GPX files from your GPS devices or tracking apps. GPX files contain waypoints, 
                tracks, and routes with timestamps that can be processed into your location history.
            </p>
            <form id="gpx-upload-form"
                  hx-post="/settings/import/gpx"
                  hx-target="#file-upload"
                  hx-encoding="multipart/form-data">
                <div class="form-group">
                    <input type="file" name="files" accept=".gpx" multiple required>
                </div>
                <button type="submit" class="btn" th:text="#{upload.button.gpx}">Upload GPX File</button>
            </form>
            <progress id='progress-gpx' value='0' max='100' style="display: none"></progress>
            <script>
                htmx.on('#gpx-upload-form', 'htmx:xhr:progress', function(evt) {
                    htmx.find('#progress-gpx').setAttribute('value', evt.detail.loaded/evt.detail.total * 100)
                    htmx.find('#progress-gpx').setAttribute('style', null)
                });
            </script>
        </div>
        
        <div class="upload-option">
            <h3 th:text="#{upload.google.title}">Google Takeout</h3>
            <p class="description" th:text="#{upload.google.description}">
                Upload location history from Google Takeout. Export your data from Google 
                (takeout.google.com) and upload the Location History JSON file. This contains 
                your location history with timestamps and activity information.
            </p>
            <form id="takeout-upload-form"
                  hx-post="/settings/import/google-takeout"
                  hx-target="#file-upload"
                  hx-swap="innerHTML"
                  hx-encoding="multipart/form-data">
                <div class="form-group">
                    <input type="file" name="file" accept=".json" required>
                </div>
                <button type="submit" class="btn" th:text="#{upload.button.google}">Upload Google Takeout</button>
            </form>
            <progress id='progress-google' value='0' max='100'  style="display: none"></progress>
            <script>
                htmx.on('#takeout-upload-form', 'htmx:xhr:progress', function(evt) {
                    htmx.find('#progress-google').setAttribute('value', evt.detail.loaded/evt.detail.total * 100)
                    htmx.find('#progress-google').setAttribute('style', null)
                });
            </script>
        </div>
        
        <div class="upload-option">
            <h3 th:text="#{upload.geojson.title}">GeoJSON Files</h3>
            <p class="description" th:text="#{upload.geojson.description}">
                Upload GeoJSON files containing Point features with location data. GeoJSON files 
                should contain Point geometries with coordinates and optional timestamp properties. 
                Supports both single Feature and FeatureCollection formats.
            </p>
            <form id="geojson-upload-form"
                  hx-post="/settings/import/geojson"
                  hx-target="#file-upload"
                  hx-swap="innerHTML"
                  hx-encoding="multipart/form-data">
                <div class="form-group">
                    <input type="file" name="files" accept=".geojson,.json" multiple required>
                </div>
                <button type="submit" class="btn" th:text="#{upload.button.geojson}">Upload GeoJSON File</button>
            </form>
            <progress id='progress-geojson' value='0' max='100' style="display: none"></progress>
            <script>
                htmx.on('#geojson-upload-form', 'htmx:xhr:progress', function(evt) {
                    htmx.find('#progress-geojson').setAttribute('value', evt.detail.loaded/evt.detail.total * 100)
                    htmx.find('#progress-geojson').setAttribute('style', null)
                });
            </script>
        </div>
    </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>
            <summary>
                📱 <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 Content-Type header to: <code>application/json</code></li>
                            <li>Configure logging frequency as desired (e.g., every 30 seconds)</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>Set Host to: <code th:text="${serverUrl}">https://your-domain.com</code></li>
                            <li>Set Path to: <code th:text="${hasToken ? '/api/v1/ingest/owntracks?token=' + firstToken : '/api/v1/ingest/owntracks?token=YOUR_API_TOKEN'}">/api/v1/ingest/owntracks?token=YOUR_API_TOKEN</code></li>
                            <li>Disable <strong>Authentication</strong> (we use the token in the URL instead)</li>
                            <li>Configure tracking settings as desired</li>
                            <li>The app will automatically start sending location updates</li>
                        </ol>
                    </div>
                </div>
            </div>
        </details>
        <details>
            <summary>
                📸 <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>
    </div>
    
    <!-- Photos Collapsible Section -->

</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 style="border: 1px solid #b3d9ff; border-radius: 4px; padding: 15px; margin-bottom: 20px;">
        <h4 th:text="#{data.about.title}">About Data Processing</h4>
        <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="data-management-actions">
        <div class="action-card" style="border: 1px solid #dee2e6; border-radius: 4px; padding: 15px; margin-bottom: 15px;">
            <h4 th:text="#{data.process.visits.title}">Process Visits and Trips</h4>
            <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="border: 1px solid #dee2e6; border-radius: 4px; padding: 15px; margin-bottom: 15px;">
            <h4 th:text="#{data.clear.reprocess.title}">Clear and Reprocess All Data</h4>
            <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>
</div>

<!-- Language Selection Content Fragment -->
<div th:fragment="language-content">
    <h2 th:text="#{language.title}">Language Settings</h2>
    
    <div th:if="${successMessage}" class="alert alert-success" style="display: block;">
        <span th:text="${successMessage}">Language changed successfully</span>
    </div>
    
    <div style="border: 1px solid #b3d9ff; border-radius: 4px; padding: 15px; margin-bottom: 20px;">
        <h4 th:text="#{language.select}">Select Your Language</h4>
        <p th:text="#{language.description}">Choose your preferred language for the application interface. You may need to reload the page for all changes to take effect.</p>
    </div>
    
    <div class="language-selection">
        <div class="language-buttons">
            <button class="btn language-btn"
                    th:classappend="${#locale.language == 'en'} ? 'active' : ''"
                    th:attr="hx-post=@{/settings/language(lang=en)}"
                    hx-target="#language-settings"
                    hx-swap="innerHTML">
                <span class="language-flag">🇺🇸</span>
                <span th:text="#{language.english}" class="language-name">English</span>
            </button>
            
            <button class="btn language-btn"
                    th:classappend="${#locale.language == 'fi'} ? 'active' : ''"
                    th:attr="hx-post=@{/settings/language(lang=fi)}"
                    hx-target="#language-settings"
                    hx-swap="innerHTML">
                <span class="language-flag">🇫🇮</span>
                <span th:text="#{language.finnish}" class="language-name">Suomi</span>
            </button>
            
            <button class="btn language-btn"
                    th:classappend="${#locale.language == 'de'} ? 'active' : ''"
                    th:attr="hx-post=@{/settings/language(lang=de)}"
                    hx-target="#language-settings"
                    hx-swap="innerHTML">
                <span class="language-flag">🇩🇪</span>
                <span th:text="#{language.german}" class="language-name">Deutsch</span>
            </button>
            
            <button class="btn language-btn"
                    th:classappend="${#locale.language == 'fr'} ? 'active' : ''"
                    th:attr="hx-post=@{/settings/language(lang=fr)}"
                    hx-target="#language-settings"
                    hx-swap="innerHTML">
                <span class="language-flag">🇫🇷</span>
                <span  th:text="#{language.french}" class="language-name">Français</span>
            </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 style="border: 1px solid #b3d9ff; border-radius: 4px; padding: 15px; margin-bottom: 20px;">
        <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>
    
    <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>
    
    <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>

<!-- About Content Fragment -->
<div th:fragment="about-content">
    <h2 th:text="#{about.title}">About Application</h2>
    <div class="about-info" style="padding: 15px; border: 1px solid #dee2e6; border-radius: 4px;">
        <p style="margin-bottom: 10px;">
            <strong th:text="#{about.app.version}">Application Version:</strong>
            <span th:text="${buildVersion}">N/A</span>
        </p>
        <p style="margin-bottom: 10px;">
            <strong th:text="#{about.git.commit.details}">Commit Details:</strong>
            <span th:text="${gitCommitDetails}">N/A</span>
        </p>
        <p style="margin-bottom: 0;">
            <strong th:text="#{about.build.time}">Build Time:</strong>
            <span th:text="${buildTime}">N/A</span>
        </p>
    </div>
</div>

</body>
</html>
