import { api } from '/static/js/api.js';

const form = document.getElementById('login-form');
const errorBox = document.getElementById('error');

function safeNext() {
  const next = new URLSearchParams(window.location.search).get('next') || '/';
  return next.startsWith('/') && !next.startsWith('//') ? next : '/';
}

form.addEventListener('submit', async (e) => {
  e.preventDefault();
  errorBox.textContent = '';
  try {
    const res = await api('POST', '/api/v1/auth/login', {
      email: document.getElementById('email').value.trim(),
      password: document.getElementById('password').value,
    });
    window.location.href = res.mustChangePassword ? '/change-password' : safeNext();
  } catch (err) {
    errorBox.textContent = err.message;
  }
});
