import { t, getSiteLocale } from "../config/site.js";
import { escapeHtml } from "../utils/escape-html.js";
import { fetchHomeCampaignEvents } from "../utils/home-public-cache.js";
import { homeEventsSkeletonHtml } from "../utils/home-skeleton.js";

let homeEventsCountdownTimer = null;
let homeEventsCarouselTimer = null;
let homeEventsCarouselCleanup = null;
let homeEventsMount = null;

const EVENTS_CAROUSEL_MS = 5000;

function eventsCarouselArrowSvg(direction) {
  if (direction === "prev") {
    return `<svg 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>`;
  }
  return `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" d="M9 5l7 7-7 7"/></svg>`;
}

const HOME_FEED_MOBILE_MQ = "(max-width: 1023px)";

function isHomeEventsMobileGrid() {
  return window.matchMedia(HOME_FEED_MOBILE_MQ).matches;
}

function getHomeEventsPerView() {
  if (isHomeEventsMobileGrid()) return 2;
  if (window.matchMedia("(max-width: 1279px)").matches) return 2;
  return 4;
}

function parseAmountToken(raw) {
  const s = String(raw || "").trim();
  if (!s) return NaN;
  if (s.includes(",") && s.includes(".")) {
    if (s.lastIndexOf(",") > s.lastIndexOf(".")) {
      return Number.parseFloat(s.replace(/\./g, "").replace(",", "."));
    }
    return Number.parseFloat(s.replace(/,/g, ""));
  }
  if (s.includes(",")) {
    const frac = s.split(",")[1] || "";
    if (frac.length === 2) return Number.parseFloat(s.replace(/\./g, "").replace(",", "."));
    return Number.parseFloat(s.replace(/,/g, ""));
  }
  if (s.includes(".")) {
    const parts = s.split(".");
    if (parts.length > 2 || (parts.length === 2 && parts[1].length === 3)) {
      return Number.parseFloat(s.replace(/\./g, ""));
    }
    return Number.parseFloat(s);
  }
  return Number.parseFloat(s);
}

function extractPrizeAmount(text) {
  const s = String(text || "").trim();
  if (!s) return null;
  const tokens = s.match(/\d[\d.,]*/g);
  if (!tokens?.length) return null;
  let best = null;
  for (const token of tokens) {
    const val = parseAmountToken(token);
    if (!Number.isFinite(val) || val <= 0) continue;
    if (best == null || val > best) best = val;
  }
  return best;
}

function formatPrizeDisplay(ev, locale) {
  const fromDesc = extractPrizeAmount(ev.prizeDescription);
  if (fromDesc != null) {
    const loc = locale === "en" ? "en-GB" : "tr-TR";
    return `${new Intl.NumberFormat(loc, { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(fromDesc)} ₺`;
  }
  const desc = String(ev.prizeDescription || "").trim();
  if (desc) return desc;
  const fromTitle = extractPrizeAmount(ev.title);
  if (fromTitle != null) {
    const loc = locale === "en" ? "en-GB" : "tr-TR";
    return `${new Intl.NumberFormat(loc, { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(fromTitle)} ₺`;
  }
  return "—";
}

function splitCountdown(endsAt, nowSec) {
  if (!endsAt || !Number.isFinite(endsAt)) return null;
  let diff = Math.max(0, endsAt - nowSec);
  const days = Math.floor(diff / 86400);
  diff -= days * 86400;
  const hours = Math.floor(diff / 3600);
  diff -= hours * 3600;
  const mins = Math.floor(diff / 60);
  const secs = diff - mins * 60;
  return {
    days: String(days).padStart(2, "0"),
    hours: String(hours).padStart(2, "0"),
    mins: String(mins).padStart(2, "0"),
    secs: String(secs).padStart(2, "0"),
  };
}

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

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

function countdownBlockHtml(ev) {
  const status = String(ev?.status || "open");
  if (status !== "open") {
    return `<p class="home-event-card__ended">${escapeHtml(eventStatusLabel(status))}</p>`;
  }
  const endsAt = ev.endsAt;
  if (!endsAt) {
    return `<p class="home-event-card__no-end">${escapeHtml(t("homeEventsNoEnd"))}</p>`;
  }
  const parts = splitCountdown(endsAt, Math.floor(Date.now() / 1000)) || {
    days: "00",
    hours: "00",
    mins: "00",
    secs: "00",
  };
  return `<div class="home-event-card__countdown" data-ends-at="${endsAt}">
    ${countdownUnitHtml(parts.days, t("homeEventsCountdownDay"))}
    ${countdownUnitHtml(parts.hours, t("homeEventsCountdownHour"))}
    ${countdownUnitHtml(parts.mins, t("homeEventsCountdownMin"))}
    ${countdownUnitHtml(parts.secs, t("homeEventsCountdownSec"))}
  </div>`;
}

