<script lang="ts">
	import Badge from '$lib/components/Badge.svelte';
	import { getSelectionContext } from '$lib/selection/Selection.svelte';
	import { accelerator } from '$lib/Shortcuts';
	import { fadeDefault, slideXFast } from '$lib/Transitions';
	import { onDestroy, type Snippet } from 'svelte';
	import { fade, slide } from 'svelte/transition';

	let { page = false, children }: { page?: boolean; children?: Snippet } = $props();
	let selection = getSelectionContext();

	onDestroy(selection.clear);
</script>

<div class="rounded-group flex">
	<button
		type="button"
		class="btn-slate relative"
		class:toggled={selection.active}
		title={`${selection.active ? 'Exit' : 'Enter'} ${page ? 'page ' : ' '}selection mode`}
		onclick={selection.toggle}
		use:accelerator={'s'}
	>
		{#if selection.active}
			{#if page}
				<span class="icon-base icon-[material-symbols--edit-document]"></span>
			{:else}
				<span class="icon-base icon-[material-symbols--remove-selection]"></span>
			{/if}
		{:else if page}
			<span class="icon-base icon-[material-symbols--edit-document-outline]"></span>
		{:else}
			<span class="icon-base icon-[material-symbols--select]"></span>
		{/if}
		<Badge number={selection.size} />
	</button>
	{#if selection.active}
		<div class="rounded-group-end flex" transition:slide={slideXFast}>
			<button
				type="button"
				class="btn-slate"
				title="Select all"
				aria-label="Select all"
				onclick={selection.all}
			>
				<span class="icon-base icon-[material-symbols--select-all]"></span>
			</button>
			<button
				type="button"
				class="btn-slate"
				title="Select none"
				aria-label="Select all"
				onclick={selection.none}
			>
				<span class="icon-base icon-[material-symbols--deselect]"></span>
			</button>
		</div>
	{/if}
</div>
{#if selection.size > 0}
	<div class="rounded-group flex" transition:fade={fadeDefault}>
		{@render children?.()}
	</div>
{/if}
