<script lang="ts">
import { m } from '$lib/paraglide/messages.js';
import { formatDate } from '$lib/shared/utils/date';
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.by(() => {
	const parts: string[] = [];
	if (formattedDate) parts.push(formattedDate);
	if (doc.senderName && doc.receiverName) {
		parts.push(m.journey_item_meta_from_to({ sender: doc.senderName, receiver: doc.receiverName }));
	} else if (doc.senderName) {
		parts.push(doc.senderName);
	}
	return parts.join(' · ');
});
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-white p-3">
		<!-- plaintext — do NOT use {@html} here -->
		<p class="mb-0.5 font-serif text-sm leading-snug text-ink">{doc.title}</p>
		{#if metaLine}
			<p class="mb-2 text-xs text-ink-3">{metaLine}</p>
		{/if}
		<a
			href="/documents/{doc.id}"
			aria-label={openAriaLabel}
			class="inline-flex items-center gap-1 text-xs 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="border-mint mt-3 rounded-r-sm border-l-2 bg-surface py-1.5 pr-2 pl-3">
				<p class="text-xs leading-relaxed text-ink-2 italic">{item.note}</p>
			</div>
		{/if}
	</div>
</div>
