import { t, getSiteLocale } from "../config/site.js";
import { apiUrl } from "../auth/session.js";
import { escapeHtml } from "../utils/escape-html.js";
import { showToast } from "../components/toast.js";
import { bindTrackClick } from "../utils/track-click.js";

function formatExpiry(expiresAt, locale) {
  if (expiresAt == null || !Number.isFinite(expiresAt) || expiresAt <= 0) {
    return t("promoCodesNoExpiry");
  }
  const now = Math.floor(Date.now() / 1000);
  const diff = expiresAt - now;
  if (diff <= 0) return t("promoCodesExpired");
  const days = Math.floor(diff / 86400);
  const hours = Math.floor((diff % 86400) / 3600);
  if (days >= 1) {
    return t("promoCodesExpiresInDays").replace("{n}", String(days));
  }
  if (hours >= 1) {
    return t("promoCodesExpiresInHours").replace("{n}", String(hours));
  }
  const mins = Math.max(1, Math.floor(diff / 60));
  return t("promoCodesExpiresInMinutes").replace("{n}", String(mins));
}

function formatExpiryDate(expiresAt, locale) {
  if (expiresAt == null || !Number.isFinite(expiresAt) || expiresAt <= 0) return "";
  try {
    const loc = locale === "en" ? "en-GB" : "tr-TR";
    return new Intl.DateTimeFormat(loc, {
      dateStyle: "medium",
      timeStyle: "short",
    }).format(new Date(expiresAt * 1000));
  } catch {
    return "";
  }
}

function promoCardHtml(item, locale) {
  const title = escapeHtml(item.sponsorTitle || "");
  const code = escapeHtml(item.code || "");
  const label = item.label ? escapeHtml(item.label) : "";
  const desc = item.description ? escapeHtml(item.description) : "";
  const expiryRel = escapeHtml(formatExpiry(item.expiresAt, locale));
  const expiryAbs = formatExpiryDate(item.expiresAt, locale);
  const expiryAbsHtml = expiryAbs
    ? `<p class="mt-0.5 text-[11px] text-slate-500">${escapeHtml(t("promoCodesExpiresOn"))}: ${escapeHtml(expiryAbs)}</p>`
    : "";
  const logo = item.logo && String(item.logo).trim();
  const logoBlock = logo
    ? `<img src="${escapeHtml(logo)}" alt="" width="140" height="48" loading="lazy" decoding="async" class="max-h-12 w-auto max-w-[88%] object-contain" />`
    : `<span class="text-sm font-bold uppercase tracking-wide text-slate-200">${title}</span>`;
  const href =
    item.url && String(item.url).trim().startsWith("http")
      ? escapeHtml(String(item.url).trim())
      : "";
  const visitBtn = href
    ? `<a href="${href}" target="_blank" rel="noopener sponsored noreferrer" class="promo-visit-link k-btn k-btn--ghost mt-3 inline-flex w-full items-center justify-center gap-2 rounded-xl border border-white/10 bg-white/[0.04] px-4 py-2.5 text-sm font-semibold text-slate-200 transition hover:border-accent/35 hover:text-white" data-promo-id="${escapeHtml(String(item.id ?? ""))}" data-track-label="${title}">${escapeHtml(t("sponsorCta"))}</a>`
    : "";

  return `
    <article class="sponsor-promo-card flex flex-col rounded-[1.15rem] border border-[rgba(22,119,255,0.24)] bg-[#1e2739] p-5 shadow-panel ring-1 ring-[rgba(22,119,255,0.12)]">
      <div class="flex min-h-[4.5rem] items-center justify-center rounded-xl bg-[rgba(22,119,255,0.12)] px-3 py-4">
        ${logoBlock}
      </div>
      <h2 class="mt-4 text-center text-lg font-bold tracking-tight text-white">${title}</h2>
      ${label ? `<p class="mt-1 text-center text-xs font-semibold uppercase tracking-wide text-accent-bright/90">${label}</p>` : ""}
      <div class="mt-4 rounded-xl border border-dashed border-accent/35 bg-accent/10 px-4 py-3 text-center">
        <p class="text-[10px] font-semibold uppercase tracking-[0.14em] text-slate-400">${escapeHtml(t("promoCodesCodeLabel"))}</p>
        <p class="mt-1 font-mono text-xl font-bold tracking-wide text-white sm:text-2xl">${code}</p>
      </div>
      ${desc ? `<p class="mt-3 text-center text-sm leading-relaxed text-slate-400">${desc}</p>` : ""}
      <div class="mt-3 rounded-lg bg-black/20 px-3 py-2 text-center">
        <p class="text-xs font-medium text-slate-300">${expiryRel}</p>
        ${expiryAbsHtml}
      </div>
      <button type="button" class="promo-code-copy k-btn k-btn--primary mt-4 inline-flex w-full items-center justify-center gap-2 rounded-xl px-4 py-2.5 text-sm font-semibold" aria-label="${escapeHtml(t("promoCodesCopyAria").replace("{site}", title))}">
        <svg class="h-4 w-4 shrink-0" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"/></svg>
        ${escapeHtml(t("sponsorCopy"))}
      </button>
      ${visitBtn}
    </article>`;
}

