<!DOCTYPE html>
<html lang="en">
<head>
    {{template "html-head" .}}
</head>
<body class="app-shell">
    {{template "navbar" .}}

    <div class="app-body container-fluid px-3 px-lg-4 px-xxl-5">
        <main class="container">
        <div class="page-header">
            <h2>Settings</h2>
            <p class="help-text">Manage API keys locally. Keys are stored in <code>config/api_keys.json</code> (gitignored).</p>
        </div>

        <div class="gx-card" style="margin-top: 1.5rem; padding: 1.5rem;">
            <div class="form-grid">
                <label class="form-label">TPDB API Key</label>
                <input type="password" id="tpdb-key" class="input" placeholder="TPDB API key">

                <label class="form-label">Adult Empire API Key</label>
                <input type="password" id="ae-key" class="input" placeholder="Adult Empire API key (optional)">

                <label class="form-label">StashDB API Key</label>
                <input type="password" id="stashdb-key" class="input" placeholder="StashDB API key">

                <label class="form-label">StashDB Endpoint</label>
                <input type="text" id="stashdb-endpoint" class="input" placeholder="https://stashdb.org/graphql">
            </div>

            <div class="action-buttons" style="margin-top: 1rem;">
                <button class="btn" onclick="saveApiKeys()">Save Keys<div class="hoverEffect"><div></div></div></button>
                <button class="btn-secondary" onclick="loadApiKeys()">Reload<div class="hoverEffect"><div></div></div></button>
            </div>

            <div id="settings-status" class="status-banner" style="margin-top: 1rem;"></div>
        </div>

        <div class="gx-card" style="margin-top: 1.5rem; padding: 1.5rem; border: 1px solid #ff8a8a;">
            <h4 style="color: #ff8a8a;">Database Maintenance</h4>
            <p class="help-text">Current database: <code>{{.DBPath}}</code></p>
            <div class="action-buttons" style="margin-top: 0.75rem;">
                <button class="btn-secondary" onclick="loadDbInfo()">Refresh Info<div class="hoverEffect"><div></div></div></button>
                <button class="btn" style="background: #ff4d4d;" onclick="confirmDeleteDb()">Delete Database<div class="hoverEffect"><div></div></div></button>
            </div>
            <div id="db-info" class="status-banner" style="margin-top: 0.75rem;"></div>
        </div>
        </main>
    </div>

    {{template "html-scripts" .}}
    <script>
        async function loadApiKeys() {
            setSettingsStatus('Loading...');
            try {
                const res = await fetch('/api/settings/api-keys');
                const result = await res.json();
                if (result.success && result.data) {
                    const d = result.data;
                    document.getElementById('tpdb-key').value = d.tpdb_api_key || '';
                    document.getElementById('ae-key').value = d.ae_api_key || '';
                    document.getElementById('stashdb-key').value = d.stashdb_api_key || '';
                    document.getElementById('stashdb-endpoint').value = d.stashdb_endpoint || 'https://stashdb.org/graphql';
                    setSettingsStatus('Loaded');
                } else {
                    setSettingsStatus(result.message || 'Failed to load', true);
                }
            } catch (err) {
                setSettingsStatus('Error: ' + err.message, true);
            }
        }

        async function saveApiKeys() {
            const payload = {
                tpdb_api_key: document.getElementById('tpdb-key').value,
                ae_api_key: document.getElementById('ae-key').value,
                stashdb_api_key: document.getElementById('stashdb-key').value,
                stashdb_endpoint: document.getElementById('stashdb-endpoint').value,
            };
            setSettingsStatus('Saving...');
            try {
                const res = await fetch('/api/settings/api-keys', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(payload),
                });
                const result = await res.json();
                if (result.success) {
                    setSettingsStatus('Saved. Restart not required; new keys are active.');
                } else {
                    setSettingsStatus(result.message || 'Failed to save', true);
                }
            } catch (err) {
                setSettingsStatus('Error: ' + err.message, true);
            }
        }

        function setSettingsStatus(msg, isError) {
            const el = document.getElementById('settings-status');
            el.textContent = msg;
            el.classList.toggle('error', !!isError);
            el.style.display = msg ? 'block' : 'none';
        }

        async function loadDbInfo() {
            try {
                const res = await fetch('/api/settings/database');
                const result = await res.json();
                if (result.success && result.data) {
                    const d = result.data;
                    const el = document.getElementById('db-info');
                    el.textContent = `Path: ${d.path || ''} | Size: ${ (d.size_mb || 0).toFixed ? (d.size_mb.toFixed(2) + ' MB') : 'n/a'}`;
                    el.classList.remove('error');
                    el.style.display = 'block';
                }
            } catch (err) {
                const el = document.getElementById('db-info');
                el.textContent = 'Error loading DB info: ' + err.message;
                el.classList.add('error');
                el.style.display = 'block';
            }
        }

        async function confirmDeleteDb() {
            if (!confirm('This will DELETE the database file and recreate an empty one. Continue?')) return;
            try {
                const res = await fetch('/api/settings/database', { method: 'DELETE' });
                const result = await res.json();
                const el = document.getElementById('db-info');
                if (result.success) {
                    el.textContent = result.message;
                    el.classList.remove('error');
                    el.style.display = 'block';
                } else {
                    el.textContent = result.message || 'Failed to delete DB';
                    el.classList.add('error');
                    el.style.display = 'block';
                }
            } catch (err) {
                const el = document.getElementById('db-info');
                el.textContent = 'Error deleting DB: ' + err.message;
                el.classList.add('error');
                el.style.display = 'block';
            }
        }

        document.addEventListener('DOMContentLoaded', loadApiKeys);
    </script>
</body>
</html>
