<script lang="ts">
import { m } from '$lib/paraglide/messages.js';
import { formatDate } from '$lib/shared/utils/date';
import { formatDocumentMetaLine } from './utils';
import type { components } from '$lib/generated/api';

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

interface Props {
	item: JourneyItemView;
}

let { item }: Props = $props();

// Safe: JourneyReader filters out items where document === null before rendering this component.
const doc = $derived(item.document!);
const formattedDate = $derived(doc.documentDate ? formatDate(doc.documentDate, 'short') : null);
const metaLine = $derived(formatDocumentMetaLine(doc));
const openAriaLabel = $derived(
	formattedDate
		? m.journey_item_open_aria({ date: formattedDate })
		: m.journey_item_open_aria_undated()
);
const hasNote = $derived(item.note != null && item.note.trim().length > 0);
</script>

<div class="mb-3">
	<div class="rounded-sm border border-line bg-surface p-3">
		<!-- plaintext — do NOT use {@html} here -->
		<p class="mb-0.5 font-serif text-base leading-snug text-ink">{doc.title}</p>
		{#if metaLine}
			<p class="mb-2 text-sm text-ink-3">{metaLine}</p>
		{/if}
		<a
			href="/documents/{doc.id}"
			aria-label={openAriaLabel}
			class="-my-2 inline-flex min-h-[44px] items-center gap-1 text-sm font-semibold text-ink hover:text-primary focus:outline-none focus-visible:ring-2 focus-visible:ring-focus-ring"
		>
			<svg class="h-3 w-3 shrink-0" viewBox="0 0 10 12" fill="none">
				<rect x="1" y="1" width="8" height="10" rx="1" stroke="currentColor" stroke-width="1" />
				<path
					d="M3 4h4M3 6.5h4M3 9h2"
					stroke="currentColor"
					stroke-width=".7"
					stroke-linecap="round"
				/>
			</svg>
			{m.journey_item_open()}
			<svg class="h-3 w-3 shrink-0" viewBox="0 0 10 10" fill="none">
				<path
					d="M4 2l4 3-4 3"
					stroke="currentColor"
					stroke-width="1.5"
					stroke-linecap="round"
					stroke-linejoin="round"
				/>
			</svg>
		</a>
		{#if hasNote}
			<!-- plaintext — do NOT use {@html} here -->
			<div class="mt-3 rounded-r-sm border-l-2 border-brand-mint bg-muted py-1.5 pr-2 pl-3">
				<p class="text-base leading-relaxed text-ink-2 italic">{item.note}</p>
			</div>
		{/if}
	</div>
</div>
