<script lang="ts">
	import { onMount } from 'svelte';
	import { addRecentSearch } from '$lib/stores/recentSearches';

	interface Props {
		value: string;
		recentSearches?: string[];
	}

	let { value = $bindable(), recentSearches = [] }: Props = $props();

	// Internal state for immediate user input
	let inputValue = $state(value);
	let searchInput: HTMLInputElement;
	let isFocused = $state(false);

	// Show dropdown when focused, empty input, and have recent searches
	let showRecentSearches = $derived(isFocused && inputValue === '' && recentSearches.length > 0);

	// Debounce: update bound value 300ms after user stops typing
	$effect(() => {
		const timeout = setTimeout(() => {
			// Only trigger when >= 2 chars OR cleared to empty
			if (inputValue.length >= 2 || inputValue.length === 0) {
				value = inputValue;
			}
		}, 300);

		return () => clearTimeout(timeout);
	});

	// Sync inputValue if parent changes value externally
	$effect(() => {
		if (value !== inputValue && (value === '' || inputValue === '')) {
			inputValue = value;
		}
	});

	// "/" keyboard shortcut - use native listener to avoid Svelte 5 bug
	onMount(() => {
		function handleKeydown(e: KeyboardEvent) {
			// Skip if already in an input or textarea
			if (e.target instanceof HTMLInputElement || e.target instanceof HTMLTextAreaElement) {
				return;
			}

			if (e.key === '/') {
				e.preventDefault();
				searchInput?.focus();
			}
		}

		document.addEventListener('keydown', handleKeydown);
		return () => document.removeEventListener('keydown', handleKeydown);
	});

	function handleFocus() {
		isFocused = true;
	}

	function handleBlur() {
		isFocused = false;
		// Add to recent searches on blur if value is long enough
		if (inputValue.length >= 2) {
			addRecentSearch(inputValue);
		}
	}

	function selectRecentSearch(search: string) {
		inputValue = search;
		value = search;
		isFocused = false;
	}
</script>

<div class="relative">
	<input
		bind:this={searchInput}
		bind:value={inputValue}
		onfocus={handleFocus}
		onblur={handleBlur}
		type="text"
		placeholder='Search entries... (press "/")'
		class="w-full px-4 py-2 border border-gray-200 rounded-lg text-base focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
	/>

	{#if showRecentSearches}
		<div
			class="absolute top-full left-0 right-0 mt-1 bg-white border border-gray-200 rounded-lg shadow-lg z-20"
		>
			<div class="px-3 py-2 text-xs font-medium text-gray-500 uppercase tracking-wide border-b border-gray-100">
				Recent searches
			</div>
			{#each recentSearches as search}
				<button
					type="button"
					onmousedown={() => selectRecentSearch(search)}
					class="w-full px-3 py-2 text-left text-sm text-gray-700 hover:bg-gray-50 focus:bg-gray-50 focus:outline-none"
				>
					{search}
				</button>
			{/each}
		</div>
	{/if}
</div>
