<script lang="ts">
  import { slide } from "svelte/transition";
  import { tick } from "svelte";
  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 normalizedQuery = $derived(query.trim().toLowerCase());
  const results = $derived.by<SearchHit[]>(() => {
    if (!allHits || normalizedQuery.length < 2) return [];
    const q = normalizedQuery;
    return allHits
      .filter((h) => {
        const hay = `${h.title} ${h.subtitle} ${h.excerpt} ${h.slug}`.toLowerCase();
        return hay.includes(q);
      })
      .slice(0, 40);
  });

  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();
    };
    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="mdi:magnify" 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="mdi:close" class="h-4 w-4" />
          </button>
        {/if}
      </label>

      <div class="max-w-xl mx-auto mt-4 text-sm">
        {#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}
          <ul class="divide-y divide-stein-200">
            {#each results as hit}
              <li>
                <a
                  href={hit.href}
                  onclick={closeSearch}
                  class="flex items-start gap-3 py-3 hover:bg-stein-50 rounded-xs px-2 -mx-2 no-underline"
                >
                  {#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" ? "mdi:file-document-outline" : "mdi:file-outline"} 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">{hit.title}</div>
                    {#if hit.excerpt}
                      <div class="text-xs text-stein-600 line-clamp-2">{hit.excerpt}</div>
                    {/if}
                  </div>
                </a>
              </li>
            {/each}
          </ul>
        {/if}
      </div>
    </div>
  </div>
{/if}
