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

let eventsPageEvents = [];
let eventsPageLocale = "tr";
let eventsPageLoggedIn = false;

function formatTs(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",
      hour: "2-digit",
      minute: "2-digit",
    }).format(new Date(ts * 1000));
  } catch {
    return "—";
  }
}

function statusLabel(status) {
  if (status === "open") return t("eventsStatusOpen");
  if (status === "closed") return t("eventsStatusClosed");
  if (status === "drawn") return t("eventsStatusDrawn");
  return status;
}

function siteLabel(ev) {
  const name = ev.sponsorTitle && String(ev.sponsorTitle).trim();
  return name || t("eventsSiteLoginBtnGeneric");
}

function eventTitlesMatch(ev) {
  const title = String(ev.title || "").trim();
  const sponsor = String(ev.sponsorTitle || "").trim();
  if (!title || !sponsor) return false;
  return title.toLocaleLowerCase("tr") === sponsor.toLocaleLowerCase("tr");
}

function statusBadgeHtml(status, large = false) {
  const cls =
    status === "open"
      ? "border-emerald-500/50 bg-emerald-500/15 text-emerald-300"
      : status === "drawn"
        ? "border-accent/40 bg-accent/15 text-accent-bright"
        : "border-white/20 bg-white/5 text-slate-300";
  const size = large ? "px-3 py-1 text-xs" : "px-2 py-0.5 text-[10px]";
  return `<span class="inline-flex rounded-md border font-bold uppercase tracking-wide ${size} ${cls}">${escapeHtml(statusLabel(status))}</span>`;
}

function ticketListCardHtml(ev, locale) {
  const title = escapeHtml(String(ev.title || "").trim());
  const sponsorRaw = String(ev.sponsorTitle || "").trim();
  const sponsor = sponsorRaw ? escapeHtml(sponsorRaw) : "";
  const showSponsorLine = sponsor && !eventTitlesMatch(ev);
  const prize = ev.prizeDescription ? escapeHtml(ev.prizeDescription) : "";
  const coverUrl = ev.logoUrl && String(ev.logoUrl).trim();
  const isOpen = ev.status === "open";
  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" />`
    : "";

  const cta = isOpen
    ? `<button type="button" class="event-open-detail k-btn k-btn--primary btn-site-action mt-4 w-full rounded-xl px-4 py-2.5 text-sm font-semibold" data-event-id="${ev.id}" data-open-tab="how">
        ${escapeHtml(t("eventsRequestBtn"))}
      </button>`
    : `<button type="button" class="event-open-detail k-btn k-btn--ghost mt-4 w-full rounded-xl border border-white/10 px-4 py-2.5 text-sm font-semibold text-slate-300 hover:border-accent/30 hover:text-white" data-event-id="${ev.id}" data-open-tab="rules">
        ${escapeHtml(t("eventsViewDetail"))}
      </button>`;

  const inactiveCls = isOpen ? "" : " event-list-card--inactive";

  return `
    <article class="event-list-card group${inactiveCls}" data-event-status="${escapeHtml(String(ev.status || ""))}">
      <div class="event-list-card__media">
        ${img}
        <div class="event-list-card__fade"></div>
        <div class="absolute left-3 top-3">${statusBadgeHtml(ev.status)}</div>
      </div>
      <div class="event-list-card__body">
        ${showSponsorLine ? `<p class="event-list-card__sponsor">${sponsor}</p>` : ""}
        <h2 class="event-list-card__title ${showSponsorLine ? "mt-1" : ""}">${title || sponsor}</h2>
        ${prize ? `<p class="event-list-card__meta line-clamp-2">${escapeHtml(t("eventsPrize"))}: ${prize}</p>` : ""}
        <p class="event-list-card__participants">${escapeHtml(t("eventsParticipants"))}: <strong>${Number(ev.participantCount) || 0}</strong></p>
        ${cta}
      </div>
    </article>`;
}

