<script lang="ts">
import * as m from '$lib/paraglide/messages.js';
import type { components } from '$lib/generated/api';
import { hasAnyDocuments } from '$lib/shared/utils/tagUtils';

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

interface Props {
	tags: TagTreeNodeDTO[];
	compact?: boolean;
}

const MAX_VISIBLE_TAGS = 6;

const { tags, compact = false }: Props = $props();

const visibleTags = $derived.by(() => tags.filter(hasAnyDocuments));
const shownTags = $derived(visibleTags.slice(0, MAX_VISIBLE_TAGS));
</script>

<section class="rounded-sm border border-line bg-surface p-5 shadow-sm">
	<div class="mb-4 flex items-center justify-between">
		<h2 class="font-sans text-xs font-bold tracking-widest text-ink-3 uppercase">
			{m.themen_widget_title()}
		</h2>
		<a
			href="/themen"
			class="flex min-h-[44px] items-center text-[11px] font-semibold text-ink-2 no-underline focus-visible:ring-2 focus-visible:ring-brand-navy focus-visible:outline-none"
		>
			{m.themen_alle()} →
		</a>
	</div>

	{#if visibleTags.length === 0}
		<p class="font-sans text-sm text-ink-3">{m.themen_leer()}</p>
	{:else}
		<div
			class="grid gap-2 {compact ? 'grid-cols-1' : 'grid-cols-1 sm:grid-cols-2'}"
			data-compact={compact}
		>
			{#each shownTags as tag (tag.id)}
				<a
					href="/documents?tag={encodeURIComponent(tag.name)}"
					aria-label="{tag.name}{tag.subtreeDocumentCount > 0
						? ', ' + m.themen_dokumente({ count: tag.subtreeDocumentCount })
						: ''}"
					class="flex cursor-pointer items-stretch overflow-hidden rounded-sm border border-line bg-canvas hover:bg-surface focus-visible:ring-2 focus-visible:ring-brand-navy focus-visible:outline-none"
					style="min-height: 56px"
				>
					<span
						class="w-1 flex-shrink-0 self-stretch"
						aria-hidden="true"
						style="background: var(--c-tag-{tag.color ?? 'slate'})"
					></span>
					<span class="flex min-w-0 flex-1 flex-col justify-center gap-0.5 px-3 py-3">
						<span class="truncate font-serif text-sm font-semibold text-ink">{tag.name}</span>
						{#if tag.subtreeDocumentCount > 0}
							<span class="font-sans text-xs text-ink-3 tabular-nums">
								{m.themen_dokumente({ count: tag.subtreeDocumentCount })}
							</span>
						{/if}
					</span>
				</a>
			{/each}
		</div>
	{/if}
</section>
