import { apiLogin, apiRegister, apiGetMe, apiResendConfirmation, apiForgotPassword, apiResetPassword } from "./api.js";
import { setCurrentTeam, refreshFromServer } from "./game.js";

// ── DOM refs ──────────────────────────────────────────────────────────────────

const authOverlay     = document.getElementById("authOverlay");
const authTabsBar     = document.getElementById("authTabsBar");
const tabLogin        = document.getElementById("tabLogin");
const tabRegister     = document.getElementById("tabRegister");
const loginForm       = document.getElementById("loginForm");
const registerForm    = document.getElementById("registerForm");
const forgotPanel     = document.getElementById("forgotPanel");
const checkEmailPanel = document.getElementById("checkEmailPanel");
const resetPanel      = document.getElementById("resetPanel");
const confirmedPanel  = document.getElementById("confirmedPanel");
const loginUsernameEl = document.getElementById("loginUsername");
const loginPasswordEl = document.getElementById("loginPassword");
const loginErrorEl    = document.getElementById("loginError");
const regUsernameEl   = document.getElementById("regUsername");
const regEmailEl      = document.getElementById("regEmail");
const regPasswordEl   = document.getElementById("regPassword");
const registerErrorEl = document.getElementById("registerError");
const forgotForm      = document.getElementById("forgotForm");
const forgotEmailEl   = document.getElementById("forgotEmail");
const forgotErrorEl   = document.getElementById("forgotError");
const resetForm       = document.getElementById("resetForm");
const resetPasswordEl = document.getElementById("resetPassword");
const resetErrorEl    = document.getElementById("resetError");
const checkEmailMsg   = document.getElementById("checkEmailMsg");
const resendEmailBtn  = document.getElementById("resendEmailBtn");
const userDisplayEl   = document.getElementById("userDisplay");
const logoutBtn       = document.getElementById("logoutBtn");

// ── Auth state ────────────────────────────────────────────────────────────────

export let authToken   = localStorage.getItem("authToken") ?? null;
export let currentUser = null;

// Tracks which email to use for resend (set after register)
let pendingEmail = null;

// ── Helpers ───────────────────────────────────────────────────────────────────

function showError(el, msg) { el.textContent = msg; el.classList.remove("hidden"); }
function clearError(el)     { el.textContent = "";  el.classList.add("hidden"); }

// Show only one panel, hide all others
const allPanels = [loginForm, registerForm, forgotPanel, checkEmailPanel, resetPanel, confirmedPanel];

function showPanel(panel) {
  for (const p of allPanels) p.classList.add("hidden");
  authTabsBar.classList.add("hidden");
  panel.classList.remove("hidden");
}

function showLoginTab() {
  for (const p of allPanels) p.classList.add("hidden");
  authTabsBar.classList.remove("hidden");
  loginForm.classList.remove("hidden");
  tabLogin.classList.add("authTab--active");
  tabRegister.classList.remove("authTab--active");
}

function showRegisterTab() {
  for (const p of allPanels) p.classList.add("hidden");
  authTabsBar.classList.remove("hidden");
  registerForm.classList.remove("hidden");
  tabRegister.classList.add("authTab--active");
  tabLogin.classList.remove("authTab--active");
}

export function showAuthOverlay() { authOverlay.classList.remove("hidden"); }
export function hideAuthOverlay() { authOverlay.classList.add("hidden"); }

// ── Apply user (after login / register / session restore) ─────────────────────

export function applyUser(user, token) {
  currentUser = user;
  authToken   = token;
  localStorage.setItem("authToken", token);
  setCurrentTeam(user.team);
  userDisplayEl.textContent = `${user.username} [${user.team}]`;
  logoutBtn.classList.remove("hidden");
}

function logout() {
  currentUser = null;
  authToken   = null;
  localStorage.removeItem("authToken");
  userDisplayEl.textContent = "—";
  logoutBtn.classList.add("hidden");
  showAuthOverlay();
  showLoginTab();
}

// ── Session restore ───────────────────────────────────────────────────────────

export async function tryRestoreSession() {
  if (!authToken) return false;
  try {
    const res = await apiGetMe(authToken);
    if (!res.ok) { localStorage.removeItem("authToken"); authToken = null; return false; }
    const data = await res.json();
    applyUser(data.user, data.token);
    return true;
  } catch {
    return false;
  }
}

