<script lang="ts">
  import { slide } from "svelte/transition";
  import { tick } from "svelte";
  import { goto } from "$app/navigation";
  import Icon from "@iconify/svelte";
  import "$lib/iconify-offline";

  type SearchHit = {
    type: "page" | "post";
    slug: string;
    href: string;
    title: string;
    subtitle: string;
    excerpt: string;
    image: string | null;
    created: string | null;
    isEvent?: boolean;
    eventDate?: string | null;
  };

  let { open = $bindable(false) } = $props();

  let query = $state("");
  let allHits = $state<SearchHit[] | null>(null);
  let loading = $state(false);
  let loadError = $state<string | null>(null);
  let inputEl = $state<HTMLInputElement | null>(null);

  const MAX_RESULTS = 40;

  const normalizedQuery = $derived(query.trim().toLowerCase());
  const tokens = $derived(normalizedQuery.split(/\s+/).filter((t) => t.length > 0));

  // All tokens must match (AND); score by field weight so title hits rank first.
  const results = $derived.by<SearchHit[]>(() => {
    if (!allHits || normalizedQuery.length < 2) return [];
    const scored: { hit: SearchHit; score: number }[] = [];
    for (const h of allHits) {
      const title = h.title.toLowerCase();
      const subtitle = h.subtitle.toLowerCase();
      const excerpt = h.excerpt.toLowerCase();
      const slug = h.slug.toLowerCase();
      let score = 0;
      let allMatch = true;
      for (const tok of tokens) {
        const inTitle = title.includes(tok);
        const inSub = subtitle.includes(tok);
        const inExcerpt = excerpt.includes(tok);
        const inSlug = slug.includes(tok);
        if (!(inTitle || inSub || inExcerpt || inSlug)) {
          allMatch = false;
          break;
        }
        if (inTitle) score += title.startsWith(tok) ? 12 : 8;
        if (inSub) score += 4;
        if (inExcerpt) score += 2;
        if (inSlug) score += 1;
      }
      if (allMatch) scored.push({ hit: h, score });
    }
    scored.sort((a, b) => b.score - a.score);
    return scored.slice(0, MAX_RESULTS).map((s) => s.hit);
  });

  let activeIndex = $state(-1);
  let itemEls = $state<(HTMLAnchorElement | null)[]>([]);
  // Reset cursor whenever the result set changes.
  $effect(() => {
    void results;
    activeIndex = -1;
  });
  // Keep the keyboard-selected item visible.
  $effect(() => {
    if (activeIndex >= 0) itemEls[activeIndex]?.scrollIntoView({ block: "nearest" });
  });

  function escapeHtml(s: string): string {
    return s
      .replace(/&/g, "&amp;")
      .replace(/</g, "&lt;")
      .replace(/>/g, "&gt;");
  }
  function highlight(text: string): string {
    const safe = escapeHtml(text);
    if (tokens.length === 0) return safe;
    const pattern = tokens
      .map((t) => t.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))
      .join("|");
    return safe.replace(
      new RegExp(`(${pattern})`, "gi"),
      '<mark class="bg-wald-100 text-inherit rounded-xs px-0.5">$1</mark>',
    );
  }

  async function loadIndex() {
    if (allHits || loading) return;
    loading = true;
    loadError = null;
    try {
      const res = await fetch("/api/search-index");
      if (!res.ok) throw new Error("search index fetch failed");
      const data = (await res.json()) as { hits: SearchHit[] };
      allHits = data.hits ?? [];
    } catch (e) {
      loadError = e instanceof Error ? e.message : String(e);
      allHits = [];
    } finally {
      loading = false;
    }
  }

  function closeSearch() {
    open = false;
  }

  function formatDate(iso: string | null | undefined): string {
    if (!iso) return "";
    const d = new Date(iso);
    if (Number.isNaN(d.getTime())) return "";
    return d.toLocaleDateString("de-DE", { day: "2-digit", month: "long", year: "numeric" });
  }

  $effect(() => {
    if (!open) return;
    void loadIndex();
    tick().then(() => inputEl?.focus());
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") {
        closeSearch();
        return;
      }
      const n = results.length;
      if (n === 0) return;
      if (e.key === "ArrowDown") {
        e.preventDefault();
        activeIndex = (activeIndex + 1) % n;
      } else if (e.key === "ArrowUp") {
        e.preventDefault();
        activeIndex = (activeIndex - 1 + n) % n;
      } else if (e.key === "Enter" && activeIndex >= 0) {
        e.preventDefault();
        const href = results[activeIndex]?.href;
        if (href) {
          closeSearch();
          void goto(href);
        }
      }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  });
