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

function escapeHtml(s) {
  return String(s ?? "")
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;");
}

function resolveGamdomLogoUrl(url) {
  const v = String(url ?? "").trim();
  if (!v) return "";
  if (/^https?:\/\//i.test(v)) return v;
  if (v.startsWith("/")) return v;
  return `/${v.replace(/^\/+/, "")}`;
}

function avatarUrl(username, size = 128) {
  const name = encodeURIComponent(username && username !== "Hidden user" ? username : "?");
  return `https://ui-avatars.com/api/?name=${name}&size=${size}&background=1a1a1a&color=ef4444&bold=true`;
}

let countdownTimer = null;

function formatCountdown(endAt) {
  const end = Number(endAt);
  if (!Number.isFinite(end) || end <= 0) return null;
  const now = Math.floor(Date.now() / 1000);
  let diff = end - now;
  if (diff <= 0) {
    return { days: 0, hours: 0, minutes: 0, seconds: 0, over: true };
  }
  const days = Math.floor(diff / 86400);
  diff -= days * 86400;
  const hours = Math.floor(diff / 3600);
  diff -= hours * 3600;
  const minutes = Math.floor(diff / 60);
  const seconds = diff - minutes * 60;
  return { days, hours, minutes, seconds, over: false };
}

function pad2(n) {
  return String(n).padStart(2, "0");
}

function countdownHtml(endAt) {
  const c = formatCountdown(endAt);
  if (!c) return "";
  const units = [
    { v: c.days, l: t("gamdomCountDays") },
    { v: c.hours, l: t("gamdomCountHours") },
    { v: c.minutes, l: t("gamdomCountMinutes") },
    { v: c.seconds, l: t("gamdomCountSeconds") },
  ];
  return `
    <div class="gd-countdown" data-gd-countdown="${Number(endAt)}" role="timer" aria-live="polite">
      <p class="gd-countdown__label">${escapeHtml(t("gamdomCountdownLabel"))}</p>
      <div class="gd-countdown__grid">
        ${units
          .map(
            (u) => `
          <div class="gd-countdown__unit">
            <span class="gd-countdown__value" data-gd-unit>${pad2(u.v)}</span>
            <span class="gd-countdown__name">${escapeHtml(u.l)}</span>
          </div>`
          )
          .join("")}
      </div>
    </div>`;
}

function periodTabsHtml(periods, activeId) {
  if (!periods?.length) return "";
  return `
    <nav class="gd-periods" aria-label="${escapeHtml(t("gamdomPeriodsAria"))}">
      ${periods
        .map((p) => {
          const on = p.id === activeId;
          return `<button type="button" class="gd-periods__btn${on ? " is-active" : ""}" data-gd-period="${escapeHtml(p.id)}" aria-pressed="${on ? "true" : "false"}">${escapeHtml(p.label || p.id)}</button>`;
        })
        .join("")}
    </nav>`;
}

function podiumSlotHtml(entry, place) {
  if (!entry) return "";
  const displayName = entry.hidden ? t("gamdomHiddenUser") : entry.username || "—";
  const wager = entry.wagerDisplay || "—";
  const reward = entry.reward
    ? `<p class="gd-podium__reward">${escapeHtml(t("gamdomReward"))}: <strong>${escapeHtml(entry.reward)}</strong></p>`
    : "";
  return `
    <article class="gd-podium__slot gd-podium__slot--${place}">
      <div class="gd-podium__card">
        <span class="gd-podium__badge">${place}</span>
        <div class="gd-podium__avatar-wrap">
          <img class="gd-podium__avatar" src="${avatarUrl(displayName, place === 1 ? 256 : 192)}" alt="" width="96" height="96" loading="lazy" decoding="async" />
        </div>
        <p class="gd-podium__name" title="${escapeHtml(displayName)}">${escapeHtml(displayName)}</p>
        <p class="gd-podium__wager">${escapeHtml(wager)}</p>
        ${reward}
      </div>
    </article>`;
}

function listRowHtml(entry) {
  const displayName = entry.hidden ? t("gamdomHiddenUser") : entry.username || "—";
  const wager = entry.wagerDisplay || "—";
  const reward = entry.reward || "—";
  return `
    <div class="gd-list__row" role="row">
      <span class="gd-list__rank" role="cell">${entry.rank}</span>
      <div class="gd-list__player" role="cell">
        <img class="gd-list__avatar" src="${avatarUrl(displayName, 64)}" alt="" width="40" height="40" loading="lazy" decoding="async" />
        <span class="gd-list__name" title="${escapeHtml(displayName)}">${escapeHtml(displayName)}</span>
      </div>
      <span class="gd-list__wager" role="cell" data-label="${escapeHtml(t("gamdomColWager"))}">${escapeHtml(wager)}</span>
      <span class="gd-list__reward" role="cell" data-label="${escapeHtml(t("gamdomColReward"))}">${escapeHtml(reward)}</span>
    </div>`;
}

function warnBannerHtml(message) {
  if (!message) return "";
  return `<div class="gd-alert" role="status">${escapeHtml(message)}</div>`;
}

function formatRulesBody(text) {
  const raw = String(text ?? "").trim();
  if (!raw) return "";
  return escapeHtml(raw).replace(/\n/g, "<br />");
}

function rulesModalHtml(data) {
  const title = (data.rulesTitle && String(data.rulesTitle).trim()) || t("gamdomRules");
  return `
    <div class="gd-rules-modal" data-gd-rules-modal hidden aria-hidden="true">
      <div class="gd-rules-modal__backdrop" data-gd-rules-close tabindex="-1"></div>
      <div class="gd-rules-modal__panel" role="dialog" aria-modal="true" aria-labelledby="gd-rules-modal-title">
        <header class="gd-rules-modal__head">
          <h2 id="gd-rules-modal-title" class="gd-rules-modal__title">${escapeHtml(title)}</h2>
          <button type="button" class="gd-rules-modal__close" data-gd-rules-close aria-label="${escapeHtml(t("gamdomRulesClose"))}">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="M6 18L18 6M6 6l12 12"/></svg>
          </button>
        </header>
        <div class="gd-rules-modal__body site-scrollbar" data-gd-rules-body></div>
      </div>
    </div>`;
}

export function renderGamdomTurnuvaHtml(data) {
  if (!data?.enabled) {
    return `<div class="gd-page"><p class="gd-empty">${escapeHtml(t("gamdomDisabled"))}</p></div>`;
  }

  const warn =
    data.warning === "api_fallback" && data.apiError
      ? warnBannerHtml(t("gamdomApiFallback"))
      : "";

  const entries = Array.isArray(data.entries) ? data.entries : [];
  const top3 = entries.slice(0, 3);
  const rest = entries.slice(3);
  const second = top3[1];
  const first = top3[0];
  const third = top3[2];

  const logoSrc = resolveGamdomLogoUrl(data.logoUrl);
  const logoAlt = escapeHtml(data.title || t("gamdomDefaultTitle"));
  const logo = logoSrc
    ? `<img class="gd-hero__logo" src="${escapeHtml(logoSrc)}" alt="${logoAlt}" decoding="async" />`
    : `<span class="gd-hero__logo-text" aria-hidden="true">Gamdom</span>`;

  const cta =
    data.ctaUrl && data.ctaLabel
      ? `<a href="${escapeHtml(data.ctaUrl)}" class="gd-hero__cta gd-hero__cta--primary" target="_blank" rel="noopener noreferrer">${escapeHtml(data.ctaLabel)}</a>`
      : data.ctaLabel
        ? `<span class="gd-hero__cta gd-hero__cta--primary gd-hero__cta--static">${escapeHtml(data.ctaLabel)}</span>`
        : "";

  const rulesLabel = (data.rulesTitle && String(data.rulesTitle).trim()) || t("gamdomRules");
  const rules = `<button type="button" class="gd-hero__cta gd-hero__cta--ghost" data-gd-rules-open>${escapeHtml(rulesLabel)}</button>`;

  const prize = data.prizePool
    ? `<p class="gd-hero__prize">${escapeHtml(data.prizePool)}</p>`
    : "";

  const podium =
    top3.length > 0
      ? `
    <section class="gd-podium" aria-label="${escapeHtml(t("gamdomTop3Aria"))}">
      ${podiumSlotHtml(second, 2)}
      ${podiumSlotHtml(first, 1)}
      ${podiumSlotHtml(third, 3)}
    </section>`
      : "";

  const list =
    rest.length > 0
      ? `
    <section class="gd-list-wrap" aria-label="${escapeHtml(t("gamdomListAria"))}">
      <header class="gd-list-wrap__head">
        <h2 class="gd-list-wrap__title">${escapeHtml(t("gamdomListAria"))}</h2>
        <span class="gd-list-wrap__count">${rest.length}</span>
      </header>
      <div class="gd-list">
        <div class="gd-list__head" role="row">
          <span class="gd-list__th gd-list__th--rank">#</span>
          <span class="gd-list__th gd-list__th--player">${escapeHtml(t("gamdomColPlayer"))}</span>
          <span class="gd-list__th gd-list__th--wager">${escapeHtml(t("gamdomColWager"))}</span>
          <span class="gd-list__th gd-list__th--reward">${escapeHtml(t("gamdomColReward"))}</span>
        </div>
        <div class="gd-list__body" role="rowgroup">
          ${rest.map(listRowHtml).join("")}
        </div>
      </div>
    </section>`
      : entries.length === 0
        ? `<p class="gd-empty">${escapeHtml(t("gamdomEmpty"))}</p>`
        : "";

  return (
    warn +
    `
    <div class="gd-page k-page k-page--gamdom" data-gd-active-period="${escapeHtml(data.activePeriodId || "")}">
      <header class="gd-hero">
        <div class="gd-hero__glow" aria-hidden="true"></div>
        <div class="gd-hero__inner">
          ${logo}
          ${prize}
          <h1 class="gd-hero__title">${escapeHtml(data.title || t("gamdomDefaultTitle"))}</h1>
          ${countdownHtml(data.endAt)}
          <div class="gd-hero__actions">${cta}${rules}</div>
        </div>
      </header>
      ${periodTabsHtml(data.periods, data.activePeriodId)}
      <div class="gd-board">
        ${podium}
        ${list}
      </div>
      ${rulesModalHtml(data)}
    </div>`
  );
}

let rulesModalState = { text: "", url: "" };

function bindRulesModal(root, data) {
  rulesModalState = {
    text: String(data?.rulesText ?? "").trim(),
    url: String(data?.rulesUrl ?? "").trim(),
  };
  const modal = root?.querySelector("[data-gd-rules-modal]");
  const bodyEl = modal?.querySelector("[data-gd-rules-body]");
  if (!modal || !bodyEl) return;

  const close = () => {
    modal.hidden = true;
    modal.setAttribute("aria-hidden", "true");
    document.body.classList.remove("gd-rules-modal-open");
    document.removeEventListener("keydown", onKey);
  };

  const open = () => {
    const html = formatRulesBody(rulesModalState.text);
    if (html) {
      bodyEl.innerHTML = `<div class="gd-rules-modal__content">${html}</div>`;
    } else if (rulesModalState.url && /^https?:\/\//i.test(rulesModalState.url)) {
      bodyEl.innerHTML = `<p class="gd-rules-modal__empty">${escapeHtml(t("gamdomRulesExternalHint"))}</p>
        <a href="${escapeHtml(rulesModalState.url)}" class="gd-hero__cta gd-hero__cta--primary gd-rules-modal__link" target="_blank" rel="noopener noreferrer">${escapeHtml(t("gamdomRulesOpenLink"))}</a>`;
    } else {
      bodyEl.innerHTML = `<p class="gd-rules-modal__empty">${escapeHtml(t("gamdomRulesEmpty"))}</p>`;
    }
    modal.hidden = false;
    modal.setAttribute("aria-hidden", "false");
    document.body.classList.add("gd-rules-modal-open");
    modal.querySelector(".gd-rules-modal__close")?.focus?.();
    document.addEventListener("keydown", onKey);
  };

  function onKey(ev) {
    if (ev.key === "Escape") close();
  }

  root.querySelector("[data-gd-rules-open]")?.addEventListener("click", open);
  modal.querySelectorAll("[data-gd-rules-close]").forEach((el) => {
    el.addEventListener("click", close);
  });
}

function bindCountdown(root) {
  if (countdownTimer) {
    clearInterval(countdownTimer);
    countdownTimer = null;
  }
  const box = root?.querySelector("[data-gd-countdown]");
  if (!box) return;
  const endAt = Number(box.getAttribute("data-gd-countdown"));
  if (!Number.isFinite(endAt)) return;
  const tick = () => {
    const c = formatCountdown(endAt);
    if (!c) return;
    const vals = box.querySelectorAll("[data-gd-unit]");
    if (vals.length >= 4) {
      vals[0].textContent = pad2(c.days);
      vals[1].textContent = pad2(c.hours);
      vals[2].textContent = pad2(c.minutes);
      vals[3].textContent = pad2(c.seconds);
    }
  };
  tick();
  countdownTimer = window.setInterval(tick, 1000);
}

function bindPeriodTabs(root, reloadFn) {
  root?.querySelectorAll("[data-gd-period]").forEach((btn) => {
    btn.addEventListener("click", () => {
      const id = btn.getAttribute("data-gd-period");
      if (!id) return;
      void reloadFn(id);
    });
  });
}

export async function fetchGamdomTurnuva(periodId) {
  const q = periodId ? `?period=${encodeURIComponent(periodId)}` : "";
  const res = await fetch(apiUrl(`gamdom_turnuva.php${q}`), { credentials: "omit", cache: "no-store" });
  if (!res.ok) {
    const err = new Error("Gamdom turnuva request failed");
    err.status = res.status;
    throw err;
  }
  return res.json();
}

export async function renderGamdomTurnuvaPage(root) {
  if (!root) return;

  const renderInto = async (periodId) => {
    try {
      const data = await fetchGamdomTurnuva(periodId);
      if (!data.ok) throw new Error("bad response");
      root.innerHTML = renderGamdomTurnuvaHtml(data);
      bindCountdown(root);
      bindPeriodTabs(root, renderInto);
      bindRulesModal(root, data);
    } catch (e) {
      const st = typeof e?.status === "number" ? ` (HTTP ${e.status})` : "";
      root.innerHTML = `<div class="gd-page"><div class="gd-error" role="alert">
        <p class="gd-error__title">${escapeHtml(t("gamdomFail"))}${escapeHtml(st)}</p>
        <p class="gd-error__hint">${escapeHtml(t("gamdomFailHint"))}</p>
      </div></div>`;
    }
  };

  root.innerHTML = `<div class="gd-page gd-page--loading"><p class="gd-loading">${escapeHtml(t("gamdomLoad"))}</p></div>`;
  await renderInto("");
}
