import { describe, it, expect, afterEach } from 'vitest';
import { cleanup, render } from 'vitest-browser-svelte';
import ThemenWidget from './ThemenWidget.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('ThemenWidget', () => {
	it('renders a card link per visible tag', async () => {
		const tags = [makeTag('Briefe', 5), makeTag('Fotos', 3)];
		const { getByRole } = render(ThemenWidget, { tags });
		await expect.element(getByRole('link', { name: /Briefe/ })).toBeInTheDocument();
		await expect.element(getByRole('link', { name: /Fotos/ })).toBeInTheDocument();
	});

	it('hides tags where no document exists in the subtree', async () => {
		const tags = [makeTag('Briefe', 5), makeTag('Leer', 0)];
		render(ThemenWidget, { tags });
		expect(document.body.textContent).toContain('Briefe');
		expect(document.body.textContent).not.toContain('Leer');
	});

	it('displays the subtree rollup count for a tag with 0 direct documents', async () => {
		// 0 direct documents, but the subtree rolls up to 8 — the widget shows the rollup.
		const tags = [makeTag('Reisen', 0, [], 8)];
		render(ThemenWidget, { tags });
		expect(document.body.textContent).toContain('Reisen');
		expect(document.body.textContent).toContain('8');
	});

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

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

	it('renders in compact single-column mode when compact prop is true', async () => {
		const tags = [makeTag('Briefe', 5)];
		const { container } = render(ThemenWidget, { tags, compact: true });
		const grid = container.querySelector('[data-compact="true"]');
		expect(grid).not.toBeNull();
	});

	it('links to "Alle Themen" page', async () => {
		const tags = [makeTag('Briefe', 5)];
		const { getByRole } = render(ThemenWidget, { tags });
		const link = getByRole('link', { name: /Alle Themen/ });
		await expect.element(link).toHaveAttribute('href', '/themen');
	});
});
