import { showToast } from "./toast.js";
import { SOCIAL } from "../data/social.js";
import { t, dataJsonUrl } from "../config/site.js";
import { bindTrackClick } from "../utils/track-click.js";
import {
  SPONSOR_BADGE_ANA,
  normalizeSponsorBadge,
  sponsorBadgeLabelKey,
  sponsorHomeSectionId,
  sponsorHomeSectionTitleKey,
} from "../constants/sponsor-badges.js";

let searchQuery = "";

let sponsorGridMount = null;

function onSearch(e) {
  searchQuery = (e.detail && e.detail.query) || "";
  const r = sponsorGridMount;
  if (r) {
    applyFilter(r);
    updateGridStats(r);
  }
}

/** @type {object[] | null} */
let sponsorsMemoryCache = null;

/** @type {Promise<object[]> | null} */
let sponsorsLoadPromise = null;

async function loadSponsors() {
  if (sponsorsMemoryCache) return sponsorsMemoryCache;
  if (!sponsorsLoadPromise) {
    sponsorsLoadPromise = (async () => {
      const res = await fetch(dataJsonUrl("sponsors.json"), { cache: "default" });
      if (!res.ok) throw new Error("Sponsor listesi y���klenemedi");
      const raw = await res.json();
      const list = Array.isArray(raw)
        ? raw.map((item) => ({
            ...item,
            badge: normalizeSponsorBadge(item?.badge),
          }))
        : [];
      sponsorsMemoryCache = list;
      return list;
    })().finally(() => {
      sponsorsLoadPromise = null;
    });
  }
  return sponsorsLoadPromise;
}

function escapeHtml(s) {
  return String(s)
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/"/g, "&quot;");
}

function sponsorHeadingVariant(opts = {}) {
  const v = opts.variant != null ? String(opts.variant).trim() : "";
  if (v === "ana-sponsorlar" || v === "default") return v;
  const id = String(opts.id || "").toLowerCase();
  if (id.includes("ana-sponsor")) return "ana-sponsorlar";
  return "default";
}

function splitSponsorSectionTitle(title) {
  const raw = String(title || "").trim();
  const lastSpace = raw.lastIndexOf(" ");
  if (lastSpace <= 0) return { lead: raw, accent: "" };
  return { lead: raw.slice(0, lastSpace), accent: raw.slice(lastSpace + 1) };
}

function sponsorSectionTitlePartsHtml(title) {
  const { lead, accent } = splitSponsorSectionTitle(title);
  if (!accent) {
    return `<span class="sponsor-section-heading__part sponsor-section-heading__part--solo">${escapeHtml(lead)}</span>`;
  }
  return `<span class="sponsor-section-heading__part sponsor-section-heading__part--lead">${escapeHtml(lead)}</span><span class="sponsor-section-heading__part sponsor-section-heading__part--accent">${escapeHtml(accent)}</span>`;
}

export function sponsorCategoryHeadingHtml(title, opts = {}) {
  const tag = opts.tag === "h3" ? "h3" : "h1";
  const id =
    opts.id != null && String(opts.id).trim() !== "" ? String(opts.id) : "sponsor-category-heading";
  const variant = sponsorHeadingVariant(opts);
  const variantClass =
    variant !== "default" ? ` sponsor-section-heading--${variant}` : " sponsor-section-heading--default";
  return `
    <div class="sponsor-section-heading k-section${variantClass}">
      <${tag} id="${escapeHtml(id)}" class="sponsor-section-heading__title">${sponsorSectionTitlePartsHtml(title)}</${tag}>
      <div class="sponsor-section-heading__rule" aria-hidden="true"><span class="sponsor-section-heading__rule-dot"></span></div>
    </div>`;
}

function sponsorHref(item) {
  const u = item.url != null ? String(item.url).trim() : "";
  return u || "#";
}

function hasLogo(item) {
  return Boolean(item.logo && String(item.logo).trim() !== "");
}

function promoLines(item) {
  if (Array.isArray(item.promo) && item.promo.length) {
    return item.promo.slice(0, 4);
  }
  const parts = (item.description || "")
    .split(/[.!?]\s*/)
    .map((x) => x.trim())
    .filter(Boolean)
    .slice(0, 3);
  return parts.length ? parts : [item.title];
}

