<script lang="ts">
	import { page } from '$app/state';
	import BookBrowser from '$lib/components/view/book-browser.svelte';
	import type { Bookshelf, Publisher, Tag, Book, Author } from '$lib/schema';
	import type { PaginatedResponse } from '$lib/schema/common';
	import { setBookCollectionState } from '$lib/state/bookCollection.svelte';
	import { getBookOperationsState } from '$lib/state/bookOperations.svelte';
	import { untrack } from 'svelte';

	let {
		data
	}: {
		data: {
			books: PaginatedResponse<Book>;
			bookshelves: PaginatedResponse<Bookshelf>;
			authors: PaginatedResponse<Author>;
			publishers: PaginatedResponse<Publisher>;
			tags: PaginatedResponse<Tag>;
		};
	} = $props();

	const { books, ...filterData } = data;

	const bookOps = getBookOperationsState();
	const bookCollection = setBookCollectionState(bookOps, books, filterData);

	let skip = $state(true);

	// Update book state on data changes
	$effect(() => {
		const { books, ...filterData } = data;

		// Skip effect on first run
		if (skip) {
			skip = false;
			return;
		}

		untrack(() => {
			bookOps.libraryId = page.params.libraryId!;
			bookCollection.resetState(books, filterData);
		});
	});
</script>

<div class="flex h-full w-full items-center">
	<BookBrowser />
</div>
