<!--
  Collapsible section wrapper. Persists open/closed state in localStorage
  per-id so dashboard layout preferences survive reloads.
-->
<script lang="ts">
	import type { Snippet } from 'svelte';
	import { IconChevronDown } from '$lib/components/icons';

	interface Props {
		id: string;
		title: string;
		subtitle?: string;
		defaultOpen?: boolean;
		badge?: string;
		children: Snippet;
		actions?: Snippet;
	}

	const {
		id,
		title,
		subtitle = '',
		defaultOpen = true,
		badge = '',
		children,
		actions
	}: Props = $props();

	const storageKey = $derived(`tinyforge.section.${id}.open`);

	function readInitial(): boolean {
		if (typeof window === 'undefined') return defaultOpen;
		const raw = window.localStorage.getItem(`tinyforge.section.${id}.open`);
		if (raw === null) return defaultOpen;
		return raw === '1';
	}

	let open = $state(readInitial());

	function toggle() {
		open = !open;
		if (typeof window !== 'undefined') {
			window.localStorage.setItem(storageKey, open ? '1' : '0');
		}
	}
</script>

<section class="rounded-xl border border-[var(--border-primary)] bg-[var(--surface-card)]">
	<header class="flex items-center justify-between gap-3 px-4 py-3">
		<button
			type="button"
			onclick={toggle}
			class="flex flex-1 items-center gap-2 text-left"
			aria-expanded={open}
		>
			<span
				class="inline-flex h-5 w-5 items-center justify-center text-[var(--text-tertiary)] transition-transform {open
					? 'rotate-0'
					: '-rotate-90'}"
			>
				<IconChevronDown size={16} />
			</span>
			<div class="min-w-0 flex-1">
				<h2 class="text-sm font-semibold text-[var(--text-primary)]">
					{title}
					{#if badge}
						<span class="ml-2 rounded-full bg-[var(--surface-card-hover)] px-2 py-0.5 text-[10px] font-medium text-[var(--text-tertiary)]">
							{badge}
						</span>
					{/if}
				</h2>
				{#if subtitle}
					<p class="truncate text-xs text-[var(--text-tertiary)]">{subtitle}</p>
				{/if}
			</div>
		</button>
		{#if actions}
			<div class="flex items-center gap-2">{@render actions()}</div>
		{/if}
	</header>
	{#if open}
		<div class="border-t border-[var(--border-primary)] p-4">
			{@render children()}
		</div>
	{/if}
</section>
