import { showToast } from "./toast.js";
import {
  postLogin,
  postRegister,
  postTelegramAuthStart,
  pollTelegramAuth,
  getTelegramAuthConfig,
  fetchSessionUser,
  notifyApiFailure,
  notifyDbFailure,
} from "../auth/session.js";
import { t } from "../config/site.js";
import { updateHeaderAuth } from "./header.js";

const ICON_USER = `<svg class="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"/></svg>`;
const ICON_MAIL = `<svg class="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"/></svg>`;
const ICON_LOCK = `<svg class="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"/></svg>`;
const ICON_SHIELD = `<svg class="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12.75L11.25 15 15 9.75m-3-7.036A11.959 11.959 0 013.598 6 11.99 11.99 0 003 9.749c0 5.592 3.824 10.29 9 11.623 5.176-1.332 9-6.03 9-11.622 0-1.31-.21-2.571-.598-3.751h-.152c-3.196 0-6.1-1.248-8.25-3.285z"/></svg>`;
const ICON_PHONE = `<svg class="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z"/></svg>`;

let loginModal;
let registerModal;
let lastFocus = null;
let telegramPollAbort = null;
let loginTwofaRequired = false;
let loginTwofaChallenge = "";

function sleep(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

function setOpen(isOpen) {
  globalThis.__siteAuthModalOpen = isOpen;
  if (isOpen) {
    document.body.classList.add("overflow-hidden");
  } else if (
    !globalThis.__sitePromoModalOpen &&
    !globalThis.__siteGameSelectorModalOpen &&
    !globalThis.__siteNewsModalOpen
  ) {
    document.body.classList.remove("overflow-hidden");
  }
}

function resetLoginTwofaState() {
  loginTwofaRequired = false;
  loginTwofaChallenge = "";
  const wrap = document.getElementById("login-twofa-wrap");
  const identity = document.getElementById("login-identity");
  const password = document.getElementById("login-password");
  wrap?.classList.add("hidden");
  identity?.removeAttribute("readonly");
  password?.removeAttribute("readonly");
  document.getElementById("login-twofa")?.removeAttribute("required");
}

function closeAll() {
  telegramPollAbort?.abort();
  telegramPollAbort = null;
  resetLoginTwofaState();
  loginModal?.classList.add("hidden");
  loginModal?.classList.remove("flex");
  loginModal?.setAttribute("aria-hidden", "true");
  registerModal?.classList.add("hidden");
  registerModal?.classList.remove("flex");
  registerModal?.setAttribute("aria-hidden", "true");
  setOpen(false);
  if (lastFocus && typeof lastFocus.focus === "function") {
    try {
      lastFocus.focus();
    } catch {

    }
  }
  lastFocus = null;
}

function openLogin() {
  lastFocus = document.activeElement;
  registerModal?.classList.add("hidden");
  registerModal?.classList.remove("flex");
  registerModal?.setAttribute("aria-hidden", "true");
  loginModal?.classList.remove("hidden");
  loginModal?.classList.add("flex");
  loginModal?.setAttribute("aria-hidden", "false");
  setOpen(true);
  requestAnimationFrame(() => {
    document.getElementById("login-identity")?.focus();
  });
}

function openRegister() {
  lastFocus = document.activeElement;
  loginModal?.classList.add("hidden");
  loginModal?.classList.remove("flex");
  loginModal?.setAttribute("aria-hidden", "true");
  registerModal?.classList.remove("hidden");
  registerModal?.classList.add("flex");
  registerModal?.setAttribute("aria-hidden", "false");
  setOpen(true);
  requestAnimationFrame(() => {
    document.getElementById("reg-username")?.focus();
  });
}

function isValidEmail(s) {
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(String(s).trim());
}

function isValidPhone(s) {
  const digits = String(s || "").replace(/\D/g, "");
  return digits.length >= 10;
}

function telegramBotBlockHtml(mode) {
  const label = mode === "register" ? t("authTelegramBotRegister") : t("authTelegramBotLogin");
  return `
    <div class="auth-telegram-wrap mt-4 hidden" data-telegram-mode="${mode}">
      <div class="flex items-center gap-3">
        <div class="h-px flex-1 bg-white/10"></div>
        <span class="text-xs font-medium uppercase tracking-wider text-slate-500">${t("authOrDivider")}</span>
        <div class="h-px flex-1 bg-white/10"></div>
      </div>
      <p class="mt-3 text-center text-xs text-slate-500">${t("authTelegramBotHint")}</p>
      <button type="button" class="auth-telegram-bot-btn k-btn k-btn--secondary btn-site-secondary mt-3 flex w-full items-center justify-center gap-2 rounded-xl py-3 text-sm font-semibold" data-telegram-bot-mode="${mode}">
        <svg class="h-5 w-5 shrink-0" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm4.64 6.8c-.15 1.58-.8 5.42-1.13 7.19-.14.75-.42 1-.68 1.03-.58.05-1.02-.38-1.58-.75-.88-.58-1.38-.94-2.23-1.5-.99-.65-.35-1.01.22-1.59.15-.15 2.71-2.48 2.76-2.69a.2.2 0 00-.05-.18c-.06-.05-.14-.03-.21-.02-.09.02-1.49.95-4.22 2.79-.4.27-.76.41-1.08.4-.36-.01-1.04-.2-1.55-.37-.63-.2-1.12-.31-1.08-.66.02-.18.27-.36.74-.55 2.92-1.27 4.86-2.11 5.83-2.51 2.78-1.16 3.35-1.36 3.73-1.36.08 0 .27.02.39.12.1.08.13.19.14.27-.01.06.01.24 0 .38z"/></svg>
        ${label}
      </button>
      <p class="auth-telegram-bot-status hidden mt-2 text-center text-xs text-slate-400" aria-live="polite"></p>
    </div>
  `;
}

function setupTelegramBotAuth(root) {
  const cfg = getTelegramAuthConfig();
  root.querySelectorAll(".auth-telegram-wrap").forEach((wrap) => {
    if (!cfg.enabled || !cfg.botUsername) {
      wrap.classList.add("hidden");
      return;
    }
    wrap.classList.remove("hidden");
  });
}

async function runTelegramBotAuth(mode, btn, statusEl) {
  telegramPollAbort?.abort();
  const abort = new AbortController();
  telegramPollAbort = abort;

  const resetUi = () => {
    if (btn instanceof HTMLButtonElement) btn.disabled = false;
    statusEl?.classList.add("hidden");
    if (statusEl) statusEl.textContent = "";
  };

  if (btn instanceof HTMLButtonElement) btn.disabled = true;
  statusEl?.classList.remove("hidden");
  if (statusEl) statusEl.textContent = t("authTelegramBotOpening");

  let start;
  try {
    start = await postTelegramAuthStart(mode);
  } catch {
    notifyApiFailure();
    resetUi();
    return;
  }

  if (!start.ok || !start.data?.deepLink || !start.data?.pollToken) {
    if (start.status === 503 || start.data?.error === "db") {
      notifyDbFailure();
    } else if (start.status === 503 && start.data?.error === "telegram_config") {
      showToast(t("authTelegramUnavailable"), "error");
    } else {
      showToast(t("authTelegramFail"), "error");
    }
    resetUi();
    return;
  }

  window.open(start.data.deepLink, "_blank", "noopener,noreferrer");
  if (statusEl) statusEl.textContent = t("authTelegramBotWait");

  const token = start.data.pollToken;
  const expiresAt = (Number(start.data.expiresAt) || 0) * 1000 || Date.now() + 1800000;

  while (!abort.signal.aborted && Date.now() < expiresAt) {
    await sleep(2000);
    if (abort.signal.aborted) break;

    let poll;
    try {
      poll = await pollTelegramAuth(token);
    } catch {
      continue;
    }

    if (poll.data?.pending) continue;

    if (poll.ok && poll.data?.user) {
      await handleTelegramAuthSuccess(poll.data);
      abort.abort();
      telegramPollAbort = null;
      resetUi();
      return;
    }

    if (poll.status === 410 || poll.data?.error === "expired") {
      showToast(t("authTelegramBotExpired"), "error");
      break;
    }
    if (poll.status === 403) {
      showToast(t("authTelegramBotSession"), "error");
      break;
    }
  }

  if (!abort.signal.aborted) {
    showToast(t("authTelegramBotExpired"), "error");
  }
  resetUi();
}

async function handleTelegramAuthSuccess(data) {
  const needsProfileCompletion = !!data?.needsProfileCompletion;
  const needsPasswordChange = !!data?.needsPasswordChange;
  const isNew = !!data?.isNew;
  if (isNew) {
    const bonus = data?.user?.bonus ?? 150;
    showToast(t("authSuccessRegister").replace("{bonus}", String(bonus)), "success");
  } else {
    showToast(t("authWelcome"), "success");
  }
  closeAll();
  if (data?.user?.username) updateHeaderAuth(data.user);
  await globalThis.__siteRefreshUser?.();
  if (needsPasswordChange) {
    sessionStorage.setItem("site_profile_tab", "info");
    sessionStorage.setItem("site_password_change", "1");
    globalThis.__siteNavigateTo?.("/profil");
  } else if (needsProfileCompletion) {
    sessionStorage.setItem("site_profile_tab", "info");
    sessionStorage.setItem("site_profile_complete", "1");
    globalThis.__siteNavigateTo?.("/profil");
  }
}

export function renderAuthModals(root) {
  root.innerHTML = `
    <div id="auth-modal-login" class="k-modal k-modal--backdrop auth-modal-backdrop fixed inset-0 z-[140] hidden items-end justify-center p-4 sm:items-center" role="dialog" aria-modal="true" aria-labelledby="auth-login-title" aria-hidden="true">
      <div class="k-modal__panel auth-modal-panel relative w-full max-w-md rounded-2xl border border-[rgba(22,119,255,0.15)] bg-[#1e2739] p-6 shadow-panel ring-1 ring-black/30 sm:p-8">
        <button type="button" class="k-btn k-btn--icon k-btn--ghost auth-modal-close absolute right-4 top-4 rounded-xl p-2 text-slate-500 transition hover:bg-white/[0.06] hover:text-white" aria-label="${t("authClose")}">
          <svg class="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg>
        </button>
        <div class="mb-6 pr-8">
          <p class="text-[10px] font-semibold uppercase tracking-[0.2em] text-accent">${t("authEyebrowAccount")}</p>
          <h2 id="auth-login-title" class="mt-1 text-xl font-bold tracking-tight text-white sm:text-2xl">${t("headerLogin")}</h2>
          <p class="mt-2 text-sm leading-relaxed text-slate-500">${t("authLoginSubtitle")}</p>
        </div>
        <form id="form-login" class="k-form space-y-4" novalidate>
          <div>
            <label for="login-identity" class="k-label k-label mb-1.5 block text-[11px] font-semibold uppercase tracking-wider text-slate-500">${t("authLabelIdentity")}</label>
            <div class="relative">
              <span class="pointer-events-none absolute left-3 top-1/2 z-[1] -translate-y-1/2 text-slate-500">${ICON_USER}</span>
              <input id="login-identity" name="identity" type="text" autocomplete="username" required class="k-input input-site" placeholder="${t("authPlaceholderIdentity")}" />
            </div>
          </div>
          <div>
            <label for="login-password" class="k-label mb-1.5 block text-[11px] font-semibold uppercase tracking-wider text-slate-500">${t("authLabelPassword")}</label>
            <div class="relative">
              <span class="pointer-events-none absolute left-3 top-1/2 z-[1] -translate-y-1/2 text-slate-500">${ICON_LOCK}</span>
              <input id="login-password" name="password" type="password" autocomplete="current-password" required class="k-input input-site" placeholder="${t("authPlaceholderLoginPassword")}" />
            </div>
          </div>
          <div id="login-twofa-wrap" class="hidden space-y-2">
            <label for="login-twofa" class="k-label mb-1.5 block text-[11px] font-semibold uppercase tracking-wider text-slate-500">${t("authLabelTwofa")}</label>
            <div class="relative">
              <span class="pointer-events-none absolute left-3 top-1/2 z-[1] -translate-y-1/2 text-slate-500">${ICON_SHIELD}</span>
              <input id="login-twofa" name="twofaCode" type="text" inputmode="numeric" autocomplete="one-time-code" class="k-input input-site w-full" placeholder="${t("authPlaceholderTwofa")}" />
            </div>
            <p class="text-xs text-slate-500">${t("authTwofaHint")}</p>
          </div>
          <p id="login-error" class="hidden rounded-xl border border-red-500/30 bg-red-950/40 px-3 py-2 text-sm text-red-200" role="alert"></p>
          <button type="submit" id="auth-login-submit" class="k-btn k-btn--primary btn-site-register auth-modal-cta w-full">${t("headerLogin")}</button>
        </form>
        ${telegramBotBlockHtml("login")}
        <p class="mt-6 text-center text-sm text-slate-500">
          ${t("authNoAccount")}
          <button type="button" id="auth-switch-to-register" class="k-link k-link--inline font-semibold text-accent hover:text-accent-bright">${t("headerRegister")}</button>
        </p>
      </div>
    </div>

    <div id="auth-modal-register" class="k-modal k-modal--backdrop auth-modal-backdrop fixed inset-0 z-[140] hidden items-end justify-center p-4 sm:items-center" role="dialog" aria-modal="true" aria-labelledby="auth-register-title" aria-hidden="true">
      <div class="k-modal__panel auth-modal-panel auth-modal-panel--register relative w-full max-w-md rounded-2xl border border-[rgba(22,119,255,0.15)] bg-[#1e2739] shadow-panel ring-1 ring-black/30">
        <button type="button" class="k-btn k-btn--icon k-btn--ghost auth-modal-close absolute right-4 top-4 z-10 rounded-xl p-2 text-slate-500 transition hover:bg-white/[0.06] hover:text-white" aria-label="${t("authClose")}">
          <svg class="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg>
        </button>
        <div class="auth-modal-panel__scroll site-scrollbar">
        <div class="auth-modal-panel__head pr-10">
          <p class="text-[10px] font-semibold uppercase tracking-[0.2em] text-accent">${t("authEyebrowNew")}</p>
          <h2 id="auth-register-title" class="mt-0.5 text-lg font-bold tracking-tight text-white sm:text-xl">${t("headerRegister")}</h2>
          <p class="auth-modal-panel__subtitle mt-1 text-xs leading-snug text-slate-500 sm:text-sm">${t("authRegisterSubtitle")}</p>
        </div>
        <form id="form-register" class="k-form auth-modal-panel__form space-y-3" novalidate>
          <div>
            <label for="reg-username" class="k-label mb-1.5 block text-[11px] font-semibold uppercase tracking-wider text-slate-500">${t("authLabelUsername")}</label>
            <div class="relative">
              <span class="pointer-events-none absolute left-3 top-1/2 z-[1] -translate-y-1/2 text-slate-500">${ICON_USER}</span>
              <input id="reg-username" name="username" type="text" autocomplete="username" required minlength="2" maxlength="64" class="k-input input-site" placeholder="${t("authPlaceholderUsername")}" />
            </div>
          </div>
          <div>
            <label for="reg-email" class="k-label mb-1.5 block text-[11px] font-semibold uppercase tracking-wider text-slate-500">${t("authLabelEmail")}</label>
            <div class="relative">
              <span class="pointer-events-none absolute left-3 top-1/2 z-[1] -translate-y-1/2 text-slate-500">${ICON_MAIL}</span>
              <input id="reg-email" name="email" type="email" autocomplete="email" required class="k-input input-site" placeholder="${t("authPlaceholderEmail")}" />
            </div>
          </div>
          <div>
            <label for="reg-phone" class="k-label mb-1.5 block text-[11px] font-semibold uppercase tracking-wider text-slate-500">${t("authLabelPhone")}</label>
            <div class="relative">
              <span class="pointer-events-none absolute left-3 top-1/2 z-[1] -translate-y-1/2 text-slate-500">${ICON_PHONE}</span>
              <input id="reg-phone" name="phone" type="tel" autocomplete="tel" required class="k-input input-site" placeholder="${t("authPlaceholderPhone")}" />
            </div>
          </div>
          <div>
            <label for="reg-password" class="k-label mb-1.5 block text-[11px] font-semibold uppercase tracking-wider text-slate-500">${t("authLabelPassword")}</label>
            <div class="relative">
              <span class="pointer-events-none absolute left-3 top-1/2 z-[1] -translate-y-1/2 text-slate-500">${ICON_LOCK}</span>
              <input id="reg-password" name="password" type="password" autocomplete="new-password" required minlength="8" class="k-input input-site" placeholder="${t("authPlaceholderPassword")}" />
            </div>
          </div>
          <div>
            <label for="reg-password2" class="k-label mb-1.5 block text-[11px] font-semibold uppercase tracking-wider text-slate-500">${t("authLabelPassword2")}</label>
            <div class="relative">
              <span class="pointer-events-none absolute left-3 top-1/2 z-[1] -translate-y-1/2 text-slate-500">${ICON_LOCK}</span>
              <input id="reg-password2" name="password2" type="password" autocomplete="new-password" required minlength="8" class="k-input input-site" placeholder="${t("authPlaceholderPassword2")}" />
            </div>
          </div>
          <p id="register-error" class="hidden rounded-xl border border-red-500/30 bg-red-950/40 px-3 py-2 text-sm text-red-200" role="alert"></p>
          <button type="submit" class="k-btn k-btn--primary btn-site-register auth-modal-cta w-full">${t("headerRegister")}</button>
        </form>
        ${telegramBotBlockHtml("register")}
        <p class="auth-modal-panel__footer text-center text-sm text-slate-500">
          ${t("authHasAccount")}
          <button type="button" id="auth-switch-to-login" class="k-link k-link--inline font-semibold text-accent hover:text-accent-bright">${t("headerLogin")}</button>
        </p>
        </div>
      </div>
    </div>
  `;

  loginModal = root.querySelector("#auth-modal-login");
  registerModal = root.querySelector("#auth-modal-register");

  globalThis.__siteCloseAuthModals = closeAll;
  globalThis.__siteOpenLogin = openLogin;
  globalThis.__siteOpenRegister = openRegister;
  globalThis.__siteAuthModalOpen = false;

  const showLoginErr = (msg) => {
    const el = root.querySelector("#login-error");
    if (!el) return;
    if (!msg) {
      el.classList.add("hidden");
      el.textContent = "";
      return;
    }
    el.textContent = msg;
    el.classList.remove("hidden");
  };

  const showRegErr = (msg) => {
    const el = root.querySelector("#register-error");
    if (!el) return;
    if (!msg) {
      el.classList.add("hidden");
      el.textContent = "";
      return;
    }
    el.textContent = msg;
    el.classList.remove("hidden");
  };

  root.querySelectorAll(".auth-modal-close").forEach((btn) => {
    btn.addEventListener("click", closeAll);
  });

  [loginModal, registerModal].forEach((backdrop) => {
    backdrop?.addEventListener("click", (e) => {
      if (e.target === backdrop) closeAll();
    });
  });

  document.getElementById("auth-switch-to-register")?.addEventListener("click", () => {
    showLoginErr("");
    openRegister();
  });
  document.getElementById("auth-switch-to-login")?.addEventListener("click", () => {
    showRegErr("");
    openLogin();
  });

  document.getElementById("form-login")?.addEventListener("submit", async (e) => {
    e.preventDefault();
    showLoginErr("");
    const id = document.getElementById("login-identity")?.value?.trim() || "";
    const pw = document.getElementById("login-password")?.value || "";
    const twofaCode = document.getElementById("login-twofa")?.value?.trim() || "";
    if (!id || !pw) {
      showLoginErr(t("authErrFillAll"));
      return;
    }
    if (loginTwofaRequired && !twofaCode) {
      showLoginErr(t("authErrTwofaRequired"));
      return;
    }
    const body = loginTwofaRequired
      ? { identity: id, password: pw, twofaCode, twofaChallenge: loginTwofaChallenge }
      : { identity: id, password: pw };
    try {
      const { ok, data, status } = await postLogin(body);
      if (data?.requires2fa && typeof data.twofaChallenge === "string") {
        loginTwofaRequired = true;
        loginTwofaChallenge = data.twofaChallenge;
        document.getElementById("login-twofa-wrap")?.classList.remove("hidden");
        document.getElementById("login-identity")?.setAttribute("readonly", "readonly");
        document.getElementById("login-password")?.setAttribute("readonly", "readonly");
        document.getElementById("login-twofa")?.setAttribute("required", "required");
        document.getElementById("login-twofa")?.focus();
        showToast(t("authTwofaStepToast"), "info");
        return;
      }
      if (!ok) {
        if (status === 503 || data?.error === "db") {
          notifyDbFailure();
          return;
        }
        if (
          data?.error === "twofa_invalid" ||
          data?.error === "twofa_invalid_challenge" ||
          data?.error === "twofa_missing_challenge"
        ) {
          if (data?.error === "twofa_expired") {
            resetLoginTwofaState();
            showLoginErr(t("authErrTwofaExpired"));
          } else {
            const remaining = data?.remaining;
            showLoginErr(
              typeof remaining === "number" && remaining > 0
                ? `${t("authErrTwofaInvalid")} (${remaining})`
                : t("authErrTwofaInvalid")
            );
          }
          return;
        }
        if (status === 401 || data?.error === "invalid") {
          const remaining = data?.remaining;
          showLoginErr(
            typeof remaining === "number" && remaining > 0
              ? `${t("authErrInvalidCreds")} (${remaining} ${t("authErrAttemptsLeft")})`
              : t("authErrInvalidCreds")
          );
          return;
        }
        if (status === 403 || data?.error === "csrf") {
          showLoginErr(t("authErrCsrf"));
          return;
        }
        if (status === 403 && data?.error === "inactive") {
          showLoginErr(t("authErrInactive"));
          return;
        }
        showLoginErr(t("authErrLoginFail"));
        return;
      }
      const needsPasswordChange = !!data?.needsPasswordChange;
      const needsProfileCompletion = !!data?.needsProfileCompletion;
      showToast(t("authWelcome"), "success");
      closeAll();
      if (data?.user?.username) updateHeaderAuth(data.user);
      await globalThis.__siteRefreshUser?.();
      if (needsPasswordChange) {
        sessionStorage.setItem("site_profile_tab", "info");
        sessionStorage.setItem("site_password_change", "1");
        globalThis.__siteNavigateTo?.("/profil");
      } else if (needsProfileCompletion) {
        sessionStorage.setItem("site_profile_tab", "info");
        sessionStorage.setItem("site_profile_complete", "1");
        globalThis.__siteNavigateTo?.("/profil");
      }
    } catch {
      notifyApiFailure();
    }
  });

  document.getElementById("form-register")?.addEventListener("submit", async (e) => {
    e.preventDefault();
    showRegErr("");
    const username = document.getElementById("reg-username")?.value?.trim() || "";
    const email = document.getElementById("reg-email")?.value?.trim() || "";
    const phone = document.getElementById("reg-phone")?.value?.trim() || "";
    const pw = document.getElementById("reg-password")?.value || "";
    const pw2 = document.getElementById("reg-password2")?.value || "";

    if (username.length < 2) {
      showRegErr(t("authErrUsernameShort"));
      return;
    }
    if (!isValidEmail(email)) {
      showRegErr(t("authErrEmailInvalid"));
      return;
    }
    if (!isValidPhone(phone)) {
      showRegErr(t("authErrPhoneInvalid"));
      return;
    }
    if (pw.length < 8) {
      showRegErr(t("authErrPasswordShort"));
      return;
    }
    if (pw !== pw2) {
      showRegErr(t("authErrPasswordMismatch"));
      return;
    }
    try {
      const { ok, data, status } = await postRegister({ username, email, phone, password: pw });
      if (!ok) {
        if (status === 503 || data?.error === "db") {
          notifyDbFailure();
          return;
        }
        if (status === 409 || data?.error === "taken") {
          showRegErr(t("authErrTaken"));
          return;
        }
        if (status === 400) {
          const err = data?.error;
          if (err === "email") showRegErr(t("authErrEmailInvalid"));
          else if (err === "phone") showRegErr(t("authErrPhoneInvalid"));
          else if (err === "password") showRegErr(t("authErrPasswordShort"));
          else if (err === "username") showRegErr(t("authErrUsernameRules"));
          else showRegErr(t("authErrRegisterFail"));
          return;
        }
        if (status === 403 || data?.error === "csrf") {
          showRegErr(t("authErrCsrf"));
          return;
        }
        showRegErr(t("authErrRegisterFail"));
        return;
      }
      const bonus = data?.user?.bonus ?? 150;
      showToast(t("authSuccessRegister").replace("{bonus}", String(bonus)), "success");
      closeAll();
      if (data?.user?.username) updateHeaderAuth(data.user);
      await globalThis.__siteRefreshUser?.();
    } catch {
      notifyApiFailure();
    }
  });

  root.querySelectorAll(".auth-telegram-bot-btn").forEach((btn) => {
    btn.addEventListener("click", async () => {
      const mode = btn.getAttribute("data-telegram-bot-mode") === "register" ? "register" : "login";
      const wrap = btn.closest(".auth-telegram-wrap");
      const statusEl = wrap?.querySelector(".auth-telegram-bot-status");
      await runTelegramBotAuth(mode, btn, statusEl);
    });
  });

  void fetchSessionUser().then(() => setupTelegramBotAuth(root));
}

export function bindAuthHeaderButtons() {
  document.querySelectorAll(".auth-open-login").forEach((btn) => {
    btn.addEventListener("click", () => openLogin());
  });
  document.querySelectorAll(".auth-open-register").forEach((btn) => {
    btn.addEventListener("click", () => openRegister());
  });
}
