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

let ticketsPageEvents = [];
let ticketsPageLocale = "tr";
let ticketsPageLoggedIn = 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("ticketsStatusOpen");
  if (status === "closed") return t("ticketsStatusClosed");
  if (status === "drawn") return t("ticketsStatusDrawn");
  return status;
}

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

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="ticket-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("ticketsRequestBtn"))}
      </button>`
    : `<button type="button" class="ticket-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("ticketsViewDetail"))}
      </button>`;

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

function ticketDetailHtml(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("ticketsRulesDefault"));
  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="ticket-detail-art__placeholder">
        <span class="ticket-detail-art__logo">ALP</span>
        <span class="ticket-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("ticketsSiteLoginBtn").replace("{site}", siteLabel(ev)))}
      </a>`
    : `<p class="ticket-detail__site-note">${escapeHtml(t("ticketsRequestNote"))}</p>`;

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

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

  const requestForm =
    loggedIn && ev.status === "open"
      ? `<form id="ticket-request-form" class="ticket-detail__request-form" data-event-id="${ev.id}">
          <p class="ticket-detail__request-title">Bilet talebi gönder</p>
          <p class="ticket-detail__request-hint">Partner sitede yatırım yaptıktan sonra bilgileri gir; ekip onaylayınca biletlerin tanımlanır.</p>
          <label class="ticket-detail__field">Site kullanıcı adın *
            <input name="siteUsername" required class="ticket-detail__field-input k-input" placeholder="Partner sitedeki kullanıcı adın" />
          </label>
          <label class="ticket-detail__field">Yatırım tutarı (TRY) *
            <input name="investmentAmount" type="number" min="1" step="0.01" required class="ticket-detail__field-input k-input" placeholder="1000" />
          </label>
          <label class="ticket-detail__field">Yatırım tarihi
            <input name="investmentAt" type="datetime-local" class="ticket-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">Talep 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("ticketsActiveBadge"))}
        </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="ticket-detail" data-event-id="${ev.id}">
      <a href="#/sans-carki" class="ticket-detail__wheel-link">${escapeHtml(t("ticketsWheelSideLink"))}</a>

      <div class="ticket-detail__toolbar">
        <button type="button" class="ticket-detail__back ticket-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("ticketsBackToList"))}
        </button>
        ${activeBadge}
      </div>

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

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

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

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

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

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

  const reqForm = root.querySelector("#ticket-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 postTicketRequest({
      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] || "Talep gönderilemedi.", "error");
      return;
    }
    reqForm.reset();
    showToast(
      `Talebin alındı${data.ticketsEligible ? ` — ${data.ticketsEligible} bilet hakkı` : ""}.`,
      "success",
    );
  });
}

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

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

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

  const tab = resolveTicketDetailTab(ev, initialTab);
  detailHost.innerHTML = ticketDetailHtml(ev, ticketsPageLocale, ticketsPageLoggedIn, tab);
  detailHost.classList.remove("hidden");
  grid.classList.add("hidden");

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

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

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

export async function renderTicketsPage(outlet) {
  const locale = getSiteLocale();
  const user = await fetchSessionUser();
  ticketsPageLocale = locale;
  ticketsPageLoggedIn = 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("pageTicketsEyebrow"))}</span>
          <h1 id="page-tickets-heading" class="promo-page-header__title">${escapeHtml(t("pageTicketsTitle"))}</h1>
          <p class="promo-page-header__subtitle">${escapeHtml(t("pageTicketsSubtitle"))}</p>
        </div>
      </header>
      <div id="tickets-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("ticketsLoading"))}</p>
      </div>
    </section>
  `;

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

    bindTicketList(listEl);

    let pendingOpenId = 0;
    try {
      const raw = sessionStorage.getItem("mocker_open_ticket_event_id");
      pendingOpenId = parseInt(raw || "0", 10);
      if (pendingOpenId) sessionStorage.removeItem("mocker_open_ticket_event_id");
    } catch {
      pendingOpenId = 0;
    }
    if (pendingOpenId && ticketsPageEvents.some((e) => e.id === pendingOpenId)) {
      openTicketDetail(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("ticketsLoadError"))}</p>`;
  }
}
