let mode = 'login'; // 'login', 'setup', 'invite'
    let inviteToken = null;
    let setupTokenRequired = false;

    const params = new URLSearchParams(location.search);

    // Show errors/success from URL params
    if (params.get('error')) {
      showStatus('error', decodeURIComponent(params.get('error')));
    }
    if (params.get('success')) {
      showStatus('success', decodeURIComponent(params.get('success')));
    }

    // Check for invite token
    if (params.get('invite')) {
      inviteToken = params.get('invite');
      setMode('invite');
    } else {
      checkSetup();
    }

    async function checkSetup() {
      try {
        const r = await fetch('/auth/setup-check');
        const data = await r.json();
        setupTokenRequired = Boolean(data.setupTokenRequired);
        if (data.setupMode) setMode('setup');
      } catch {}
    }

    function setMode(m) {
      mode = m;
      const nameGroup = document.getElementById('name-group');
      const pwConfirm = document.getElementById('pw-confirm-group');
      const pwStrength = document.getElementById('pw-strength');
      const pwInput = document.getElementById('password');
      const setupTokenGroup = document.getElementById('setup-token-group');
      const setupTokenInput = document.getElementById('setup-token');

      if (mode === 'setup') {
        document.getElementById('view-title').textContent = 'Ersten Admin anlegen';
        document.getElementById('view-subtitle').textContent = 'Noch kein User vorhanden. Erstelle den ersten Admin-Account.';
        document.getElementById('login-btn').textContent = 'Admin-Account erstellen';
        document.getElementById('footer-text').textContent = 'Erster Start — Admin-Setup';
        nameGroup.classList.remove('hidden');
        pwConfirm.classList.remove('hidden');
        pwStrength.classList.remove('hidden');
        pwInput.autocomplete = 'new-password';
        pwInput.minLength = 10;
        document.getElementById('password-confirm').minLength = 10;
        setupTokenGroup.classList.toggle('hidden', !setupTokenRequired);
        setupTokenInput.required = setupTokenRequired;
      } else if (mode === 'invite') {
        document.getElementById('view-title').textContent = 'Einladung annehmen';
        document.getElementById('view-subtitle').textContent = 'Setze deinen Namen und dein Passwort, um deinen Account zu aktivieren.';
        document.getElementById('login-btn').textContent = 'Account aktivieren';
        document.getElementById('footer-text').textContent = 'Einladung vom Admin';
        nameGroup.classList.remove('hidden');
        pwConfirm.classList.remove('hidden');
        pwStrength.classList.remove('hidden');
        pwInput.autocomplete = 'new-password';
        pwInput.minLength = 10;
        document.getElementById('password-confirm').minLength = 10;
      }
    }

    // Password strength indicator
    document.getElementById('password').addEventListener('input', (e) => {
      if (mode === 'login') return;
      const pw = e.target.value;
      const bar = document.getElementById('pw-strength');
      bar.className = 'pw-strength';
      if (pw.length === 0) { bar.classList.add('hidden'); return; }
      bar.classList.remove('hidden');
      const strong = pw.length >= 10 && /[a-z]/.test(pw) && /[A-Z]/.test(pw) && /[0-9]/.test(pw) && /[^A-Za-z0-9]/.test(pw);
      if (strong) bar.classList.add('strong');
      else if (pw.length >= 8) bar.classList.add('medium');
      else bar.classList.add('weak');
    });

    document.getElementById('login-form').addEventListener('submit', async (e) => {
      e.preventDefault();
      const btn = document.getElementById('login-btn');
      const email = document.getElementById('email').value.trim();
      const password = document.getElementById('password').value;
      if (!email || !password) return;

      // Validate password confirm for setup/invite
      if (mode === 'setup' || mode === 'invite') {
        const confirm = document.getElementById('password-confirm').value;
        if (password !== confirm) {
          showStatus('error', 'Passwörter stimmen nicht überein');
          return;
        }
        const strong = password.length >= 10 && /[a-z]/.test(password) && /[A-Z]/.test(password) && /[0-9]/.test(password) && /[^A-Za-z0-9]/.test(password);
        if (!strong) {
          showStatus('error', 'Passwort: mindestens 10 Zeichen sowie Kleinbuchstabe, Großbuchstabe, Zahl und Sonderzeichen');
          return;
        }
      }

      btn.disabled = true;
      btn.innerHTML = '<span class="spinner"></span>Sende...';
      clearStatus();

      try {
        let url, body;
        if (mode === 'setup') {
          url = '/auth/setup';
          body = { email, password, name: document.getElementById('setup-name').value.trim() || email.split('@')[0], setup_token: document.getElementById('setup-token').value };
        } else if (mode === 'invite') {
          url = '/auth/accept-invite';
          body = { token: inviteToken, password, name: document.getElementById('setup-name').value.trim() || '' };
        } else {
          url = '/auth/login';
          body = { email, password };
        }

        const r = await fetch(url, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          credentials: 'same-origin',
          body: JSON.stringify(body),
        });
        const data = await r.json();

        if (r.ok && data.redirect) {
          window.location.href = data.redirect;
          return;
        } else if (!r.ok) {
          showStatus('error', data.error || 'Fehler aufgetreten');
        }
      } catch (err) {
        showStatus('error', 'Verbindung zum Server fehlgeschlagen');
      }

      btn.disabled = false;
      btn.textContent = mode === 'setup' ? 'Admin-Account erstellen' : mode === 'invite' ? 'Account aktivieren' : 'Anmelden';
    });

    function showStatus(type, message) {
      const s = document.getElementById('status');
      s.className = `status ${type}`;
      s.textContent = message;
    }
    function clearStatus() {
      const s = document.getElementById('status');
      s.className = 'status';
      s.removeAttribute('style');
    }
