import { apiUrl } from "../auth/session.js";
import { openNewsModal } from "../components/news-modal.js";
import { escapeHtml } from "../utils/escape-html.js";
import { t, getSiteLocale } from "../config/site.js";

let newsItems = [];

function formatDate(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 newsDateBadgeHtml(dateStr) {
  const label = dateStr || "—";
  return `<span class="inline-flex rounded-md border border-emerald-500/50 bg-emerald-500/15 px-2 py-0.5 text-[10px] font-bold uppercase tracking-wide text-emerald-300">${escapeHtml(label)}</span>`;
}

function newsListCardHtml(item, locale) {
  const title = escapeHtml(String(item.title || "").trim());
  const summary = escapeHtml(String(item.summary || "").trim());
  const date = formatDate(item.publishedAt, locale);
  const category = escapeHtml(
    String(t("navNews")).toLocaleUpperCase(locale === "en" ? "en-US" : "tr-TR"),
  );
  const coverUrl = item.imageUrl && String(item.imageUrl).trim();
  const img = coverUrl
    ? `<img src="${escapeHtml(coverUrl)}" alt="" class="h-full w-full object-cover transition duration-500 group-hover:scale-[1.03]" loading="lazy" decoding="async" />`
    : "";

  return `
    <article class="event-list-card group" data-news-id="${item.id}">
      <div class="event-list-card__media">
        ${img}
        <div class="event-list-card__fade"></div>
        <div class="absolute left-3 top-3">${newsDateBadgeHtml(date)}</div>
      </div>
      <div class="event-list-card__body">
        <p class="event-list-card__sponsor">${category}</p>
        <h2 class="event-list-card__title mt-1">${title}</h2>
        ${summary ? `<p class="event-list-card__meta line-clamp-2">${summary}</p>` : ""}
        <button type="button" class="k-btn k-btn--primary mt-4 w-full rounded-xl px-4 py-2.5 text-sm font-semibold" data-news-open="${item.id}">
          ${escapeHtml(t("newsDetailsBtn"))}
        </button>
      </div>
    </article>`;
}

function bindNewsList(root) {
  root.querySelectorAll("[data-news-open]").forEach((btn) => {
    btn.addEventListener("click", async () => {
      const id = parseInt(btn.getAttribute("data-news-open") || "0", 10);
      let item = newsItems.find((n) => n.id === id);
      if (!item) return;

      if (!item.body) {
        try {
          const r = await fetch(apiUrl(`news_public.php?id=${id}`), { cache: "default" });
          const data = await r.json().catch(() => ({}));
          if (r.ok && data.ok && data.item) {
            item = { ...item, ...data.item };
            const idx = newsItems.findIndex((n) => n.id === id);
            if (idx >= 0) newsItems[idx] = item;
          }
        } catch {

        }
      }
      openNewsModal(item);
    });
  });
}

export async function renderNewsPage(outlet) {
  const locale = getSiteLocale();

  outlet.innerHTML = `
    <section class="news-page relative w-full min-w-0 space-y-8 px-1 pb-4">
      <header class="promo-page-header">
        <div class="promo-page-header__glow"></div>
        <div class="relative space-y-3 text-left">
          <span class="promo-page-header__eyebrow">${escapeHtml(t("pageNewsEyebrow"))}</span>
          <h1 class="promo-page-header__title">${escapeHtml(t("pageNewsTitle"))}</h1>
          <p class="promo-page-header__subtitle">${escapeHtml(t("pageNewsSubtitle"))}</p>
        </div>
      </header>
      <div id="news-list" class="min-h-[12rem]" aria-live="polite">
        <p class="news-page__state">${escapeHtml(t("newsLoading"))}</p>
      </div>
    </section>
  `;

  const listEl = outlet.querySelector("#news-list");
  try {
    const r = await fetch(apiUrl("news_public.php"), { cache: "default" });
    const data = await r.json().catch(() => ({}));
    if (!r.ok || !data.ok) throw new Error(data.error || "load");
    newsItems = Array.isArray(data.items) ? data.items : [];
    if (!newsItems.length) {
      listEl.innerHTML = `<p class="news-page__state" role="status">${escapeHtml(t("newsEmpty"))}</p>`;
      return;
    }
    listEl.innerHTML = `
      <div class="grid grid-cols-1 gap-6 sm:grid-cols-2 xl:grid-cols-3" role="list">
        ${newsItems.map((item) => newsListCardHtml(item, locale)).join("")}
      </div>`;
    bindNewsList(listEl);
  } catch {
    listEl.innerHTML = `<p class="news-page__state news-page__state--error" role="alert">${escapeHtml(t("newsLoadError"))}</p>`;
  }
}
