<script lang="ts">
import { m } from '$lib/paraglide/messages.js';
import { formatDate } from '$lib/shared/utils/date';
import { formatDocumentStatus } from '$lib/document/documentStatusLabel';
import { getInitials, personAvatarColor } from '$lib/person/personFormat';
import RelationshipPill from '$lib/person/relationship/RelationshipPill.svelte';
import DocumentDate from './DocumentDate.svelte';
import type { DatePrecision } from '$lib/shared/utils/documentDate';

type Person = { id: string; firstName?: string | null; lastName: string; displayName: string };
type Tag = { id: string; name: string };
type GeschichteSummary = {
	id: string;
	title: string;
	publishedAt?: string;
	author?: { firstName?: string; lastName?: string; email: string };
};

type Props = {
	documentDate: string | null;
	metaDatePrecision?: DatePrecision | null;
	metaDateEnd?: string | null;
	metaDateRaw?: string | null;
	location: string | null;
	status: string;
	sender: Person | null;
	receivers: Person[];
	tags: Tag[];
	inferredRelationship?: { labelFromA: string; labelFromB: string } | null;
	geschichten?: GeschichteSummary[];
	documentId?: string;
	canBlogWrite?: boolean;
};

let {
	documentDate,
	metaDatePrecision = null,
	metaDateEnd = null,
	metaDateRaw = null,
	location,
	status,
	sender,
	receivers,
	tags,
	inferredRelationship = null,
	geschichten = [],
	documentId,
	canBlogWrite = false
}: Props = $props();

const VISIBLE_RECEIVER_LIMIT = 5;
const VISIBLE_GESCHICHTEN_LIMIT = 3;
const showGeschichtenColumn = $derived(geschichten.length > 0 || canBlogWrite);
const visibleGeschichten = $derived(geschichten.slice(0, VISIBLE_GESCHICHTEN_LIMIT));
const hasGeschichtenOverflow = $derived(geschichten.length >= VISIBLE_GESCHICHTEN_LIMIT);
const gridClass = $derived(showGeschichtenColumn ? 'lg:grid-cols-4' : 'lg:grid-cols-3');

function formatGeschichteAuthor(g: GeschichteSummary): string {
	const a = g.author;
	if (!a) return '';
	const full = [a.firstName, a.lastName].filter(Boolean).join(' ').trim();
	return full || a.email || '';
}

function formatGeschichteDate(g: GeschichteSummary): string {
	if (!g.publishedAt) return '';
	return formatDate(g.publishedAt.slice(0, 10), 'short');
}

const displayLocation = $derived(location ?? '—');
const statusLabel = $derived(formatDocumentStatus(status));
const visibleReceivers = $derived(receivers.slice(0, VISIBLE_RECEIVER_LIMIT));
const hiddenReceiverCount = $derived(Math.max(0, receivers.length - VISIBLE_RECEIVER_LIMIT));
const hasPersons = $derived(sender !== null || receivers.length > 0);
const hasTags = $derived(tags.length > 0);

let showAllReceivers = $state(false);

const displayedReceivers = $derived(showAllReceivers ? receivers : visibleReceivers);

function getFullName(person: Person): string {
	return person.displayName;
}
</script>

