<script lang="ts">
	import { ChevronDown } from '@lucide/svelte';

	import type { FoliateTocItem } from '$foliate/view.js';
	import * as Collapsible from '$lib/components/ui/collapsible/index';
	import * as Sidebar from '$lib/components/ui/sidebar/index';

	let {
		toc,
		activeId = null,
		onnavigate
	}: {
		toc: FoliateTocItem[];
		/** From relocate.tocItem.id — foliate assigns these, books do not carry them. */
		activeId?: number | null;
		onnavigate: (href: string) => void;
	} = $props();

	/** True when this item or any descendant is the current chapter. */
	function contains(item: FoliateTocItem, id: number | null): boolean {
		if (id === null) return false;
		if (item.id === id) return true;
		return item.subitems?.some((sub) => contains(sub, id)) ?? false;
	}
</script>

<Sidebar.Root>
	<Sidebar.Header class="px-4 py-3">
		<p class="font-mono text-[10px] tracking-widest text-muted-foreground uppercase">Chapters</p>
	</Sidebar.Header>
	<Sidebar.Content>
		<Sidebar.GroupContent>
			<Sidebar.Menu>
				{#each toc as chapter (chapter.id)}
					{#if chapter.subitems?.length}
						<Collapsible.Root class="group/collapsible" open={contains(chapter, activeId)}>
							<div class="flex w-full items-center gap-1">
								<Sidebar.MenuItem class="min-w-0 flex-1">
									<Sidebar.MenuButton
										class="w-full"
										isActive={chapter.id === activeId}
										onclick={() => onnavigate(chapter.href)}
									>
										<span class="block truncate" title={chapter.label}>{chapter.label}</span>
									</Sidebar.MenuButton>
								</Sidebar.MenuItem>
								<Collapsible.Trigger class="flex-shrink-0 p-2">
									<ChevronDown
										class="size-4 transition-transform group-data-[state=open]/collapsible:rotate-180"
									/>
								</Collapsible.Trigger>
							</div>
							<Collapsible.Content>
								<Sidebar.MenuSub>
									{#each chapter.subitems ?? [] as subchapter (subchapter.id)}
										<Sidebar.MenuSubItem class="min-w-0">
											<Sidebar.MenuButton
												class="w-full"
												isActive={subchapter.id === activeId}
												onclick={() => onnavigate(subchapter.href)}
											>
												<span class="block truncate" title={subchapter.label}>
													{subchapter.label}
												</span>
											</Sidebar.MenuButton>
										</Sidebar.MenuSubItem>
									{/each}
								</Sidebar.MenuSub>
							</Collapsible.Content>
						</Collapsible.Root>
					{:else}
						<Sidebar.MenuItem class="min-w-0">
							<Sidebar.MenuButton
								class="w-full"
								isActive={chapter.id === activeId}
								onclick={() => onnavigate(chapter.href)}
							>
								<span class="block truncate" title={chapter.label}>{chapter.label}</span>
							</Sidebar.MenuButton>
						</Sidebar.MenuItem>
					{/if}
				{/each}
			</Sidebar.Menu>
		</Sidebar.GroupContent>
	</Sidebar.Content>
</Sidebar.Root>
