<script lang="ts">
	import BookDelete from '$lib/components/forms/book-delete.svelte';
	import { BookEdit } from '$lib/components/forms/edit-book';
	import { getBookOperationsState } from '$lib/state/bookOperations.svelte';
	import { getLibraryState } from '$lib/state/library.svelte';
	import { setBookSelectionState } from '$lib/state/bookSelection.svelte';
	import type { Snippet } from 'svelte';

	let { children }: { children: Snippet } = $props();

	const libraryState = getLibraryState();
	const bookOps = getBookOperationsState();
	const bookSelection = setBookSelectionState();

	// Deselect all when active library changes
	$effect(() => {
		libraryState.activeLibrary; // Track this
		bookSelection.deselectAll();
	});

	// Exit selection mode the ESC key
	function handleKeyDown(event: KeyboardEvent) {
		if (event.key === 'Escape' && bookSelection.selectionModeActive) bookSelection.deselectAll();
	}
</script>

<svelte:window onkeydown={handleKeyDown} />

{@render children?.()}

<BookDelete
	bind:open={bookOps.deleteDialogOpen}
	deleteFn={bookOps.deleteFn}
	title={bookOps.deleteDialogTitle}
/>

<BookEdit book={bookOps.bookToEdit} bind:open={bookOps.editDialogOpen} />