function skeletonBlock() {
  const cell = `
    <div class="relative flex h-full min-h-[11.5rem] flex-col overflow-hidden rounded-xl border border-white/[0.08] bg-[#1e2739] p-2.5 shadow-panel ring-1 ring-white/[0.04] sm:min-h-[304px] sm:rounded-[1.15rem] sm:p-5">
      <div class="skeleton-shimmer mx-auto h-7 w-[70%] rounded-md bg-white/[0.07] sm:h-9 sm:w-28 sm:rounded-lg"></div>
      <div class="mt-3 flex flex-1 flex-col items-center gap-1.5 sm:mt-5 sm:gap-2.5">
        <div class="skeleton-shimmer h-2.5 w-[88%] rounded bg-white/[0.07] sm:h-3.5 sm:rounded-md"></div>
        <div class="skeleton-shimmer hidden h-3.5 w-[72%] rounded-md bg-white/[0.06] sm:block"></div>
      </div>
      <div class="skeleton-shimmer mt-auto h-8 w-full rounded-lg bg-white/[0.09] sm:h-11 sm:rounded-xl"></div>
    </div>`;
  return `<div class="${GRID_COLS}" aria-busy="true" aria-label="${t("skeletonLoading")}">${Array(9).fill(cell).join("")}</div>`;
}

function filterByBadge(all, badgeFilter) {
  if (!badgeFilter) return [...all];
  const norm = (b) => normalizeSponsorBadge(b) ?? b;
  if (Array.isArray(badgeFilter)) {
    const keys = new Set(badgeFilter.map((b) => norm(b)));
    return all.filter((x) => x.badge && keys.has(x.badge));
  }
  const key = norm(badgeFilter);
  return all.filter((x) => x.badge === key);
}

function flattenByBadgeOrder(list, badgeOrder) {
  const out = [];
  for (const b of badgeOrder) {
    out.push(...list.filter((x) => x.badge === b));
  }
  return out;
}

const GRID_COLS =
  "sponsor-grid grid grid-cols-3 gap-2 sm:gap-4 md:gap-6 lg:grid-cols-4";

const CTA_CHEVRON = `<svg class="hidden h-3.5 w-3.5 shrink-0 opacity-70 transition-transform duration-300 ease-out group-hover:translate-x-0.5 group-hover:opacity-100 sm:block sm:h-4 sm:w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.25" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M9 5l7 7-7 7"/></svg>`;

function groupedSectionsHtml(list, badgeOrder, sectionTitleKey = null) {
  const parts = [];
  for (const badge of badgeOrder) {
    const group = list.filter((x) => x.badge === badge);
    if (!group.length) continue;
    const titleKey = sectionTitleKey || sponsorHomeSectionTitleKey(badge);
    const title = titleKey ? t(titleKey) : badge;
    const sid = sponsorHomeSectionId(badge);
    parts.push(`
      <section class="mb-10 last:mb-0" aria-labelledby="${sid}">
        ${sponsorCategoryHeadingHtml(title, {
          id: sid,
          tag: "h3",
          variant: badge === SPONSOR_BADGE_ANA ? "ana-sponsorlar" : "default",
        })}
        <div class="${GRID_COLS}">
          ${group.map(cardHtml).join("")}
        </div>
      </section>
    `);
  }
  return parts.join("");
}

function logoMarqueeHtml(items) {
  if (!items.length) return "";
  const cell = (item) => {
    const href = sponsorHref(item);
    if (hasLogo(item)) {
      return `<a href="${escapeHtml(href)}" class="home-marquee-item" rel="noopener sponsored noreferrer" target="_blank" aria-label="${escapeHtml(item.title)}">
        <img src="${escapeHtml(item.logo)}" alt="" class="home-marquee-logo-img" loading="lazy" decoding="async" />
      </a>`;
    }
    return `<a href="${escapeHtml(href)}" class="home-marquee-item home-marquee-item--label" rel="noopener sponsored noreferrer" target="_blank">${escapeHtml(item.title)}</a>`;
  };
  const row = items.map((item) => cell(item)).join("");
  return `
    <div class="home-logo-marquee" role="region" aria-label="${escapeHtml(t("navAnaSponsors"))}">
      <div class="home-logo-marquee__fade home-logo-marquee__fade--left" aria-hidden="true"></div>
      <div class="home-logo-marquee__fade home-logo-marquee__fade--right" aria-hidden="true"></div>
      <div class="home-logo-marquee__inner">
        <div class="flex items-center">${row}</div>
        <div class="flex items-center" aria-hidden="true">${row}</div>
      </div>
    </div>`;
}

export async function renderHomeSponsorLogoMarquee(root, badgeFilter = null) {
  if (!root) return { ok: false };
  try {
    const all = await loadSponsors();
    const list = filterByBadge(all, badgeFilter);
    root.innerHTML = list.length ? logoMarqueeHtml(list) : "";
    return { ok: true, count: list.length };
  } catch {
    root.innerHTML = "";
    return { ok: false };
  }
}

