<script lang="ts">
  import { page } from '$app/state';
  import { goto } from '$app/navigation';
  import { untrack } from 'svelte';
  import { Search } from 'lucide-svelte';

  let value = $state(page.url.searchParams.get('q') ?? '');
  let timeout: ReturnType<typeof setTimeout> | null = null;

  // Re-sync local value when the URL changes from outside (back/forward,
  // result-link clicks). Read `value` non-reactively to avoid a feedback
  // loop where the user's typing would race against the URL re-read.
  $effect(() => {
    const fromUrl = page.url.searchParams.get('q') ?? '';
    if (fromUrl !== untrack(() => value)) value = fromUrl;
  });

  function navigate(next: string) {
    const onSearchPage = page.url.pathname.startsWith('/search');
    const trimmed = next.trim();
    // keepFocus: SvelteKit blurs the active element on navigation by default.
    // For a typeahead-style URL update we want the user to keep typing
    // without re-clicking the input every 250 ms.
    if (trimmed === '') {
      if (onSearchPage) goto('/search', { replaceState: true, keepFocus: true });
      return;
    }
    goto(`/search?q=${encodeURIComponent(trimmed)}`, {
      replaceState: onSearchPage,
      keepFocus: true,
    });
  }

  function onInput() {
    if (timeout) clearTimeout(timeout);
    timeout = setTimeout(() => {
      timeout = null;
      navigate(value);
    }, 250);
  }

  function onKey(e: KeyboardEvent) {
    if (e.key === 'Escape') {
      e.preventDefault();
      value = '';
      if (timeout) {
        clearTimeout(timeout);
        timeout = null;
      }
      navigate('');
    }
  }
</script>

<label class="relative block w-full max-w-md">
  <Search
    size={14}
    strokeWidth={1.5}
    aria-hidden="true"
    class="pointer-events-none absolute left-2 top-1/2 -translate-y-1/2 text-text-secondary"
  />
  <input
    type="search"
    placeholder="Search"
    aria-label="Search"
    bind:value
    oninput={onInput}
    onkeydown={onKey}
    class="w-full rounded border border-border bg-surface pl-7 pr-3 py-1 text-sm focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent"
  />
</label>
