// Login page logic: detects first-run setup mode and swaps the form into // admin-creation mode. Talks to /api/auth/setup or /api/auth/login. (async function init() { const errorBox = document.getElementById('errorBox'); const errorText = document.getElementById('errorText'); const setupNote = document.getElementById('setupNote'); const setupTopBar = document.getElementById('setupTopBar'); const brandIcon = document.getElementById('brandIcon'); const title = document.getElementById('title'); const subtitle = document.getElementById('subtitle'); const submitBtn = document.getElementById('submitBtn'); const submitLabel = document.getElementById('submitLabel'); const submitIcon = document.getElementById('submitIcon'); const form = document.getElementById('loginForm'); const passwordInput = document.getElementById('password'); let setupMode = false; function showError(msg) { errorText.textContent = msg; errorBox.style.display = 'flex'; } function clearError() { errorText.textContent = ''; errorBox.style.display = 'none'; } try { const r = await fetch('/api/auth/setup-required'); if (r.ok) { const data = await r.json(); setupMode = !!data.setupRequired; } } catch (_) { // network error -> stay in login mode } if (setupMode) { title.textContent = 'Ersteinrichtung'; subtitle.textContent = 'Willkommen beim Provisions-Tracker.'; setupNote.style.display = 'flex'; setupTopBar.style.display = 'block'; submitLabel.textContent = 'Administrator anlegen'; submitIcon.textContent = 'person_add'; // Brand icon switches to admin look in setup mode brandIcon.classList.remove('bg-primary', 'text-on-primary'); brandIcon.classList.add('bg-surface-variant', 'text-on-surface'); brandIcon.querySelector('span').textContent = 'admin_panel_settings'; passwordInput.setAttribute('autocomplete', 'new-password'); passwordInput.setAttribute('minlength', '8'); } form.addEventListener('submit', async (e) => { e.preventDefault(); clearError(); submitBtn.disabled = true; const username = document.getElementById('username').value.trim(); const password = passwordInput.value; try { const url = setupMode ? '/api/auth/setup' : '/api/auth/login'; const r = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'same-origin', body: JSON.stringify({ username, password }), }); const data = await r.json().catch(() => ({})); if (!r.ok) { showError(data.error || 'Anmeldung fehlgeschlagen'); submitBtn.disabled = false; return; } window.location.href = '/'; } catch (err) { showError('Netzwerkfehler: ' + err.message); submitBtn.disabled = false; } }); })();