function eventCardHtml(ev, locale) {
  const status = String(ev.status || "open");
  const isOpen = status === "open";
  const title = escapeHtml(String(ev.title || ev.sponsorTitle || "").trim());
  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 sponsor = escapeHtml(String(ev.sponsorTitle || "").trim());
  const logoInner = logoUrl
    ? `<img src="${escapeHtml(logoUrl)}" alt="" class="home-event-card__logo-img" loading="lazy" decoding="async" />`
    : `<span class="home-event-card__logo-fallback">${sponsor || "ALP"}</span>`;
  const inactiveCls = isOpen ? "" : " home-event-card--inactive";
  const statusBadge = isOpen
    ? ""
    : `<span class="home-event-card__status home-event-card__status--${escapeHtml(status)}">${escapeHtml(eventStatusLabel(status))}</span>`;
  const ctaCls = isOpen ? "home-event-card__cta" : "home-event-card__cta home-event-card__cta--inactive";

  return `<article class="home-event-card${inactiveCls}" data-event-id="${ev.id}" data-event-status="${escapeHtml(status)}">
    ${statusBadge}
    <div class="home-event-card__logo">${logoInner}</div>
    <h3 class="home-event-card__title">${title}</h3>
    <p class="home-event-card__prize">${prize}</p>
    ${countdownBlockHtml(ev)}
    <button type="button" class="${ctaCls}" data-home-event-join="${ev.id}">
      ${escapeHtml(isOpen ? t("homeEventsJoin") : t("homeEventsViewDetail"))}
      <span aria-hidden="true">&rsaquo;</span>
    </button>
  </article>`;
}

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

function tickHomeEventCountdowns() {
  if (!homeEventsMount) return;
  const nowSec = Math.floor(Date.now() / 1000);
  homeEventsMount.querySelectorAll(".home-event-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 vals = block.querySelectorAll("[data-cd-val]");
    if (vals.length >= 4) {
      vals[0].textContent = parts.days;
      vals[1].textContent = parts.hours;
      vals[2].textContent = parts.mins;
      vals[3].textContent = parts.secs;
    }
  });
}

export function destroyHomeEvents() {
  if (homeEventsCountdownTimer != null) {
    clearInterval(homeEventsCountdownTimer);
    homeEventsCountdownTimer = null;
  }
  if (homeEventsCarouselTimer != null) {
    clearInterval(homeEventsCarouselTimer);
    homeEventsCarouselTimer = null;
  }
  homeEventsCarouselCleanup?.();
  homeEventsCarouselCleanup = null;
  homeEventsMount = null;
}

