<script lang="ts">
import { m } from '$lib/paraglide/messages.js';
import { enhance } from '$app/forms';
import BackButton from '$lib/shared/primitives/BackButton.svelte';
import PersonEditForm from './PersonEditForm.svelte';
import PersonEditSaveBar from './PersonEditSaveBar.svelte';
import NameHistoryEditCard from './NameHistoryEditCard.svelte';
import PersonMergePanel from '../PersonMergePanel.svelte';
import StammbaumCard from '$lib/person/genealogy/StammbaumCard.svelte';

let { data, form } = $props();
const person = $derived(data.person);
</script>

<div class="mx-auto max-w-2xl px-4 py-8">
	<!-- Back link -->
	<div class="mb-6">
		<BackButton />
		<h1 class="font-serif text-3xl text-ink">{m.person_edit_heading()}</h1>
	</div>

	{#if form?.updateError}
		<div class="mb-6 rounded border border-red-200 bg-red-50 p-4 text-red-700">
			{form.updateError}
		</div>
	{/if}

	<form id="person-edit-form" method="POST" use:enhance>
		<div class="rounded-sm border border-line bg-surface p-6 shadow-sm">
			<h2 class="mb-5 text-xs font-bold tracking-widest text-ink-3 uppercase">
				{m.persons_section_details()}
			</h2>
			<PersonEditForm person={person} />
		</div>
	</form>

	<NameHistoryEditCard aliases={data.aliases} canWrite={true} aliasError={form?.aliasError} />

	<StammbaumCard
		personId={person.id}
		familyMember={person.familyMember ?? false}
		relationships={data.relationships}
		inferredRelationships={data.inferredRelationships}
		canWrite={true}
		relationshipError={form?.relationshipError}
	/>

	{#key person.id}
		<PersonMergePanel person={person} form={form} />
	{/key}

	<PersonEditSaveBar discardHref="/persons/{person.id}" formId="person-edit-form" />
</div>
