const params = new URLSearchParams(location.search);
const returnUrl = params.get('returnUrl') || '/';

const flash = document.getElementById('flash');
const form = document.getElementById('loginForm');

form.addEventListener('submit', async (e) => {
  e.preventDefault();
  flash.hidden = true;

  const body = {
    username: document.getElementById('username').value.trim(),
    password: document.getElementById('password').value,
    rememberMe: document.getElementById('remember').checked
  };

  try {
    const res = await fetch('/api/auth/login', {
      method: 'POST',
      credentials: 'same-origin',
      headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
      body: JSON.stringify(body)
    });

    if (!res.ok) {
      const data = await res.json().catch(() => ({}));
      flash.textContent = data.error || 'Anmeldung fehlgeschlagen.';
      flash.hidden = false;
      return;
    }

    location.href = returnUrl.startsWith('/') ? returnUrl : '/';
  } catch (err) {
    flash.textContent = 'Server nicht erreichbar.';
    flash.hidden = false;
  }
});