{#snippet personCard(person: Person, relationLabel: string | null = null)}
	<a
		href="/persons/{person.id}"
		class="group flex items-center gap-2.5 rounded px-2 py-1.5 transition-colors hover:bg-muted"
	>
		<span
			class="flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-xs font-bold text-white"
			style="background-color: {personAvatarColor(person.id)}"
			aria-hidden="true"
		>
			{getInitials(person.displayName)}
		</span>
		<span class="min-w-0 truncate font-serif text-sm text-ink">{getFullName(person)}</span>
		{#if relationLabel}
			<RelationshipPill label={relationLabel} />
		{/if}
	</a>
{/snippet}

<div class="border-b border-line p-6">
	<div class="grid grid-cols-1 gap-6 {gridClass}">
		<!-- Column 1: Details -->
		<div>
			<h2 class="mb-4 font-sans text-xs font-bold tracking-widest text-ink-3 uppercase">
				{m.doc_details_section_details()}
			</h2>
			<dl class="space-y-3 font-serif text-sm">
				<div>
					<dt class="font-sans text-xs font-medium text-ink-3">{m.doc_details_field_date()}</dt>
					<dd class="text-ink">
						{#if documentDate}
							<DocumentDate
								iso={documentDate}
								precision={metaDatePrecision}
								end={metaDateEnd}
								raw={metaDateRaw}
							/>
						{:else}
							—
						{/if}
					</dd>
				</div>
				<div>
					<dt class="font-sans text-xs font-medium text-ink-3">{m.form_label_location()}</dt>
					<dd class="text-ink">{displayLocation}</dd>
				</div>
				<div>
					<dt class="font-sans text-xs font-medium text-ink-3">{m.doc_details_field_status()}</dt>
					<dd class="text-ink">{statusLabel}</dd>
				</div>
			</dl>
		</div>

		<!-- Column 2: Personen -->
		<div>
			<h2 class="mb-4 font-sans text-xs font-bold tracking-widest text-ink-3 uppercase">
				{m.doc_details_section_persons()}
			</h2>
			{#if hasPersons}
				<div class="space-y-3">
					{#if sender}
						<div>
							<p class="mb-1 font-sans text-xs font-medium text-ink-3">
								{m.doc_details_field_sender()}
							</p>
							{@render personCard(sender, inferredRelationship?.labelFromA ?? null)}
						</div>
					{/if}
					{#if receivers.length > 0}
						<div>
							<p class="mb-1 font-sans text-xs font-medium text-ink-3">
								{m.doc_details_field_receivers()}
							</p>
							<div class="space-y-0.5">
								{#each displayedReceivers as receiver, i (receiver.id)}
									{@render personCard(
										receiver,
										// Badge only shown when there is exactly one receiver — with multiple
										// receivers the inferred label is computed from the sender's viewpoint
										// and cannot be attributed to a specific receiver.
										i === 0 && receivers.length === 1
											? (inferredRelationship?.labelFromB ?? null)
											: null
									)}
								{/each}
							</div>
							{#if hiddenReceiverCount > 0 && !showAllReceivers}
								<button
									type="button"
									onclick={() => (showAllReceivers = true)}
									class="mt-1 px-2 font-sans text-xs font-medium text-ink-2 transition-colors hover:text-ink"
								>
									{m.doc_details_more_receivers({ count: hiddenReceiverCount })}
								</button>
							{/if}
						</div>
					{/if}
				</div>
			{:else}
				<p class="font-serif text-sm text-ink-3">{m.doc_details_no_persons()}</p>
			{/if}
		</div>

		<!-- Column 3: Schlagwoerter -->
		<div>
			<h2 class="mb-4 font-sans text-xs font-bold tracking-widest text-ink-3 uppercase">
				{m.doc_details_section_tags()}
			</h2>
			{#if hasTags}
				<div class="flex flex-wrap gap-2">
					{#each tags as tag (tag.id)}
						<a
							href="/?tag={encodeURIComponent(tag.name)}"
							class="rounded bg-muted px-2 py-0.5 text-xs font-bold tracking-wide text-ink uppercase transition-colors hover:bg-accent"
						>
							{tag.name}
						</a>
					{/each}
				</div>
			{:else}
				<p class="font-serif text-sm text-ink-3">{m.doc_details_no_tags()}</p>
			{/if}
		</div>

		<!-- Column 4: Geschichten (visible when stories exist or user can author) -->
		{#if showGeschichtenColumn}
			<div>
				<div class="mb-4 flex items-center justify-between">
					<h2 class="font-sans text-xs font-bold tracking-widest text-ink-3 uppercase">
						{m.geschichten_card_heading()}
					</h2>
					{#if canBlogWrite && documentId}
						<a
							href="/geschichten/new?documentId={documentId}"
							class="font-sans text-xs font-medium text-ink-2 hover:text-ink"
						>
							{m.geschichten_card_attach_action()}
						</a>
					{/if}
				</div>

				{#if geschichten.length === 0}
					<p class="font-serif text-sm text-ink-3">—</p>
				{:else}
					<ul class="space-y-2 font-serif text-sm">
						{#each visibleGeschichten as g (g.id)}
							<li>
								<a href="/geschichten/{g.id}" class="block text-ink hover:underline">
									{g.title}
								</a>
								<p class="font-sans text-xs text-ink-3">
									{formatGeschichteAuthor(g)}
									{#if formatGeschichteDate(g)}· {formatGeschichteDate(g)}{/if}
								</p>
							</li>
						{/each}
					</ul>

					{#if hasGeschichtenOverflow && documentId}
						<a
							href="/geschichten?documentId={documentId}"
							class="mt-3 inline-flex font-sans text-xs font-medium text-ink hover:underline"
						>
							{m.geschichten_card_show_all()} →
						</a>
					{/if}
				{/if}
			</div>
		{/if}
	</div>
</div>
