<script lang="ts">
  import { slide } from "svelte/transition";
  import { tick } from "svelte";

  let { open = $bindable(false) } = $props();
  let pagefindInstance: { destroy?: () => void } | null = $state(null);
  let pagefindLoaded = $state(false);

  function closeSearch() {
    if (typeof pagefindInstance?.destroy === "function") {
      pagefindInstance.destroy();
      pagefindInstance = null;
    }
    pagefindLoaded = false;
    open = false;
  }

  $effect(() => {
    if (!open) return;
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") closeSearch();
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  });

  $effect(() => {
    if (!open) {
      if (typeof pagefindInstance?.destroy === "function") {
        pagefindInstance.destroy();
        pagefindInstance = null;
      }
      pagefindLoaded = false;
      return;
    }
    if (typeof window === "undefined") return;
    const PagefindUI = (window as unknown as { PagefindUI?: new (opts: Record<string, unknown>) => { destroy: () => void } }).PagefindUI;
    if (!PagefindUI) return;
    let cancelled = false;
    tick().then(() => {
      if (cancelled) return;
      const el = document.getElementById("pagefind-ui");
      if (!el?.isConnected) return;
      try {
        pagefindInstance = new PagefindUI({ element: "#pagefind-ui", showSubResults: true });
        pagefindLoaded = true;
      } catch (_) {
        pagefindInstance = null;
      }
    });
    return () => {
      cancelled = true;
    };
  });
</script>

{#if open}
  <div
    id="search-panel"
    class="border-t border-white/10 bg-zinc-950/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)]">
      <div id="pagefind-ui" class="pagefind-ui-wrapper"></div>
      {#if !pagefindLoaded}
        <div class="pagefind-fallback max-w-xl mx-auto">
          <div class="h-10 bg-black"></div>
        </div>
      {/if}
    </div>
  </div>
{/if}

<style>
  :global(.pagefind-ui-wrapper),
  :global(#pagefind-ui) {
    --pagefind-ui-scale: .7;
    --pagefind-ui-primary: #22c55e;
    --pagefind-ui-text: #e4e4e7;
    --pagefind-ui-background: #000;
    --pagefind-ui-border : #fff;
    --pagefind-ui-border: #3f3f46;
    --pagefind-ui-tag: #3f3f46;
    --pagefind-ui-font: var(--font-body);
    --pagefind-ui-border-width: 2px;
    --pagefind-ui-border-radius: 0;
    --pagefind-ui-border-color: var(--color-link);
    
  }
</style>
