document.addEventListener('DOMContentLoaded', () => {
  const form = document.getElementById('login-form');
  const errorBox = document.getElementById('login-error');

  form.addEventListener('submit', async (e) => {
    e.preventDefault();
    const email = document.getElementById('email').value;
    const password = document.getElementById('password').value;
    const btn = form.querySelector('button[type="submit"]');

    btn.disabled = true;
    btn.textContent = 'Iniciando sesión...';
    errorBox.style.display = 'none';

    try {
      const formData = new URLSearchParams();
      formData.append('username', email);
      formData.append('password', password);

      const response = await fetch('/api/auth/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: formData
      });

      if (response.ok) {
        // Redirigir al dashboard
        window.location.href = '/dashboard';
      } else {
        const errorData = await response.json();
        errorBox.textContent = errorData.detail || 'Credenciales inválidas';
        errorBox.style.display = 'block';
        btn.disabled = false;
        btn.textContent = 'Iniciar Sesión';
      }
    } catch (err) {
      errorBox.textContent = 'Error de conexión con el servidor.';
      errorBox.style.display = 'block';
      btn.disabled = false;
      btn.textContent = 'Iniciar Sesión';
    }
  });
});
