<script lang="ts">
	import { createEventDispatcher, getContext, onDestroy } from 'svelte';
	import type { Writable } from 'svelte/store';
	import { ChevronDown, ChevronUp } from 'svelte-heros-v2';

	let id = crypto.randomUUID();
	let asc = false;
	let { ascHeader } = getContext('sortableTr') as { ascHeader: Writable<null | string> };
	ascHeader.subscribe((v) => {
		if (v !== id) asc = false;
	});

	let dispatch = createEventDispatcher();

	onDestroy(() => {
		if ($ascHeader === id) $ascHeader = null;
	});
</script>

<th>
	<button
		class="flex flex-center"
		on:click={() => {
			dispatch('sort', { asc: (asc = !asc) });
			$ascHeader = id;
		}}
	>
		<span class="mr-1"><slot /></span>
		{#if $ascHeader === id && asc}
			<ChevronUp variation="solid" />
		{:else}
			<ChevronDown variation="solid" />
		{/if}
	</button>
</th>
