const form = document.getElementById("loginForm");
const message = document.getElementById("loginMessage");
const base = window.location.pathname.includes("/phenocrypto") ? "/phenocrypto" : "";

form.addEventListener("submit", async (event) => {
  event.preventDefault();
  message.textContent = "Checking credentials...";
  const button = form.querySelector("button");
  button.disabled = true;

  try {
    const response = await fetch(`${base}/api/login`, {
      method: "POST",
      credentials: "same-origin",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        username: form.username.value.trim(),
        password: form.password.value,
      }),
    });
    const payload = await response.json();
    if (!response.ok || payload.ok === false) {
      throw new Error(payload.error || "Login failed");
    }
    window.location.href = `${base}/dashboard`;
  } catch (error) {
    message.textContent = error.message;
    button.disabled = false;
  }
});
