<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 { getUploadQueueState } from '$lib/state/upload-queue.svelte';
	import { untrack } from 'svelte';

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

	// Seeds the collection state once, deliberately: it owns the list from here on, and the
	// effect below feeds it later navigations. untrack says so, rather than reading props
	// outside a closure and being warned about capturing only the initial value.
	const { books, filterData } = untrack(() => {
		const { books: initialBooks, ...rest } = data;
		return { books: initialBooks, filterData: rest };
	});

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

	// An upload refreshes this list every couple of seconds so books show up as
	// they land. That refresh returns the first page, so it waits while the reader
	// is reading further down. Cleared on the way out: this list is gone, and a
	// stale hold would stop the next one refreshing at all.
	$effect(() => {
		queue.holdRefresh = bookCollection.pastFirstPage;
		return () => (queue.holdRefresh = false);
	});

	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>
