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

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

interface Props {
	documents: Document[];
}

const { documents }: Props = $props();

function isNew(doc: Document): boolean {
	return new Date(doc.createdAt).getTime() === new Date(doc.updatedAt).getTime();
}
</script>

<div class="flex flex-col overflow-hidden rounded-sm border border-line bg-surface">
	<!-- Card-head -->
	<div class="flex items-center justify-between border-b border-line px-3 py-1.5">
		<h3 class="text-[11px] font-bold tracking-[.12em] text-ink-3 uppercase">
			{m.dashboard_reader_recent_docs_heading()}
		</h3>
		<a
			href="/documents"
			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.dashboard_all_documents()}
		</a>
	</div>

	<!-- Doc list -->
	<ul class="flex flex-col">
		{#each documents as doc (doc.id)}
			<li>
				<a
					href="/documents/{doc.id}"
					class="flex min-h-[44px] items-center gap-2 border-b border-line/50 px-3 py-3 last:border-b-0 hover:bg-muted focus-visible:ring-2 focus-visible:ring-brand-navy focus-visible:outline-none"
				>
					<!-- Thumb -->
					<span
						class="flex h-6 w-5 shrink-0 items-center justify-center rounded-[2px] border border-line bg-canvas"
					>
						<svg
							width="10"
							height="12"
							viewBox="0 0 10 12"
							fill="none"
							aria-hidden="true"
							class="text-ink-3"
						>
							<path d="M1 1h5.5L9 3.5V11H1V1z" stroke="currentColor" stroke-width="1" fill="none" />
							<path d="M6 1v3h3" stroke="currentColor" stroke-width="1" fill="none" />
						</svg>
					</span>

					<!-- Middle -->
					<span class="flex min-w-0 flex-1 flex-col gap-0.5">
						<span class="flex flex-wrap items-center gap-1.5">
							<span class="truncate font-serif text-sm text-ink">{doc.title}</span>
							{#if isNew(doc)}
								<span
									class="shrink-0 rounded-full bg-accent-bg px-1.5 py-px text-[11px] font-bold text-ink"
								>
									{m.dashboard_badge_new()}
								</span>
							{/if}
						</span>
						<span class="text-xs text-ink-3">
							{#if doc.sender}
								{doc.sender.displayName ?? doc.sender.lastName}
							{:else}
								—
							{/if}
						</span>
					</span>

					<!-- Date -->
					<span class="shrink-0 text-[11px] text-ink-3">
						{relativeTimeDe(new Date(doc.updatedAt))}
					</span>
				</a>
			</li>
		{/each}
	</ul>
</div>
