// /static/js/login.js
// Handles secure login against /auth/login (JWT cookie).
// Shows a pop-up “Invalid credentials” message on failure.

(function () {
  const sel = (id) => document.getElementById(id);

  function showErrorPopup(msg) {
    // 1) Prefer a Bootstrap alert block if the page has #loginError
    const alertEl = sel("loginError");
    if (alertEl) {
      alertEl.textContent = msg || "Invalid credentials";
      alertEl.classList.remove("d-none");
      return;
    }
    // 2) Otherwise fall back to a browser popup
    window.alert(msg || "Invalid credentials");
  }

  function hideError() {
    const alertEl = sel("loginError");
    if (alertEl) alertEl.classList.add("d-none");
  }

  async function handleLogin(e) {
    e.preventDefault();
    hideError();

    const username = (sel("username")?.value || "").trim();
    const password = sel("password")?.value || "";

    if (!username || !password) {
      showErrorPopup("Please enter both ID and password.");
      return;
    }

    // Disable submit to prevent double-clicks
    const submitBtn = (e.submitter || sel("loginSubmit"));
    const prevText = submitBtn ? submitBtn.innerHTML : null;
    if (submitBtn) {
      submitBtn.disabled = true;
      submitBtn.innerHTML = "Signing in…";
    }

    try {
      const res = await fetch("/auth/login", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        credentials: "include", // receive HttpOnly JWT cookie
        body: JSON.stringify({ username, password })
      });

      if (res.ok) {
        // Clear local frontend state used by dashboard / history / audit
        try {
          // Known keys used by your pages (includes common variants)
          const keysToRemove = [
            // Audit
            "auditFilters", "auditFiltersApplied",
            // Process History
            "historyFilters", "historyFiltersApplied",
            // Dashboard (common naming)
            "dashboardFilters", "dashboardFiltersApplied",
            // Final QC page
            "qcFilters", "qcFiltersApplied",
            // Generic/common variants used in various pages
            "filters", "filtersApplied",
            "processFilters", "processFiltersApplied",
            // any other UI state you might persist
            "filesFilters", "filesFiltersApplied"
          ];
          keysToRemove.forEach(k => localStorage.removeItem(k));

          // Broadcast to other tabs/windows (storage events fire in other tabs)
          localStorage.setItem("vitu_clear_on_login", Date.now().toString());
          // Remove quickly to keep storage clean; other tabs still receive the event.
          localStorage.removeItem("vitu_clear_on_login");
        } catch (ex) {
          // ignore storage errors
          console.warn("Could not clear localStorage:", ex);
        }

        // Optional: keep your existing navbar name behavior (set after clearing)
        try {
          localStorage.setItem("loggedIn", "1");
          localStorage.setItem("username", username);
        } catch (ex) {}

        // Go to dashboard (relative URL works from /static/login.html too)
        window.location.href = "dashboard.html";
        return;
      }

      if (res.status === 401) {
        showErrorPopup("Invalid credentials");
        return;
      }

      // Other errors
      const txt = await res.text().catch(() => "");
      showErrorPopup(txt || "Login failed. Please try again.");
    } catch (err) {
      showErrorPopup("Network error. Please try again.");
    } finally {
      if (submitBtn) {
        submitBtn.disabled = false;
        if (prevText != null) submitBtn.innerHTML = prevText;
      }
    }
  }

  document.addEventListener("DOMContentLoaded", () => {
    const form = sel("loginForm");
    if (!form) return;

    // Attach handler
    form.addEventListener("submit", handleLogin);

    // Press Enter in password field submits the form (browser default),
    // but we hide previous error if user starts typing again.
    sel("username")?.addEventListener("input", hideError);
    sel("password")?.addEventListener("input", hideError);
  });
})();
