<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title th:text="#{settings.title}">Settings - Reitti</title>
    <link rel="icon" th:href="@{/img/logo.svg}">
    <link rel="apple-touch-icon" th:href="@{/img/logo.svg}">
    <link rel="shortcut icon" type="image/x-icon" th:href="@{/img/logo.svg}">
    <link rel="stylesheet" href="/css/main.css">
    <link rel="stylesheet" href="/css/lineicons.css">
    <script src="/js/htmx.min.js"></script>
    <script src="/js/util.js"></script>
</head>
<body class="settings-page">
<div class="navigation-container" th:replace="~{fragments/main-navigation :: main-navigation('settings')}"></div>

<div class="settings-container">
    <div th:replace="~{fragments/settings-navigation :: settings-nav(${activeSection}, ${dataManagementEnabled}, ${isAdmin})}"></div>
    <div class="settings-content-area">
        <div id="integrations" class="settings-section active">
            <div th:fragment="integrations-content">
                <h2 th:text="#{integrations.title}">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 th:text="#{integrations.no.token.title}">⚠️ 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>
                            <div class="alert alert-info" style="margin-bottom: 20px;">
                                <strong th:text="#{integrations.tracking.frequency.title}">📍 GPS Tracking Frequency</strong><br>
                                <span th:text="#{integrations.tracking.frequency.description}">For optimal results, Reitti works best with a continuous stream of GPS locations. Make sure your tracking app records a point at least every 30 seconds to ensure accurate visit and trip detection.</span>
                            </div>
                            <p th:text="#{integrations.data.ingestion.description}">Configure mobile apps to automatically send location data to Reitti</p>

                            <!-- Token Selection Dropdown -->
                            <div th:if="${hasToken && tokens.size() > 1}" >
                                <label for="tokenSelect" th:text="#{integrations.token.select.label}">Select API Token:</label>
                                <select id="tokenSelect" name="selectedToken" class="form-control" hx-get="/settings/integrations/integrations-content" hx-vals='{"openSection": "data-ingestion"}' hx-target="#integrations" hx-swap="innerHTML" hx-trigger="change">
                                    <option th:each="token : ${tokens}" th:value="${token.token}" th:text="${token.name}" th:selected="${token.token == selectedToken}"></option>
                                </select>
                                <small th:text="#{integrations.token.select.help}">Choose the API token to use in the setup URLs below. The selected token will be automatically inserted into the example URLs.</small>
                            </div>

                            <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>
                                <p><strong th:text="#{integrations.download}">Download:</strong> <a href="https://gpslogger.app/" target="_blank" rel="noopener noreferrer" style="color: var(--color-accent); text-decoration: underline;">https://gpslogger.app/</a></p>
                                <div class="setup-steps">
                                    <h4 th:text="#{integrations.setup.instructions}">Setup Instructions:</h4>
                                    <ol>
                                        <li th:text="#{integrations.gpslogger.step1}">Download GPSLogger from the Google Play Store</li>
                                        <li th:utext="#{integrations.gpslogger.step2}">Open GPSLogger and go to <strong>Logging details → Log to custom URL</strong></li>
                                        <li th:utext="#{integrations.gpslogger.step3}">Enable "Log to custom URL"</li>
                                        <li th:if="${hasToken}" th:utext="#{integrations.gpslogger.step4.with.token(${serverUrl + '/api/v1/ingest/owntracks?token=' + selectedToken})}">Set the URL to: <code th:text="${serverUrl + '/api/v1/ingest/owntracks?token=' + selectedToken}">https://your-domain.com/api/v1/location-data</code></li>
                                        <li th:unless="${hasToken}" th:utext="#{integrations.gpslogger.step4.without.token(${serverUrl + '/api/v1/ingest/owntracks?token=<YOUR TOKEN>'})}">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 th:utext="#{integrations.gpslogger.step5}">Set HTTP Method to <strong>POST</strong></li>
                                        <li><span th:utext="#{integrations.gpslogger.step6}">Set HTTP Body to:</span> <code>{
                                            "_type" : "location",
                                            "t": "u",
                                            "acc": "%ACC",
                                            "alt": "%ALT",
                                            "batt": "%BATT",
                                            "bs": "%ISCHARGING",
                                            "lat": "%LAT",
                                            "lon": "%LON",
                                            "tst": "%TIMESTAMP",
                                            "vel": "%SPD"
                                            }</code></li>
                                        <li th:utext="#{integrations.gpslogger.step7}">Set HTTP header to: <code>Content-Type: application/json</code></li>
                                        <li th:text="#{integrations.gpslogger.step8}">Start logging!</li>
                                    </ol>
                                </div>
                                <div th:if="${hasToken}">
                                    <div><a id="gpslogger-config-link" class="btn" th:text="#{integrations.gpslogger.configure}">Configure GPSLogger</a></div>
                                    <div><small th:text="#{integrations.gpslogger.configure.description}">This will create a new profile 'reitti' with the configured settings.</small></div>
                                </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>
                                <p><strong th:text="#{integrations.download}">Download:</strong> <a href="https://owntracks.org/" target="_blank" rel="noopener noreferrer" style="color: var(--color-accent); text-decoration: underline;">https://owntracks.org/</a></p>
                                <div class="setup-steps">
                                    <h4 th:text="#{integrations.setup.instructions}">Setup Instructions:</h4>
                                    <ol>
                                        <li th:text="#{integrations.owntracks.step1}">Download OwnTracks from the App Store or Google Play Store</li>
                                        <li th:utext="#{integrations.owntracks.step2}">Open OwnTracks and go to <strong>Settings → Connection</strong></li>
                                        <li th:utext="#{integrations.owntracks.step3}">Set Mode to <strong>HTTP</strong></li>
                                        <li th:if="${hasToken}" th:utext="#{integrations.owntracks.step4.with.token(${serverUrl + '/api/v1/ingest/owntracks?token=' + selectedToken})}">Set the Endpoint to: <code th:text="${serverUrl + '/api/v1/ingest/owntracks?token=' + selectedToken}">https://your-domain.com/api/v1/location-data</code></li>
                                        <li th:unless="${hasToken}" th:utext="#{integrations.owntracks.step4.without.token(${serverUrl + '/api/v1/ingest/owntracks?token=<YOUR TOKEN>'})}">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 th:utext="#{integrations.owntracks.step5}">Disable <strong>Authentication</strong> (we use the token in the URL instead)</li>
                                        <li th:text="#{integrations.owntracks.step6}">Configure tracking settings as desired. Make sure that Owntracks records a point at least every 30 seconds.</li>
                                        <li th:utext="#{integrations.owntracks.step7}">On the map view, set tracking mode to "Movement"</li>
                                        <li th:text="#{integrations.owntracks.step8}">The app will automatically start sending location updates</li>
                                    </ol>
                                </div>
                                <div th:if="${hasToken}">
                                    <div><a id="owntracks-config-link" class="btn" th:text="#{integrations.owntracks.configure}">Configure OwnTracks</a></div>
                                    <div><small th:text="#{integrations.owntracks.configure.description}">This will create a new profile 'reitti' with the configured settings.</small></div>
                                </div>
                            </div>

                            <div class="integration-section">
                                <h3 th:text="#{integrations.overland.title}">📍 Overland Setup</h3>
                                <p th:text="#{integrations.overland.description}">Overland is a GPS logger for iOS that sends location data in GeoJSON format.</p>
                                <p>
                                    <strong th:text="#{integrations.homepage}">Homepage:</strong>
                                    <a href="https://overland.p3k.app/" target="_blank" rel="noopener noreferrer" style="color: var(--color-accent); text-decoration: underline;">https://overland.p3k.app/</a>
                                </p>
                                <div class="setup-steps">
                                    <h4 th:text="#{integrations.setup.instructions}">Setup Instructions:</h4>
                                    <ol>
                                        <li th:text="#{integrations.overland.step1}">Install Overland</li>
                                        <li th:utext="#{integrations.overland.step2}">Open Overland and go to the <strong>Settings</strong> tab</li>
                                        <li th:utext="#{integrations.overland.step3}"><strong>Important:</strong> Tap the <strong>Request Permission</strong> button to grant location access - Overland will not track anything without this permission</li>
                                        <li th:utext="#{integrations.overland.step4}">Tap on <strong>Receiver Endpoint</strong></li>
                                        <li th:if="${hasToken}" th:utext="#{integrations.overland.step5.with.token(${serverUrl + '/api/v1/ingest/overland?token=' + selectedToken})}">Set the Endpoint URL to: <code th:text="${serverUrl + '/api/v1/ingest/overland?token=' + selectedToken}">https://your-domain.com/api/v1/ingest/overland?token=YOUR_TOKEN</code></li>
                                        <li th:unless="${hasToken}" th:utext="#{integrations.overland.step5.without.token(${serverUrl + '/api/v1/ingest/overland?token=<YOUR TOKEN>'})}">Set the Endpoint URL to: <code th:text="${serverUrl + '/api/v1/ingest/overland?token=<YOUR TOKEN>'}">https://your-domain.com/api/v1/ingest/overland?token=YOUR_TOKEN</code></li>
                                        <li th:utext="#{integrations.overland.step6}">Leave the <strong>Device ID</strong> field empty or set a custom identifier</li>
                                        <li th:utext="#{integrations.overland.step7}">Leave the <strong>Access Token</strong> field empty (we use the token in the URL)</li>
                                        <li th:utext="#{integrations.overland.step8}">Configure tracking settings:
                                            <ul>
                                                <li><strong>Desired Accuracy:</strong> Best (for high accuracy) or 100m (for battery saving)</li>
                                                <li><strong>Points per Batch:</strong> 50-200 (lower for unreliable connections)</li>
                                                <li><strong>Significant Location:</strong> Disabled for continuous tracking</li>
                                            </ul>
                                        </li>
                                        <li th:utext="#{integrations.overland.step9}">Go to the <strong>Tracker</strong> tab and turn tracking <strong>On</strong></li>
                                        <li th:text="#{integrations.overland.step10}">Adjust the sending interval slider (1 second to 30 minutes)</li>
                                        <li th:text="#{integrations.overland.step11}">The app will start sending location data automatically</li>
                                    </ol>
                                </div>
                                <div th:if="${hasToken}">
                                    <div><a id="overland-config-link" class="btn" th:text="#{integrations.overland.configure}">Configure Overland</a></div>
                                    <div><small th:text="#{integrations.overland.configure.description}">This will create a new profile 'reitti' with the configured settings.</small></div>
                                </div>

                            </div>

                            <div class="alert alert-info" style="margin-top: 20px">
                                <strong th:text="#{integrations.mobile.help.title}">Need Help?</strong><br>
                                <span th:text="#{integrations.mobile.help.description}">For detailed setup instructions and tips, visit our comprehensive guide:</span>
                                <a href="https://www.dedicatedcode.com/projects/reitti/configurations/mobile-app-integration/"
                                   target="_blank"
                                   rel="noopener noreferrer"
                                   style="color: var(--color-accent); text-decoration: underline;"
                                   th:text="#{integrations.mobile.help.link.text}">
                                    Mobile Integration Documentation
                                </a>
                            </div>

                            <div style="margin-top: 20px; padding: 15px; background-color: rgba(255,255,255,0.1); border-radius: 4px;" id="data-quality">
                                <h4 style="margin: 0 0 10px 0; color: var(--color-accent);" th:text="#{integrations.data.quality.title}">Data Quality Verification</h4>
                                <p style="margin-bottom: 15px; color: var(--color-text-white);" th:text="#{integrations.data.quality.description}">Check the quality and frequency of your incoming location data to ensure optimal tracking performance.</p>
                                <button class="btn"
                                        id="data-quality-btn"
                                        hx-get="/settings/integrations/data-quality-content"
                                        hx-target="#integrations"
                                        hx-swap="innerHTML"
                                        hx-indicator="#data-quality-spinner">
                                    <span class="button-text" th:text="#{integrations.data.quality.button}">Verify Data Quality</span>
                                    <span id="data-quality-spinner" class="htmx-indicator">
                                        <i class="lni lni-is-spinning lni-spinner-2-sacle"></i>
                                    </span>
                                </button>
                            </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>
                            <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/integrations/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 for="recorderAuthUsername" th:text="#{integrations.owntracks.recorder.auth.username}">Authentication Username</label>
                                        <input type="text"
                                               id="recorderAuthUsername"
                                               name="authUsername"
                                               autocomplete="off"
                                               th:placeholder="#{integrations.owntracks.recorder.auth.username.placeholder}"
                                               th:value="${ownTracksRecorderIntegration?.authUsername}">
                                        <small th:text="#{integrations.owntracks.recorder.auth.optional}">Leave empty if no authentication is needed</small>
                                    </div>

                                    <div class="form-group">
                                        <label for="recorderAuthPassword" th:text="#{integrations.owntracks.recorder.auth.password}">Authentication Password</label>
                                        <input type="password"
                                               id="recorderAuthPassword"
                                               name="authPassword"
                                               autocomplete="off"
                                               th:placeholder="#{integrations.owntracks.recorder.auth.password.placeholder}"
                                               th:value="${ownTracksRecorderIntegration?.authPassword}">
                                        <small th:text="#{integrations.owntracks.recorder.auth.optional}">Leave empty if no authentication is needed</small>
                                    </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/integrations/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 authUsername = document.getElementById('recorderAuthUsername').value;
                                        const authPassword = document.getElementById('recorderAuthPassword').value;
                                        const resultDiv = document.getElementById('recorder-connection-test-result');

                                        if (!baseUrl || !username || !deviceId) {
                                            const message = window.locale?.['integrations.owntracks.recorder.test.missing.fields'] || 'Please fill in Base URL, Username, and Device ID';
                                            resultDiv.innerHTML = '<div class="alert alert-warning" style="display: block;">' + message + '</div>';
                                            return;
                                        }

                                        // Show loading state
                                        const loadingMessage = window.locale?.['integrations.owntracks.recorder.test.loading'] || 'Testing connection...';
                                        resultDiv.innerHTML = '<div style="color: var(--color-text-white);">' + loadingMessage + '</div>';

                                        // Make AJAX request to test connection
                                        fetch('/settings/integrations/owntracks-recorder-integration/test', {
                                            method: 'POST',
                                            headers: {
                                                'Content-Type': 'application/x-www-form-urlencoded',
                                            },
                                            body: new URLSearchParams({
                                                baseUrl: baseUrl,
                                                username: username,
                                                deviceId: deviceId,
                                                authUsername: authUsername,
                                                authPassword: authPassword
                                            })
                                        })
                                            .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 => {
                                                const errorMessage = window.locale?.['integrations.owntracks.recorder.test.failed'] || 'Connection test failed';
                                                resultDiv.innerHTML = '<div class="alert alert-danger" style="display: block;">' + errorMessage + ': ' + 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') {
                                            const loadingText = window.locale?.['integrations.owntracks.recorder.loading.historical'] || 'Loading Historical Data...';
                                            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>' + loadingText + '</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/integrations/photos-content" hx-trigger="load" hx-swap="innerHTML">
                            <!-- <span th:text="#{integrations.photos.loading}">Photos content will be loaded here</span> -->
                        </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/integrations/shared-instances-content" hx-trigger="load" hx-swap="innerHTML">
                            <!-- <span th:text="#{integrations.shared.instances.loading}">Shared instances content will be loaded here</span> -->
                        </div>
                    </details>
                </div>
                <script th:inline="javascript">
                    (function() {
                        const serverUrl = /*[[${serverUrl}]]*/ '';
                        const firstToken = /*[[${firstToken}]]*/ '';
                        const tokenSelect = document.getElementById('tokenSelect');
                        const currentToken = tokenSelect ? tokenSelect.value : firstToken;

                        if (currentToken == null) {
                            return;
                        }
                        // Set initial hrefs
                        const owntracksConfig = generateOwnTracksConfig(currentToken, serverUrl);
                        const gpsloggerPropertiesUrl = generateGpsLoggerPropertiesUrl(currentToken, serverUrl);
                        const overlandConfigUrl = generateOverlandUrl(currentToken, serverUrl);

                        document.getElementById('gpslogger-config-link').href = 'gpslogger://properties/' + gpsloggerPropertiesUrl;
                        document.getElementById('owntracks-config-link').href = 'owntracks:///config?inline=' + owntracksConfig;
                        document.getElementById('overland-config-link').href = overlandConfigUrl;

                        if (tokenSelect) {
                            tokenSelect.addEventListener('change', function () {
                                const selectedToken = this.value;

                                // Update config links
                                const owntracksConfig = generateOwnTracksConfig(selectedToken, serverUrl);
                                const gpsloggerPropertiesUrl = generateGpsLoggerPropertiesUrl(selectedToken, serverUrl);
                                const overlandConfigUrl = generateOverlandUrl(selectedToken, serverUrl);

                                document.getElementById('gpslogger-config-link').href = 'gpslogger://properties/' + gpsloggerPropertiesUrl;
                                document.getElementById('owntracks-config-link').href = 'owntracks:///config?inline=' + owntracksConfig;
                                document.getElementById('overland-config-link').href = overlandConfigUrl;
                            });
                        }

                        function generateOwnTracksConfig(token, serverUrl) {
                            const url = serverUrl + '/api/v1/ingest/owntracks?token=' + token;
                            const json = JSON.stringify({
                                "_type": "configuration",
                                "url": url,
                                "tid": "reitti",
                                "locatorInterval": 15,
                                "moveModeLocatorInterval": 15
                            });
                            return btoa(json);
                        }

                        function generateGpsLoggerPropertiesUrl(token, serverUrl) {
                            return serverUrl + '/settings/integrations/reitti.properties?token=' + token;
                        }

                        function generateOverlandUrl(token, serverUrl) {
                            const ingestUrl = serverUrl + '/api/v1/ingest/overland?token=' + token;
                            const encodedUrl = encodeURIComponent(ingestUrl);
                            return 'overland://setup?url=' + encodedUrl + '&device_id=1&unique_id=yes';
                        }
                    })();
                </script>
            </div>
        </div>
    </div>
</div>


<!-- Data Quality Content Fragment -->
<div th:if="${dataQuality}" th:fragment="data-quality-content">
    <h2 style="color: var(--color-highlight); margin-bottom: 20px;" th:text="#{integrations.data.quality.report.title}">📊 Data Quality Report</h2>
    <div th:if="${errorMessage}" class="alert alert-danger" style="display: block; margin-bottom: 20px;">
        <span th:text="${errorMessage}">Error loading data quality information</span>
    </div>

    <div style="color: var(--color-text-white);">
        <!-- Overall Status -->
        <div style="margin-bottom: 25px; padding: 20px; background-color: rgba(255,255,255,0.1); border-radius: 8px;">
            <h3 style="margin: 0 0 15px 0; color: var(--color-accent);" th:text="#{integrations.data.quality.overall.title}">📈 Overall Data Quality</h3>
            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px;">
                <div>
                    <div style="font-size: 0.9em; color: #ccc;" th:text="#{integrations.data.quality.total.points}">Total Location Points</div>
                    <div style="font-size: 1.5em; font-weight: bold;" th:text="${dataQuality.totalPoints}">0</div>
                </div>
                <div>
                    <div style="font-size: 0.9em; color: #ccc;" th:text="#{integrations.data.quality.last.24h}">Last 24 Hours</div>
                    <div style="font-size: 1.5em; font-weight: bold;" th:text="${dataQuality.pointsLast24h}">0</div>
                </div>
                <div>
                    <div style="font-size: 0.9em; color: #ccc;" th:text="#{integrations.data.quality.last.7d}">Last 7 Days</div>
                    <div style="font-size: 1.5em; font-weight: bold;" th:text="${dataQuality.pointsLast7d}">0</div>
                </div>
                <div>
                    <div style="font-size: 0.9em; color: #ccc;" th:text="#{integrations.data.quality.avg.per.day}">Average per Day</div>
                    <div style="font-size: 1.5em; font-weight: bold;" th:text="${dataQuality.avgPointsPerDay}">0</div>
                </div>
            </div>
        </div>

        <!-- Data Freshness -->
        <div style="margin-bottom: 25px; padding: 20px; background-color: rgba(255,255,255,0.1); border-radius: 8px;">
            <h3 th:text="#{integrations.data.quality.freshness.title}">🕒 Data Freshness</h3>
            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 15px;">
                <div>
                    <div th:text="#{integrations.data.quality.latest.point}">Latest Point Received</div>
                    <div th:text="${dataQuality.latestPointTime ?: #messages.msg('integrations.data.quality.no.data')}">Never</div>
                </div>
                <div>
                    <div style="font-size: 0.9em; color: #ccc;" th:text="#{integrations.data.quality.time.since}">Time Since Last Point</div>
                    <div style="font-size: 1.2em;" th:text="${dataQuality.timeSinceLastPoint ?: 'N/A'}">N/A</div>
                </div>
            </div>
        </div>

        <!-- Tracking Quality -->
        <div style="margin-bottom: 25px; padding: 20px; background-color: rgba(255,255,255,0.1); border-radius: 8px;">
            <h3 style="margin: 0 0 15px 0; color: var(--color-accent);" th:text="#{integrations.data.quality.tracking.title}">📍 Tracking Quality</h3>
            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px;">
                <div>
                    <div style="font-size: 0.9em; color: #ccc;" th:text="#{integrations.data.quality.avg.accuracy}">Average Accuracy</div>
                    <div style="font-size: 1.2em;" th:text="${dataQuality.avgAccuracy != null ? dataQuality.avgAccuracy + 'm' : 'N/A'}">N/A</div>
                </div>
                <div>
                    <div style="font-size: 0.9em; color: #ccc;" th:text="#{integrations.data.quality.good.accuracy}">Points with Good Accuracy (&lt;50m)</div>
                    <div style="font-size: 1.2em;" th:text="${dataQuality.goodAccuracyPercentage != null ? dataQuality.goodAccuracyPercentage + '%' : 'N/A'}">N/A</div>
                </div>
                <div>
                    <div style="font-size: 0.9em; color: #ccc;" th:text="#{integrations.data.quality.avg.interval}">Average Interval</div>
                    <div style="font-size: 1.2em;" th:text="${dataQuality.avgInterval ?: 'N/A'}">N/A</div>
                </div>
            </div>
        </div>
        <!-- Status Indicators -->
        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 15px;">
            <div th:if="${dataQuality.isActivelyTracking}" class="alert alert-info">
                <div th:text="#{integrations.data.quality.status.actively.tracking}">✅ Actively Tracking</div>
                <div th:text="#{integrations.data.quality.status.actively.tracking.desc}">Location data is being received regularly</div>
            </div>
            <div th:unless="${dataQuality.isActivelyTracking}" class="alert alert-danger">
                <div th:text="#{integrations.data.quality.status.not.tracking}">❌ Not Actively Tracking</div>
                <div th:text="#{integrations.data.quality.status.not.tracking.desc}">No recent location data received</div>
            </div>

            <div th:if="${dataQuality.hasGoodFrequency}" class="alert alert-info">
                <div th:text="#{integrations.data.quality.status.good.frequency}">✅ Good Frequency</div>
                <div th:text="#{integrations.data.quality.status.good.frequency.desc}">Location points are frequent enough for accurate tracking</div>
            </div>
            <div th:unless="${dataQuality.hasGoodFrequency}" class="alert alert-warning">
                <div th:text="#{integrations.data.quality.status.low.frequency}">⚠️ Low Frequency</div>
                <div th:text="#{integrations.data.quality.status.low.frequency.desc}">Consider increasing tracking frequency for better accuracy</div>
            </div>

            <div th:if="${dataQuality.hasFluctuatingFrequency}" class="alert alert-warning">
                <div th:text="#{integrations.data.quality.status.fluctuating.frequency}">⚠️ Fluctuating Frequency</div>
                <div th:text="#{integrations.data.quality.status.fluctuating.frequency.desc}">Tracking intervals vary significantly, which may affect accuracy</div>
            </div>

            <div th:unless="${dataQuality.hasFluctuatingFrequency}" class="alert alert-info">
                <div th:text="#{integrations.data.quality.status.good.consistency}">✅ Good Consistency</div>
                <div th:text="#{integrations.data.quality.status.good.consistency.desc}">Tracking intervals are consistent and stable</div>
            </div>
        </div>

        <!-- Recommendations -->
        <div th:if="${dataQuality.recommendations != null && !dataQuality.recommendations.isEmpty()}" class="alert alert-warning">
            <p th:text="#{integrations.data.quality.recommendations.title}">💡 Recommendations</p>
            <ul>
                <li th:each="recommendation : ${dataQuality.recommendations}"
                    th:text="${recommendation}">
                    Recommendation
                </li>
            </ul>
        </div>

        <!-- Action Buttons -->
        <div style="margin-top: 25px; text-align: center; display: flex; gap: 15px; justify-content: center;">
            <button class="btn"
                    hx-get="/settings/integrations/data-quality-content"
                    hx-target="#integrations"
                    hx-swap="innerHTML"
                    hx-indicator="#refresh-data-spinner">
                <span class="button-text" th:text="#{integrations.data.quality.refresh}">Refresh Data</span>
                <span id="refresh-data-spinner" class="htmx-indicator">
                    <i class="lni lni-is-spinning lni-spinner-2-sacle"></i>
                </span>
            </button>
            <button class="btn btn-secondary"
                    hx-get="/settings/integrations/integrations-content"
                    hx-target="#integrations"
                    hx-swap="innerHTML"
                    th:text="#{form.close}">
                Close
            </button>
        </div>
    </div>
</div>

<span th:text="${firstToken}" id="current-token" style="display:none;"></span>
<script th:inline="javascript">
    window.userSettings = /*[[${userSettings}]]*/ {};
    window.locale = {
        'integrations.owntracks.recorder.test.missing.fields': /*[[#{integrations.owntracks.recorder.test.missing.fields}]]*/ 'Please fill in Base URL, Username, and Device ID',
        'integrations.owntracks.recorder.test.loading': /*[[#{integrations.owntracks.recorder.test.loading}]]*/ 'Testing connection...',
        'integrations.owntracks.recorder.test.failed': /*[[#{integrations.owntracks.recorder.test.failed}]]*/ 'Connection test failed',
        'integrations.owntracks.recorder.loading.historical': /*[[#{integrations.owntracks.recorder.loading.historical}]]*/ 'Loading Historical Data...'
    };
</script>

</body>
</html>