// ── Handle URL params (email confirmation / password reset) ───────────────────

export function handleUrlEmailFlows() {
  const params = new URLSearchParams(window.location.search);

  if (params.has("email_confirm")) {
    // Trigger confirmation via API redirect — this is handled server-side.
    // The server redirects to /?email_confirmed=1 or /?confirm_error=...
    const token = params.get("email_confirm");
    window.history.replaceState({}, "", "/");
    // Call server-side confirm endpoint by navigating (GET request)
    window.location.href = `/api/auth/confirm-email?token=${encodeURIComponent(token)}`;
    return true;
  }

  if (params.has("email_confirmed")) {
    window.history.replaceState({}, "", "/");
    showAuthOverlay();
    showPanel(confirmedPanel);
    return true;
  }

  if (params.has("confirm_error")) {
    const err = params.get("confirm_error");
    window.history.replaceState({}, "", "/");
    showAuthOverlay();
    showLoginTab();
    const msgs = {
      expired: "Le lien de confirmation a expiré. Connectez-vous pour en recevoir un nouveau.",
      invalid:  "Lien de confirmation invalide.",
      server_error: "Erreur serveur. Réessayez plus tard.",
    };
    showError(loginErrorEl, msgs[err] ?? "Erreur de confirmation.");
    return true;
  }

  if (params.has("reset")) {
    const token = params.get("reset");
    window.history.replaceState({}, "", "/");
    showAuthOverlay();
    resetPanel.dataset.token = token;
    showPanel(resetPanel);
    return true;
  }

  return false;
}

// ── Tab switching ─────────────────────────────────────────────────────────────

tabLogin.addEventListener("click", () => {
  showLoginTab();
  clearError(loginErrorEl);
});

tabRegister.addEventListener("click", () => {
  showRegisterTab();
  clearError(registerErrorEl);
});

// ── Login form ────────────────────────────────────────────────────────────────

loginForm.addEventListener("submit", async (e) => {
  e.preventDefault();
  clearError(loginErrorEl);
  const username = loginUsernameEl.value.trim();
  const password = loginPasswordEl.value;
  if (!username || !password) return;
  try {
    const res  = await apiLogin(username, password);
    const data = await res.json();
    if (!res.ok) {
      if (data.error === "email_not_verified") {
        // Show check-email panel with resend option
        pendingEmail = null; // email unknown here, ask user to re-register or resend
        checkEmailMsg.textContent = "Votre adresse email n'a pas encore été confirmée. Vérifiez votre boîte de réception ou renvoyez l'email de confirmation.";
        resendEmailBtn.dataset.email = "";
        showPanel(checkEmailPanel);
        return;
      }
      const msgs = { invalid_credentials: "Identifiant ou mot de passe invalide.", missing_fields: "Veuillez remplir tous les champs." };
      showError(loginErrorEl, msgs[data.error] ?? "Connexion échouée.");
      return;
    }
    applyUser(data.user, data.token);
    hideAuthOverlay();
    await refreshFromServer();
  } catch {
    showError(loginErrorEl, "Erreur réseau. Réessayez.");
  }
});

// ── Register form ─────────────────────────────────────────────────────────────

registerForm.addEventListener("submit", async (e) => {
  e.preventDefault();
  clearError(registerErrorEl);
  const username  = regUsernameEl.value.trim();
  const email     = regEmailEl.value.trim();
  const password  = regPasswordEl.value;
  const teamInput = registerForm.querySelector('input[name="regTeam"]:checked');
  if (!teamInput) { showError(registerErrorEl, "Veuillez choisir une équipe."); return; }
  try {
    const res  = await apiRegister(username, email, password, teamInput.value);
    const data = await res.json();
    if (!res.ok) {
      const msgs = {
        username_taken:    "Ce nom d'utilisateur est déjà pris.",
        email_taken:       "Cette adresse email est déjà utilisée.",
        password_too_short:"Le mot de passe doit comporter au moins 6 caractères.",
        invalid_username:  "Le nom d'utilisateur doit comporter entre 2 et 32 caractères.",
        missing_fields:    "Veuillez remplir tous les champs.",
        invalid_team:      "Équipe invalide.",
      };
      showError(registerErrorEl, msgs[data.error] ?? "Inscription échouée.");
      return;
    }
    // Registration successful — pending email confirmation
    pendingEmail = email;
    resendEmailBtn.dataset.email = email;
    checkEmailMsg.textContent = `Un email de confirmation a été envoyé à ${email}. Cliquez sur le lien pour activer votre compte.`;
    document.getElementById("checkEmailTitle").textContent = "Vérifiez votre courriel";
    showPanel(checkEmailPanel);
  } catch {
    showError(registerErrorEl, "Erreur réseau. Réessayez.");
  }
});

