document.addEventListener("DOMContentLoaded", () => {
  const form = document.getElementById("formLogin");
  const btn = document.getElementById("btnLogin");
  const spinner = btn?.querySelector(".spinner-border");
  const alertBx = document.getElementById("loginAlert");

  form?.addEventListener("submit", async (e) => {
    e.preventDefault();

    form.classList.add("was-validated");
    if (!form.checkValidity()) return;

    alertBx?.classList.add("d-none");
    btn.disabled = true;
    spinner?.classList.remove("d-none");

    try {
      // URL definida en el atributo action del form
      const url = form.getAttribute("action");

      const fd = new FormData(form);
      fd.set("accion", "LOGIN"); // lo espera login.ajax.php

      const resp = await fetch(url, {
        method: "POST",
        body: fd,
        credentials: "same-origin",
      });

      if (!resp.ok) throw new Error(`Error de red (${resp.status})`);
      const data = await resp.json();
      if (!data.ok) throw new Error(data.message || "Credenciales inválidas");

      form.classList.add("d-none");

      window.location.assign(data.redirect || "index.php");

      return;
    } catch (err) {
      const msg = err.message || "Error al iniciar sesión";
      if (alertBx) {
        alertBx.textContent = msg;
        alertBx.classList.remove("d-none");
      } else {
        alert(msg);
      }
    } finally {
      btn.disabled = false;
      spinner?.classList.add("d-none");
    }
  });
});
