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

vi.mock('$app/navigation', () => ({
	beforeNavigate: () => {},
	afterNavigate: () => {},
	goto: vi.fn(),
	invalidate: vi.fn(),
	invalidateAll: vi.fn(),
	preloadCode: vi.fn(),
	preloadData: vi.fn(),
	pushState: vi.fn(),
	replaceState: vi.fn(),
	disableScrollHandling: vi.fn(),
	onNavigate: () => () => {}
}));

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

afterEach(cleanup);

const baseData = {
	initialPersons: [] as { id: string; displayName: string }[],
	initialDocuments: [] as { id: string; title: string }[]
};

describe('geschichten/new page', () => {
	it('renders the page heading', async () => {
		render(GeschichtenNewPage, { props: { data: baseData } });

		await expect.element(page.getByRole('heading', { level: 1 })).toBeVisible();
	});

	it('renders a button (BackButton component)', async () => {
		render(GeschichtenNewPage, { props: { data: baseData } });

		const buttons = document.querySelectorAll('button');
		expect(buttons.length).toBeGreaterThan(0);
	});

	it('does not render an error banner by default', async () => {
		render(GeschichtenNewPage, { props: { data: baseData } });

		expect(document.querySelector('[role="alert"]')).toBeNull();
	});

	it('renders the GeschichteEditor child component', async () => {
		render(GeschichtenNewPage, { props: { data: baseData } });

		// Editor renders inputs/textarea — verify at least one form input is present
		const inputs = document.querySelectorAll('input, textarea');
		expect(inputs.length).toBeGreaterThan(0);
	});

	it('passes initialPersons and initialDocuments through to the editor', async () => {
		render(GeschichtenNewPage, {
			props: {
				data: {
					initialPersons: [{ id: 'p1', displayName: 'Anna Schmidt' }],
					initialDocuments: [{ id: 'd1', title: 'Brief 1923' }]
				}
			}
		});

		// Both should appear somewhere in the rendered editor
		await expect.element(page.getByText('Anna Schmidt')).toBeVisible();
		await expect.element(page.getByText('Brief 1923')).toBeVisible();
	});
});
