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

afterEach(cleanup);

const persons = [
	{ id: 'p1', firstName: 'Anna', lastName: 'Müller' },
	{ id: 'p2', firstName: 'Hans', lastName: 'Schmidt' }
];

describe('OverflowPillButton', () => {
	it('renders button with correct aria-haspopup and collapsed aria-expanded', async () => {
		render(OverflowPillButton, { extraCount: 2, persons });
		const btn = page.getByRole('button');
		await expect.element(btn).toHaveAttribute('aria-haspopup', 'true');
		await expect.element(btn).toHaveAttribute('aria-expanded', 'false');
	});

	it('shows tooltip on click and sets aria-expanded true', async () => {
		render(OverflowPillButton, { extraCount: 2, persons });
		const btn = page.getByRole('button');
		await userEvent.click(btn);
		const tooltip = page.getByRole('list');
		await expect.element(tooltip).toBeInTheDocument();
		await expect.element(btn).toHaveAttribute('aria-expanded', 'true');
	});

	it('closes tooltip on Escape and returns focus to button', async () => {
		render(OverflowPillButton, { extraCount: 2, persons });
		const btn = page.getByRole('button');
		await userEvent.click(btn);
		await expect.element(page.getByRole('list')).toBeInTheDocument();
		await userEvent.keyboard('{Escape}');
		await expect.element(page.getByRole('list')).not.toBeInTheDocument();
		await expect.element(btn).toHaveFocus();
	});

	it('renders person links inside tooltip', async () => {
		render(OverflowPillButton, { extraCount: 2, persons });
		await userEvent.click(page.getByRole('button'));
		const links = page.getByRole('link');
		await expect.element(links.nth(0)).toHaveAttribute('href', '/persons/p1');
		await expect.element(links.nth(1)).toHaveAttribute('href', '/persons/p2');
	});
});
