{{define "setup.html"}}
<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>OFS - Настройка подключения</title>
    <link rel="stylesheet" href="/static/app.css">
    <script src="/static/vendor/tailwindcss.browser.js"></script>
</head>
<body class="bg-gray-100 min-h-screen flex items-center justify-center">
    <div class="max-w-md w-full mx-4">
        <div class="bg-white rounded-lg shadow-lg p-8">
            <div class="text-center mb-8">
                <h1 class="text-2xl font-bold text-blue-600">QuoteForge</h1>
                <p class="text-gray-600 mt-2">Настройка подключения к базе данных</p>
            </div>

            <div class="bg-amber-50 border border-amber-300 rounded-md p-3 mb-4 flex items-start gap-2">
                <svg class="w-5 h-5 text-amber-500 mt-0.5 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"/>
                </svg>
                <p class="text-sm text-amber-800"><span class="font-semibold">Важно:</span> не закрывайте консольное окно приложения — без него программа не работает.</p>
            </div>

            <form id="setup-form" class="space-y-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Хост сервера</label>
                    <input type="text" name="host" id="host"
                           value="{{if .Settings}}{{.Settings.Host}}{{else}}localhost{{end}}"
                           class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                           placeholder="localhost или IP-адрес">
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Порт</label>
                    <input type="number" name="port" id="port"
                           value="{{if .Settings}}{{.Settings.Port}}{{else}}3306{{end}}"
                           class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                           placeholder="3306">
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">База данных</label>
                    <input type="text" name="database" id="database"
                           value="{{if .Settings}}{{.Settings.Database}}{{else}}RFQ_LOG{{end}}"
                           class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                           placeholder="RFQ_LOG">
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Пользователь</label>
                    <input type="text" name="user" id="user"
                           value="{{if .Settings}}{{.Settings.User}}{{end}}"
                           class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                           placeholder="username">
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Пароль</label>
                    <input type="password" name="password" id="password"
                           class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                           placeholder="{{if .Settings}}********{{else}}password{{end}}">
                    {{if .Settings}}
                    <p class="text-xs text-gray-500 mt-1">Оставьте пустым, чтобы сохранить текущий пароль</p>
                    {{end}}
                </div>

                <div id="status" class="hidden p-3 rounded-md text-sm"></div>

                <div class="flex space-x-3 pt-4">
                    {{if .Settings}}
                    <a href="/"
                       class="flex-1 px-4 py-2 bg-gray-100 text-gray-700 rounded-md hover:bg-gray-200 transition text-center">
                        Назад
                    </a>
                    {{end}}
                    <button type="button" onclick="testConnection()"
                            class="flex-1 px-4 py-2 bg-gray-100 text-gray-700 rounded-md hover:bg-gray-200 transition">
                        Проверить
                    </button>
                    <button type="submit"
                            class="flex-1 px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition">
                        Сохранить
                    </button>
                </div>
            </form>
        </div>

        <p class="text-center text-gray-500 text-sm mt-4">
            QuoteForge v1.0 - Конфигуратор серверов
        </p>
    </div>

    <!-- Dead-man's switch overlay -->
    <div id="backend-offline-overlay" class="hidden fixed inset-0 z-[9999] bg-black/80 flex items-center justify-center p-6">
        <div class="bg-white rounded-xl shadow-2xl max-w-md w-full p-8 text-center">
            <div class="text-red-500 mb-4">
                <svg class="w-16 h-16 mx-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"/>
                </svg>
            </div>
            <h2 class="text-xl font-bold text-gray-900 mb-3">Приложение остановлено</h2>
            <p class="text-gray-600 mb-4">Консольное окно QuoteForge было закрыто — без него программа не работает.</p>
            <div class="bg-amber-50 border border-amber-200 rounded-lg p-3 mb-6 text-sm text-amber-800">
                Запустите программу заново и нажмите «Обновить страницу».
            </div>
            <button onclick="window.location.reload()" class="w-full px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 font-medium">
                Обновить страницу
            </button>
        </div>
    </div>

    <script>
        let awaitingRestart = false;

        function showStatus(message, type) {
            const status = document.getElementById('status');
            status.classList.remove('hidden', 'bg-green-100', 'text-green-800', 'bg-red-100', 'text-red-800', 'bg-blue-100', 'text-blue-800', 'bg-yellow-100', 'text-yellow-800');

            if (type === 'success') {
                status.classList.add('bg-green-100', 'text-green-800');
            } else if (type === 'error') {
                status.classList.add('bg-red-100', 'text-red-800');
            } else if (type === 'warning') {
                status.classList.add('bg-yellow-100', 'text-yellow-800');
            } else {
                status.classList.add('bg-blue-100', 'text-blue-800');
            }

            status.textContent = message;
        }

        async function testConnection() {
            showStatus('Проверка подключения...', 'info');

            const formData = new FormData(document.getElementById('setup-form'));

            try {
                const resp = await fetch('/setup/test', {
                    method: 'POST',
                    body: formData
                });
                const data = await resp.json();

                if (data.success) {
                    let msg = data.message;
                    if (data.can_write) {
                        msg += ' Права на запись: есть.';
                    } else {
                        msg += ' Права на запись: только чтение.';
                    }
                    showStatus(msg, 'success');
                } else {
                    showStatus(data.error, 'error');
                }
            } catch (e) {
                showStatus('Ошибка сети: ' + e.message, 'error');
            }
        }

        async function checkServerReady() {
            let attempts = 0;
            const maxAttempts = 30; // 30 seconds max

            const checkInterval = setInterval(async () => {
                attempts++;
                try {
                    const resp = await fetch('/health', { method: 'GET' });
                    const data = await resp.json();

                    // Check if we're out of setup mode
                    if (data.status === 'ok') {
                        clearInterval(checkInterval);
                        showStatus('✓ Приложение запущено! Перенаправление...', 'success');
                        setTimeout(() => {
                            window.location.href = '/';
                        }, 1000);
                    }
                } catch (e) {
                    // Server still restarting, continue polling
                    if (attempts >= maxAttempts) {
                        clearInterval(checkInterval);
                        showStatus('Сервер не отвечает. Обновите страницу вручную.', 'error');
                    }
                }
            }, 1000); // Check every second
        }

        async function requestRestartAndWait() {
            awaitingRestart = true;
            showStatus('Перезапуск приложения...', 'info');
            try {
                await fetch('/api/restart', { method: 'POST' });
            } catch (e) {
                // Ignore network errors here: restart may break connection immediately.
            }
            checkServerReady();
        }

        document.getElementById('setup-form').addEventListener('submit', async function(e) {
            e.preventDefault();
            showStatus('Сохранение настроек...', 'info');

            const formData = new FormData(this);

            try {
                const resp = await fetch('/setup', {
                    method: 'POST',
                    body: formData
                });
                const data = await resp.json();

                if (data.success) {
                    showStatus('✓ ' + data.message, 'success');

                    // Check if restart is required
                    if (data.restart_required) {
                        setTimeout(() => {
                            requestRestartAndWait();
                        }, 2000);
                    } else {
                        // In setup mode, auto-restart is happening
                        setTimeout(() => {
                            showStatus('✓ Настройки сохранены. Проверка подключения...', 'success');
                            // Poll until server is back
                            checkServerReady();
                        }, 2000);
                    }
                } else {
                    showStatus(data.error, 'error');
                }
            } catch (e) {
                showStatus('Ошибка сети: ' + e.message, 'error');
            }
        });
        // Dead-man's switch: detect if the backend process has stopped
        (function() {
            const POLL_MS = 5000;
            const FAIL_THRESHOLD = 2;
            let failCount = 0;

            async function checkBackend() {
                if (awaitingRestart) return;
                try {
                    const ctrl = new AbortController();
                    const timer = setTimeout(() => ctrl.abort(), 3000);
                    const resp = await fetch('/health', { signal: ctrl.signal });
                    clearTimeout(timer);
                    if (resp.ok) {
                        failCount = 0;
                        document.getElementById('backend-offline-overlay').classList.add('hidden');
                    } else {
                        failCount++;
                    }
                } catch (_) {
                    failCount++;
                }
                if (failCount >= FAIL_THRESHOLD) {
                    document.getElementById('backend-offline-overlay').classList.remove('hidden');
                }
            }

            setInterval(checkBackend, POLL_MS);
        })();
    </script>
</body>
</html>
{{end}}
