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

afterEach(cleanup);

describe('WhoWhenSection — date input behavior', () => {
	it('marks the date input as invalid when input has text but no valid ISO', async () => {
		render(WhoWhenSection, {});

		const dateInput = document.querySelector('input#documentDate') as HTMLInputElement;
		dateInput.value = '32.13';
		dateInput.dispatchEvent(new Event('input', { bubbles: true }));

		await vi.waitFor(() => {
			// Invalid → border-red-400 class
			expect(dateInput.className).toContain('border-red-400');
			expect(document.querySelector('#date-error')).not.toBeNull();
		});
	});

	it('does not show the error before the user has typed', async () => {
		render(WhoWhenSection, {});

		const error = document.querySelector('#date-error');
		expect(error).toBeNull();
	});

	it('updates the hidden ISO input when typing a valid German date', async () => {
		render(WhoWhenSection, {});

		const dateInput = document.querySelector('input#documentDate') as HTMLInputElement;
		dateInput.value = '15.03.2024';
		dateInput.dispatchEvent(new Event('input', { bubbles: true }));

		await vi.waitFor(() => {
			const hidden = document.querySelector(
				'input[name="documentDate"][type="hidden"]'
			) as HTMLInputElement;
			expect(hidden.value).toBe('2024-03-15');
		});
	});

	it('renders the location input outside editMode with initialLocation', async () => {
		render(WhoWhenSection, { editMode: false, initialLocation: 'Hamburg' });

		const loc = document.querySelector('input#location') as HTMLInputElement;
		expect(loc.value).toBe('Hamburg');
	});

	it('hides the location input in editMode', async () => {
		render(WhoWhenSection, { editMode: true });

		const loc = document.querySelector('input#location');
		expect(loc).toBeNull();
	});

	it('shows the FieldLabelBadge for receivers in editMode', async () => {
		render(WhoWhenSection, { editMode: true });

		// FieldLabelBadge with variant=additive is rendered (just check the heading area)
		const labels = Array.from(document.querySelectorAll('p, label')).filter((el) =>
			/empfänger/i.test(el.textContent ?? '')
		);
		expect(labels.length).toBeGreaterThan(0);
	});

	it('renders the date asterisk indicator (required field)', async () => {
		render(WhoWhenSection, {});

		const label = document.querySelector('label[for="documentDate"]');
		expect(label?.textContent).toContain('*');
	});
});
