<script lang="ts">
	import { resolve } from '$app/paths';
	import { page } from '$app/state';
	import { Button, buttonVariants } from '$lib/components/ui/button/index.js';
	import { Spinner } from '$lib/components/ui/spinner/index';
	import ThemeToggle from '$lib/components/layout/theme-toggle.svelte';
	import { RotateCcw, TriangleAlert } from '@lucide/svelte';

	let { data } = $props();

	const fileId = page.params.fileId;
	const bookId = page.params.bookId;

	const fileUrl = `${page.url.origin}/api/books/download/${bookId}/${fileId}`;

	let iframeEl = $state<HTMLIFrameElement>();
	let loading = $state(true);
	let loadError = $state<string | null>(null);
	let attempt = $state(0);

	async function load() {
		loading = true;
		loadError = null;

		try {
			// Ask for the file before handing it to pdf.js. The viewer runs in an
			// iframe and reports its own failures inside that frame, so without
			// this probe a missing file just showed an empty grey panel.
			const response = await fetch(fileUrl, { method: 'HEAD' });

			if (!response.ok) {
				throw new Error(`The server returned ${response.status} for this file.`);
			}

			if (iframeEl) {
				iframeEl.src = `/pdfjs/web/viewer.html?file=${encodeURIComponent(fileUrl)}`;
			}
		} catch (error) {
			console.error('Error loading PDF', error);
			loadError = error instanceof Error ? error.message : 'The file could not be opened.';
			loading = false;
		}
	}

	$effect(() => {
		attempt;
		if (iframeEl) load();
	});
</script>

<svelte:head>
	<title>{data?.title ? `${data.title} — Chitai` : 'Reader — Chitai'}</title>
</svelte:head>

<main class="flex h-screen w-full flex-col overflow-hidden bg-background">
	<!-- Same chrome as the EPUB reader, so leaving works the same way in both -->
	<header class="flex h-12 shrink-0 items-center gap-2 border-b px-3">
		<a
			href={resolve('/(root)/(library)/book/[bookId]', { bookId: String(bookId) })}
			class="min-w-0 flex-1 truncate font-serif text-sm hover:underline"
			title={data?.title}
		>
			{data?.title || 'Reader'}
		</a>
		<ThemeToggle />
	</header>

	<div class="relative flex-1">
		{#if loadError}
			<div class="absolute inset-0 flex items-center justify-center p-6">
				<div class="flex max-w-sm flex-col items-center gap-3 text-center">
					<TriangleAlert class="size-8 text-destructive" />
					<h2 class="font-serif text-lg">This file wouldn't open</h2>
					<p class="text-sm text-muted-foreground">{loadError}</p>
					<div class="mt-2 flex gap-2">
						<Button onclick={() => attempt++}>
							<RotateCcw class="size-4" />
							Try again
						</Button>
						<a
							href={resolve('/(root)/(library)/book/[bookId]', { bookId: String(bookId) })}
							class={buttonVariants({ variant: 'outline' })}
						>
							Back to book
						</a>
					</div>
				</div>
			</div>
		{:else if loading}
			<div class="absolute inset-0 flex items-center justify-center gap-3">
				<Spinner />
				<span class="text-sm text-muted-foreground">Opening…</span>
			</div>
		{/if}

		<iframe
			bind:this={iframeEl}
			title="PDF viewer"
			class="h-full w-full border-0 {loading || loadError ? 'invisible' : ''}"
			onload={() => (loading = false)}
		></iframe>
	</div>
</main>
