<script lang="ts">
	import { onMount } from "svelte";
	import { page } from "$app/state";
	import { ensureSeeded, getClientDb } from "$lib/db/client-db";
	import { getAnimeWithSongsByAnnId } from "$lib/db/client-db/queries";
	import { seasonName } from "$lib/utils/amq";

	type PageStatus = "idle" | "loading" | "ready" | "not-found" | "error";

	let status = $state<PageStatus>("idle");
	let error = $state<string | null>(null);

	type Data = Awaited<ReturnType<typeof getAnimeWithSongsByAnnId>>;
	let data = $state<NonNullable<Data> | null>(null);

	function parseAnnId(value: string | null): number | null {
		if (!value) return null;
		const n = Number(value);
		if (!Number.isInteger(n) || n <= 0) return null;
		return n;
	}

	function songTypeLabel(type: number) {
		// Matches schema comment in `anime_song_links.type`: 1(OP) | 2(ED) | 3(INS)
		switch (type) {
			case 1:
				return "OP";
			case 2:
				return "ED";
			case 3:
				return "INS";
			default:
				return "SONG";
		}
	}

	function songCode(type: number, number: number) {
		return `${songTypeLabel(type)}${number}`;
	}

	function audioUrl(fileName: string) {
		return `/cdn/${encodeURIComponent(fileName)}`;
	}

	async function load() {
		status = "loading";
		error = null;
		data = null;

		const annId = parseAnnId(page.params.annId ?? null);
		if (!annId) {
			status = "not-found";
			return;
		}

		try {
			const { db } = getClientDb();
			await ensureSeeded();
			const res = await getAnimeWithSongsByAnnId(db, annId);

			if (!res) {
				status = "not-found";
				return;
			}

			data = res;
			status = "ready";
		} catch (e) {
			error = e instanceof Error ? e.message : String(e);
			status = "error";
		}
	}

	onMount(() => {
		void load();
	});
</script>

{#if status === "loading"}
	<p class="mt-3 text-sm text-muted-foreground">Loading anime…</p>
{:else if status === "error"}
	<p class="mt-3 text-sm text-red-600">Error: {error}</p>
{:else if status === "not-found"}
	<h1 class="text-2xl font-semibold">Anime not found</h1>
	<p class="mt-2 text-sm text-muted-foreground">
		The requested anime entry doesn’t exist (or the route param wasn’t a valid
		ANN id).
	</p>
{:else if status === "ready" && data}
	<header class="mt-2 space-y-1">
		<h1 class="text-2xl font-semibold">{data.anime.mainName}</h1>
		<p class="text-sm text-muted-foreground">
			{data.anime.year}{seasonName(Number(data.anime.seasonId))} • ANN {data
				.anime.annId} • MAL {data.anime.malId}
		</p>
	</header>

	<section class="mt-6">
		<h2 class="text-lg font-semibold">Songs</h2>

		{#if data.songs.length === 0}
			<p class="mt-2 text-sm text-muted-foreground">
				No linked songs found for this anime.
			</p>
		{:else}
			<ul class="mt-3 space-y-3">
				{#each data.songs as s (s.annSongId)}
					<li class="rounded border p-3">
						<div class="flex flex-col gap-1">
							<div
								class="flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1"
							>
								<div class="font-medium">
									<span
										class="mr-2 inline-flex rounded bg-muted px-2 py-0.5 text-xs text-muted-foreground"
									>
										{songCode(s.type, s.number)}
									</span>
									{s.songName}
								</div>
								{#if s.artistName}
									<div class="text-sm text-muted-foreground">
										{s.artistName}
									</div>
								{/if}
							</div>

							{#if s.fileName}
								<audio
									class="mt-2 w-full"
									controls
									preload="none"
									src={audioUrl(s.fileName)}
								></audio>
								<div class="mt-1 text-xs text-muted-foreground">
									Source: <span class="font-mono">{s.fileName}</span>
								</div>
							{:else}
								<p class="mt-2 text-sm text-muted-foreground">
									No audio filename in the snapshot for this song.
								</p>
							{/if}
						</div>
					</li>
				{/each}
			</ul>
		{/if}
	</section>
{/if}
