<script module lang="ts">
	import type { Component } from "svelte";
	import type { SvelteHTMLElements } from "svelte/elements";

	export interface TabDef {
		id: string;
		label: string;
		href: string;
		icon?: Component<SvelteHTMLElements["svg"]>;
		count?: number;
	}
</script>

<script lang="ts">
	import { resolve } from "$app/paths";

	interface Props {
		tabs: TabDef[];
		active: string;
		label?: string;
		vertical?: boolean;
	}

	let { tabs, active, label, vertical = false }: Props = $props();

	const navClass = $derived(
		vertical
			? "h-fit divide-y divide-border-default overflow-hidden rounded border border-border-default"
			: "relative z-10 flex w-full overflow-x-auto overflow-y-hidden pl-4"
	);

	const itemClass = (isActive: boolean) =>
		vertical
			? `flex items-center gap-3 px-3 py-2 text-sm no-underline hover:no-underline ${
					isActive
						? "bg-background-default text-foreground-default dark:bg-background-inset"
						: "bg-background-inset text-foreground-muted hover:text-foreground-default dark:bg-background-default"
				}`
			: `relative mr-1 flex items-center rounded-t px-4 pt-1 pb-[5px] whitespace-nowrap text-foreground-default no-underline hover:no-underline ${
					isActive
						? "border border-b-0 border-border-default bg-background-default [-webkit-text-stroke:0.3px_currentColor]"
						: "border border-b-0 border-transparent hover:bg-background-muted hover:dark:bg-background-subtle/50"
				}`;
</script>

<nav class={navClass} aria-label={label}>
	{#each tabs as tab (tab.id)}
		{@const isActive = active === tab.id}
		{@const Glyph = tab.icon}
		<a
			href={tab.href.startsWith("/") ? resolve(tab.href as "/") : tab.href}
			aria-current={isActive ? "page" : undefined}
			class={itemClass(isActive)}
		>
			{#if Glyph}
				<Glyph class={vertical ? "size-4 shrink-0" : "mr-2 h-4 w-4"} aria-hidden="true" />
			{/if}
			{#if vertical}
				{tab.label}
			{:else}
				<span class="flex flex-col">
					{tab.label}
					<span aria-hidden="true" class="invisible h-0 overflow-hidden font-medium select-none"
						>{tab.label}</span
					>
				</span>
			{/if}
			{#if tab.count}
				<span class="rounded bg-background-inset px-1 text-sm {vertical ? 'ml-auto' : 'ml-1'}"
					>{tab.count}</span
				>
			{/if}
		</a>
	{/each}
</nav>
