<script lang="ts">
	let { value = '', onSearch, placeholder = 'Rechercher...', debounceMs = 300 }: {
		value?: string;
		onSearch: (value: string) => void;
		placeholder?: string;
		debounceMs?: number;
	} = $props();

	let inputValue = $state(value);
	let timeoutId: ReturnType<typeof setTimeout> | null = null;

	$effect(() => {
		inputValue = value;
	});

	function handleInput(event: Event) {
		const target = event.target as HTMLInputElement;
		inputValue = target.value;

		if (timeoutId !== null) {
			clearTimeout(timeoutId);
		}

		timeoutId = setTimeout(() => {
			onSearch(inputValue);
		}, debounceMs);
	}

	function handleClear() {
		inputValue = '';
		if (timeoutId !== null) {
			clearTimeout(timeoutId);
		}
		onSearch('');
	}

	function handleKeydown(event: KeyboardEvent) {
		if (event.key === 'Escape') {
			handleClear();
		}
	}
</script>

<div class="search-input-wrapper">
	<svg class="search-icon" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
		<path fill-rule="evenodd" d="M9 3.5a5.5 5.5 0 100 11 5.5 5.5 0 000-11zM2 9a7 7 0 1112.452 4.391l3.328 3.329a.75.75 0 11-1.06 1.06l-3.329-3.328A7 7 0 012 9z" clip-rule="evenodd" />
	</svg>
	<input
		type="search"
		class="search-input"
		{placeholder}
		value={inputValue}
		oninput={handleInput}
		onkeydown={handleKeydown}
		aria-label={placeholder}
	/>
	{#if inputValue}
		<button
			class="search-clear"
			onclick={handleClear}
			aria-label="Effacer la recherche"
			type="button"
		>
			✕
		</button>
	{/if}
</div>

<style>
	.search-input-wrapper {
		position: relative;
		display: flex;
		align-items: center;
		max-width: 24rem;
	}

	.search-icon {
		position: absolute;
		left: 0.75rem;
		width: 1.25rem;
		height: 1.25rem;
		color: #9ca3af;
		pointer-events: none;
	}

	.search-input {
		width: 100%;
		padding: 0.5rem 2.25rem 0.5rem 2.5rem;
		border: 1px solid #d1d5db;
		border-radius: 0.375rem;
		font-size: 0.875rem;
		color: #374151;
		background: white;
		transition: border-color 0.15s, box-shadow 0.15s;
	}

	.search-input:focus {
		outline: none;
		border-color: #3b82f6;
		box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
	}

	.search-input::placeholder {
		color: #9ca3af;
	}

	/* Hide browser-default search clear button */
	.search-input::-webkit-search-cancel-button {
		-webkit-appearance: none;
	}

	.search-clear {
		position: absolute;
		right: 0.5rem;
		display: flex;
		align-items: center;
		justify-content: center;
		width: 1.5rem;
		height: 1.5rem;
		border: none;
		border-radius: 50%;
		background: #e5e7eb;
		color: #6b7280;
		font-size: 0.75rem;
		cursor: pointer;
		transition: background-color 0.15s;
	}

	.search-clear:hover {
		background: #d1d5db;
		color: #374151;
	}
</style>
