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

afterEach(cleanup);

describe('PersonalInfoForm', () => {
	it('renders the section heading and the four labelled inputs by default', async () => {
		render(PersonalInfoForm, { props: { user: null, form: null } });

		await expect.element(page.getByRole('heading', { name: /persönliche daten/i })).toBeVisible();
		await expect.element(page.getByLabelText(/vorname/i)).toBeVisible();
		await expect.element(page.getByLabelText(/nachname/i)).toBeVisible();
		await expect.element(page.getByLabelText(/e-mail-adresse/i)).toBeVisible();
	});

	it('hydrates inputs from the user prop', async () => {
		render(PersonalInfoForm, {
			props: {
				user: {
					firstName: 'Anna',
					lastName: 'Schmidt',
					email: 'anna@example.com',
					contact: 'Telefon 123'
				},
				form: null
			}
		});

		const first = (await page.getByLabelText(/vorname/i).element()) as HTMLInputElement;
		const last = (await page.getByLabelText(/nachname/i).element()) as HTMLInputElement;
		const email = (await page.getByLabelText(/e-mail-adresse/i).element()) as HTMLInputElement;
		expect(first.value).toBe('Anna');
		expect(last.value).toBe('Schmidt');
		expect(email.value).toBe('anna@example.com');
	});

	it('converts the user.birthDate ISO value to German display format', async () => {
		render(PersonalInfoForm, {
			props: {
				user: {
					firstName: 'A',
					lastName: 'B',
					birthDate: '1923-04-15',
					email: 'x@y',
					contact: ''
				},
				form: null
			}
		});

		const dateInput = (await page.getByLabelText(/geburtsdatum/i).element()) as HTMLInputElement;
		expect(dateInput.value).toBe('15.04.1923');
	});

	it('shows the success banner when form.updateSuccess is true', async () => {
		render(PersonalInfoForm, { props: { user: null, form: { updateSuccess: true } } });

		await expect.element(page.getByText('Gespeichert.')).toBeVisible();
	});

	it('shows the error banner with the supplied message when form.updateError is set', async () => {
		render(PersonalInfoForm, {
			props: { user: null, form: { updateError: 'Email-Adresse bereits vergeben' } }
		});

		await expect.element(page.getByText('Email-Adresse bereits vergeben')).toBeVisible();
	});

	it('hides both banners when form is null', async () => {
		render(PersonalInfoForm, { props: { user: null, form: null } });

		await expect.element(page.getByText('Gespeichert.')).not.toBeInTheDocument();
	});

	it('declares POST as the form method and routes to the updateProfile action', async () => {
		render(PersonalInfoForm, { props: { user: null, form: null } });

		const form = document.querySelector('form');
		expect(form?.getAttribute('method')).toBe('POST');
		expect(form?.getAttribute('action')).toBe('?/updateProfile');
	});
});
