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) {
  if (expiresAt == null || !Number.isFinite(expiresAt) || expiresAt <= 0) {
    return t("bonusesNoExpiry");
  }
  const now = Math.floor(Date.now() / 1000);
  const diff = expiresAt - now;
  if (diff <= 0) return t("bonusesExpired");
  const days = Math.floor(diff / 86400);
  const hours = Math.floor((diff % 86400) / 3600);
  if (days >= 1) {
    return t("bonusesExpiresInDays").replace("{n}", String(days));
  }
  if (hours >= 1) {
    return t("bonusesExpiresInHours").replace("{n}", String(hours));
  }
  const mins = Math.max(1, Math.floor(diff / 60));
  return t("bonusesExpiresInMinutes").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 bonusCardHtml(item, locale) {
  const sponsorTitle = escapeHtml(item.sponsorTitle || "");
  const title = escapeHtml(item.title || "");
  const badge = item.badge ? escapeHtml(item.badge) : "";
  const desc = item.description ? escapeHtml(item.description) : "";
  const promoCode = String(item.promoCode || "").trim();
  const expiryRel = escapeHtml(formatExpiry(item.expiresAt));
  const expiryAbs = formatExpiryDate(item.expiresAt, locale);
  const expiryAbsHtml = expiryAbs
    ? `<p class="mt-0.5 text-[11px] text-slate-500">${escapeHtml(t("bonusesExpiresOn"))}: ${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">${sponsorTitle}</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="bonus-visit-link 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" data-bonus-id="${escapeHtml(String(item.id ?? ""))}" data-track-label="${title}">${escapeHtml(t("sponsorCta"))}</a>`
    : "";
  const promoBlock =
    promoCode !== ""
      ? `<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("bonusesPromoCodeLabel"))}</p>
        <p class="mt-1 font-mono text-lg font-bold tracking-wide text-white">${escapeHtml(promoCode)}</p>
        <button type="button" class="bonus-code-copy 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 text-sm font-semibold text-slate-200 transition hover:border-accent/35 hover:text-white">
          ${escapeHtml(t("sponsorCopy"))}
        </button>
      </div>`
      : "";

  return `
    <article class="bonus-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>
      <p class="mt-3 text-center text-xs font-medium uppercase tracking-wide text-slate-500">${sponsorTitle}</p>
      <h2 class="mt-1 text-center text-xl font-bold tracking-tight text-white">${title}</h2>
      ${badge ? `<p class="mt-2 text-center"><span class="inline-flex rounded-full border border-emerald-500/35 bg-emerald-500/15 px-2.5 py-0.5 text-[11px] font-semibold uppercase tracking-wide text-emerald-200">${badge}</span></p>` : ""}
      ${desc ? `<p class="mt-3 text-center text-sm leading-relaxed text-slate-400">${desc}</p>` : ""}
      ${promoBlock}
      <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>
      ${visitBtn}
    </article>`;
}

export async function renderBonusesPage(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("pageBonusesEyebrow"))}</span>
          <h1 id="page-bonuses-heading" class="text-3xl font-bold tracking-tight text-white sm:text-4xl">${escapeHtml(t("pageBonusesTitle"))}</h1>
          <p class="max-w-2xl text-sm leading-relaxed text-slate-400 sm:text-base">${escapeHtml(t("pageBonusesSubtitle"))}</p>
        </div>
      </header>
      <div id="bonuses-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("bonusesLoading"))}</p>
      </div>
    </section>
  `;

  const listEl = outlet.querySelector("#bonuses-list");
  try {
    const r = await fetch(apiUrl("bonuses.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("bonusesEmpty"))}
        </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) => bonusCardHtml(item, locale)).join("")}
      </div>`;

    listEl.querySelectorAll(".bonus-code-copy").forEach((btn, index) => {
      btn.addEventListener("click", async () => {
        const text = String(items[index]?.promoCode || "").trim();
        if (!text) return;
        try {
          await navigator.clipboard.writeText(text);
          showToast(t("toastLinkCopied"), "success");
        } catch {
          showToast(t("toastCopyFailed"), "error");
        }
      });
    });
    bindTrackClick(listEl, ".bonus-visit-link", "bonus", "data-bonus-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("bonusesLoadError"))}
      </div>`;
  }
}