export function renderHomeMobileSocialStrip(target) {
  if (!target) return;
  target.innerHTML = homeMobileSocialStripHtml();
}

function homeMobileSocialStripHtml() {
  if (!SOCIAL.length) return "";
  const items = SOCIAL.map(
    (s, i) => {
      const isLast = i === SOCIAL.length - 1;
      const lastSpan = isLast ? " col-span-2 w-full" : "";
      return `
    <a
      href="${escapeHtml(s.href)}"
      rel="noopener noreferrer"
      target="_blank"
      aria-label="${escapeHtml(s.name)}"
      style="--hs:${i}"
      class="home-social-mobile-link group flex min-h-[4.25rem] min-w-0 flex-col items-center justify-center gap-1.5 rounded-xl px-2 py-2.5 text-center sm:min-h-0 sm:py-2${lastSpan}"
    >
      <span class="home-social-mobile-link__icon h-9 w-9 shrink-0 rounded-lg">
        <svg class="h-[1.125rem] w-[1.125rem]" viewBox="0 0 24 24" aria-hidden="true">${s.icon}</svg>
      </span>
      <span class="home-social-mobile-link__label line-clamp-2 min-w-0 max-w-full text-center text-[12px] font-medium leading-snug sm:text-[13px]">${escapeHtml(s.name)}</span>
    </a>`;
    }
  ).join("");
  return `
    <section class="home-social-mobile-strip lg:hidden" aria-label="${escapeHtml(t("homeSocialStrip"))}">
      <div class="home-social-mobile-strip__box rounded-2xl px-3 py-4">
        <p class="home-social-mobile-strip__title mb-3 text-center text-[10px] font-semibold uppercase">${escapeHtml(t("homeSocialStrip"))}</p>
        <div class="grid grid-cols-2 gap-2">${items}</div>
      </div>
    </section>`;
}

function badgePill(item) {
  const base =
    "sponsor-card-badge absolute left-1/2 top-3 z-10 max-w-[calc(100%-1.5rem)] -translate-x-1/2 whitespace-nowrap rounded-full px-2.5 py-1 text-center text-[10px] font-bold uppercase tracking-[0.12em] text-white shadow-[0_4px_14px_rgba(0,0,0,0.35)] ring-1 ring-white/25 backdrop-blur-sm";
  const labelKey = sponsorBadgeLabelKey(item.badge);
  if (!labelKey) return "";
  const cls = "bg-gradient-to-r from-accent to-accent-muted";
  return `<span class="${base} ${cls}">${escapeHtml(t(labelKey))}</span>`;
}

