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

afterEach(cleanup);

describe('CorrespondenzHero', () => {
	it('renders the headline and cross-link', async () => {
		render(CorrespondenzHero, { props: { onSelectPerson: () => {} } });

		await expect.element(page.getByRole('heading', { name: /wessen briefe/i })).toBeVisible();
		await expect.element(page.getByRole('link', { name: /dokumentensuche/i })).toBeVisible();
	});

	it('omits the recent-persons section when recentPersons is empty', async () => {
		render(CorrespondenzHero, { props: { onSelectPerson: () => {} } });

		await expect.element(page.getByText('Zuletzt geöffnet')).not.toBeInTheDocument();
	});

	it('renders the recent-persons divider and chips when persons are provided', async () => {
		render(CorrespondenzHero, {
			props: {
				onSelectPerson: () => {},
				recentPersons: [
					{ id: 'p1', name: 'Anna Schmidt' },
					{ id: 'p2', name: 'Bert Meier' }
				]
			}
		});

		await expect.element(page.getByText('Zuletzt geöffnet')).toBeVisible();
		await expect.element(page.getByText('Anna Schmidt')).toBeVisible();
		await expect.element(page.getByText('Bert Meier')).toBeVisible();
	});

	it('calls onSelectPerson with the recent-person id when clicked', async () => {
		const onSelectPerson = vi.fn();
		render(CorrespondenzHero, {
			props: {
				onSelectPerson,
				recentPersons: [{ id: 'p-42', name: 'Anna Schmidt' }]
			}
		});

		const btn = document.querySelector('[data-testid="recent-person-p-42"]') as HTMLButtonElement;
		btn.click();

		expect(onSelectPerson).toHaveBeenCalledWith('p-42');
	});

	it('renders the avatar initial in the recent-person chip', async () => {
		render(CorrespondenzHero, {
			props: {
				onSelectPerson: () => {},
				recentPersons: [{ id: 'p1', name: 'anna schmidt' }]
			}
		});

		// Avatar shows the uppercase first letter
		const avatars = document.querySelectorAll(
			'[data-testid^="recent-person-"] span[aria-hidden="true"]'
		);
		expect(avatars[0].textContent?.trim()).toBe('A');
	});
});