</script>

{#if open}
  <div
    id="search-panel"
    class="border-t border-white/30 bg-white/95 backdrop-blur overflow-hidden"
    role="region"
    aria-label="Suche"
    in:slide={{ duration: 200 }}
    out:slide={{ duration: 150 }}
  >
    <div class="container-custom py-4 overflow-auto max-h-[calc(100vh-120px)]">
      <label class="relative block max-w-xl mx-auto">
        <span class="sr-only">Suche</span>
        <span class="pointer-events-none absolute top-1/2 left-3 -translate-y-1/2 text-stein-500">
          <Icon icon="lucide:search" class="h-5 w-5" />
        </span>
        <input
          bind:this={inputEl}
          type="search"
          bind:value={query}
          placeholder="Seiten und Beiträge durchsuchen…"
          class="w-full rounded-xs border border-stein-300 bg-white py-3 pl-10 pr-10 text-sm focus:border-stein-500 focus:outline-none"
        />
        {#if query}
          <button
            type="button"
            onclick={() => (query = "")}
            aria-label="Eingabe leeren"
            class="absolute top-1/2 right-2 -translate-y-1/2 rounded-xs p-1 text-stein-500 hover:bg-stein-100 hover:text-stein-900"
          >
            <Icon icon="lucide:x" class="h-4 w-4" />
          </button>
        {/if}
      </label>

      <div class="max-w-xl mx-auto mt-4 text-sm">
        <p class="sr-only" role="status" aria-live="polite">
          {#if normalizedQuery.length >= 2 && !loading && !loadError}
            {results.length === 0 ? "Keine Treffer." : `${results.length} Treffer.`}
          {/if}
        </p>
        {#if loading}
          <p class="text-stein-500 text-center py-2">Lade Suchindex…</p>
        {:else if loadError}
          <p class="text-fire-600 text-center py-2">Suche nicht verfügbar: {loadError}</p>
        {:else if normalizedQuery.length < 2}
          <p class="text-stein-500 text-center py-2">Mindestens 2 Zeichen eingeben.</p>
        {:else if results.length === 0}
          <p class="text-stein-500 text-center py-2">Keine Treffer.</p>
        {:else}
          <p class="text-stein-400 text-xs mb-2">
            {results.length === MAX_RESULTS ? `${MAX_RESULTS}+ Treffer` : `${results.length} Treffer`} · ↑↓ zum Wählen, ⏎ zum Öffnen
          </p>
          <ul class="divide-y divide-stein-200">
            {#each results as hit, i}
              <li>
                <a
                  bind:this={itemEls[i]}
                  href={hit.href}
                  onclick={closeSearch}
                  onmouseenter={() => (activeIndex = i)}
                  aria-current={i === activeIndex ? "true" : undefined}
                  class="flex items-start gap-3 py-3 rounded-xs px-2 -mx-2 no-underline {i === activeIndex ? 'bg-stein-100' : 'hover:bg-stein-50'}"
                >
                  {#if hit.image}
                    <img
                      src={hit.image}
                      alt=""
                      class="w-20 h-12 object-cover shrink-0 rounded-xs border border-stein-200"
                      loading="lazy"
                    />
                  {:else}
                    <span class="w-20 h-12 shrink-0 bg-stein-100 rounded-xs border border-stein-200 flex items-center justify-center text-stein-400">
                      <Icon icon={hit.type === "post" ? "lucide:file-text" : "lucide:file"} class="h-5 w-5" />
                    </span>
                  {/if}
                  <div class="min-w-0 flex-1">
                    <div class="flex items-center gap-2 text-[.65rem] uppercase tracking-wide text-stein-500">
                      <span>{hit.type === "post" ? "Beitrag" : "Seite"}</span>
                      {#if hit.isEvent && hit.eventDate}
                        <span class="text-wald-700">{formatDate(hit.eventDate)}</span>
                      {:else if hit.created}
                        <span>{formatDate(hit.created)}</span>
                      {/if}
                    </div>
                    <div class="font-medium text-stein-900 truncate">{@html highlight(hit.title)}</div>
                    {#if hit.excerpt}
                      <div class="text-xs text-stein-600 line-clamp-2">{@html highlight(hit.excerpt)}</div>
                    {/if}
                  </div>
                </a>
              </li>
            {/each}
          </ul>
        {/if}
      </div>
    </div>
  </div>
{/if}
