import { describe, it, expect, afterEach } from 'vitest';
import { cleanup, render } from 'vitest-browser-svelte';
import { page } from 'vitest/browser';

import { createConfirmService, CONFIRM_KEY } from '$lib/shared/services/confirm.svelte.js';

const { default: PersonEditPage } = await import('./+page.svelte');

afterEach(cleanup);

const basePerson = {
	id: 'p-1',
	firstName: 'Anna',
	lastName: 'Schmidt',
	displayName: 'Anna Schmidt',
	personType: 'PERSON' as const,
	familyMember: false
};

const baseData = (overrides: Record<string, unknown> = {}) => ({
	person: basePerson,
	aliases: [],
	relationships: [],
	inferredRelationships: [],
	...overrides
});

describe('persons/[id]/edit page', () => {
	it('renders the edit heading', async () => {
		render(PersonEditPage, {
			context: new Map([[CONFIRM_KEY, createConfirmService()]]),
			props: { data: baseData(), form: undefined }
		});

		await expect.element(page.getByRole('heading', { name: /person bearbeiten/i })).toBeVisible();
	});

	it('renders the persons-section heading', async () => {
		render(PersonEditPage, {
			context: new Map([[CONFIRM_KEY, createConfirmService()]]),
			props: { data: baseData(), form: undefined }
		});

		await expect.element(page.getByRole('heading', { name: /angaben zur person/i })).toBeVisible();
	});

	it('shows the form-error banner when form.updateError is set', async () => {
		render(PersonEditPage, {
			context: new Map([[CONFIRM_KEY, createConfirmService()]]),
			props: { data: baseData(), form: { updateError: 'Last name is required' } }
		});

		await expect.element(page.getByText('Last name is required')).toBeVisible();
	});

	it('does not show the form-error banner when form is undefined', async () => {
		render(PersonEditPage, {
			context: new Map([[CONFIRM_KEY, createConfirmService()]]),
			props: { data: baseData(), form: undefined }
		});

		const banner = document.querySelector('.bg-red-50.border-red-200');
		expect(banner).toBeNull();
	});

	it('renders the save bar with the discard href pointing to the person detail', async () => {
		render(PersonEditPage, {
			context: new Map([[CONFIRM_KEY, createConfirmService()]]),
			props: { data: baseData(), form: undefined }
		});

		const link = document.querySelector('a[href="/persons/p-1"]');
		expect(link).not.toBeNull();
	});
});
