import { describe, it, expect, afterEach } from 'vitest';
import { cleanup, render } from 'vitest-browser-svelte';
import ThemenPage from './+page.svelte';
import type { components } from '$lib/generated/api';

afterEach(() => {
	cleanup();
});

type TagTreeNodeDTO = components['schemas']['TagTreeNodeDTO'];

function makeTag(
	name: string,
	documentCount: number,
	children: TagTreeNodeDTO[] = [],
	subtreeDocumentCount: number = documentCount
): TagTreeNodeDTO {
	return { id: 'id-' + name, name, documentCount, subtreeDocumentCount, children };
}

describe('/themen +page', () => {
	it('renders one card per visible root tag', async () => {
		const tree = [makeTag('Briefe', 5), makeTag('Fotos', 3)];
		render(ThemenPage, { data: { tree } });
		expect(document.body.textContent).toContain('Briefe');
		expect(document.body.textContent).toContain('Fotos');
	});

	it('does not render a tag with no documents in its subtree', async () => {
		const tree = [makeTag('Briefe', 5), makeTag('Leer', 0)];
		render(ThemenPage, { data: { tree } });
		expect(document.body.textContent).not.toContain('Leer');
	});

	it('shows empty state when all tags filtered out', async () => {
		render(ThemenPage, { data: { tree: [makeTag('Leer', 0)] } });
		expect(document.body.textContent).toMatch(/Noch keine Themen/);
	});

	it('shows empty state when tree is empty', async () => {
		render(ThemenPage, { data: { tree: [] } });
		expect(document.body.textContent).toMatch(/Noch keine Themen/);
	});

	it('renders child tags for a root tag', async () => {
		const tree = [makeTag('Briefe', 5, [makeTag('Brautbriefe', 3), makeTag('Kriegsbriefe', 2)])];
		render(ThemenPage, { data: { tree } });
		expect(document.body.textContent).toContain('Brautbriefe');
		expect(document.body.textContent).toContain('Kriegsbriefe');
	});

	it('shows the subtree rollup in the header for a parent with 0 direct documents', async () => {
		// AC#5: 0 direct docs, but the subtree rolls up to 7 (child contributes 3).
		const tree = [makeTag('Reisen', 0, [makeTag('Italien', 3)], 7)];
		render(ThemenPage, { data: { tree } });
		expect(document.body.textContent).toContain('Reisen');
		expect(document.body.textContent).toContain('7');
	});

	it('shows "+ N weitere" when a root tag has more than 5 children', async () => {
		const children = Array.from({ length: 7 }, (_, i) => makeTag(`Kind${i}`, i + 1));
		const tree = [makeTag('Briefe', 10, children)];
		render(ThemenPage, { data: { tree } });
		expect(document.body.textContent).toMatch(/\+\s*2\s*weitere/);
	});
});
