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

afterEach(cleanup);

const allTags = [
	{ id: 't1', name: 'Root', documentCount: 0 },
	{ id: 't2', name: 'Child', parentId: 't1', documentCount: 0 },
	{ id: 't3', name: 'Grandchild', parentId: 't2', documentCount: 0 }
];

describe('TagAncestry', () => {
	it('renders nothing for a root tag', async () => {
		const { container } = render(TagAncestry, {
			tag: { id: 't1', name: 'Root', documentCount: 0 },
			allTags
		});
		expect(container.querySelector('nav')).toBeFalsy();
	});

	it('renders a nav element for a child tag', async () => {
		const { container } = render(TagAncestry, {
			tag: { id: 't2', name: 'Child', parentId: 't1', documentCount: 0 },
			allTags
		});
		expect(container.querySelector('nav')).toBeTruthy();
	});

	it('shows parent name as a link', async () => {
		render(TagAncestry, {
			tag: { id: 't2', name: 'Child', parentId: 't1', documentCount: 0 },
			allTags
		});
		await expect.element(page.getByRole('link', { name: 'Root' })).toBeInTheDocument();
		await expect
			.element(page.getByRole('link', { name: 'Root' }))
			.toHaveAttribute('href', '/admin/tags/t1');
	});

	it('shows full ancestor chain for deeply nested tag', async () => {
		render(TagAncestry, {
			tag: { id: 't3', name: 'Grandchild', parentId: 't2', documentCount: 0 },
			allTags
		});
		await expect.element(page.getByRole('link', { name: 'Root' })).toBeInTheDocument();
		await expect.element(page.getByRole('link', { name: 'Child' })).toBeInTheDocument();
	});

	it('does not render current tag as a link', async () => {
		render(TagAncestry, {
			tag: { id: 't2', name: 'Child', parentId: 't1', documentCount: 0 },
			allTags
		});
		const links = document.querySelectorAll('nav a');
		const linkTexts = Array.from(links).map((a) => a.textContent?.trim());
		expect(linkTexts).not.toContain('Child');
	});
});