function cardHtml(item) {
  const href = sponsorHref(item);
  const badge = badgePill(item);

  const lines = promoLines(item)
    .map((line, idx) => {
      const hiddenOnMobile = idx > 0 ? " hidden sm:block" : "";
      const lineClass =
        idx === 0
          ? "line-clamp-3 text-[10px] font-bold leading-snug tracking-tight text-white sm:line-clamp-none sm:text-[15px] sm:leading-[1.35] sm:tracking-[-0.01em] sm:text-base"
          : "text-[11px] font-medium leading-snug text-slate-400/95 sm:text-[13px] sm:leading-relaxed";
      return `<p class="${lineClass}${hiddenOnMobile}">${escapeHtml(line)}</p>`;
    })
    .join("");

  const logoBlock = hasLogo(item)
    ? `<img src="${escapeHtml(item.logo)}" alt="${escapeHtml(item.title)}" width="160" height="48" loading="lazy" decoding="async" fetchpriority="low" class="sponsor-card-logo max-h-[2.25rem] w-auto max-w-[94%] object-contain transition-transform duration-300 ease-out will-change-transform drop-shadow-[0_2px_10px_rgba(0,0,0,0.4)] group-hover:scale-[1.04] sm:max-h-[3.25rem] sm:drop-shadow-[0_4px_16px_rgba(0,0,0,0.45)]" />`
    : `<span class="max-w-full px-0.5 text-center text-[11px] font-bold uppercase leading-tight tracking-tight text-slate-100 sm:text-lg">${escapeHtml(item.title)}</span>`;

  const searchBlob = `${item.title} ${item.description || ""} ${(item.promo || []).join(" ")}`.toLowerCase();

  return `
    <article
      class="sponsor-card group relative isolate flex h-full min-w-0 flex-col overflow-hidden rounded-xl border border-[rgba(22,119,255,0.24)] bg-[#1e2739] shadow-panel ring-1 ring-[rgba(22,119,255,0.12)] transition-[transform,box-shadow,border-color] duration-300 ease-[cubic-bezier(0.22,1,0.36,1)] before:pointer-events-none before:absolute before:inset-x-0 before:top-0 before:z-[1] before:h-px before:bg-gradient-to-r before:from-transparent before:via-[rgba(96,165,250,0.2)] before:to-transparent after:pointer-events-none after:absolute after:inset-0 after:z-[1] after:rounded-xl after:shadow-[inset_0_1px_0_rgba(255,255,255,0.05)] hover:border-[rgba(22,119,255,0.38)] hover:shadow-[0_20px_44px_-18px_rgba(22,119,255,0.15),0_12px_32px_-16px_rgba(0,0,0,0.45)] sm:rounded-[1.15rem] sm:after:rounded-[1.15rem] sm:hover:-translate-y-1 motion-reduce:transform-none motion-reduce:hover:translate-y-0"
      data-title="${escapeHtml(item.title.toLowerCase())}"
      data-desc="${escapeHtml(searchBlob)}"
      data-sponsor-id="${escapeHtml(String(item.id ?? ""))}">
      <div class="pointer-events-none absolute -right-10 -top-14 z-0 hidden h-36 w-36 rounded-full bg-[rgba(22,119,255,0.08)] blur-3xl sm:block sm:-right-16 sm:-top-20 sm:h-56 sm:w-56" aria-hidden="true"></div>
      <div class="pointer-events-none absolute -bottom-14 -left-8 z-0 hidden h-32 w-32 rounded-full bg-[rgba(22,119,255,0.12)] blur-3xl sm:block sm:-bottom-24 sm:-left-12 sm:h-48 sm:w-48" aria-hidden="true"></div>
      <a href="${escapeHtml(href)}" class="k-card k-link k-link--cta sponsor-card-link relative z-10 flex h-full min-h-[11.5rem] flex-1 flex-col items-center px-2 pb-2.5 pt-5 text-center outline-none focus-visible:ring-2 focus-visible:ring-white/30 focus-visible:ring-offset-2 focus-visible:ring-offset-[#1e2739] sm:min-h-[304px] sm:px-6 sm:pb-6 sm:pt-10" rel="noopener sponsored noreferrer" target="_blank" data-sponsor-id="${escapeHtml(String(item.id ?? ""))}" data-track-label="${escapeHtml(item.title)}" aria-label="${escapeHtml(item.title)} ${escapeHtml(t("sponsorVisitAriaSuffix"))}">
        ${badge}
        <div class="sponsor-card-head relative flex min-h-[3.25rem] w-full shrink-0 flex-col items-center justify-center overflow-hidden rounded-lg bg-[rgba(22,119,255,0.12)] px-1.5 py-2.5 transition-[background-color] duration-300 group-hover:bg-[rgba(22,119,255,0.1)] sm:min-h-[5.25rem] sm:rounded-[0.85rem] sm:px-3 sm:py-4">
          ${logoBlock}
        </div>
        <div class="my-0.5 hidden h-px w-10 shrink-0 bg-gradient-to-r from-transparent via-white/12 to-transparent sm:my-1.5 sm:block" aria-hidden="true"></div>
        <div class="sponsor-card-promo flex w-full min-h-0 flex-1 flex-col items-center justify-start gap-1 px-0 py-1.5 sm:gap-2 sm:justify-center sm:px-0.5 sm:py-4">
          ${lines}
        </div>
        <span class="sponsor-card-cta mt-auto flex w-full shrink-0 min-h-[2rem] cursor-pointer items-center justify-center gap-1 rounded-lg px-2 py-2 text-[10px] font-semibold leading-none tracking-wide transition duration-200 active:translate-y-px sm:min-h-0 sm:gap-2 sm:rounded-[0.85rem] sm:px-4 sm:py-[0.95rem] sm:text-sm">
          ${escapeHtml(t("sponsorCta"))}
          ${CTA_CHEVRON}
        </span>
      </a>
    </article>`;
}

function applyFilter(root) {
  const q = searchQuery;
  root.querySelectorAll(".sponsor-card").forEach((el) => {
    const t = el.getAttribute("data-title") || "";
    const d = el.getAttribute("data-desc") || "";
    const match = !q || t.includes(q) || d.includes(q);
    el.classList.toggle("hidden", !match);
  });
}

function updateGridStats(mount) {
  const cards = mount.querySelectorAll(".sponsor-card");
  const visible = [...cards].filter((el) => !el.classList.contains("hidden")).length;
  const total = cards.length;

  const empty = document.getElementById("sponsor-empty-search");
  if (empty) {
    const show = Boolean(searchQuery) && visible === 0 && total > 0;
    empty.classList.toggle("hidden", !show);
  }
}

