<script lang="ts">
	import { onMount, type Snippet } from 'svelte';
	import type { ClassValue } from 'svelte/elements';
	import { sections } from './article.svelte';

	interface Props {
		h?: 1 | 2 | 3 | 4 | 5 | 6;
		id: string;
		children: Snippet;
		ref?: string;
		top?: string;
		toc?: boolean;
		class?: ClassValue | null;
	}

	let { h = 1, id, children, ref, top = '#top', toc = true, class: className }: Props = $props();

	const tag = $derived(`h${h}`);
	const href = $derived(`#${id}`);
	const sign = $derived.by(() => {
		switch (h) {
			case 1:
				return '';
			case 2:
				return '§ ';
			default:
				return '¶ ';
		}
	});

	onMount(() => {
		if (!toc) {
			return;
		}
		sections.push({ id, h, children });
		return () => sections.pop();
	});
</script>

<svelte:element this={tag} {id} class={['relative w-full', className]}>
	<!-- eslint-disable svelte/no-navigation-without-resolve -->
	<a {href}><span class="hidden md:inline">{sign}</span> {@render children()}</a>
	<div class="absolute right-0 bottom-0 inline-block text-end align-bottom text-sm whitespace-nowrap">
		{#if ref != null}
			<a href={ref} target="_blank" rel="noopener noreferrer">Ref &UpperRightArrow;</a>
		{/if}
		{#if h >= 2}
			<a href={top} class="ml-4">Top ▲</a>
		{/if}
	</div>
</svelte:element>
