<script lang="ts">
	import BookImage from './book-image.svelte';
	import { Progress } from '$lib/components/ui/progress/index';
	import { getLibraryState } from '$lib/state/library.svelte';
	import { getBookSelectionState } from '$lib/state/bookSelection.svelte';
	import type { Book } from '$lib/schema';

	let { book, class: className = '', ...rest }: { book: Book, class?: string} = $props();

	const selectionState = getBookSelectionState();
	const libraryState = getLibraryState();

	let darkened = $derived(selectionState.selectionModeActive);
	let selected = $derived(selectionState.isSelected(book.id));

	function handleClick(e: MouseEvent) {
		if (darkened) {
			e.preventDefault();
			selectionState.toggleSelection(book);
		}
	}
</script>

<div class="flex w-full flex-shrink-0 flex-col gap-1 {className}">
	<!-- Book Cover -->
	<a
		href="/book/{book.id}"
		class="group relative aspect-9/12 w-full overflow-hidden rounded shadow-lg drop-shadow-lg transition-all duration-200 {selected
			? 'ring-2 ring-yellow-300'
			: ''}"
		onclick={handleClick}
	>
		<BookImage
			src="/api/{book.cover_image}"
			class="h-full w-full rounded object-cover transition-all duration-200 group-hover:brightness-50 {selected ||
			darkened
				? 'brightness-50'
				: ''}"
		/>
	</a>
	{#if book.progress?.percentage && !selected && !darkened}
		<Progress
			value={book.progress.percentage}
			max={1}
			class="mt-[-8px] h-1 rounded {book.progress.completed
				? '[&>div]:bg-green-600'
				: '[&>div]:bg-yellow-500'}"
		/>
	{/if}

	<!-- Book Title -->
	<a href="/book/{book.id}" class="text-base-content mt-1 line-clamp-2 w-full text-sm hover:underline"
		>{book.title}</a
	>

	<!-- Authors list -->
	<p class="line-clamp-1 w-full text-xs text-muted-foreground">
		{#each book.authors as author}
			<a
				href="/library/{libraryState.activeLibrary?.id}/view?authors={author.id}"
				class="cs-list hover:underline">{author.name}</a
			> &thinsp;
		{/each}
	</p>
</div>
