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

afterEach(cleanup);

const allTags = [
	{ id: 't1', name: 'Root', documentCount: 0 },
	{ id: 't2', name: 'Alpha', parentId: 't1', documentCount: 0 },
	{ id: 't3', name: 'Beta', parentId: 't1', documentCount: 0 },
	{ id: 't4', name: 'Gamma', parentId: 't1', documentCount: 0 },
	{ id: 't5', name: 'Delta', parentId: 't1', documentCount: 0 },
	{ id: 't6', name: 'Epsilon', parentId: 't1', documentCount: 0 },
	{ id: 't7', name: 'Zeta', parentId: 't1', documentCount: 0 }
];

describe('TagChildrenPreview', () => {
	it('renders nothing for a leaf tag', async () => {
		const { container } = render(TagChildrenPreview, {
			tag: { id: 't2', name: 'Alpha', parentId: 't1', documentCount: 0 },
			allTags
		});
		expect(container.querySelector('[data-testid="children-preview"]')).toBeFalsy();
	});

	it('renders section heading for a tag with children', async () => {
		render(TagChildrenPreview, {
			tag: { id: 't1', name: 'Root', documentCount: 0 },
			allTags
		});
		await expect.element(page.getByTestId('children-preview')).toBeInTheDocument();
	});

	it('shows up to 5 children as chips', async () => {
		render(TagChildrenPreview, {
			tag: { id: 't1', name: 'Root', documentCount: 0 },
			allTags
		});
		// Alpha through Epsilon should be visible (5 chips)
		await expect.element(page.getByText('Alpha')).toBeInTheDocument();
		await expect.element(page.getByText('Epsilon')).toBeInTheDocument();
	});

	it('shows expand button when there are more than 5 children', async () => {
		render(TagChildrenPreview, {
			tag: { id: 't1', name: 'Root', documentCount: 0 },
			allTags
		});
		// There are 6 children — should show "und 1 weitere" expand button
		const expandBtn = document.querySelector<HTMLButtonElement>(
			'button[data-testid="expand-children"]'
		);
		expect(expandBtn).toBeTruthy();
	});

	it('expand button reveals hidden children inline', async () => {
		render(TagChildrenPreview, {
			tag: { id: 't1', name: 'Root', documentCount: 0 },
			allTags
		});
		// Zeta is hidden behind the expand button
		await expect.element(page.getByText('Zeta')).not.toBeInTheDocument();
		await page.getByTestId('expand-children').click();
		await expect.element(page.getByText('Zeta')).toBeInTheDocument();
	});

	it('does not show expand button when children count <= 5', async () => {
		render(TagChildrenPreview, {
			tag: { id: 't1', name: 'Root', documentCount: 0 },
			allTags: allTags.slice(0, 4) // Root + 3 children
		});
		expect(document.querySelector('[data-testid="expand-children"]')).toBeFalsy();
	});
});