// ── Forgot password ───────────────────────────────────────────────────────────

document.getElementById("forgotPasswordBtn").addEventListener("click", () => {
  clearError(forgotErrorEl);
  forgotEmailEl.value = "";
  showPanel(forgotPanel);
});

document.getElementById("backToLoginBtn").addEventListener("click", () => {
  showLoginTab();
  clearError(loginErrorEl);
});

forgotForm.addEventListener("submit", async (e) => {
  e.preventDefault();
  clearError(forgotErrorEl);
  const email = forgotEmailEl.value.trim();
  if (!email) return;
  try {
    await apiForgotPassword(email);
    // Always show the same message regardless of whether email exists (anti-enumeration)
    checkEmailMsg.textContent = `Si un compte existe pour ${email}, un lien de réinitialisation a été envoyé.`;
    document.getElementById("checkEmailTitle").textContent = "Email envoyé";
    resendEmailBtn.dataset.email = "";
    resendEmailBtn.classList.add("hidden");
    showPanel(checkEmailPanel);
  } catch {
    showError(forgotErrorEl, "Erreur réseau. Réessayez.");
  }
});

// ── Check-email panel ─────────────────────────────────────────────────────────

document.getElementById("backToLoginBtn2").addEventListener("click", () => {
  resendEmailBtn.classList.remove("hidden");
  showLoginTab();
  clearError(loginErrorEl);
});

resendEmailBtn.addEventListener("click", async () => {
  const email = resendEmailBtn.dataset.email;
  if (!email) return;
  resendEmailBtn.disabled = true;
  resendEmailBtn.textContent = "Envoi…";
  try {
    await apiResendConfirmation(email);
    resendEmailBtn.textContent = "Email renvoyé !";
  } catch {
    resendEmailBtn.textContent = "Erreur — réessayez";
  } finally {
    setTimeout(() => {
      resendEmailBtn.disabled = false;
      resendEmailBtn.textContent = "Renvoyer l'email";
    }, 3000);
  }
});

// ── Reset password form ───────────────────────────────────────────────────────

resetForm.addEventListener("submit", async (e) => {
  e.preventDefault();
  clearError(resetErrorEl);
  const token    = resetPanel.dataset.token;
  const password = resetPasswordEl.value;
  if (!token) { showError(resetErrorEl, "Token manquant."); return; }
  try {
    const res  = await apiResetPassword(token, password);
    const data = await res.json();
    if (!res.ok) {
      const msgs = {
        invalid_token:    "Ce lien est invalide.",
        token_expired:    "Ce lien a expiré. Refaites une demande.",
        password_too_short: "Le mot de passe doit comporter au moins 6 caractères.",
        missing_fields:   "Veuillez remplir tous les champs.",
      };
      showError(resetErrorEl, msgs[data.error] ?? "Erreur lors de la réinitialisation.");
      return;
    }
    showLoginTab();
    showError(loginErrorEl, ""); // clear
    clearError(loginErrorEl);
    // Show success in login form briefly
    loginErrorEl.style.color = "rgba(100,220,100,0.95)";
    loginErrorEl.style.background = "rgba(30,100,30,0.12)";
    loginErrorEl.style.border = "1px solid rgba(30,100,30,0.25)";
    showError(loginErrorEl, "Mot de passe réinitialisé ! Vous pouvez vous connecter.");
    setTimeout(() => {
      loginErrorEl.removeAttribute("style");
      clearError(loginErrorEl);
    }, 6000);
  } catch {
    showError(resetErrorEl, "Erreur réseau. Réessayez.");
  }
});

// ── Confirmed panel ───────────────────────────────────────────────────────────

document.getElementById("goToLoginBtn").addEventListener("click", () => {
  showLoginTab();
});

// ── Logout ────────────────────────────────────────────────────────────────────

logoutBtn.addEventListener("click", logout);