function eventDetailHtml(ev, locale, loggedIn, initialTab = "how") {
  const sponsor = escapeHtml(siteLabel(ev));
  const rulesText =
    ev.description && String(ev.description).trim()
      ? escapeHtml(String(ev.description).trim())
      : escapeHtml(t("eventsRulesDefault"));
  const coverUrl = ev.logoUrl && String(ev.logoUrl).trim() ? escapeHtml(String(ev.logoUrl).trim()) : "";
  const href =
    ev.siteUrl && String(ev.siteUrl).trim().startsWith("http") ? escapeHtml(String(ev.siteUrl).trim()) : "";

  const artInner = coverUrl
    ? `<img src="${coverUrl}" alt="" class="h-full w-full object-cover object-center" loading="lazy" decoding="async" />`
    : `<div class="event-detail-art__placeholder">
        <span class="event-detail-art__logo">ALP</span>
        <span class="event-detail-art__sponsor">${sponsor}</span>
      </div>`;

  const siteBtn = href
    ? `<a href="${href}" target="_blank" rel="noopener sponsored noreferrer" class="k-btn k-btn--primary btn-site-action flex w-full items-center justify-center gap-2 rounded-lg px-4 py-3.5 text-sm font-bold uppercase tracking-wide">
        ${escapeHtml(t("eventsSiteLoginBtn").replace("{site}", siteLabel(ev)))}
      </a>`
    : `<p class="event-detail__site-note">${escapeHtml(t("eventsRequestNote"))}</p>`;

  const mockerBlock = !loggedIn
    ? `<div class="event-detail__login-banner">
        <p class="event-detail__login-text">${escapeHtml(t("eventsMockerLoginHint"))}</p>
        <button type="button" class="event-detail__login-btn event-login-btn">${escapeHtml(t("eventsMockerLoginBtn"))}</button>
      </div>`
    : "";

  const joinGuide = getJoinGuideTexts("events");
  const steps = joinGuide.steps
    .map((stepText, idx) => {
      const n = idx + 1;
      const raw = String(stepText || "").replace(/\{site\}/g, siteLabel(ev));
      return `<li class="event-detail__step">
        <span class="event-detail__step-num">${n}</span>
        <span class="event-detail__step-text">${escapeHtml(raw)}</span>
      </li>`;
    })
    .join("");

  const requestForm =
    loggedIn && ev.status === "open"
      ? `<form id="event-request-form" class="event-detail__request-form" data-event-id="${ev.id}">
          <p class="event-detail__request-title">Katılım talebi gönder</p>
          <p class="event-detail__request-hint">Partner sitede yatırım yaptıktan sonra bilgileri gir; ekip onaylayınca katılımın onaylanır.</p>
          <label class="event-detail__field">Site kullanıcı adın *
            <input name="siteUsername" required class="event-detail__field-input k-input" placeholder="Partner sitedeki kullanıcı adın" />
          </label>
          <label class="event-detail__field">Yatırım tutarı (TRY) *
            <input name="investmentAmount" type="number" min="1" step="0.01" required class="event-detail__field-input k-input" placeholder="1000" />
          </label>
          <label class="event-detail__field">Yatırım tarihi
            <input name="investmentAt" type="datetime-local" class="event-detail__field-input k-input" />
          </label>
          <button type="submit" class="k-btn k-btn--primary btn-site-action w-full rounded-lg py-2.5 text-sm font-bold">Katılım talebi gönder</button>
        </form>`
      : "";

  const activeBadge =
    ev.status === "open"
      ? `<span class="inline-flex items-center gap-1 rounded-md border border-accent/40 bg-accent/20 px-2.5 py-0.5 text-[11px] font-bold uppercase tracking-wider text-accent-bright">
          <span class="h-1.5 w-1.5 rounded-full bg-accent-bright animate-pulse" aria-hidden="true"></span>
          ${escapeHtml(t("eventsActiveBadge"))}
        </span>`
      : statusBadgeHtml(ev.status, true);

  const startTs = ev.createdAt || null;
  const endTs = ev.endsAt || null;
  const rulesActive = initialTab !== "how";
  const howActive = initialTab === "how";

  return `
    <div class="event-detail" data-event-id="${ev.id}">
      <a href="#/sans-carki" class="event-detail__wheel-link">${escapeHtml(t("eventsWheelSideLink"))}</a>

      <div class="event-detail__toolbar">
        <button type="button" class="event-detail__back event-detail-back">
          <svg class="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" d="M15 19l-7-7 7-7"/></svg>
          ${escapeHtml(t("eventsBackToList"))}
        </button>
        ${activeBadge}
      </div>

      <div class="event-detail__tabs" role="tablist">
        <button type="button" class="event-detail-tab${howActive ? " event-detail-tab--active" : ""}" role="tab" aria-selected="${howActive ? "true" : "false"}" data-tab="how">${escapeHtml(t("eventsTabHowTo"))}</button>
        <button type="button" class="event-detail-tab${rulesActive ? " event-detail-tab--active" : ""}" role="tab" aria-selected="${rulesActive ? "true" : "false"}" data-tab="rules">${escapeHtml(t("eventsTabRules"))}</button>
      </div>

      <div class="event-detail__layout">
        <aside class="event-detail-stat">
          <div class="event-detail-art">${artInner}</div>
          ${siteBtn}
          <div class="event-detail__metric">
            <p class="event-detail__metric-label">${escapeHtml(t("eventsTotalParticipants"))}</p>
            <p class="event-detail__metric-value">${Number(ev.participantCount) || 0} <span class="event-detail__metric-unit">${escapeHtml(t("eventsTotalParticipantsUnit"))}</span></p>
          </div>
          ${mockerBlock}
          <div class="event-detail__dates">
            <div class="event-detail__date-card">
              <p class="event-detail__date-label">${escapeHtml(t("eventsStart"))}</p>
              <p class="event-detail__date-value">${escapeHtml(formatTs(startTs, locale))}</p>
            </div>
            <div class="event-detail__date-card">
              <p class="event-detail__date-label">${escapeHtml(t("eventsEnd"))}</p>
              <p class="event-detail__date-value">${escapeHtml(formatTs(endTs, locale))}</p>
            </div>
          </div>
        </aside>

        <div class="event-detail__main">
          <div class="event-detail-panel event-detail-panel--how${howActive ? "" : " hidden"}" data-panel="how" role="tabpanel"${howActive ? "" : " hidden"}>
            <p class="event-detail__steps-title">${escapeHtml(joinGuide.title)}</p>
            <ol class="event-detail__steps">${steps}</ol>
            ${requestForm}
          </div>
          <div class="event-detail-panel event-detail-panel--rules${rulesActive ? "" : " hidden"}" data-panel="rules" role="tabpanel"${rulesActive ? "" : " hidden"}>
            <div class="event-detail__rules">${rulesText}</div>
            ${ev.prizeDescription ? `<p class="event-detail__prize"><span class="font-semibold text-accent-bright">${escapeHtml(t("eventsPrize"))}:</span> ${escapeHtml(ev.prizeDescription)}</p>` : ""}
            <p class="event-detail__note">${escapeHtml(t("eventsRequestNote"))}</p>
          </div>
        </div>
      </div>
    </div>`;
}

