import { loadSponsorsJson } from "./sponsor-grid.js";
import { escapeHtml } from "../utils/escape-html.js";
import { t } from "../config/site.js";

let backdropEl = null;
let panelEl = null;
let bodyEl = null;
let sponsorsEl = null;
let lastFocus = null;
let onSpinAgainCb = null;
let sponsorsCache = null;

const ICON_CLOSE = `<svg class="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg>`;
const ICON_PLAY = `<svg class="h-4 w-4 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>`;
const ICON_REFRESH = `<svg class="h-4 w-4 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"/></svg>`;
const ICON_EXTERNAL = `<svg class="h-3.5 w-3.5 shrink-0 opacity-70 transition group-hover:translate-x-0.5 group-hover:opacity-100" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"/></svg>`;

function setModalOpen(isOpen) {
  globalThis.__siteGameSelectorModalOpen = isOpen;
  if (isOpen) {
    document.body.classList.add("overflow-hidden");
    return;
  }
  panelEl?.classList.remove("game-selector-modal--sponsors");
  if (
    !globalThis.__siteAuthModalOpen &&
    !globalThis.__sitePromoModalOpen &&
    !globalThis.__siteNewsModalOpen
  ) {
    document.body.classList.remove("overflow-hidden");
  }
}

export function closeGameSelectorModal() {
  backdropEl?.classList.add("hidden");
  backdropEl?.classList.remove("flex");
  backdropEl?.setAttribute("aria-hidden", "true");
  panelEl?.classList.remove("game-selector-modal--sponsors");
  setModalOpen(false);
  if (bodyEl) bodyEl.innerHTML = "";
  if (sponsorsEl) {
    sponsorsEl.innerHTML = "";
    sponsorsEl.classList.add("hidden");
  }
  onSpinAgainCb = null;
  if (lastFocus && typeof lastFocus.focus === "function") {
    try {
      lastFocus.focus();
    } catch {

    }
  }
  lastFocus = null;
}

function sponsorUrl(item) {
  const u = item?.url != null ? String(item.url).trim() : "";
  return u && u !== "#" ? u : "";
}

async function loadPlaySponsors() {
  if (sponsorsCache) return sponsorsCache;
  try {
    const all = await loadSponsorsJson();
    sponsorsCache = all.filter((s) => sponsorUrl(s));
  } catch {
    sponsorsCache = [];
  }
  return sponsorsCache;
}

function renderSponsorsInModal(list) {
  if (!sponsorsEl) return;
  if (!list.length) {
    sponsorsEl.innerHTML = `<p class="gs-modal-sponsors__empty">${escapeHtml(t("gameSelectorSponsorsEmpty"))}</p>`;
    sponsorsEl.classList.remove("hidden");
    return;
  }
  sponsorsEl.innerHTML = `
    <div class="gs-modal-sponsors__head">
      <h3 class="gs-modal-sponsors__title">${escapeHtml(t("gameSelectorSponsorsTitle"))}</h3>
      <p class="gs-modal-sponsors__lead">${escapeHtml(t("gameSelectorSponsorsLead"))}</p>
    </div>
    <div class="gs-modal-sponsors__list">
      ${list
        .map((s) => {
          const url = sponsorUrl(s);
          const logo = s.logo && String(s.logo).trim() ? String(s.logo).trim() : "";
          const logoHtml = logo
            ? `<img class="gs-modal-sponsor__logo" src="${escapeHtml(logo)}" alt="" loading="lazy" decoding="async" />`
            : `<span class="gs-modal-sponsor__initial" aria-hidden="true">${escapeHtml(String(s.title || "?").charAt(0))}</span>`;
          return `
            <a href="${escapeHtml(url)}" class="gs-modal-sponsor group" target="_blank" rel="noopener sponsored noreferrer">
              <div class="gs-modal-sponsor__logo-wrap">${logoHtml}</div>
              <div class="gs-modal-sponsor__text">
                <span class="gs-modal-sponsor__name">${escapeHtml(s.title || "")}</span>
                <span class="gs-modal-sponsor__cta">${escapeHtml(t("sponsorCta"))}${ICON_EXTERNAL}</span>
              </div>
            </a>`;
        })
        .join("")}
    </div>
  `;
  sponsorsEl.classList.remove("hidden");
}

async function onPlayClick() {
  const list = await loadPlaySponsors();
  renderSponsorsInModal(list);
  panelEl?.classList.add("game-selector-modal--sponsors");
  requestAnimationFrame(() => {
    sponsorsEl?.scrollIntoView({ behavior: "smooth", block: "nearest" });
  });
}

function bindModalActions() {
  backdropEl?.querySelector(".gs-modal-close")?.addEventListener("click", closeGameSelectorModal);
  bodyEl?.querySelector("[data-gs-spin-again]")?.addEventListener("click", () => {
    const cb = onSpinAgainCb;
    closeGameSelectorModal();
    cb?.();
  });
  bodyEl?.querySelector("[data-gs-play]")?.addEventListener("click", () => {
    void onPlayClick();
  });
}

function onDocumentKeydown(e) {
  if (e.key === "Escape" && globalThis.__siteGameSelectorModalOpen) {
    e.preventDefault();
    closeGameSelectorModal();
  }
}

/**
 * @param {object} game - { name, image, rtp }
 * @param {{ providerLabel: string, onSpinAgain?: () => void }} opts
 */
