document.getElementById("loginForm").addEventListener("submit", async (e) => {
  e.preventDefault();
  const data = new FormData(e.target);
  const json = Object.fromEntries(data.entries());

  try {
    const res = await fetch("api.php?action=login", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      credentials: "include",
      body: JSON.stringify(json)
    });

    const result = await res.json();

    if (result.success) {
      sessionStorage.setItem("admin", "true");
      sessionStorage.setItem("rol", result.rol);
      sessionStorage.setItem("usuario", result.usuario);

      await Swal.fire({
        icon: "success",
        title: "Inicio de sesin correcto!",
        text: `Bienvenido ${result.usuario}`,
        timer: 2000,
        showConfirmButton: false
      });

      window.location.href = "dashboard.html";
    } else {
      Swal.fire({
        icon: "error",
        title: "Error de acceso",
        text: result.mensaje || "Credenciales invalidas"
      });
    }
  } catch (error) {
    console.error("Error:", error);
    Swal.fire({
      icon: "error",
      title: "Error del servidor",
      text: "Hubo un problema al intentar iniciar sesion."
    });
  }
});