function bindEventDetail(root, onBack) {
  root.querySelector(".event-detail-back")?.addEventListener("click", onBack);

  root.querySelectorAll(".event-detail-tab").forEach((tab) => {
    tab.addEventListener("click", () => {
      const name = tab.getAttribute("data-tab");
      root.querySelectorAll(".event-detail-tab").forEach((t) => {
        const on = t.getAttribute("data-tab") === name;
        t.classList.toggle("event-detail-tab--active", on);
        t.setAttribute("aria-selected", on ? "true" : "false");
      });
      root.querySelectorAll(".event-detail-panel").forEach((panel) => {
        const on = panel.getAttribute("data-panel") === name;
        panel.classList.toggle("hidden", !on);
        panel.hidden = !on;
      });
    });
  });

  root.querySelectorAll(".event-login-btn").forEach((btn) => {
    btn.addEventListener("click", () => globalThis.__siteOpenLogin?.());
  });

  const reqForm = root.querySelector("#event-request-form");
  reqForm?.addEventListener("submit", async (e) => {
    e.preventDefault();
    const fd = new FormData(reqForm);
    const eventId = parseInt(reqForm.getAttribute("data-event-id") || "0", 10);
    const { ok, data } = await postEventRequest({
      eventId,
      siteUsername: String(fd.get("siteUsername") || "").trim(),
      investmentAmount: Number(fd.get("investmentAmount")),
      investmentAt: String(fd.get("investmentAt") || "").trim(),
    });
    if (!ok) {
      const errMap = {
        auth: "Giriş yapmalısın.",
        pending_exists: "Bekleyen talebin var.",
        closed: "Etkinlik kapalı.",
        site_username: "Site kullanıcı adı gerekli.",
        amount: "Geçerli tutar gir.",
      };
      showToast(errMap[data?.error] || "Katılım talebi gönderilemedi.", "error");
      return;
    }
    reqForm.reset();
    showToast(
      `Talebin alındı${data.ticketsEligible ? ` — ${data.ticketsEligible} katılım hakkı` : ""}.`,
      "success",
    );
  });
}

