<script lang="ts">
	import { goto } from '$app/navigation';

	interface Props {
		compact?: boolean;
	}

	let { compact = false }: Props = $props();

	let query = $state('');
	let inputEl: HTMLInputElement;

	function handleSubmit(e: Event) {
		e.preventDefault();
		if (query.trim().length >= 2) {
			goto(`/search?q=${encodeURIComponent(query.trim())}`);
			query = '';
			inputEl?.blur();
		}
	}

	function handleKeydown(e: KeyboardEvent) {
		// Allow Escape to blur
		if (e.key === 'Escape') {
			query = '';
			inputEl?.blur();
		}
	}
</script>

<form onsubmit={handleSubmit} class="relative">
	<input
		bind:this={inputEl}
		bind:value={query}
		onkeydown={handleKeydown}
		type="search"
		placeholder={compact ? 'Search...' : 'Search posts...'}
		class="w-full pl-8 pr-3 py-1.5 text-sm rounded-md border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 placeholder-gray-400 dark:placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-violet-500 focus:border-transparent {compact
			? 'w-32 focus:w-48 transition-all'
			: ''}"
	/>
	<svg
		class="absolute left-2.5 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400 dark:text-gray-500"
		fill="none"
		stroke="currentColor"
		viewBox="0 0 24 24"
	>
		<path
			stroke-linecap="round"
			stroke-linejoin="round"
			stroke-width="2"
			d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
		/>
	</svg>
</form>
