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

afterEach(() => cleanup());

describe('WhoWhenSection — onMount seeding (Felix B1 fix regression fence)', () => {
	it('pre-fills the date input from initialDateIso when the bindable is empty', async () => {
		render(WhoWhenSection, { initialDateIso: '2024-03-15' });
		// isoToGerman('2024-03-15') → '15.03.2024'
		const dateInput = document.querySelector('input#documentDate') as HTMLInputElement;
		expect(dateInput).not.toBeNull();
		expect(dateInput.value).toBe('15.03.2024');
	});

	it('does not stomp a parent-bound dateIso that is already non-empty', async () => {
		// dateIso bindable is '2026-01-01' from the parent; initialDateIso is the
		// "fallback seed". onMount must not overwrite the already-bound value.
		render(WhoWhenSection, { dateIso: '2026-01-01', initialDateIso: '1900-01-01' });
		const dateInput = document.querySelector('input#documentDate') as HTMLInputElement;
		expect(dateInput.value).toBe('01.01.2026');
	});

	it('hides the date field when hideDate=true (bulk-edit mode)', async () => {
		render(WhoWhenSection, { hideDate: true });
		await expect.element(page.getByTestId('who-when-date')).not.toBeInTheDocument();
	});

	it('renders the meta_location input only outside editMode', async () => {
		const { rerender } = render(WhoWhenSection, { editMode: true });
		expect(document.querySelector('input#location')).toBeNull();
		await rerender({ editMode: false });
		expect(document.querySelector('input#location')).not.toBeNull();
	});

	it('pre-fills the location input from initialLocation', async () => {
		render(WhoWhenSection, { editMode: false, initialLocation: 'Berlin' });
		const locationInput = document.querySelector('input#location') as HTMLInputElement;
		expect(locationInput.value).toBe('Berlin');
	});

	// Regression fence for the DatePrecisionField extraction (#781): the existing
	// spec covered only date pre-fill / hideDate / location, so the RANGE end-date
	// reveal had no red signal. This test must stay green across the extraction.
	it('reveals the end-date field when precision is RANGE', async () => {
		render(WhoWhenSection, { precision: 'RANGE' });
		await expect.element(page.getByLabelText('Enddatum')).toBeVisible();
	});

	it('hides the end-date field when precision is not RANGE', async () => {
		render(WhoWhenSection, { precision: 'YEAR' });
		await expect.element(page.getByTestId('who-when-end-date')).not.toBeInTheDocument();
	});
});