export async function renderSponsorGrid(root, opts = {}) {
  const {
    badgeFilter = null,
    logoMarquee = false,
    groupSections = false,
    sectionTitleKey = null,
    detachMobileSocial = false,
  } = opts;

  document.removeEventListener("site:search", onSearch);
  document.addEventListener("site:search", onSearch);
  sponsorGridMount = root;

  root.innerHTML = skeletonBlock();

  let list;
  try {
    const all = await loadSponsors();
    list = filterByBadge(all, badgeFilter);
  } catch {
    root.innerHTML = `
      <div class="rounded-2xl border border-red-500/30 bg-red-950/20 p-6 text-center text-sm text-red-200">
        ${escapeHtml(t("sponsorLoadError"))}
      </div>`;
    showToast(t("sponsorListError"), "error");
    return { ok: false };
  }

  const useGrouped =
    groupSections && Array.isArray(badgeFilter) && badgeFilter.length >= 1;
  const marqueeList = useGrouped && Array.isArray(badgeFilter) ? flattenByBadgeOrder(list, badgeFilter) : list;
  const marqueeBlock = logoMarquee && marqueeList.length ? logoMarqueeHtml(marqueeList) : "";
  const showMobileStrip = Boolean(marqueeList.length && (logoMarquee || detachMobileSocial));
  const mobileSocialBlock =
    !detachMobileSocial && showMobileStrip ? homeMobileSocialStripHtml() : "";
  const gridBlock = useGrouped
    ? groupedSectionsHtml(list, badgeFilter, sectionTitleKey)
    : `<div class="${GRID_COLS}" id="sponsor-grid-inner">${list.map(cardHtml).join("")}</div>`;

  root.innerHTML = `
    ${marqueeBlock}
    ${gridBlock}
    ${mobileSocialBlock}
    <div id="sponsor-empty-search" class="mt-4 hidden rounded-xl border border-white/10 bg-brand-50/40 px-4 py-3 text-center text-sm text-slate-400 ring-1 ring-white/[0.06]" role="status">
      ${escapeHtml(t("sponsorEmptySearch"))}
    </div>
    ${
      list.length === 0
        ? `<p class="mt-2 rounded-2xl border border-white/10 bg-brand-50/50 p-6 text-slate-400 ring-1 ring-white/[0.06]">${escapeHtml(t("sponsorEmptySection"))}</p>`
        : ""
    }
  `;

  applyFilter(root);
  updateGridStats(root);
  bindTrackClick(root, ".sponsor-card-link", "sponsor", "data-sponsor-id", "data-track-label");

  root.querySelectorAll("img.sponsor-card-logo").forEach((img) => {
    img.addEventListener("error", () => {
      const wrap = img.closest(".sponsor-card-head");
      if (!wrap || wrap.querySelector(".sponsor-logo-fallback")) return;
      img.classList.add("hidden");
      const alt = img.getAttribute("alt") || "";
      const fb = document.createElement("span");
      fb.className =
        "sponsor-logo-fallback max-w-full text-center text-base font-black uppercase leading-tight tracking-tight text-white sm:text-lg";
      fb.textContent = alt;
      wrap.appendChild(fb);
    });
  });

  return {
    ok: true,
    showMobileSocialStrip: detachMobileSocial && showMobileStrip,
  };
}

export async function loadSponsorsJson() {
  return loadSponsors();
}

export function buildSponsorCardHtml(item) {
  return cardHtml(item);
}

export const SPONSOR_GRID_LAYOUT_CLASS = GRID_COLS;

export function attachSponsorCardBehaviors(root) {
  root.querySelectorAll("img.sponsor-card-logo").forEach((img) => {
    img.addEventListener("error", () => {
      const wrap = img.closest(".sponsor-card-head");
      if (!wrap || wrap.querySelector(".sponsor-logo-fallback")) return;
      img.classList.add("hidden");
      const alt = img.getAttribute("alt") || "";
      const fb = document.createElement("span");
      fb.className =
        "sponsor-logo-fallback max-w-full text-center text-base font-black uppercase leading-tight tracking-tight text-white sm:text-lg";
      fb.textContent = alt;
      wrap.appendChild(fb);
    });
  });
}

export function filterSponsorCardsInRoot(root, query) {
  const q = String(query || "")
    .trim()
    .toLowerCase();
  root.querySelectorAll(".sponsor-card").forEach((el) => {
    const title = el.getAttribute("data-title") || "";
    const desc = el.getAttribute("data-desc") || "";
    const match = !q || title.includes(q) || desc.includes(q);
    el.classList.toggle("hidden", !match);
  });
}
