<script lang="ts">
	import { page } from '$app/state';
	import { SortDirection } from '$gql/graphql';
	import { navigate, type SortData } from '$lib/Navigation';
	import { slideXFast } from '$lib/Transitions';
	import { getRandomInt } from '$lib/Utils';
	import { slide } from 'svelte/transition';

	let { sort, labels }: { sort: SortData<string>; labels: Record<string, string> } = $props();

	function apply(sort: SortData<string>) {
		navigate({ sort }, page.url.searchParams);
	}

	function toggle() {
		if (sort.direction === SortDirection.Ascending) {
			apply({ ...sort, direction: SortDirection.Descending });
		} else {
			apply({ ...sort, direction: SortDirection.Ascending });
		}
	}

	function newSeed() {
		return getRandomInt(0, 1000000000);
	}

	function shuffle() {
		apply({ ...sort, seed: newSeed() });
	}

	function onchange(e: Event & { currentTarget: EventTarget & HTMLSelectElement }) {
		let seed: number | undefined = undefined;

		if (e.currentTarget.value === 'RANDOM') {
			seed = newSeed();
		}

		apply({ ...sort, on: e.currentTarget.value, seed });
	}
</script>

<div class="rounded-group flex flex-row">
	<select class="btn-slate appearance-none" value={sort.on} {onchange} title="Sort by...">
		{#each Object.entries(labels) as [value, label] (value)}
			<option {value}>{label}</option>
		{/each}
	</select>
	<button type="button" class="btn-slate" title="Toggle sort direction" onclick={toggle}>
		{#if sort.direction === SortDirection.Ascending}
			<span class="icon-base icon-[material-symbols--sort] -scale-y-100"></span>
		{:else}
			<span class="icon-base icon-[material-symbols--sort]"></span>
		{/if}
	</button>
	{#if sort.on === 'RANDOM'}
		<button
			type="button"
			class="btn-slate"
			title="Reshuffle"
			aria-label="Reshuffle"
			onclick={shuffle}
			transition:slide={slideXFast}
		>
			<div class="flex">
				<span class="icon-base icon-[material-symbols--shuffle]"></span>
			</div>
		</button>
	{/if}
</div>
