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

afterEach(cleanup);

const persons = [
	{ id: 'p1', firstName: 'Anna', lastName: 'Schmidt', displayName: 'Anna Schmidt' },
	{ id: 'p2', firstName: 'Bert', lastName: 'Meier', displayName: 'Bert Meier' }
];

describe('OverflowPillButton', () => {
	it('renders the +N pill labelled with the count', async () => {
		render(OverflowPillButton, { props: { extraCount: 3, persons } });

		await expect.element(page.getByText(/\+3/)).toBeVisible();
	});

	it('starts with aria-expanded=false', async () => {
		render(OverflowPillButton, { props: { extraCount: 2, persons } });

		await expect
			.element(page.getByRole('button', { name: /weitere empfänger/i }))
			.toHaveAttribute('aria-expanded', 'false');
	});

	it('opens the dropdown when the pill is clicked', async () => {
		render(OverflowPillButton, { props: { extraCount: 2, persons } });

		await page.getByRole('button', { name: /weitere empfänger/i }).click();

		await expect
			.element(page.getByRole('button', { name: /weitere empfänger/i }))
			.toHaveAttribute('aria-expanded', 'true');
	});

	it('renders one link per person inside the open dropdown', async () => {
		render(OverflowPillButton, { props: { extraCount: 2, persons } });

		await page.getByRole('button', { name: /weitere empfänger/i }).click();

		await expect
			.element(page.getByRole('link', { name: 'Anna Schmidt' }))
			.toHaveAttribute('href', '/persons/p1');
		await expect
			.element(page.getByRole('link', { name: 'Bert Meier' }))
			.toHaveAttribute('href', '/persons/p2');
	});

	it('closes the dropdown when Escape is pressed', async () => {
		render(OverflowPillButton, { props: { extraCount: 2, persons } });

		const btn = page.getByRole('button', { name: /weitere empfänger/i });
		await btn.click();
		const btnEl = (await btn.element()) as HTMLButtonElement;
		btnEl.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));

		await expect.element(btn).toHaveAttribute('aria-expanded', 'false');
	});
});