export async function renderPromoCodesPage(outlet) {
  const locale = getSiteLocale();
  outlet.innerHTML = `
    <section class="relative w-full min-w-0 space-y-8 px-1 pb-4">
      <header class="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="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("pagePromoCodesEyebrow"))}</span>
          <h1 id="page-promo-codes-heading" class="text-3xl font-bold tracking-tight text-white sm:text-4xl">${escapeHtml(t("pagePromoCodesTitle"))}</h1>
          <p class="max-w-2xl text-sm leading-relaxed text-slate-400 sm:text-base">${escapeHtml(t("pagePromoCodesSubtitle"))}</p>
        </div>
      </header>
      <div id="promo-codes-list" class="min-h-[12rem]" aria-live="polite">
        <p class="rounded-2xl border border-white/10 bg-brand-50/40 px-6 py-10 text-center text-sm text-slate-400">${escapeHtml(t("promoCodesLoading"))}</p>
      </div>
    </section>
  `;

  const listEl = outlet.querySelector("#promo-codes-list");
  try {
    const r = await fetch(apiUrl("sponsor_promo_codes.php"), { credentials: "omit", cache: "no-store" });
    const j = await r.json().catch(() => ({}));
    if (!r.ok || !j.ok) {
      throw new Error(j.error || "load");
    }
    const items = Array.isArray(j.items) ? j.items : [];
    if (!items.length) {
      listEl.innerHTML = `
        <p class="rounded-2xl border border-white/10 bg-brand-50/40 px-6 py-12 text-center text-sm text-slate-400" role="status">
          ${escapeHtml(t("promoCodesEmpty"))}
        </p>`;
      return;
    }
    listEl.innerHTML = `
      <div class="grid grid-cols-1 gap-5 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4" role="list">
        ${items.map((item) => promoCardHtml(item, locale)).join("")}
      </div>`;

    listEl.querySelectorAll(".promo-code-copy").forEach((btn, index) => {
      btn.addEventListener("click", async () => {
        const text = String(items[index]?.code || "").trim();
        if (!text) return;
        try {
          await navigator.clipboard.writeText(text);
          showToast(t("toastLinkCopied"), "success");
        } catch {
          showToast(t("toastCopyFailed"), "error");
        }
      });
    });
    bindTrackClick(listEl, ".promo-visit-link", "promo", "data-promo-id", "data-track-label");
  } catch {
    listEl.innerHTML = `
      <div class="rounded-2xl border border-red-500/30 bg-red-950/20 p-6 text-center text-sm text-red-200" role="alert">
        ${escapeHtml(t("promoCodesLoadError"))}
      </div>`;
  }
}
