<script lang="ts">
	import { reveal } from '$lib/actions/reveal';
	import LazyLoadingImg from './LazyLoadingImg.svelte';
	import type { CurrentlyReading, FinishedBook } from '$lib/types';

	let {
		currentlyReading,
		finishedBooks
	}: {
		currentlyReading: Promise<CurrentlyReading | null>;
		finishedBooks: Promise<FinishedBook[]>;
	} = $props();

	const READING_GOAL = 24;

	function finishedLabel(iso: string | null): string {
		if (!iso) return '';
		const date = new Date(iso);
		if (Number.isNaN(date.getTime())) return '';
		return date.toLocaleDateString('en', { month: 'short', year: 'numeric' });
	}

	type YearGroup = { year: string; books: FinishedBook[] };

	function groupByYear(books: FinishedBook[]): YearGroup[] {
		const buckets = new Map<string, FinishedBook[]>();
		for (const book of books) {
			const dateFinished = book.finishedAt ? new Date(book.finishedAt) : null;
			const dateStarted = book.startedAt ? new Date(book.startedAt) : null;
			const date = dateFinished ?? dateStarted ?? null;
			const year = date && !Number.isNaN(date.getTime()) ? String(date.getFullYear()) : 'Unknown';
			(buckets.get(year) ?? buckets.set(year, []).get(year)!).push(book);
		}
		return [...buckets.entries()]
			.map(([year, books]) => ({ year, books }))
			.sort((a, b) => {
				if (a.year === 'Unknown') return 1;
				if (b.year === 'Unknown') return -1;
				return Number(b.year) - Number(a.year);
			});
	}
</script>

<section class="mx-auto mt-24 max-w-4xl px-2 md:mt-32">
	<div class="flex flex-col items-center justify-center">
		<h1 class="text-center font-urbanist text-3xl font-semibold md:text-5xl">Books</h1>
		<span class="text-md mt-2 px-2 text-center font-urbanist opacity-70 md:mt-4 md:text-xl">
			What I'm reading &amp; what I've recently finished
		</span>
	</div>

	{#await currentlyReading}
		<div class="card mx-auto mt-10 max-w-xl bg-base-100 shadow-sm">
			<div class="card-body flex-row items-start gap-5">
				<div class="h-40 w-28 flex-none skeleton rounded-md"></div>
				<div class="flex flex-1 flex-col gap-3">
					<div class="h-5 w-32 skeleton"></div>
					<div class="h-6 w-3/4 skeleton"></div>
					<div class="h-4 w-1/2 skeleton"></div>
				</div>
			</div>
		</div>
	{:then currentlyReading}
		{#if currentlyReading}
			<div class="card mx-auto mt-10 max-w-xl bg-base-100 shadow-sm">
				<div class="card-body flex-row items-start gap-5">
					{#if currentlyReading.cover}
						<LazyLoadingImg
							class="h-40 w-28 flex-none rounded-md shadow-sm"
							src={currentlyReading.cover}
							alt={currentlyReading.title}
						/>
					{/if}
					<div class="flex flex-col">
						<span class="badge font-urbanist badge-primary">Currently reading</span>
						<h2 class="mt-2 card-title font-urbanist text-2xl font-black">
							{currentlyReading.title}
						</h2>
						<p class="text-md font-urbanist font-medium opacity-60">{currentlyReading.authors}</p>
						<div class="mt-3 card-actions">
							<a
								class="btn font-urbanist btn-sm btn-primary"
								href={currentlyReading.bookUrl}
								target="_blank"
								rel="noopener noreferrer"
							>
								Read
							</a>
						</div>
					</div>
				</div>
			</div>
		{/if}
	{/await}

	{#await finishedBooks}
		<h3 class="mt-14 text-center font-urbanist text-xl font-semibold opacity-80 md:text-2xl">
			Recently finished
		</h3>
		<div class="mt-6 grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
			{#each Array(6) as _, i (i)}
				<div class="card bg-base-100 shadow-sm">
					<div class="card-body flex-row items-start gap-4">
						<div class="h-32 w-22 flex-none skeleton rounded-md"></div>
						<div class="flex min-w-0 flex-1 flex-col gap-2">
							<div class="h-5 w-3/4 skeleton"></div>
							<div class="h-4 w-1/2 skeleton"></div>
							<div class="h-4 w-1/3 skeleton"></div>
						</div>
					</div>
				</div>
			{/each}
		</div>
	{:then finishedBooks}
		{#if finishedBooks.length > 0}
			{#each groupByYear(finishedBooks) as group (group.year)}
				<h3 class="mt-14 text-center font-urbanist text-2xl font-semibold opacity-80 md:text-3xl">
					{group.year}
				</h3>
				{#if group.year !== 'Unknown'}
					<div class="mx-auto mt-3 w-full max-w-md">
						<progress
							class="progress w-full progress-accent"
							value={group.books.length}
							max={READING_GOAL}
						></progress>
						<p class="mt-1 text-center font-urbanist text-sm opacity-50">
							{group.books.length} of {READING_GOAL} books
						</p>
					</div>
				{/if}
				<div class="mt-6 grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
					{#each group.books as book (book.bookUrl)}
						<div class="card bg-base-100 shadow-sm transition duration-300 hover:-translate-y-1">
							<div class="card-body flex-row items-start gap-4">
								{#if book.cover}
									<LazyLoadingImg
										class="h-32 w-22 flex-none rounded-md shadow-sm"
										src={book.cover}
										alt={book.title}
									/>
								{/if}
								<div class="flex min-w-0 flex-col">
									<h4 class="font-urbanist text-lg font-black">{book.title}</h4>
									<p class="font-urbanist text-sm font-medium opacity-60">{book.authors}</p>
									{#if book.stars}
										<p
											class="mt-1 font-urbanist text-sm text-warning"
											aria-label={`${book.stars} stars`}
										>
											{'★'.repeat(Math.round(book.stars))}<span class="opacity-30"
												>{'★'.repeat(Math.max(0, 5 - Math.round(book.stars)))}</span
											>
										</p>
									{/if}
									{#if book.finishedAt}
										<p class="mt-auto pt-2 font-urbanist text-xs opacity-40">
											{finishedLabel(book.finishedAt)}
										</p>
									{/if}
									<div class="mt-2 card-actions">
										<a
											class="btn font-urbanist btn-ghost btn-xs"
											href={book.bookUrl}
											target="_blank"
											rel="noopener noreferrer"
										>
											View
										</a>
									</div>
								</div>
							</div>
						</div>
					{/each}
				</div>
			{/each}
		{:else}
			<p class="mt-10 text-center font-urbanist opacity-60">Nothing to show right now.</p>
		{/if}
	{/await}
</section>
