import { t, getSiteLocale } from "../config/site.js";
import { escapeHtml } from "../utils/escape-html.js";
import { fetchHomeTicketEvents } from "../utils/home-public-cache.js";
import { formatPrizeDisplay, splitCountdown } from "../utils/home-campaign-format.js";
import { homeTicketsSkeletonHtml } from "../utils/home-skeleton.js";

let homeTicketsTimer = null;
let homeTicketsMount = null;

function countdownUnitHtml(value, label) {
  return `<div class="home-ticket-card__cd-unit">
    <span class="home-ticket-card__cd-box" data-cd-val>${escapeHtml(value)}</span>
    <span class="home-ticket-card__cd-label">${escapeHtml(label)}</span>
  </div>`;
}

function countdownBlockHtml(endsAt) {
  if (!endsAt) {
    return `<p class="home-ticket-card__no-end">${escapeHtml(t("homeTicketsNoEnd"))}</p>`;
  }
  const parts = splitCountdown(endsAt, Math.floor(Date.now() / 1000)) || {
    days: "00",
    hours: "00",
    mins: "00",
    secs: "00",
  };
  const pad = (v) => String(v).padStart(2, "0");
  return `<div class="home-ticket-card__countdown" data-ends-at="${endsAt}">
    ${countdownUnitHtml(pad(parts.days), t("homeTicketsCountdownDay"))}
    ${countdownUnitHtml(pad(parts.hours), t("homeTicketsCountdownHour"))}
    ${countdownUnitHtml(pad(parts.mins), t("homeTicketsCountdownMin"))}
    ${countdownUnitHtml(pad(parts.secs), t("homeTicketsCountdownSec"))}
  </div>`;
}

function ticketCardHtml(ev, locale) {
  const sponsor = String(ev.sponsorTitle || "").trim();
  const titleRaw = String(ev.title || "").trim();
  const displayTitle =
    titleRaw && titleRaw.toLocaleLowerCase("tr") !== sponsor.toLocaleLowerCase("tr")
      ? titleRaw
      : sponsor || titleRaw || "—";
  const prize = escapeHtml(formatPrizeDisplay(ev, locale));
  const sponsorLogo = ev.sponsorLogo && String(ev.sponsorLogo).trim();
  const coverLogo = ev.logoUrl && String(ev.logoUrl).trim();
  const logoUrl = sponsorLogo || coverLogo;
  const logoInner = logoUrl
    ? `<img src="${escapeHtml(logoUrl)}" alt="" class="home-ticket-card__logo-img" loading="lazy" decoding="async" />`
    : `<span class="home-ticket-card__logo-fallback">${escapeHtml(sponsor || "ALP")}</span>`;

  return `<article class="home-ticket-card" data-ticket-id="${ev.id}" role="listitem">
    <div class="home-ticket-card__logo">${logoInner}</div>
    <h3 class="home-ticket-card__title">${escapeHtml(displayTitle)}</h3>
    <p class="home-ticket-card__prize">${prize}</p>
  ${countdownBlockHtml(ev.endsAt)}
    <button type="button" class="home-ticket-card__cta" data-home-ticket-join="${ev.id}">
      ${escapeHtml(t("homeTicketsJoin"))}
      <span aria-hidden="true">&rsaquo;</span>
    </button>
  </article>`;
}

function bindHomeTicketRows(root) {
  root.querySelectorAll("[data-home-ticket-join]").forEach((btn) => {
    btn.addEventListener("click", () => {
      const id = btn.getAttribute("data-home-ticket-join");
      if (id) {
        try {
          sessionStorage.setItem("mocker_open_ticket_event_id", id);
        } catch {
          /* ignore */
        }
      }
      globalThis.__siteNavigateTo?.("/biletler");
    });
  });
}

function tickHomeTicketCountdowns() {
  if (!homeTicketsMount) return;
  const nowSec = Math.floor(Date.now() / 1000);
  homeTicketsMount.querySelectorAll(".home-ticket-card__countdown[data-ends-at]").forEach((block) => {
    const endsAt = Number.parseInt(block.getAttribute("data-ends-at") || "0", 10);
    const parts = splitCountdown(endsAt, nowSec);
    if (!parts) return;
    const pad = (v) => String(v).padStart(2, "0");
    const vals = block.querySelectorAll("[data-cd-val]");
    if (vals.length >= 4) {
      vals[0].textContent = pad(parts.days);
      vals[1].textContent = pad(parts.hours);
      vals[2].textContent = pad(parts.mins);
      vals[3].textContent = pad(parts.secs);
    }
  });
}

export function destroyHomeTickets() {
  if (homeTicketsTimer != null) {
    clearInterval(homeTicketsTimer);
    homeTicketsTimer = null;
  }
  homeTicketsMount = null;
}

export async function renderHomeTickets(mount) {
  if (!mount) return;
  destroyHomeTickets();
  homeTicketsMount = mount;
  mount.innerHTML = homeTicketsSkeletonHtml();

  let tickets = [];
  try {
    tickets = await fetchHomeTicketEvents();
  } catch {
    tickets = [];
  }

  if (!tickets.length) {
    mount.innerHTML = "";
    homeTicketsMount = null;
    return;
  }

  const locale = getSiteLocale();
  mount.innerHTML = `
    <section class="home-tickets" aria-labelledby="home-tickets-heading">
      <h2 id="home-tickets-heading" class="home-tickets__title">${escapeHtml(t("homeTicketsTitle"))}</h2>
      <div class="home-tickets__list" role="list">
        ${tickets.map((ev) => ticketCardHtml(ev, locale)).join("")}
      </div>
    </section>
  `;

  bindHomeTicketRows(mount);
  tickHomeTicketCountdowns();
  homeTicketsTimer = window.setInterval(tickHomeTicketCountdowns, 1000);
}
