<!--
    Component: SearchBar

    Search input with popover dropdown for results/suggestions
    - Features keyboard navigation (ArrowDown/Up/Enter) and auto-focus prevention on popover open.
    - The input field serves as the popover trigger.
-->
<script lang="ts">
import { Input } from '$shared/shadcn/ui/input';
import { Label } from '$shared/shadcn/ui/label';
import {
    Content as PopoverContent,
    Root as PopoverRoot,
    Trigger as PopoverTrigger,
} from '$shared/shadcn/ui/popover';
import { useId } from 'bits-ui';
import type { Snippet } from 'svelte';

interface Props {
    /** Unique identifier for the input element */
    id?: string;
    /** Current search value (bindable) */
    value: string;
    /** Additional CSS classes for the container */
    class?: string;
    /** Placeholder text for the input */
    placeholder?: string;
    /** Optional label displayed above the input */
    label?: string;
    /** Content to render inside the popover (receives unique content ID) */
    children: Snippet<[{ id: string }]> | undefined;
}

let {
    id = 'search-bar',
    value = $bindable(),
    class: className,
    placeholder,
    label,
    children,
}: Props = $props();

let open = $state(false);
let triggerRef = $state<HTMLInputElement>(null!);
// svelte-ignore state_referenced_locally
const contentId = useId(id);

function handleKeyDown(event: KeyboardEvent) {
    if (event.key === 'ArrowDown' || event.key === 'ArrowUp' || event.key === 'Enter') {
        event.preventDefault();
    }
}

function handleInputClick() {
    open = true;
}
</script>

<PopoverRoot bind:open>
    <PopoverTrigger bind:ref={triggerRef}>
        {#snippet child({ props })}
            {@const { onclick, ...rest } = props}
            <div {...rest} class="flex flex-row flex-1 w-full">
                {#if label}
                    <Label for={id}>{label}</Label>
                {/if}
                <Input
                    id={id}
                    placeholder={placeholder}
                    bind:value={value}
                    onkeydown={handleKeyDown}
                    onclick={handleInputClick}
                    class="flex flex-row flex-1"
                />
            </div>
        {/snippet}
    </PopoverTrigger>

    <PopoverContent
        onOpenAutoFocus={e => e.preventDefault()}
        onInteractOutside={(e => {
            if (e.target === triggerRef) {
                e.preventDefault();
            }
        })}
        class="w-(--bits-popover-anchor-width) min-w-(--bits-popover-anchor-width)"
    >
        {@render children?.({ id: contentId })}
    </PopoverContent>
</PopoverRoot>
