import { initI18n, t } from "./i18n";

document.addEventListener("DOMContentLoaded", () => {
  initI18n();

  const tabs = document.querySelectorAll<HTMLButtonElement>(".login-tab");
  const loginForm = document.getElementById("login-form") as HTMLFormElement;
  const registerForm = document.getElementById("register-form") as HTMLFormElement;

  // Tab switching
  tabs.forEach((btn) => {
    btn.addEventListener("click", () => {
      tabs.forEach((t) => t.classList.remove("active"));
      btn.classList.add("active");
      const isLogin = btn.dataset.tab === "login";
      loginForm.style.display = isLogin ? "" : "none";
      registerForm.style.display = isLogin ? "none" : "";
      clearMessages();
    });
  });

  // Login form
  loginForm.addEventListener("submit", async (e) => {
    e.preventDefault();
    clearMessages();
    const data = new FormData(loginForm);

    try {
      const res = await fetch("/api/login", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          email: data.get("email"),
          password: data.get("password"),
        }),
      });
      const json = await res.json();
      if (res.ok) {
        window.location.href = "/";
      } else {
        showError(json.error);
      }
    } catch {
      showError(t("login.error.connection"));
    }
  });

  // Register form
  registerForm.addEventListener("submit", async (e) => {
    e.preventDefault();
    clearMessages();
    const data = new FormData(registerForm);
    const password = data.get("password") as string;
    const confirm = data.get("confirm") as string;

    if (password !== confirm) {
      showError(t("login.error.mismatch"));
      return;
    }
    if (password.length < 8) {
      showError(t("login.error.minlength"));
      return;
    }

    try {
      const res = await fetch("/api/register", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          email: data.get("email"),
          password: password,
        }),
      });
      const json = await res.json();
      if (res.ok) {
        if (json.redirect) {
          window.location.href = json.redirect;
        } else {
          showSuccess(json.message || t("login.success.created"));
          tabs[0].click();
        }
      } else {
        showError(json.error);
      }
    } catch {
      showError(t("login.error.connection"));
    }
  });
});

function clearMessages() {
  document.querySelectorAll(".login-error, .login-success").forEach((el) => el.remove());
}

function showError(msg: string) {
  showMessage(msg, "login-error");
}

function showSuccess(msg: string) {
  showMessage(msg, "login-success");
}

function showMessage(msg: string, cls: string) {
  clearMessages();
  const div = document.createElement("div");
  div.className = cls;
  div.textContent = msg;
  const tabs = document.querySelector(".login-tabs");
  if (tabs) {
    tabs.after(div);
  }
}
