import { escapeHtml } from "../utils/escape-html.js";
import { t, getSiteLocale } from "../config/site.js";

let backdropEl = null;
let lastFocus = null;

function setNewsModalOpen(isOpen) {
  globalThis.__siteNewsModalOpen = isOpen;
  if (isOpen) {
    document.body.classList.add("overflow-hidden");
    return;
  }
  if (
    !globalThis.__siteAuthModalOpen &&
    !globalThis.__sitePromoModalOpen &&
    !globalThis.__siteGameSelectorModalOpen
  ) {
    document.body.classList.remove("overflow-hidden");
  }
}

export function closeNewsModal() {
  backdropEl?.classList.add("hidden");
  backdropEl?.classList.remove("flex");
  backdropEl?.setAttribute("aria-hidden", "true");
  setNewsModalOpen(false);
  const body = backdropEl?.querySelector("#news-modal-body");
  if (body) body.innerHTML = "";
  if (lastFocus && typeof lastFocus.focus === "function") {
    try {
      lastFocus.focus();
    } catch {

    }
  }
  lastFocus = null;
}

function formatNewsDate(ts, locale) {
  if (!ts || !Number.isFinite(ts)) return "";
  try {
    const loc = locale === "en" ? "en-GB" : "tr-TR";
    return new Intl.DateTimeFormat(loc, {
      day: "2-digit",
      month: "2-digit",
      year: "numeric",
    }).format(new Date(ts * 1000));
  } catch {
    return "";
  }
}

function renderBodyHtml(text) {
  const raw = String(text || "").trim();
  if (!raw) return `<p class="news-modal__empty">${escapeHtml(t("newsModalNoBody"))}</p>`;
  const paragraphs = raw.split(/\n{2,}/);
  if (paragraphs.length > 1) {
    return paragraphs
      .map((block) => block.trim())
      .filter(Boolean)
      .map((block) => `<p>${escapeHtml(block).replace(/\n/g, "<br />")}</p>`)
      .join("");
  }
  return `<p>${escapeHtml(raw).replace(/\n/g, "<br />")}</p>`;
}

/**
 * @param {{ id: number, title: string, summary?: string, body?: string, imageUrl?: string, publishedAt?: number }} item
 */
export function openNewsModal(item) {
  if (!backdropEl || !item) return;
  lastFocus = document.activeElement;

  const locale = getSiteLocale();
  const date = formatNewsDate(item.publishedAt, locale);
  const img = item.imageUrl
    ? `<img class="news-modal__img" src="${escapeHtml(item.imageUrl)}" alt="" loading="lazy" decoding="async" />`
    : "";

  const titleEl = backdropEl.querySelector("#news-modal-title");
  const dateEl = backdropEl.querySelector("#news-modal-date");
  const mediaEl = backdropEl.querySelector("#news-modal-media");
  const bodyEl = backdropEl.querySelector("#news-modal-body");

  if (titleEl) titleEl.textContent = String(item.title || "");
  if (dateEl) dateEl.textContent = date;
  if (mediaEl) {
    mediaEl.innerHTML = img;
    mediaEl.classList.toggle("hidden", !img);
  }
  if (bodyEl) {
    bodyEl.innerHTML = renderBodyHtml(item.body || item.summary || "");
  }

  backdropEl.classList.remove("hidden");
  backdropEl.classList.add("flex");
  backdropEl.setAttribute("aria-hidden", "false");
  setNewsModalOpen(true);
  requestAnimationFrame(() => {
    backdropEl.querySelector(".news-modal-close")?.focus();
  });
}

export function renderNewsModal(root) {
  root.innerHTML = `
    <div id="news-modal-backdrop" class="news-modal-backdrop k-modal k-modal--backdrop fixed inset-0 z-[150] hidden items-end justify-center p-4 sm:items-center" role="dialog" aria-modal="true" aria-labelledby="news-modal-title" aria-hidden="true">
      <div class="news-modal__panel relative flex w-full max-w-2xl max-h-[min(92vh,720px)] flex-col overflow-hidden rounded-2xl border border-[rgba(22,119,255,0.22)] bg-[#1e2739] shadow-panel ring-1 ring-white/[0.04]">
        <header class="news-modal__header relative z-10 flex shrink-0 items-center justify-end border-b border-white/[0.06] px-4 py-3 sm:px-5">
          <button type="button" class="news-modal-close k-btn k-btn--icon k-btn--ghost shrink-0 rounded-xl p-2 text-slate-400 transition hover:bg-white/[0.06] hover:text-white" aria-label="${escapeHtml(t("authClose"))}">
            <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>
          </button>
        </header>
        <div id="news-modal-media" class="news-modal__media shrink-0 hidden"></div>
        <div class="news-modal__scroll site-scrollbar min-h-0 flex-1 overflow-y-auto overscroll-contain px-5 pb-6 pt-5 sm:px-7 sm:pb-7 sm:pt-6">
          <p id="news-modal-date" class="news-modal__date"></p>
          <h2 id="news-modal-title" class="news-modal__title"></h2>
          <div id="news-modal-body" class="news-modal__body prose-news"></div>
        </div>
      </div>
    </div>
  `;

  backdropEl = root.querySelector("#news-modal-backdrop");
  backdropEl?.addEventListener("click", (e) => {
    if (e.target === backdropEl || e.target.classList.contains("news-modal-backdrop")) {
      closeNewsModal();
    }
  });
  backdropEl?.querySelector(".news-modal-close")?.addEventListener("click", closeNewsModal);

  document.addEventListener("keydown", (e) => {
    if (e.key === "Escape" && globalThis.__siteNewsModalOpen) {
      e.preventDefault();
      closeNewsModal();
    }
  });
}

globalThis.__siteCloseNewsModal = closeNewsModal;
