import { t } from "../config/site.js";
import { debounce } from "../utils/debounce.js";
import { escapeHtml } from "../utils/escape-html.js";
import {
  loadSponsorsJson,
  buildSponsorCardHtml,
  attachSponsorCardBehaviors,
  filterSponsorCardsInRoot,
} from "./sponsor-grid.js";

const DEBOUNCE_MS = 240;

const PALETTE_GRID_CLASS =
  "grid grid-cols-2 gap-3 sm:grid-cols-3 sm:gap-4 md:grid-cols-4 lg:grid-cols-4 xl:grid-cols-5";

let mount = null;

let panel = null;

let gridHost = null;

let input = null;

let emptyEl = null;

let debouncedEmit = null;

function dispatchSearch(q) {
  document.dispatchEvent(new CustomEvent("site:search", { detail: { query: q } }));
}

function syncPaletteGeometry() {
  const header = document.querySelector(".site-header");
  const bar = document.querySelector(".site-header__bar");
  const searchBtn = document.querySelector("#site-search-trigger");
  const toolbar = document.querySelector(".site-header__toolbar");
  const isDesktopUnified = window.matchMedia("(min-width: 1024px)").matches;

  const topPx = header ? Math.round(header.getBoundingClientRect().bottom) : 72;
  document.documentElement.style.setProperty("--search-palette-top", `${topPx}px`);

  /* Masaüstü: şerit sidebar sonundan başlar; sidebar gölge/overlay altında kalmaz. */
  if (isDesktopUnified && header) {
    const hr = header.getBoundingClientRect();
    const sidebar = document.getElementById("sidebar");
    const brand = document.querySelector(".site-header__brand");
    const sideRight = sidebar
      ? Math.round(sidebar.getBoundingClientRect().right)
      : brand
        ? Math.round(brand.getBoundingClientRect().right)
        : Math.round(hr.left);
    const left = sideRight;
    const width = Math.round(Math.max(220, hr.right - left));
    document.documentElement.style.setProperty("--search-palette-left", `${left}px`);
    document.documentElement.style.setProperty("--search-palette-width", `${width}px`);
    document.documentElement.style.setProperty("--search-palette-backdrop-left", `${left}px`);
    return;
  }

  document.documentElement.style.setProperty("--search-palette-backdrop-left", "0px");

  const sr = searchBtn?.getBoundingClientRect();
  const tr = toolbar?.getBoundingClientRect();
  const searchVisible = Boolean(sr && sr.width > 0 && sr.height > 0);
  const toolbarVisible = Boolean(tr && tr.width > 0);

  if (searchVisible && toolbarVisible) {
    const left = Math.round(sr.left);
    const width = Math.round(Math.max(0, tr.right - sr.left));
    document.documentElement.style.setProperty("--search-palette-left", `${left}px`);
    document.documentElement.style.setProperty("--search-palette-width", `${Math.max(220, width)}px`);
    return;
  }

  if (bar) {
    const br = bar.getBoundingClientRect();
    document.documentElement.style.setProperty("--search-palette-left", `${Math.round(br.left)}px`);
    document.documentElement.style.setProperty("--search-palette-width", `${Math.round(br.width)}px`);
    return;
  }

  if (header) {
    const r = header.getBoundingClientRect();
    document.documentElement.style.setProperty("--search-palette-left", `${Math.round(r.left)}px`);
    document.documentElement.style.setProperty("--search-palette-width", `${Math.round(r.width)}px`);
  } else {
    document.documentElement.style.setProperty("--search-palette-left", "0px");
    document.documentElement.style.setProperty("--search-palette-width", "100%");
  }
}

function syncEmptyState() {
  if (!gridHost || !emptyEl) return;
  const q = (input?.value || "").trim();
  const cards = gridHost.querySelectorAll(".sponsor-card");
  const visible = [...cards].filter((el) => !el.classList.contains("hidden")).length;
  const show = Boolean(q) && visible === 0 && cards.length > 0;
  emptyEl.classList.toggle("hidden", !show);
}

function cacheRefs() {
  panel = mount?.querySelector("#search-palette") ?? null;
  gridHost = mount?.querySelector("#search-palette-grid") ?? null;
  input = mount?.querySelector("#search-palette-input") ?? null;
  emptyEl = mount?.querySelector("#search-palette-empty") ?? null;
}

function setAriaOpen(open) {
  const el = mount?.querySelector("#search-palette");
  if (el) {
    el.setAttribute("aria-hidden", open ? "false" : "true");
  }
}

