<script lang="ts">
	import { page } from '$app/state';
	import { goto } from '$app/navigation';

	interface Tab {
		id: string;
		label: string;
		count?: number;
	}

	interface Props {
		tabs: Tab[];
		paramName?: string;
		class?: string;
	}

	let { tabs, paramName = 'tab', class: className = '' }: Props = $props();

	let currentTab = $derived(page.url.searchParams.get(paramName) ?? tabs[0]?.id ?? '');

	function selectTab(tabId: string) {
		const url = new URL(page.url);
		if (tabId === tabs[0]?.id) {
			url.searchParams.delete(paramName);
		} else {
			url.searchParams.set(paramName, tabId);
		}
		goto(url.toString(), { replaceState: true, noScroll: true });
	}
</script>

<div class="flex gap-1 rounded-lg bg-black/5 p-1 dark:bg-white/10 {className}">
	{#each tabs as tab (tab.id)}
		<button
			onclick={() => selectTab(tab.id)}
			class="flex items-center gap-2 rounded-md px-4 py-2 text-sm font-medium transition-all duration-150
				{currentTab === tab.id
				? 'bg-theme-card text-theme shadow-sm'
				: 'text-theme-secondary hover:text-theme'}"
		>
			{tab.label}
			{#if tab.count !== undefined && tab.count > 0}
				<span
					class="flex h-5 min-w-5 items-center justify-center rounded-full px-1.5 text-xs font-semibold
					{currentTab === tab.id
						? 'bg-primary-500 text-white'
						: 'bg-black/10 text-theme-secondary dark:bg-white/20'}"
				>
					{tab.count > 99 ? '99+' : tab.count}
				</span>
			{/if}
		</button>
	{/each}
</div>
