import { apiUrl } from "../auth/session.js";
import { setSiteTheme, getSiteTheme } from "./theme.js";
import { t } from "../config/site.js";

const STORAGE_KEY_AUTOLOGIN = "mocker_tg_miniapp_autologin_v1";
const TELEGRAM_SCRIPT_URL = "https://telegram.org/js/telegram-web-app.js";

let telegramScriptPromise = null;

export function getTelegramWebApp() {
  try {
    const tg = globalThis.Telegram?.WebApp;
    if (!tg || typeof tg !== "object") return null;
    return tg;
  } catch {
    return null;
  }
}

export function isInsideTelegramMiniApp() {
  const tg = getTelegramWebApp();
  if (!tg) return false;
  const initData = typeof tg.initData === "string" ? tg.initData.trim() : "";
  return initData.length > 0;
}

export function mightNeedTelegramMiniApp() {
  if (getTelegramWebApp()) return true;
  try {
    const ua = String(navigator.userAgent || "");
    if (/Telegram/i.test(ua)) return true;
    const search = String(globalThis.location?.search || "");
    const hash = String(globalThis.location?.hash || "");
    if (search.includes("tgWebApp") || hash.includes("tgWebApp")) return true;
  } catch {
    /* noop */
  }
  return false;
}

export function ensureTelegramWebAppScript() {
  if (getTelegramWebApp()) return Promise.resolve(true);
  if (telegramScriptPromise) return telegramScriptPromise;
  telegramScriptPromise = new Promise((resolve) => {
    const existing = document.querySelector(`script[src="${TELEGRAM_SCRIPT_URL}"]`);
    if (existing) {
      existing.addEventListener("load", () => resolve(!!getTelegramWebApp()), { once: true });
      existing.addEventListener("error", () => resolve(false), { once: true });
      return;
    }
    const script = document.createElement("script");
    script.src = TELEGRAM_SCRIPT_URL;
    script.async = true;
    script.onload = () => resolve(!!getTelegramWebApp());
    script.onerror = () => resolve(false);
    document.head.appendChild(script);
  });
  return telegramScriptPromise;
}

function readCsrfTokenFromCookie() {
  return null;
}

async function ensureCsrfToken() {
  try {
    const r = await fetch(apiUrl("user_me.php"), {
      credentials: "include",
      cache: "no-store",
    });
    const data = await r.json().catch(() => ({}));
    if (typeof data?.csrfToken === "string" && data.csrfToken.length > 0) {
      return { token: data.csrfToken, sessionUser: data?.user || null };
    }
  } catch {
    /* noop */
  }
  return { token: "", sessionUser: null };
}

async function postMiniAppAuth(initData, csrfToken, twofa = {}) {
  const headers = { "Content-Type": "application/json" };
  if (csrfToken) headers["X-CSRF-Token"] = csrfToken;
  const body = { initData };
  if (twofa.twofaChallenge) body.twofaChallenge = twofa.twofaChallenge;
  if (twofa.twofaCode) body.twofaCode = twofa.twofaCode;
  const r = await fetch(apiUrl("telegram_miniapp_auth.php"), {
    method: "POST",
    credentials: "include",
    cache: "no-store",
    headers,
    body: JSON.stringify(body),
  });
  const data = await r.json().catch(() => ({}));
  const ok = data?.ok === true && (data?.requires2fa === true || r.ok);
  return { ok, status: r.status, data };
}

function removeTelegramTwofaOverlay() {
  document.getElementById("tg-miniapp-twofa")?.remove();
}

function promptTelegramTwofa(challenge, initData, csrfToken) {
  removeTelegramTwofaOverlay();
  return new Promise((resolve) => {
    const wrap = document.createElement("div");
    wrap.id = "tg-miniapp-twofa";
    wrap.className =
      "fixed inset-0 z-[9995] flex items-end justify-center bg-black/70 p-4 sm:items-center";
    wrap.innerHTML = `
      <div class="w-full max-w-sm rounded-2xl border border-white/10 bg-[#1e2739] p-5 shadow-2xl ring-1 ring-white/[0.06]">
        <h2 class="text-lg font-bold text-white">${t("tgTwofaTitle")}</h2>
        <p class="mt-2 text-sm text-slate-400">${t("tgTwofaHint")}</p>
        <input id="tg-miniapp-twofa-code" type="text" inputmode="numeric" autocomplete="one-time-code" class="input-site-field mt-4 w-full text-center text-lg tracking-widest" maxlength="8" />
        <p id="tg-miniapp-twofa-err" class="mt-2 hidden text-sm text-red-300" role="alert"></p>
        <button type="button" id="tg-miniapp-twofa-submit" class="k-btn k-btn--primary btn-site-primary mt-4 w-full rounded-xl py-2.5 text-sm font-semibold">${t("tgTwofaSubmit")}</button>
      </div>`;
    document.body.appendChild(wrap);

    const input = wrap.querySelector("#tg-miniapp-twofa-code");
    const errEl = wrap.querySelector("#tg-miniapp-twofa-err");
    const btn = wrap.querySelector("#tg-miniapp-twofa-submit");
    const submit = async () => {
      const code = input?.value?.trim() || "";
      if (!code) return;
      if (btn) btn.disabled = true;
      errEl?.classList.add("hidden");
      const res = await postMiniAppAuth(initData, csrfToken, {
        twofaChallenge: challenge,
        twofaCode: code,
      });
      if (res.ok && res.data?.requires2fa !== true && res.data?.user) {
        removeTelegramTwofaOverlay();
        resolve(res);
        return;
      }
      if (btn) btn.disabled = false;
      if (errEl) {
        errEl.textContent = t("tgTwofaInvalid");
        errEl.classList.remove("hidden");
      }
      input?.focus();
    };
    btn?.addEventListener("click", () => void submit());
    input?.addEventListener("keydown", (e) => {
      if (e.key === "Enter") {
        e.preventDefault();
        void submit();
      }
    });
    input?.focus();
  });
}

