<script lang="ts">
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 {
	tree,
	autocollapse = false
}: {
	tree: TagTreeNodeDTO[];
	autocollapse?: boolean;
} = $props();

function loadCollapseMap(): SvelteMap<string, boolean> {
	if (typeof localStorage !== 'undefined') {
		try {
			const stored = localStorage.getItem('admin_tags_tree_state');
			const parsed: Record<string, boolean> = stored ? JSON.parse(stored) : {};
			return new SvelteMap(Object.entries(parsed));
		} catch {
			// ignore parse errors
		}
	}
	return new SvelteMap();
}

const collapseMap = loadCollapseMap();

$effect(() => {
	if (typeof localStorage !== 'undefined') {
		const obj: Record<string, boolean> = {};
		for (const [k, v] of collapseMap) {
			obj[k] = v;
		}
		localStorage.setItem('admin_tags_tree_state', JSON.stringify(obj));
	}
});

let manualCollapse = $state(
	typeof localStorage !== 'undefined' &&
		localStorage.getItem('admin_tags_list_collapsed') === 'true'
);
const isCollapsed = $derived(autocollapse || manualCollapse);

$effect(() => {
	if (typeof localStorage !== 'undefined') {
		localStorage.setItem('admin_tags_list_collapsed', String(manualCollapse));
	}
});
</script>

{#if isCollapsed}
	<!-- Collapsed handle: 32px -->
	<button
		onclick={() => (manualCollapse = false)}
		aria-label={m.admin_btn_expand_list()}
		class="flex w-8 flex-shrink-0 flex-col items-center gap-2 border-r border-line bg-surface pt-2 hover:bg-muted"
	>
		<span class="text-sm font-bold text-ink-2">›</span>
		<span
			class="text-[8px] font-extrabold tracking-widest text-ink-3 uppercase"
			style="writing-mode: vertical-rl; transform: rotate(180deg);"
		>
			{m.admin_tab_tags()}
		</span>
	</button>
{:else}
	<div class="flex w-60 flex-shrink-0 flex-col overflow-hidden border-r border-line bg-surface">
		<!-- Panel header -->
		<div class="flex items-center justify-between border-b border-line px-3 py-2">
			<span class="text-xs font-bold tracking-widest text-ink-3 uppercase">
				{m.admin_tag_tree_label()}
			</span>
			<button
				onclick={() => (manualCollapse = true)}
				aria-label={m.admin_btn_collapse_list()}
				class="flex h-6 w-6 items-center justify-center rounded-sm text-xs font-bold text-ink-2 transition-colors hover:bg-muted"
			>
				‹
			</button>
		</div>

		<!-- Scrollable tag tree -->
		<div class="flex-1 overflow-y-auto">
			{#if tree.length === 0}
				<p class="px-4 py-6 text-center text-xs text-ink-3">
					{m.admin_tags_empty()}
				</p>
			{:else}
				<ul role="tree" aria-label={m.admin_tag_tree_label()}>
					{#each tree as node (node.id)}
						<TagTreeNode node={node} depth={0} collapseMap={collapseMap} />
					{/each}
				</ul>
			{/if}
		</div>
	</div>
{/if}
