document.addEventListener('DOMContentLoaded', function() {
  const form = document.getElementById("kt_sign_in_form");
  if (!form) return;

  form.addEventListener("submit", function (e) {
    e.preventDefault();

    const username = form.username.value.trim();
    const password = form.password.value.trim();

    const button = document.getElementById("kt_sign_in_submit");
    const spinner = button.querySelector(".indicator-progress");

    // Mostrar spinner
    spinner.style.display = "inline-block";
    button.disabled = true;

    fetch("api/login.php", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ username, password }),
    })
      .then((res) => res.json())
      .then((data) => {
        if (data.success) {
          window.location.href = data.redirect;
        } else {
          alert(data.message || "Login fallido");
        }
      })
      .catch(() => {
        alert("Error en la conexión.");
      })
      .finally(() => {
        spinner.style.display = "none";
        button.disabled = false;
      });
  });
});