function applyTelegramTheme(tg) {
  if (!tg) return;
  try {
    const scheme = String(tg.colorScheme || "").toLowerCase();
    if (scheme === "light" || scheme === "dark") {
      const cur = getSiteTheme();
      if (cur !== scheme) {
        setSiteTheme(scheme);
      }
    }
  } catch {
    /* noop */
  }
}

function bindBackButton(tg) {
  if (!tg || !tg.BackButton) return;
  const back = tg.BackButton;

  function isHome() {
    const h = (window.location.hash || "").replace(/^#/, "").trim();
    return h === "" || h === "/" || h === "/#" || h === "#/";
  }

  function update() {
    try {
      if (isHome()) back.hide();
      else back.show();
    } catch {
      /* noop */
    }
  }

  try {
    back.onClick(() => {
      if (isHome()) {
        try { tg.close(); } catch { /* noop */ }
        return;
      }
      try {
        if (window.history.length > 1) window.history.back();
        else window.location.hash = "#/";
      } catch {
        window.location.hash = "#/";
      }
    });
  } catch {
    /* noop */
  }

  window.addEventListener("hashchange", update, false);
  update();
}

function applyMiniAppViewport(tg) {
  if (!tg) return;
  try { tg.ready(); } catch { /* noop */ }
  try { tg.expand(); } catch { /* noop */ }
  try {
    document.documentElement.classList.add("mocker-tg-miniapp");
    document.body?.classList.add("mocker-tg-miniapp");
  } catch {
    /* noop */
  }
}

function handleStartParam(tg) {
  try {
    const startParam = String(tg?.initDataUnsafe?.start_param || "").trim();
    if (!startParam) return;
    const map = {
      market: "/market",
      promo: "/promosyon-kodlari",
      promosyon: "/promosyon-kodlari",
      wheel: "/sans-carki",
      cark: "/sans-carki",
      events: "/etkinlikler",
      tickets: "/biletler",
      games: "/oyunlar",
      slot: "/oyunlar/slot",
      blackjack: "/oyunlar/blackjack",
      rulet: "/oyunlar/rulet",
      profile: "/profil",
      profil: "/profil",
      news: "/haberler",
      leaderboard: "/liderlik",
      contact: "/iletisim",
      sponsors: "/ana-sponsorlar",
      odds: "/ozel-oranlar",
    };
    const target = map[startParam.toLowerCase()] || (startParam.startsWith("/") ? startParam : "");
    if (!target) return;
    if (typeof globalThis.__siteNavigateTo === "function") {
      setTimeout(() => globalThis.__siteNavigateTo(target), 0);
    } else {
      window.location.hash = target.startsWith("#") ? target : `#${target}`;
    }
  } catch {
    /* noop */
  }
}

let initStarted = false;
let initDone = false;

export async function initTelegramMiniApp() {
  if (initStarted) return initDone;
  initStarted = true;

  const tg = getTelegramWebApp();
  if (!tg) {
    initDone = false;
    return false;
  }

  applyMiniAppViewport(tg);
  applyTelegramTheme(tg);
  bindBackButton(tg);

  try {
    tg.onEvent?.("themeChanged", () => applyTelegramTheme(tg));
  } catch {
    /* noop */
  }

  const initData = typeof tg.initData === "string" ? tg.initData.trim() : "";
  if (initData === "") {
    initDone = true;
    return false;
  }

  let alreadyAuthed = false;
  let csrfToken = "";
  try {
    const { token, sessionUser } = await ensureCsrfToken();
    csrfToken = token;
    alreadyAuthed = !!sessionUser;
  } catch {
    /* noop */
  }

  if (alreadyAuthed) {
    handleStartParam(tg);
    initDone = true;
    return true;
  }

  if (!csrfToken) {
    initDone = false;
    return false;
  }

  let res = await postMiniAppAuth(initData, csrfToken);
  if (res.data?.requires2fa && typeof res.data.twofaChallenge === "string") {
    res = await promptTelegramTwofa(res.data.twofaChallenge, initData, csrfToken);
  }
  if (!res.ok || res.data?.requires2fa) {
    initDone = false;
    return false;
  }

  try {
    sessionStorage.setItem(STORAGE_KEY_AUTOLOGIN, String(Date.now()));
  } catch {
    /* noop */
  }

  if (typeof globalThis.__siteRefreshUser === "function") {
    try { await globalThis.__siteRefreshUser(); } catch { /* noop */ }
  }

  handleStartParam(tg);
  initDone = true;
  return true;
}