export function closeSearchPalette() {
  if (!panel?.classList.contains("search-palette--open")) return;
  input?.blur();
  panel.classList.remove("search-palette--open");
  setAriaOpen(false);
  window.setTimeout(() => {
    document.body.classList.remove("overflow-hidden");
    document.body.classList.remove("search-palette-open");
  }, 280);
}

async function loadGridOnce() {
  if (!gridHost) return;
  if (gridHost.dataset.loaded === "1") return;
  gridHost.innerHTML = `
    <div class="flex flex-col items-center justify-center gap-2 py-10 text-slate-500" role="status">
      <div class="h-8 w-8 animate-spin rounded-full border-2 border-accent/25 border-t-accent" aria-hidden="true"></div>
      <span class="text-xs sm:text-sm">${escapeHtml(t("searchPaletteLoading"))}</span>
    </div>`;
  try {
    const all = await loadSponsorsJson();
    gridHost.innerHTML = `<div class="${PALETTE_GRID_CLASS}">${all.map((item) => buildSponsorCardHtml(item)).join("")}</div>`;
    gridHost.dataset.loaded = "1";
    attachSponsorCardBehaviors(gridHost);
  } catch {
    gridHost.removeAttribute("data-loaded");
    gridHost.innerHTML = `
      <div class="rounded-xl border border-red-500/30 bg-red-950/20 p-4 text-center text-sm text-red-200">
        ${escapeHtml(t("sponsorLoadError"))}
      </div>`;
  }
}

export function openSearchPalette() {
  if (!panel) return;
  if (panel.classList.contains("search-palette--open")) return;

  syncPaletteGeometry();
  document.body.classList.add("overflow-hidden");
  document.body.classList.add("search-palette-open");
  panel.classList.add("search-palette--open");
  setAriaOpen(true);
  requestAnimationFrame(() => {
    syncPaletteGeometry();
  });

  void (async () => {
    await loadGridOnce();
    syncPaletteGeometry();
    const q = (input?.value || "").trim().toLowerCase();
    if (gridHost) filterSponsorCardsInRoot(gridHost, q);
    syncEmptyState();
    requestAnimationFrame(() => {
      const v = input?.value?.trim() || "";
      mount?.querySelector("#search-palette-clear")?.classList.toggle("hidden", !v);
      input?.focus();
    });
  })();
}

function mountPaletteDom() {
  if (!mount) return;
  mount.innerHTML = `
    <div id="search-palette" class="fixed inset-0 z-[138]" role="dialog" aria-modal="true" aria-hidden="true" aria-label="${escapeHtml(t("searchPaletteAria"))}">
      <div
        class="search-palette__backdrop absolute inset-0 z-0 backdrop-blur-[2px]"
        style="background:rgba(14,19,28,0.64)"
        data-palette-backdrop
        aria-hidden="true"
      ></div>
      <div
        class="search-palette__anchor fixed z-10 box-border max-w-[100vw]"
        style="top:var(--search-palette-top,4.5rem);left:var(--search-palette-left,0);width:var(--search-palette-width,100%)"
      >
        <div
          id="search-palette-panel"
          class="search-palette__sheet flex max-h-[min(52vh,520px)] w-full flex-col overflow-hidden border-b border-white/[0.08] shadow-[0_16px_40px_-18px_rgba(0,0,0,0.55)] sm:max-h-[min(58vh,600px)]"
          style="background:var(--site-surface-gradient)"
        >
          <div class="search-palette__toolbar flex shrink-0 items-center gap-2 px-3 py-2.5 sm:gap-3 sm:px-6 sm:py-3 lg:px-8">
            <svg class="pointer-events-none h-4 w-4 shrink-0 text-accent-bright/55 sm:h-[1.1rem] sm:w-[1.1rem]" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/></svg>
            <input
              type="search"
              id="search-palette-input"
              autocomplete="off"
              placeholder="${escapeHtml(t("headerSearchPlaceholder"))}"
              class="k-input search-palette-input min-w-0 flex-1 rounded-xl border border-white/[0.08] py-2 pl-3 pr-2 text-sm text-slate-100 placeholder:text-slate-500 outline-none transition focus:border-accent-bright/38 sm:text-base"
              style="background:var(--site-raised-gradient);box-shadow:inset 0 1px 3px rgba(0,0,0,0.35)"
            />
            <button type="button" id="search-palette-clear" class="k-btn k-btn--icon k-btn--ghost search-palette-clear hidden shrink-0 rounded-lg p-1.5 text-slate-400 transition hover:bg-[rgba(22,119,255,0.16)] hover:text-white" aria-label="${escapeHtml(t("headerSearchClear"))}">
              <svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg>
            </button>
            <button type="button" id="search-palette-close" class="k-btn k-btn--icon btn-site-icon h-9 w-9 shrink-0 rounded-xl" aria-label="${escapeHtml(t("searchPaletteClose"))}">
              <svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg>
            </button>
          </div>
          <div id="search-palette-scroll" class="search-palette__scroll site-scrollbar min-h-0 flex-1 overflow-y-auto overscroll-contain px-3 pb-4 pt-3 sm:px-6 sm:pb-5 sm:pt-4 lg:px-8">
            <div id="search-palette-grid" class="min-h-[80px]"></div>
            <div id="search-palette-empty" class="mt-3 hidden rounded-lg border border-white/10 px-3 py-2.5 text-center text-xs text-slate-400 ring-1 ring-white/[0.06] sm:text-sm" style="background:var(--site-raised-gradient)" role="status">
              ${escapeHtml(t("sponsorEmptySearch"))}
            </div>
          </div>
        </div>
      </div>
    </div>`;
  cacheRefs();
}

