<script lang="ts">
	import { goto } from '$app/navigation';
	import { page } from '$app/state';
	import { createQuery } from '@tanstack/svelte-query';
	import {
		listDuplicateGroups,
		type DuplicateGroup
	} from '$lib/services/adapters/duplicates';
	import { isAuthenticated } from '$lib/stores/session.svelte';
	import {
		setThumbnailSize,
		THUMBNAIL_SIZE_LABELS,
		THUMBNAIL_SIZE_PRESETS,
		view
	} from '$lib/stores/view.svelte';
	import Toolbar from '$lib/components/layout/Toolbar.svelte';
	import DuplicatesView from '$lib/components/duplicates/DuplicatesView.svelte';

	// Same pill-tab pattern as /tags: tab state is URL-driven so the user
	// can share / refresh / hit Back and land on the right panel.
	type Tab = 'stacks' | 'cross-folder';
	const TABS: { id: Tab; label: string }[] = [
		{ id: 'stacks', label: 'Stacks' },
		{ id: 'cross-folder', label: 'Cross-folder' }
	];
	const activeTab = $derived<Tab>(parseTab(page.url.searchParams.get('tab')));
	function parseTab(raw: string | null): Tab {
		return raw === 'cross-folder' ? 'cross-folder' : 'stacks';
	}
	function setTab(tab: Tab) {
		const params = new URLSearchParams();
		if (tab !== 'stacks') params.set('tab', tab);
		void goto(`/duplicates${params.size ? '?' + params : ''}`, {
			keepFocus: true,
			noScroll: true
		});
	}

	// Stale-time matches mule-image's DuplicatesView (30 s) so quick
	// toolbar bounces don't refetch the (potentially expensive) stack
	// listing. Invalidation by mutations is explicit, not time-driven.
	const dupesQuery = createQuery<DuplicateGroup[]>(() => ({
		queryKey: ['duplicates'],
		queryFn: listDuplicateGroups,
		enabled: isAuthenticated() && activeTab === 'stacks',
		staleTime: 30_000
	}));
</script>

<Toolbar>
	<span class="rounded-md border border-border px-2 py-0.5 text-[11px] text-muted-foreground">
		Duplicates
	</span>
	<!-- Tabs mirror /tags' pill row visually: same height, same active
	     treatment, same hover affordance. -->
	<div class="flex items-center gap-1">
		{#each TABS as t (t.id)}
			<button
				type="button"
				class="rounded border px-2 py-0.5 text-[11px] {activeTab === t.id
					? 'border-primary/40 bg-primary/10 text-primary'
					: 'border-border text-muted-foreground hover:bg-accent hover:text-foreground'}"
				onclick={() => setTab(t.id)}
			>
				{t.label}
			</button>
		{/each}
	</div>
	{#snippet trailing()}
		<!-- Thumbnail-size control mirrors the timeline Toolbar. The view
		     store is global, so the picked size persists across routes —
		     when you come back to the timeline it stays where you left it. -->
		<div
			class="flex items-center overflow-hidden rounded border border-border"
			role="group"
			aria-label="Thumbnail size"
		>
			{#each THUMBNAIL_SIZE_PRESETS as size, i (size)}
				<button
					type="button"
					class="px-1.5 py-0.5 text-[10px] font-medium hover:bg-accent"
					class:bg-accent={view.thumbnailSize === size}
					class:text-foreground={view.thumbnailSize === size}
					class:text-muted-foreground={view.thumbnailSize !== size}
					onclick={() => setThumbnailSize(size)}
					title={`${THUMBNAIL_SIZE_LABELS[i]} · ${size}px`}
				>
					{THUMBNAIL_SIZE_LABELS[i]}
				</button>
			{/each}
		</div>
	{/snippet}
</Toolbar>

<main class="min-h-0 flex-1 overflow-y-auto">
	<DuplicatesView
		{activeTab}
		groups={dupesQuery.data ?? []}
		pending={dupesQuery.isPending}
		error={dupesQuery.error}
	/>
</main>