function setupEventsCarousel(root) {
  const track = root.querySelector(".home-events__track");
  const carousel = root.querySelector(".home-events__carousel");
  const prevBtn = root.querySelector(".home-events__arrow--prev");
  const nextBtn = root.querySelector(".home-events__arrow--next");
  if (!track || !carousel || !prevBtn || !nextBtn) return;

  homeEventsCarouselCleanup?.();
  const ac = new AbortController();
  homeEventsCarouselCleanup = () => ac.abort();

  const mqMobileGrid = window.matchMedia(HOME_FEED_MOBILE_MQ);
  const reduceMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
  const cards = track.querySelectorAll(".home-event-card");
  const count = cards.length;
  let slideIndex = 0;

  const dotsHost = root.querySelector(".home-events__dots");
  if (dotsHost) dotsHost.innerHTML = "";

  if (mqMobileGrid.matches) {
    track.style.removeProperty("transform");
    carousel.classList.remove("home-events__carousel--nav");
    prevBtn.disabled = true;
    nextBtn.disabled = true;
    mqMobileGrid.addEventListener(
      "change",
      () => {
        if (!mqMobileGrid.matches) setupEventsCarousel(root);
      },
      { signal: ac.signal },
    );
    return;
  }

  const maxIndex = () => Math.max(0, count - getHomeEventsPerView());

  const measureStep = () => {
    const card = cards[0];
    if (!card) return 0;
    const gap = Number.parseFloat(getComputedStyle(track).gap) || 0;
    return card.offsetWidth + gap;
  };

  const syncDots = () => {
    root.querySelectorAll(".home-events__dot").forEach((dot) => {
      const i = Number.parseInt(dot.getAttribute("data-slide") || "0", 10);
      dot.classList.toggle("is-active", i === slideIndex);
    });
  };

  const syncNav = () => {
    const perView = getHomeEventsPerView();
    const showArrows = count > perView;
    carousel.classList.toggle("home-events__carousel--nav", showArrows);
    prevBtn.disabled = slideIndex <= 0;
    nextBtn.disabled = slideIndex >= maxIndex();
    syncDots();
  };

  const applyTransform = () => {
    if (count <= 0) return;
    const step = measureStep();
    track.style.transform = step > 0 ? `translate3d(-${slideIndex * step}px, 0, 0)` : "";
  };

  const goTo = (index, { wrap = false } = {}) => {
    if (count <= 0) return;
    if (wrap) {
      slideIndex = ((index % (maxIndex() + 1)) + maxIndex() + 1) % (maxIndex() + 1);
    } else {
      slideIndex = Math.max(0, Math.min(index, maxIndex()));
    }
    applyTransform();
    syncNav();
  };

  const stopCarousel = () => {
    if (homeEventsCarouselTimer != null) {
      clearInterval(homeEventsCarouselTimer);
      homeEventsCarouselTimer = null;
    }
  };

  const startCarousel = () => {
    stopCarousel();
    if (mqMobileGrid.matches || count <= getHomeEventsPerView() || reduceMotion) return;
    homeEventsCarouselTimer = window.setInterval(() => {
      const next = slideIndex >= maxIndex() ? 0 : slideIndex + 1;
      goTo(next);
    }, EVENTS_CAROUSEL_MS);
  };

  const rebuildDots = () => {
    if (!dotsHost || mqMobileGrid.matches) {
      if (dotsHost) dotsHost.innerHTML = "";
      return;
    }
    dotsHost.innerHTML = "";
  };

  prevBtn.addEventListener("click", () => goTo(slideIndex - 1), { signal: ac.signal });
  nextBtn.addEventListener("click", () => goTo(slideIndex + 1), { signal: ac.signal });

  const onLayoutChange = () => {
    rebuildDots();
    slideIndex = Math.min(slideIndex, maxIndex());
    goTo(slideIndex);
    if (mqMobileGrid.matches) {
      stopCarousel();
    } else {
      startCarousel();
    }
  };

  mqMobileGrid.addEventListener("change", onLayoutChange, { signal: ac.signal });
  window.addEventListener(
    "resize",
    () => {
      goTo(slideIndex);
    },
    { signal: ac.signal },
  );

  goTo(0);
  startCarousel();
}

export async function renderHomeEvents(mount) {
  if (!mount) return;
  destroyHomeEvents();
  homeEventsMount = mount;
  mount.innerHTML = homeEventsSkeletonHtml();

  let events = [];
  try {
    events = await fetchHomeCampaignEvents();
  } catch {
    events = [];
  }

  if (!events.length) {
    mount.innerHTML = "";
    homeEventsMount = null;
    return;
  }

  const locale = getSiteLocale();
  mount.innerHTML = `
    <section class="home-events" aria-labelledby="home-events-heading">
      <h2 id="home-events-heading" class="home-events__title">${escapeHtml(t("homeEventsTitle"))}</h2>
      <div class="home-events__carousel">
        <button type="button" class="home-events__arrow home-events__arrow--prev" aria-label="${escapeHtml(t("homeEventsCarouselPrev"))}">
          ${eventsCarouselArrowSvg("prev")}
        </button>
        <div class="home-events__viewport">
          <div class="home-events__track" role="list">
            ${events.map((ev) => eventCardHtml(ev, locale)).join("")}
          </div>
        </div>
        <button type="button" class="home-events__arrow home-events__arrow--next" aria-label="${escapeHtml(t("homeEventsCarouselNext"))}">
          ${eventsCarouselArrowSvg("next")}
        </button>
      </div>
      <div class="home-events__dots" aria-hidden="true"></div>
    </section>
  `;

  bindHomeEventCards(mount);
  setupEventsCarousel(mount);
  tickHomeEventCountdowns();
  homeEventsCountdownTimer = window.setInterval(tickHomeEventCountdowns, 1000);
}
