<script lang="ts">
import { page } from '$app/state';
import { SvelteMap } from 'svelte/reactivity';
import { m } from '$lib/paraglide/messages.js';
import type { components } from '$lib/generated/api';
import TagTreeNode from './TagTreeNode.svelte';

type TagTreeNodeDTO = components['schemas']['TagTreeNodeDTO'];

let {
	node,
	depth,
	collapseMap
}: {
	node: TagTreeNodeDTO;
	depth: number;
	collapseMap: SvelteMap<string, boolean>;
} = $props();

const hasChildren = $derived((node.children?.length ?? 0) > 0);
const isCollapsed = $derived(collapseMap.get(node.id!) ?? false);
const isActive = $derived(page.url.pathname.startsWith('/admin/tags/' + node.id));

function toggleCollapse() {
	collapseMap.set(node.id!, !isCollapsed);
}
</script>

<li role="treeitem" aria-selected={isActive} aria-expanded={hasChildren ? !isCollapsed : undefined}>
	<!-- 16px per level matches standard tree-view spacing and is large enough to be scannable -->
	<div class="flex items-center" style="padding-left: {depth * 16}px">
		{#if hasChildren}
			<button
				onclick={toggleCollapse}
				aria-label={isCollapsed ? m.admin_tag_expand_node() : m.admin_tag_collapse_node()}
				class="flex min-h-[44px] min-w-[44px] items-center justify-center text-ink-3 transition-colors hover:text-ink"
			>
				<svg
					class="h-3 w-3 transition-transform {isCollapsed ? '' : 'rotate-90'}"
					viewBox="0 0 12 12"
					fill="currentColor"
					aria-hidden="true"
				>
					<path d="M4 2l4 4-4 4V2z" />
				</svg>
			</button>
		{:else}
			<button
				class="invisible flex min-h-[44px] min-w-[44px] items-center justify-center"
				tabindex="-1"
				aria-hidden="true"
			></button>
		{/if}

		{#if depth === 0 && node.color}
			<span
				data-testid="tag-list-color-dot"
				data-color={node.color}
				style="background-color: var(--c-tag-{node.color})"
				class="mr-1.5 inline-block h-2 w-2 flex-shrink-0 rounded-full"
			></span>
		{/if}

		<a
			href="/admin/tags/{node.id}"
			aria-current={isActive ? 'page' : undefined}
			class="flex-1 truncate py-1 text-sm font-bold text-ink transition-colors hover:text-primary {isActive
				? 'text-primary'
				: ''}"
		>
			{node.name}
			{#if (node.documentCount ?? 0) > 0}
				<span class="ml-1 text-xs font-normal text-ink-3">({node.documentCount})</span>
			{/if}
		</a>
	</div>

	{#if hasChildren && !isCollapsed}
		<ul role="group">
			{#each node.children! as child (child.id)}
				<TagTreeNode node={child} depth={depth + 1} collapseMap={collapseMap} />
			{/each}
		</ul>
	{/if}
</li>
