const form = document.getElementById("loginForm"); const errorBox = document.getElementById("errorBox"); const submitBtn = document.getElementById("submitBtn"); const ERROR_MESSAGES = { missing_credentials: "Completá email y contraseña.", invalid_credentials: "Email o contraseña incorrectos.", user_inactive: "El usuario está deshabilitado.", }; function showError(code) { errorBox.textContent = ERROR_MESSAGES[code] || "No pudimos iniciarte sesión."; errorBox.classList.add("visible"); } function clearError() { errorBox.classList.remove("visible"); errorBox.textContent = ""; } form.addEventListener("submit", async (e) => { e.preventDefault(); clearError(); const email = form.email.value.trim(); const password = form.password.value; submitBtn.disabled = true; submitBtn.textContent = "Entrando..."; try { const res = await fetch("/api/auth/login", { method: "POST", headers: { "Content-Type": "application/json" }, credentials: "include", body: JSON.stringify({ email, password }), }); const data = await res.json().catch(() => ({})); if (!res.ok || !data.ok) { showError(data.error || "login_failed"); return; } const next = new URLSearchParams(window.location.search).get("next") || "/home"; window.location.replace(next); } catch (err) { showError("network"); } finally { submitBtn.disabled = false; submitBtn.textContent = "Entrar"; } }); // Si ya hay sesión activa, ir directo al home. fetch("/api/auth/me", { credentials: "include" }) .then((r) => (r.ok ? r.json() : null)) .then((d) => { if (d?.ok) window.location.replace("/home"); }) .catch(() => {});