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: GeschichtenEditPage } = await import('./+page.svelte');

afterEach(cleanup);

const baseData = (overrides: Record<string, unknown> = {}) => ({
	geschichte: {
		id: 'g1',
		title: 'Die Reise nach Berlin',
		body: '<p>Im Jahr 1923...</p>',
		status: 'PUBLISHED' as 'DRAFT' | 'PUBLISHED',
		persons: [],
		documents: []
	},
	...overrides
});

describe('geschichten/[id]/edit page', () => {
	it('renders the geschichte title in the heading', async () => {
		render(GeschichtenEditPage, { props: { data: baseData() } });

		await expect
			.element(page.getByRole('heading', { level: 1, name: /reise nach berlin/i }))
			.toBeVisible();
	});

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

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

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

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

	it('renders the GeschichteEditor with form inputs', async () => {
		render(GeschichtenEditPage, { props: { data: baseData() } });

		const inputs = document.querySelectorAll('input, textarea, [contenteditable]');
		expect(inputs.length).toBeGreaterThan(0);
	});
});
