<script lang="ts">
	import { bibleBooks, type BibleBook } from "$lib/types/bible";

	let { searchQuery = $bindable(""), guessedIds, submitGuess } = $props();

	let filteredBooks = $derived(
		bibleBooks.filter((book) =>
			book.name.toLowerCase().includes(searchQuery.toLowerCase()),
		),
	);

	function handleKeydown(e: KeyboardEvent) {
		if (e.key === "Enter" && filteredBooks.length > 0) {
			submitGuess(filteredBooks[0].id);
		}
	}
</script>

<div class="mb-12">
	<input
		bind:value={searchQuery}
		placeholder="Type to guess a book (e.g. 'Genesis', 'John')..."
		class="w-full p-4 sm:p-6 border-2 border-gray-200 rounded-2xl text-base sm:text-lg md:text-xl focus:outline-none focus:border-blue-500 focus:ring-4 focus:ring-blue-100 transition-all shadow-lg"
		onkeydown={handleKeydown}
	/>
	{#if searchQuery && filteredBooks.length > 0}
		<ul
			class="mt-4 max-h-60 sm:max-h-80 overflow-y-auto bg-white border border-gray-200 rounded-2xl shadow-lg"
		>
			{#each filteredBooks as book (book.id)}
				<li>
					<button
						class="w-full p-4 sm:p-5 text-left {guessedIds.has(
							book.id,
						)
							? 'opacity-60 cursor-not-allowed pointer-events-none hover:bg-gray-100 hover:text-gray-600'
							: 'hover:bg-blue-50 hover:text-blue-700'} transition-all border-b border-gray-100 last:border-b-0 flex items-center"
						onclick={() => submitGuess(book.id)}
					>
						<span
							class="font-semibold {guessedIds.has(book.id)
								? 'line-through text-gray-500'
								: ''}">{book.name}</span
						>
						<span class="ml-auto text-sm opacity-75"
							>({book.testament.toUpperCase()})</span
						>
					</button>
				</li>
			{/each}
		</ul>
	{:else if searchQuery}
		<p class="mt-4 text-center text-gray-500 p-8">No books found</p>
	{/if}
</div>
