<script lang="ts">
	import { page } from '$app/stores';
	import { enabledSections } from '$lib/stores/features';
	import type { SectionKey } from '@colectivo/types';
	import * as m from '$lib/paraglide/messages';
	import { ShoppingCart, CheckSquare, FileText, Search } from 'lucide-svelte';

	const allItems: Array<{ section: SectionKey; href: string; label: () => string; icon: typeof ShoppingCart }> = [
		{ section: 'lists',  href: '/lists',  label: () => m.nav_lists(),  icon: ShoppingCart },
		{ section: 'tasks',  href: '/tasks',  label: () => m.nav_tasks(),  icon: CheckSquare },
		{ section: 'notes',  href: '/notes',  label: () => m.nav_notes(),  icon: FileText },
		{ section: 'search', href: '/search', label: () => m.nav_search(), icon: Search }
	];

	// Fase 12.3.1/12.3.3: filter by enabled flags + recompute the grid column
	// count from the visible length so the tab-bar adapts (the original was
	// `justify-around` over a fixed 4; we keep that distribution but the
	// number of children is now dynamic). "lists" is always shown
	// (§12.3.4 hard override).
	const items = $derived(
		allItems.filter((it) => it.section === 'lists' || $enabledSections[it.section])
	);

	const activePath = $derived($page.url.pathname);

	function isActive(href: string): boolean {
		return activePath === href || activePath.startsWith(`${href}/`);
	}
</script>

<nav
	data-testid="bottom-tab-bar"
	data-section-count={items.length}
	class="md:hidden fixed inset-x-0 bottom-0 z-40 border-t border-black/5 bg-surface/80 backdrop-blur-xl pb-[env(safe-area-inset-bottom)] dark:border-white/5"
>
	<ul class="flex items-stretch justify-around">
		{#each items as { section, href, label, icon: Icon } (section)}
			{@const active = isActive(href)}
			<li class="flex-1">
				<a
					{href}
					data-section={section}
					aria-current={active ? 'page' : undefined}
					aria-label={label()}
					class="flex h-14 flex-col items-center justify-center gap-0.5 text-xs transition-colors {active ? 'text-slate-900 dark:text-slate-50' : 'text-slate-400 dark:text-slate-500'}"
				>
					<Icon size={22} strokeWidth={1.5} />
					<span class="sr-only">{label()}</span>
				</a>
			</li>
		{/each}
	</ul>
</nav>
