(() => {
  const $ = (id) => document.getElementById(id);

  const netBadge = $("netBadge");
  const form = $("loginForm");
  const rut = $("rut");
  const clave = $("clave");
  const btnLogin = $("btnLogin");
  const togglePass = $("togglePass");

  function updateNet() {
    const online = navigator.onLine;
    netBadge.textContent = online ? "Online" : "Offline";
    netBadge.className =
      "badge rounded-pill " + (online ? "text-bg-success" : "text-bg-secondary");
  }
  window.addEventListener("online", updateNet);
  window.addEventListener("offline", updateNet);
  updateNet();

  togglePass.addEventListener("click", () => {
    const isPass = clave.type === "password";
    clave.type = isPass ? "text" : "password";
    togglePass.innerHTML = isPass
      ? '<i class="bi bi-eye-slash"></i>'
      : '<i class="bi bi-eye"></i>';
  });

  const normalizeRut = (s) =>
    (s || "")
      .toUpperCase()
      .replace(/\./g, "")
      .replace(/-/g, "")
      .replace(/\s+/g, "");

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

    const r = normalizeRut(rut.value);
    const p = (clave.value || "").trim();

    if (!r || !p) {
      Swal.fire({
        icon: "warning",
        title: "Faltan datos",
        text: "Ingresa RUT y clave.",
      });
      return;
    }

    btnLogin.disabled = true;
    btnLogin.innerHTML =
      '<span class="spinner-border spinner-border-sm me-2"></span>Ingresando…';

    try {
      const res = await fetch("php/auth/login.php", {
        method: "POST",
        credentials: "same-origin",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ rut: r, clave: p }),
        cache: "no-store",
      });

      const data = await res.json().catch(() => null);

      if (!res.ok || !data || data.ok === false) {
        const msg =
          (data && data.message) ? data.message : "No se pudo iniciar sesión.";
        Swal.fire({ icon: "error", title: "Acceso denegado", text: msg });
        return;
      }

      sessionStorage.setItem("fp_user", JSON.stringify(data.user));

      // ✅ SweetAlert de bienvenida
      await Swal.fire({
        icon: "success",
        title: "¡Bienvenido!",
        text: `${(data.user?.nombre || "Usuario")} · ${data.user?.rol || ""}`.trim(),
        timer: 1200,
        showConfirmButton: false,
        allowOutsideClick: false,
      });

      window.location.href = "pages/dashboard.html";
    } catch (err) {
      Swal.fire({
        icon: "error",
        title: "Error",
        text: err?.message || "Error de conexión.",
      });
    } finally {
      btnLogin.disabled = false;
      btnLogin.innerHTML = '<i class="bi bi-box-arrow-in-right"></i> Ingresar';
    }
  });
})();
