<script lang="ts">
	import { buttonVariants } from '$lib/components/ui/button/button.svelte';
	import * as Tooltip from '$lib/components/ui/tooltip/index';
	import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index';
	import { ArrowUpDown, ChevronUp, ChevronDown } from '@lucide/svelte';
	import { getBookCollectionState } from '$lib/state/bookCollection.svelte';

	const bookCollection = getBookCollectionState();
</script>

<!-- Sort button -->
<Tooltip.Provider>
	<Tooltip.Root ignoreNonKeyboardFocus>
		<Tooltip.Trigger>
			{#snippet child({ props })}
				<DropdownMenu.Root>
					<DropdownMenu.Trigger
						{...props}
						class="{buttonVariants({ variant: 'ghost', size: 'icon' })} relative"
					>
						{#if bookCollection.hasActiveSort}
							<div class="absolute top-[5px] right-[5px] h-1.5 w-1.5 rounded-full bg-flag"></div>
						{/if}
						<ArrowUpDown />
					</DropdownMenu.Trigger>
					<DropdownMenu.Content class="w-40">
						<DropdownMenu.Group>
							{#each bookCollection.sortOptions as sortProp (sortProp.value)}
								<DropdownMenu.Item
									onSelect={() => bookCollection.updateSort(sortProp.value)}
									class={bookCollection.orderBy === sortProp.value ? 'bg-muted' : ''}
								>
									<div class="flex w-full items-center">
										{sortProp.name}
										{#if bookCollection.orderBy === sortProp.value}
											{#if bookCollection.sortOrder === 'asc'}
												<ChevronUp class="ml-auto" />
											{:else}
												<ChevronDown class="ml-auto" />
											{/if}
										{/if}
									</div>
								</DropdownMenu.Item>
							{/each}
						</DropdownMenu.Group>
					</DropdownMenu.Content>
				</DropdownMenu.Root>
			{/snippet}
		</Tooltip.Trigger>
		<Tooltip.Content>
			<p>Sort</p>
		</Tooltip.Content>
	</Tooltip.Root>
</Tooltip.Provider>
