<script lang="ts">
	import * as Tooltip from '$lib/components/ui/tooltip/index';
	import * as ToggleGroup from '$lib/components/ui/toggle-group/index';
	import { BOOK_VIEWS, type BookView } from '$lib/state/bookCollection.svelte';

	import { List, LayoutGrid, Table } from '@lucide/svelte';

	/**
	 * Controlled rather than bound: the parent writes the URL when the view
	 * changes, and a callback keeps that write next to the intent instead of
	 * needing an effect that also fires on the initial assignment.
	 */
	let {
		value,
		onValueChange,
		class: className = ''
	}: {
		value: BookView;
		onValueChange: (view: BookView) => void;
		class?: string;
	} = $props();

	const ICONS = { grid: LayoutGrid, list: List, table: Table };
	const LABELS = { grid: 'Grid view', list: 'List view', table: 'Table view' };
</script>

<ToggleGroup.Root
	type="single"
	{value}
	onValueChange={(next) => {
		// The group emits '' when the active item is pressed again; keep the
		// current view rather than leaving the browser with nothing to render.
		if (next) onValueChange(next as BookView);
	}}
	class={className}
>
	{#each BOOK_VIEWS as view (view)}
		{@const Icon = ICONS[view]}
		<Tooltip.Provider>
			<Tooltip.Root ignoreNonKeyboardFocus>
				<Tooltip.Trigger>
					{#snippet child({ props })}
						<ToggleGroup.Item value={view} aria-label={LABELS[view]} {...props}>
							<Icon class="size-4" />
						</ToggleGroup.Item>
					{/snippet}
				</Tooltip.Trigger>
				<Tooltip.Content side="bottom">
					<p>{LABELS[view]}</p>
				</Tooltip.Content>
			</Tooltip.Root>
		</Tooltip.Provider>
	{/each}
</ToggleGroup.Root>
