import { t, getSiteLocale, getGameCoverUrl } from "../config/site.js";

const GAME_IDS = ["slot", "blackjack", "roulette"];

const WIN_COINS_MIN = 10;
const WIN_COINS_MAX = 500;
const MULTIPLIERS = [2, 2, 3, 5, 10];

const REFRESH_INTERVAL_MS = 36_000;

let homeRecentWinnersTimer = null;
let homeRecentWinnersMount = null;
let homeRecentWinnersCoversListener = false;
let homeRecentWinnersResizeObserver = null;

function bindGamesCoversRefresh() {
  if (homeRecentWinnersCoversListener || typeof window === "undefined") return;
  homeRecentWinnersCoversListener = true;
  window.addEventListener("mocker:games-covers", () => {
    if (homeRecentWinnersMount?.isConnected) {
      renderHomeRecentWinners(homeRecentWinnersMount);
    }
  });
}

const NAMES_TR = [
  "kemal_34",
  "ayse_m",
  "burakx",
  "emre21",
  "zeynep.k",
  "mertcan",
  "ece_99",
  "alperen",
  "deniz_tr",
  "caner47",
  "selin88",
  "furkan_a",
  "oguzhan",
  "melis_7",
  "batuhan_06",
  "yigit_34",
  "elif_sr",
  "onur_k",
  "cagri_x",
  "dilara_m",
  "hakan_44",
  "irem.z",
  "kaan_17",
  "lara_21",
  "murat_b",
  "nisa_09",
  "omer_k",
  "rüya_7",
  "serkan_41",
  "tugce_m",
  "umut_23",
  "volkan_8",
  "yasin_12",
  "arda_33",
  "berk_55",
  "ceyda_19",
  "dogukan_3",
  "efe_91",
  "gamze_x",
  "halil_22",
];

const NAMES_EN = [
  "shadow_king",
  "lucky_mike",
  "nova_7",
  "player_one",
  "coin_hunter",
  "reel_master",
  "ace_spade",
  "spin_fan",
  "turbo_99",
  "night_owl",
  "pixel_win",
  "gold_rush",
  "swift_bet",
  "lucky_star",
  "blaze_42",
  "neo_slot",
  "delta_win",
  "echo_21",
  "frost_bet",
  "ghost_77",
  "hawk_eye",
  "ivy_luck",
  "jackpot_j",
  "karma_x",
  "leo_spin",
  "max_roll",
  "nexus_09",
  "orbit_win",
  "pulse_44",
  "quest_88",
  "riot_coin",
  "storm_33",
  "vex_lucky",
  "wolf_bet",
  "xenon_12",
  "yuki_win",
  "zen_spin",
  "apex_roll",
  "bolt_64",
  "cruz_slot",
];

function gameLabel(id) {
  switch (id) {
    case "slot":
      return t("gamesCategorySlot");
    case "blackjack":
      return t("profileTabBlackjack");
    case "roulette":
      return t("gamesRouletteTitle");
    default:
      return t("gamesTitle");
  }
}

function avatarUrl(username, size = 64) {
  const name = encodeURIComponent(String(username || "U").slice(0, 2));
  return `https://ui-avatars.com/api/?name=${name}&size=${size}&background=1a2332&color=6EA8E8&bold=true`;
}

function pick(arr) {
  return arr[Math.floor(Math.random() * arr.length)];
}

function randomWinCoins() {
  return WIN_COINS_MIN + Math.floor(Math.random() * (WIN_COINS_MAX - WIN_COINS_MIN + 1));
}

function sampleUniqueUsernames(locale, count) {
  const pool = locale === "en" ? NAMES_EN : NAMES_TR;
  const out = [];
  const seen = new Set();
  let guard = 0;
  while (out.length < count && guard < count * 80) {
    guard += 1;
    const base = pick(pool);
    const suffix = Math.floor(Math.random() * 9000) + 1000;
    const candidate = `${base}_${suffix}`;
    if (!seen.has(candidate)) {
      seen.add(candidate);
      out.push(candidate);
    }
  }
  while (out.length < count) {
    const fallback = `${pick(pool)}_${Math.floor(Math.random() * 90000) + 10000}`;
    if (!seen.has(fallback)) {
      seen.add(fallback);
      out.push(fallback);
    }
  }
  return out;
}

function buildRows(count) {
  const locale = getSiteLocale();
  const users = sampleUniqueUsernames(locale, count);
  return users.map((user) => {
    const gameId = pick(GAME_IDS);
    return {
      user,
      gameId,
      game: gameLabel(gameId),
      amount: randomWinCoins(),
      multiplier: pick(MULTIPLIERS),
    };
  });
}