function resolveEventDetailTab(ev, preferred) {
  const tab = String(preferred || "").trim();
  if (tab === "how" || tab === "rules") return tab;
  return ev?.status === "open" ? "how" : "rules";
}

function openEventDetail(eventId, root, initialTab) {
  const ev = eventsPageEvents.find((e) => e.id === eventId);
  if (!ev) return;

  const grid = root.querySelector("#events-grid");
  const detailHost = root.querySelector("#events-detail-host");
  if (!grid || !detailHost) return;

  const tab = resolveEventDetailTab(ev, initialTab);
  detailHost.innerHTML = eventDetailHtml(ev, eventsPageLocale, eventsPageLoggedIn, tab);
  detailHost.classList.remove("hidden");
  grid.classList.add("hidden");

  bindEventDetail(detailHost, () => {
    detailHost.classList.add("hidden");
    detailHost.innerHTML = "";
    grid.classList.remove("hidden");
    grid.scrollIntoView({ behavior: "smooth", block: "start" });
  });

  detailHost.scrollIntoView({ behavior: "smooth", block: "start" });
}

function bindEventList(root) {
  root.querySelectorAll(".event-open-detail").forEach((btn) => {
    btn.addEventListener("click", () => {
      const eid = parseInt(btn.getAttribute("data-event-id") || "0", 10);
      if (!eid) return;
      openEventDetail(eid, root, btn.getAttribute("data-open-tab"));
    });
  });
}

export async function renderEventsPage(outlet) {
  const locale = getSiteLocale();
  const user = await fetchSessionUser();
  eventsPageLocale = locale;
  eventsPageLoggedIn = Boolean(user);

  outlet.innerHTML = `
    <section class="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("pageEventsEyebrow"))}</span>
          <h1 id="page-events-heading" class="promo-page-header__title">${escapeHtml(t("pageEventsTitle"))}</h1>
          <p class="promo-page-header__subtitle">${escapeHtml(t("pageEventsSubtitle"))}</p>
        </div>
      </header>
      <div id="events-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("eventsLoading"))}</p>
      </div>
    </section>
  `;

  const listEl = outlet.querySelector("#events-list");
  try {
    const r = await fetch(apiUrl("events_public.php"), { credentials: "include", cache: "no-store" });
    const j = await r.json().catch(() => ({}));
    if (!r.ok || !j.ok) throw new Error(j.error || "load");
    eventsPageEvents = Array.isArray(j.events) ? j.events : [];
    if (!eventsPageEvents.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("eventsEmpty"))}</p>`;
      return;
    }
    listEl.innerHTML = `
      <div id="events-detail-host" class="mb-6 hidden"></div>
      <div id="events-grid" class="grid grid-cols-1 gap-6 sm:grid-cols-2 xl:grid-cols-3" role="list">
        ${eventsPageEvents.map((ev) => ticketListCardHtml(ev, locale)).join("")}
      </div>`;

    bindEventList(listEl);

    let pendingOpenId = 0;
    try {
      const raw = sessionStorage.getItem("mocker_open_event_id");
      pendingOpenId = parseInt(raw || "0", 10);
      if (pendingOpenId) sessionStorage.removeItem("mocker_open_event_id");
    } catch {
      pendingOpenId = 0;
    }
    if (pendingOpenId && eventsPageEvents.some((e) => e.id === pendingOpenId)) {
      openEventDetail(pendingOpenId, listEl, "how");
    }
  } catch {
    listEl.innerHTML = `<p class="rounded-2xl border border-rose-500/20 bg-rose-500/10 px-6 py-10 text-center text-sm text-rose-200/90">${escapeHtml(t("eventsLoadError"))}</p>`;
  }
}