export function openGameSelectorModal(game, opts = {}) {
  if (!backdropEl || !bodyEl || !game) return;
  lastFocus = document.activeElement;
  onSpinAgainCb = typeof opts.onSpinAgain === "function" ? opts.onSpinAgain : null;
  sponsorsCache = null;
  panelEl?.classList.remove("game-selector-modal--sponsors");

  if (sponsorsEl) {
    sponsorsEl.innerHTML = "";
    sponsorsEl.classList.add("hidden");
  }

  const rtpVal =
    game.rtp != null && game.rtp !== "" && !Number.isNaN(Number(game.rtp))
      ? String(Number(game.rtp).toFixed(2))
      : "";
  const providerLine = String(opts.providerLabel || "").trim();

  const poster = game.image
    ? `<img class="gs-modal-hero__img" src="${escapeHtml(game.image)}" alt="" loading="eager" decoding="async" />`
    : `<div class="gs-modal-hero__placeholder" aria-hidden="true"><span>🎰</span></div>`;

  bodyEl.innerHTML = `
    <div class="gs-modal-hero">
      <div class="gs-modal-hero__frame">
        <div class="gs-modal-hero__shine" aria-hidden="true"></div>
        ${poster}
      </div>
      <div class="gs-modal-hero__info">
        <h2 id="game-selector-modal-title" class="gs-modal-hero__title">${escapeHtml(game.name)}</h2>
        <div class="gs-modal-hero__chips">
          ${providerLine ? `<span class="gs-modal-chip gs-modal-chip--provider">${escapeHtml(providerLine.toUpperCase())}</span>` : ""}
          ${rtpVal ? `<span class="gs-modal-chip gs-modal-chip--rtp">${escapeHtml(t("gameSelectorRtp").replace("{rtp}", rtpVal))}</span>` : ""}
        </div>
      </div>
    </div>
    <div class="gs-modal-actions">
      <button type="button" class="gs-modal-actions__btn gs-modal-actions__btn--primary k-btn k-btn--primary btn-site-action" data-gs-play>
        ${ICON_PLAY}
        <span>${escapeHtml(t("gameSelectorPlay"))}</span>
      </button>
      <button type="button" class="gs-modal-actions__btn gs-modal-actions__btn--ghost k-btn k-btn--secondary btn-site-secondary" data-gs-spin-again>
        ${ICON_REFRESH}
        <span>${escapeHtml(t("gameSelectorSpinAgain"))}</span>
      </button>
    </div>
  `;

  backdropEl.classList.remove("hidden");
  backdropEl.classList.add("flex");
  backdropEl.setAttribute("aria-hidden", "false");
  setModalOpen(true);
  bindModalActions();
  requestAnimationFrame(() => {
    bodyEl?.querySelector("[data-gs-play]")?.focus();
  });
}

export function renderGameSelectorModal(root) {
  if (!root) return;
  root.innerHTML = `
    <div id="game-selector-modal" class="game-selector-modal fixed inset-0 z-[150] hidden items-end justify-center p-4 sm:items-center sm:p-6" role="dialog" aria-modal="true" aria-labelledby="game-selector-modal-title" aria-hidden="true">
      <div class="game-selector-modal__backdrop absolute inset-0 bg-[#070a10]/78 backdrop-blur-[6px]" aria-hidden="true"></div>
      <div class="game-selector-modal__panel relative z-10 flex w-full max-w-[28rem] max-h-[min(92vh,780px)] flex-col overflow-hidden rounded-2xl border border-[rgba(22,119,255,0.22)] bg-[#1e2739] shadow-[0_32px_80px_-24px_rgba(0,0,0,0.75),0_0_0_1px_rgba(255,255,255,0.04)_inset] sm:max-w-md">
        <div class="game-selector-modal__glow pointer-events-none absolute -inset-px rounded-2xl opacity-80" aria-hidden="true"></div>
        <header class="gs-modal-header relative z-[2] flex items-start justify-between gap-3 border-b border-white/[0.06] px-5 py-4 sm:px-6">
          <div class="min-w-0">
            <p class="text-[10px] font-bold uppercase tracking-[0.2em] text-accent-bright">${escapeHtml(t("gameSelectorSelectedBadge"))}</p>
            <p class="mt-1 text-xs text-slate-500">${escapeHtml(t("gameSelectorModalSubtitle"))}</p>
          </div>
          <button type="button" class="gs-modal-close k-btn k-btn--icon k-btn--ghost shrink-0 rounded-xl p-2 text-slate-500 transition hover:bg-white/[0.06] hover:text-white" aria-label="${escapeHtml(t("authClose"))}">
            ${ICON_CLOSE}
          </button>
        </header>
        <div class="game-selector-modal__scroll relative z-[1] min-h-0 flex-1 overflow-y-auto overscroll-contain px-5 py-5 sm:px-6 sm:py-6">
          <div id="game-selector-modal-body"></div>
          <div id="game-selector-modal-sponsors" class="gs-modal-sponsors hidden"></div>
        </div>
      </div>
    </div>
  `;

  backdropEl = root.querySelector("#game-selector-modal");
  panelEl = root.querySelector(".game-selector-modal__panel");
  bodyEl = root.querySelector("#game-selector-modal-body");
  sponsorsEl = root.querySelector("#game-selector-modal-sponsors");

  if (!root.dataset.gsModalBound) {
    root.dataset.gsModalBound = "1";
    document.addEventListener("keydown", onDocumentKeydown);
    backdropEl.addEventListener("click", (e) => {
      if (e.target === backdropEl || e.target.classList.contains("game-selector-modal__backdrop")) {
        closeGameSelectorModal();
      }
    });
  }

  globalThis.__siteCloseGameSelectorModal = closeGameSelectorModal;
}