function winnerCardHtml(row) {
  const locale = getSiteLocale();
  const formatted = Number(row.amount).toLocaleString(locale === "en" ? "en-US" : "tr-TR");
  const coverKey = GAME_IDS.includes(row.gameId) ? row.gameId : "slot";
  const src = escapeHtml(getGameCoverUrl(coverKey));
  const winText = escapeHtml(t("homeRecentWinnersWinLine"));
  const metaText = escapeHtml(t("homeRecentWinnersMultiplier").replace("{n}", String(row.multiplier)));

  return `
    <li class="home-winner-card" role="listitem">
      <div class="home-winner-card__thumb">
        <img src="${src}" alt="${escapeHtml(row.game)}" loading="eager" decoding="async" />
      </div>
      <div class="home-winner-card__body">
        <div class="home-winner-card__user">
          <img src="${escapeHtml(avatarUrl(row.user))}" alt="" class="home-winner-card__avatar" width="18" height="18" loading="lazy" decoding="async" />
          <span class="home-winner-card__name">${escapeHtml(row.user)}</span>
        </div>
        <p class="home-winner-card__prize">
          <span class="home-winner-card__amount">${formatted}</span>
          ${winText}
        </p>
        <p class="home-winner-card__meta">${metaText}</p>
      </div>
    </li>
  `;
}

function winnersMarqueeInnerHtml(rows) {
  const cards = rows.map((r) => winnerCardHtml(r)).join("");
  return `
    <div class="home-winners__marquee-inner">
      <ul class="home-winners__track" role="list">${cards}</ul>
      <ul class="home-winners__track" aria-hidden="true">${cards}</ul>
    </div>
  `;
}

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

/** Marquee döngüsünde subpixel sıçramasını önlemek için tam piksel kaydırma */
function syncWinnersMarqueeDistance(mount) {
  const inner = mount?.querySelector?.(".home-winners__marquee-inner");
  const track = mount?.querySelector?.(".home-winners__track");
  if (!inner || !track) return;
  const w = Math.round(track.getBoundingClientRect().width);
  if (w > 0) {
    inner.style.setProperty("--marquee-shift", `${w}px`);
  }
}

function bindWinnersMarqueeMetrics(mount) {
  homeRecentWinnersResizeObserver?.disconnect();
  homeRecentWinnersResizeObserver = null;
  if (!mount?.querySelector?.(".home-winners__marquee-inner")) return;

  const run = () => syncWinnersMarqueeDistance(mount);
  if (typeof requestAnimationFrame === "function") {
    requestAnimationFrame(() => requestAnimationFrame(run));
  } else {
    run();
  }

  if (typeof ResizeObserver !== "undefined") {
    homeRecentWinnersResizeObserver = new ResizeObserver(run);
    const track = mount.querySelector(".home-winners__track");
    if (track) homeRecentWinnersResizeObserver.observe(track);
  } else {
    window.addEventListener("resize", run, { passive: true });
  }

  mount.querySelectorAll(".home-winner-card__thumb img").forEach((img) => {
    if (!(img instanceof HTMLImageElement)) return;
    if (img.complete) return;
    img.addEventListener("load", run, { once: true });
  });
}

function refreshWinnersFeedInPlace(mount) {
  const cards = mount.querySelectorAll(".home-winner-card");
  if (!cards.length) return;
  const locale = getSiteLocale();
  cards.forEach((card) => {
    const amountEl = card.querySelector(".home-winner-card__amount");
    const metaEl = card.querySelector(".home-winner-card__meta");
    if (amountEl) {
      const n = randomWinCoins();
      amountEl.textContent = n.toLocaleString(locale === "en" ? "en-US" : "tr-TR");
    }
    if (metaEl) {
      metaEl.textContent = t("homeRecentWinnersMultiplier").replace("{n}", String(pick(MULTIPLIERS)));
    }
  });
}

export function destroyHomeRecentWinners() {
  if (homeRecentWinnersTimer != null) {
    clearInterval(homeRecentWinnersTimer);
    homeRecentWinnersTimer = null;
  }
  homeRecentWinnersResizeObserver?.disconnect();
  homeRecentWinnersResizeObserver = null;
  homeRecentWinnersMount = null;
}

export function renderHomeRecentWinners(mount) {
  if (!mount) return;
  bindGamesCoversRefresh();
  if (homeRecentWinnersTimer != null) {
    clearInterval(homeRecentWinnersTimer);
    homeRecentWinnersTimer = null;
  }
  homeRecentWinnersMount = mount;

  const stripRows = buildRows(14);
  const reduceMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;

  const trackBlock = reduceMotion
    ? `
      <ul id="home-recent-winners-list" class="home-winners__static" role="list">
        ${buildRows(8).map((r) => winnerCardHtml(r)).join("")}
      </ul>
    `
    : `
      <div
        id="home-recent-winners-list"
        class="home-winners__marquee"
        role="region"
        aria-label="${escapeHtml(t("homeRecentWinnersTitle"))}"
      >
        <span class="home-winners__fade home-winners__fade--left" aria-hidden="true"></span>
        ${winnersMarqueeInnerHtml(stripRows)}
        <span class="home-winners__fade home-winners__fade--right" aria-hidden="true"></span>
      </div>
    `;

  mount.innerHTML = `
    <section class="home-winners" aria-labelledby="home-recent-winners-heading" data-fake-feed="1">
      <h2 id="home-recent-winners-heading" class="home-winners__title">${escapeHtml(t("homeRecentWinnersTitle"))}</h2>
      ${trackBlock}
    </section>
  `;

  if (!reduceMotion) {
    bindWinnersMarqueeMetrics(mount);
    homeRecentWinnersTimer = window.setInterval(() => {
      if (!homeRecentWinnersMount?.isConnected) return;
      refreshWinnersFeedInPlace(homeRecentWinnersMount);
    }, REFRESH_INTERVAL_MS);
  }
}
