import { postUserPromoRedeem } from "../auth/user_promo.js";
import { notifyApiFailure, notifyDbFailure } from "../auth/session.js";
import { t } from "../config/site.js";
import { showToast } from "./toast.js";

let backdropEl;
let lastFocus = null;

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

function closePromoModal() {
  backdropEl?.classList.add("hidden");
  backdropEl?.classList.remove("flex");
  backdropEl?.setAttribute("aria-hidden", "true");
  setPromoOpen(false);
  if (lastFocus && typeof lastFocus.focus === "function") {
    try {
      lastFocus.focus();
    } catch {

    }
  }
  lastFocus = null;
}

function openPromoModal() {
  lastFocus = document.activeElement;
  const msg = document.getElementById("promo-modal-msg");
  if (msg) {
    msg.textContent = "";
    msg.className = "mt-2 min-h-[1.25rem] text-xs text-slate-400";
  }
  document.getElementById("promo-modal-auth-row")?.classList.add("hidden");
  const inp = document.getElementById("promo-modal-input");
  if (inp) inp.value = "";
  backdropEl?.classList.remove("hidden");
  backdropEl?.classList.add("flex");
  backdropEl?.setAttribute("aria-hidden", "false");
  setPromoOpen(true);
  requestAnimationFrame(() => {
    document.getElementById("promo-modal-input")?.focus();
  });
}

function setMsg(el, text, kind = "muted") {
  if (!el) return;
  el.textContent = text;
  el.className =
    kind === "ok"
      ? "mt-2 min-h-[1.25rem] text-xs text-accent-bright"
      : kind === "err"
        ? "mt-2 min-h-[1.25rem] text-xs text-rose-300"
        : "mt-2 min-h-[1.25rem] text-xs text-slate-400";
}

export function renderPromoModal(root) {
  root.innerHTML = `
    <div id="promo-modal-backdrop" class="k-modal k-modal--backdrop auth-modal-backdrop fixed inset-0 z-[138] hidden items-end justify-center p-4 sm:items-center" role="dialog" aria-modal="true" aria-labelledby="promo-modal-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 promo-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-bright/95">${t("quickPromoCode")}</p>
          <h2 id="promo-modal-title" class="mt-1 text-xl font-bold tracking-tight text-white sm:text-2xl">${t("profilePromoTitle")}</h2>
          <p class="mt-2 text-sm leading-relaxed text-slate-500">${t("promoModalSubtitle")}</p>
        </div>
        <div class="rounded-2xl border border-accent/22 bg-gradient-to-br from-accent/12 to-transparent p-5 ring-1 ring-accent/18">
          <div class="flex flex-col gap-2 sm:flex-row sm:items-stretch">
            <input
              id="promo-modal-input"
              type="text"
              maxlength="64"
              autocomplete="off"
              spellcheck="false"
              placeholder="${t("profilePromoPlaceholder")}"
              class="k-input promo-modal-input min-w-0 flex-1 rounded-xl border border-white/10 bg-black/30 px-3 py-2.5 font-mono text-sm uppercase text-slate-100 placeholder:normal-case placeholder:text-slate-500 focus:border-accent-bright/45 focus:outline-none focus:ring-2 focus:ring-accent/28"
            />
            <button
              type="button"
              id="promo-modal-submit"
              class="k-btn k-btn--primary promo-modal-submit inline-flex shrink-0 items-center justify-center rounded-xl px-5 py-2.5 text-sm font-semibold"
            >
              ${t("profilePromoUse")}
            </button>
          </div>
          <p id="promo-modal-msg" class="mt-2 min-h-[1.25rem] text-xs text-slate-400" role="status"></p>
          <div id="promo-modal-auth-row" class="mt-3 hidden">
            <button type="button" id="promo-modal-login" class="k-link k-link--inline text-sm font-semibold text-accent-bright underline-offset-2 hover:text-accent hover:underline">${t("headerLogin")}</button>
          </div>
        </div>
      </div>
    </div>
  `;

  backdropEl = root.querySelector("#promo-modal-backdrop");
  const msgEl = root.querySelector("#promo-modal-msg");
  const inputEl = root.querySelector("#promo-modal-input");
  const submitBtn = root.querySelector("#promo-modal-submit");
  const authRow = root.querySelector("#promo-modal-auth-row");

  globalThis.__siteOpenPromoModal = openPromoModal;
  globalThis.__siteClosePromoModal = closePromoModal;
  globalThis.__sitePromoModalOpen = false;

  const showAuthCta = (show) => {
    authRow?.classList.toggle("hidden", !show);
  };

  async function redeem() {
    showAuthCta(false);
    const raw = inputEl ? String(inputEl.value || "").trim() : "";
    if (raw.length < 4) {
      setMsg(msgEl, t("profilePromoShort"), "err");
      return;
    }
    setMsg(msgEl, t("profilePromoProcessing"), "muted");
    if (submitBtn) submitBtn.disabled = true;
    let res;
    try {
      res = await postUserPromoRedeem(raw);
    } catch {
      if (submitBtn) submitBtn.disabled = false;
      notifyApiFailure();
      setMsg(msgEl, t("profilePromoErrGeneric"), "err");
      return;
    }
    if (submitBtn) submitBtn.disabled = false;

    if (!res || !res.ok) {
      if (res?.status === 503 && res?.data?.error === "db") {
        notifyDbFailure();
        setMsg(msgEl, t("profilePromoErrGeneric"), "err");
        return;
      }
      if (res?.status === 401 || res?.data?.error === "auth") {
        setMsg(msgEl, t("promoModalNeedLogin"), "err");
        showAuthCta(true);
        return;
      }
      const err = res?.data?.error;
      const map = {
        not_found: t("profilePromoErrNotFound"),
        inactive: t("profilePromoErrInactive"),
        expired: t("profilePromoErrExpired"),
        exhausted: t("profilePromoErrExhausted"),
        already_used: t("profilePromoErrUsed"),
        code: t("profilePromoErrCode"),
      };
      setMsg(msgEl, map[err] || t("profilePromoErrGeneric"), "err");
      return;
    }

    const added = res.data?.coinsAdded;
    const total = res.data?.coins;
    const line =
      typeof added === "number"
        ? t("profilePromoOkAdded")
            .replace("{added}", String(added))
            .replace("{total}", String(Number.isFinite(Number(total)) ? total : "—"))
        : t("profilePromoOkSimple");
    showToast(line, "success");
    if (inputEl) inputEl.value = "";
    await globalThis.__siteRefreshUser?.();
    closePromoModal();
  }

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

  backdropEl?.addEventListener("click", (e) => {
    if (e.target === backdropEl) closePromoModal();
  });

  submitBtn?.addEventListener("click", () => redeem());
  inputEl?.addEventListener("keydown", (e) => {
    if (e.key === "Enter") {
      e.preventDefault();
      redeem();
    }
  });

  root.querySelector("#promo-modal-login")?.addEventListener("click", () => {
    closePromoModal();
    globalThis.__siteOpenLogin?.();
  });
}
