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

afterEach(cleanup);

const makePerson = (overrides: Record<string, unknown> = {}) => ({
	id: 'p1',
	displayName: 'Anna Schmidt',
	lastName: 'Schmidt',
	documentCount: 5,
	...overrides
});

describe('ReaderPersonChips', () => {
	it('renders the section with the persons heading via aria-label', async () => {
		render(ReaderPersonChips, { props: { persons: [] } });

		await expect.element(page.getByRole('region', { name: /personen/i })).toBeVisible();
	});

	it('renders the no-persons placeholder when persons is empty', async () => {
		render(ReaderPersonChips, { props: { persons: [] } });

		await expect.element(page.getByText('Noch keine Personen im Archiv.')).toBeVisible();
	});

	it('renders one chip per person with link to person detail', async () => {
		render(ReaderPersonChips, {
			props: {
				persons: [
					makePerson({ id: 'p1', displayName: 'Anna Schmidt' }),
					makePerson({ id: 'p2', displayName: 'Bert Meier' })
				]
			}
		});

		await expect
			.element(page.getByRole('link', { name: /anna schmidt/i }))
			.toHaveAttribute('href', '/persons/p1');
		await expect
			.element(page.getByRole('link', { name: /bert meier/i }))
			.toHaveAttribute('href', '/persons/p2');
	});

	it('renders document count chip when documentCount > 0', async () => {
		render(ReaderPersonChips, {
			props: { persons: [makePerson({ documentCount: 7 })] }
		});

		await expect.element(page.getByText('7')).toBeVisible();
	});

	it('omits document count chip when documentCount is 0', async () => {
		render(ReaderPersonChips, {
			props: { persons: [makePerson({ documentCount: 0 })] }
		});

		await expect.element(page.getByText('0')).not.toBeInTheDocument();
	});

	it('falls back to lastName when displayName is missing', async () => {
		render(ReaderPersonChips, {
			props: {
				persons: [makePerson({ displayName: null, lastName: 'Schmidt' })]
			}
		});

		await expect.element(page.getByRole('link', { name: /schmidt/i })).toBeVisible();
	});

	it('renders the all-persons footer link', async () => {
		render(ReaderPersonChips, { props: { persons: [makePerson()] } });

		await expect
			.element(page.getByRole('link', { name: /alle personen/i }))
			.toHaveAttribute('href', '/persons');
	});
});