function onResizeWhileOpen() {
  if (panel?.classList.contains("search-palette--open")) {
    syncPaletteGeometry();
  }
}

function onMountInput(e) {
  const el = e.target;
  if (!(el instanceof HTMLInputElement) || el.id !== "search-palette-input") return;
  const q = el.value.trim().toLowerCase();
  if (gridHost) filterSponsorCardsInRoot(gridHost, q);
  syncEmptyState();
  debouncedEmit?.(q);
  const v = el.value.trim();
  mount?.querySelector("#search-palette-clear")?.classList.toggle("hidden", !v);
}

function onMountClick(e) {
  const t = e.target;
  if (!(t instanceof Element)) return;
  if (t.closest("#search-palette-clear")) {
    e.preventDefault();
    if (input) input.value = "";
    if (gridHost) filterSponsorCardsInRoot(gridHost, "");
    syncEmptyState();
    dispatchSearch("");
    mount?.querySelector("#search-palette-clear")?.classList.add("hidden");
    input?.focus();
    return;
  }
  if (t.closest("#search-palette-close") || t.closest("[data-palette-backdrop]")) {
    e.preventDefault();
    closeSearchPalette();
    return;
  }
  if (t.closest("a.sponsor-card-link")) {
    closeSearchPalette();
  }
}

function onDocumentKeydown(e) {
  if (e.key === "Escape" && panel?.classList.contains("search-palette--open")) {
    e.preventDefault();
    closeSearchPalette();
    return;
  }
  if ((e.metaKey || e.ctrlKey) && (e.key === "k" || e.key === "K")) {
    const el = e.target;
    if (el instanceof HTMLElement) {
      const tag = el.tagName;
      if (tag === "INPUT" || tag === "TEXTAREA" || el.isContentEditable) return;
    }
    e.preventDefault();
    openSearchPalette();
  }
}

function onBodyClickTrigger(e) {
  const t = e.target;
  if (!(t instanceof Element)) return;
  if (t.closest("#site-search-trigger") || t.closest("#site-search-trigger-mobile")) {
    e.preventDefault();
    openSearchPalette();
  }
}

export function remountSearchPaletteForLocale() {
  closeSearchPalette();
  if (!mount) return;
  mount.innerHTML = "";
  gridHost = null;
  input = null;
  panel = null;
  emptyEl = null;
  mountPaletteDom();
}

export function initSearchPalette() {
  mount = document.getElementById("search-palette-root");
  if (!mount) return;

  debouncedEmit = debounce((q) => dispatchSearch(q), DEBOUNCE_MS);

  if (!mount.dataset.paletteEvents) {
    mount.dataset.paletteEvents = "1";
    document.body.addEventListener("click", onBodyClickTrigger);
    document.addEventListener("keydown", onDocumentKeydown);
    mount.addEventListener("input", onMountInput);
    mount.addEventListener("click", onMountClick);
    window.addEventListener("resize", onResizeWhileOpen);
    window.addEventListener("orientationchange", onResizeWhileOpen);
  }

  if (!mount.querySelector("#search-palette")) {
    mountPaletteDom();
  }

  globalThis.__siteOpenSearchPalette = openSearchPalette;
  globalThis.__siteCloseSearchPalette = closeSearchPalette;
  globalThis.__siteSyncSearchPaletteGeometry = syncPaletteGeometry;
}
