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 avatarUrl(username, size = 128) {
  const name = encodeURIComponent(username || "?");
  return `https://ui-avatars.com/api/?name=${name}&size=${size}&background=1e2739&color=69b1ff&bold=true`;
}

function formatCoins(n) {
  const x = Number(n);
  if (!Number.isFinite(x)) return "0";
  const loc = getSiteLocale() === "en" ? "en-US" : "tr-TR";
  return x.toLocaleString(loc, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}

function leaderboardPageHeaderHtml(subtitleText) {
  const sub = subtitleText ?? t("leaderboardSubtitle");
  return `
    <header class="leaderboard-page__header relative overflow-hidden rounded-3xl border border-white/[0.08] bg-[#1e2739] p-8 shadow-panel ring-1 ring-white/[0.04] sm:p-10">
      <div class="pointer-events-none absolute inset-0 bg-[radial-gradient(ellipse_80%_60%_at_100%_0%,rgba(22,119,255,0.09),transparent)]"></div>
      <div class="relative space-y-3 text-left">
        <span class="leaderboard-page__eyebrow inline-flex items-center gap-2 rounded-full border border-accent/25 bg-accent/10 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-accent-bright">${escapeHtml(t("leaderboardEyebrow"))}</span>
        <h1 id="leaderboard-page-heading" class="leaderboard-page__title text-3xl font-bold tracking-tight text-white sm:text-4xl">${escapeHtml(t("leaderboardTitle"))}</h1>
        <p class="leaderboard-page__subtitle max-w-2xl text-sm leading-relaxed text-slate-400 sm:text-base">${escapeHtml(sub)}</p>
      </div>
    </header>`;
}

function warnBannerHtml() {
  return `<div class="lb-alert" role="status">
    <strong class="lb-alert__title">${t("leaderboardWarnTitle")}</strong>
    <span class="lb-alert__text">${t("leaderboardWarnBody")}</span>
  </div>`;
}

function podiumSlotHtml(user, place) {
  if (!user) return "";
  const placeCls = `lb-podium__slot--${place}`;
  return `
    <article class="lb-podium__slot ${placeCls}">
      <div class="lb-podium__card">
        <span class="lb-medal lb-medal--${place}" aria-hidden="true">${user.rank}</span>
        <img
          class="lb-podium__avatar"
          src="${avatarUrl(user.username, place === 1 ? 256 : 192)}"
          alt=""
          width="96"
          height="96"
          loading="lazy"
          decoding="async"
        />
        <p class="lb-podium__name" title="${escapeHtml(user.username)}">${escapeHtml(user.username)}</p>
        <p class="lb-podium__score">
          <span class="lb-podium__coins">${formatCoins(user.coins)}</span>
          <span class="lb-podium__label">${escapeHtml(t("leaderboardPoints"))}</span>
        </p>
      </div>
      <div class="lb-podium__pedestal" aria-hidden="true">
        <span class="lb-podium__place">${place}</span>
      </div>
    </article>`;
}

function tableRowHtml(user) {
  return `
    <div class="lb-table__row" role="row">
      <span class="lb-table__cell lb-table__cell--rank" role="cell">
        <span class="lb-table__rank">${user.rank}</span>
      </span>
      <div class="lb-table__cell lb-table__cell--player" role="cell">
        <img
          class="lb-table__avatar"
          src="${avatarUrl(user.username, 64)}"
          alt=""
          width="40"
          height="40"
          loading="lazy"
          decoding="async"
        />
        <span class="lb-table__name" title="${escapeHtml(user.username)}">${escapeHtml(user.username)}</span>
      </div>
      <div class="lb-table__cell lb-table__cell--score" role="cell">
        <span class="lb-table__coins">${formatCoins(user.coins)}</span>
        <span class="lb-table__points-label">${escapeHtml(t("leaderboardPoints"))}</span>
      </div>
    </div>`;
}

export async function fetchLeaderboard() {
  const res = await fetch(apiUrl("leaderboard.php"), { credentials: "omit", cache: "default" });
  if (!res.ok) {
    const err = new Error("Leaderboard request failed");
    err.status = res.status;
    throw err;
  }
  const data = await res.json();
  return {
    users: Array.isArray(data.users) ? data.users : [],
    warning: typeof data.warning === "string" ? data.warning : null,
  };
}

export function renderLeaderboardPageHtml(users, warning) {
  const warn =
    warning === "db" || warning === "query" ? warnBannerHtml() : "";

  if (!users.length) {
    return (
      warn +
      leaderboardPageHeaderHtml(warning ? t("leaderboardEmptyWarn") : t("leaderboardEmpty"))
    );
  }

  const top3 = users.slice(0, 3);
  const rest = users.slice(3);
  const second = top3[1];
  const first = top3[0];
  const third = top3[2];

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

  const tableHtml =
    rest.length > 0
      ? `
    <section class="lb-table" aria-label="${escapeHtml(t("leaderboardRestAria"))}">
      <div class="lb-table__head" role="row">
        <span class="lb-table__th lb-table__th--rank" role="columnheader">#</span>
        <span class="lb-table__th lb-table__th--player" role="columnheader">${escapeHtml(t("leaderboardColPlayer"))}</span>
        <span class="lb-table__th lb-table__th--score" role="columnheader">${escapeHtml(t("leaderboardPoints"))}</span>
      </div>
      <div class="lb-table__body" role="rowgroup">
        ${rest.map(tableRowHtml).join("")}
      </div>
    </section>`
      : "";

  return (
    warn +
    leaderboardPageHeaderHtml() +
    `
    <div class="lb-board">
      ${podiumHtml}
      ${tableHtml}
    </div>`
  );
}

export async function renderLeaderboardPage(root) {
  if (!root) return;
  try {
    const { users, warning } = await fetchLeaderboard();
    root.innerHTML = `<div class="leaderboard-page">${renderLeaderboardPageHtml(users, warning)}</div>`;
  } catch (e) {
    const st = typeof e?.status === "number" ? ` (HTTP ${e.status})` : "";
    root.innerHTML = `<div class="leaderboard-page">
      <div class="lb-error" role="alert">
        <p class="lb-error__title">${escapeHtml(t("leaderboardFail"))}${escapeHtml(st)}</p>
        <p class="lb-error__hint">${escapeHtml(t("leaderboardFailHint"))}</p>
        <p class="lb-error__meta">${escapeHtml(t("leaderboardFailCache"))}</p>
      </div>
    </div>`;
  }
}
