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

vi.mock('$app/navigation', () => ({
	beforeNavigate: () => {},
	afterNavigate: () => {},
	goto: vi.fn(),
	invalidate: vi.fn(),
	invalidateAll: vi.fn(),
	preloadCode: vi.fn(),
	preloadData: vi.fn(),
	pushState: vi.fn(),
	replaceState: vi.fn(),
	disableScrollHandling: vi.fn(),
	onNavigate: () => () => {}
}));

const { default: DocumentList } = await import('./DocumentList.svelte');

afterEach(cleanup);

const sender = {
	id: 's1',
	lastName: 'Schmidt',
	displayName: 'Anna Schmidt',
	personType: 'PERSON' as const,
	familyMember: false
};
const receiver = {
	id: 'r1',
	lastName: 'Meier',
	displayName: 'Bert Meier',
	personType: 'PERSON' as const,
	familyMember: false
};

const emptyMatchData = {
	titleOffsets: [],
	senderMatched: false,
	matchedReceiverIds: [],
	matchedTagIds: [],
	snippetOffsets: [],
	summaryOffsets: []
};

const makeItem = (overrides: Record<string, unknown> = {}) => ({
	id: 'd1',
	title: 'Brief 1923',
	originalFilename: 'b.pdf',
	documentDate: '1923-04-15',
	sender,
	receivers: [receiver],
	tags: [],
	summary: undefined,
	archiveBox: undefined,
	archiveFolder: undefined,
	location: undefined,
	matchData: emptyMatchData,
	completionPercentage: 0,
	contributors: [],
	...overrides
});

describe('DocumentList', () => {
	it('renders the empty state when items is empty', async () => {
		render(DocumentList, { props: { items: [], canWrite: false } });

		await expect
			.element(page.getByRole('heading', { name: /keine dokumente gefunden/i }))
			.toBeVisible();
	});

	it('renders the term-specific empty message when q is set', async () => {
		render(DocumentList, { props: { items: [], canWrite: false, q: 'Helene' } });

		await expect.element(page.getByText(/Keine Dokumente für "Helene"/i)).toBeVisible();
	});

	it('renders the error banner when error prop is set', async () => {
		render(DocumentList, {
			props: { items: [], canWrite: false, error: 'Server unreachable' }
		});

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

	it('renders one group card per year by default', async () => {
		render(DocumentList, {
			props: {
				items: [
					makeItem({ id: 'd1', documentDate: '1923-04-15' }),
					makeItem({ id: 'd2', documentDate: '1925-06-20' })
				],
				canWrite: false
			}
		});

		const groups = document.querySelectorAll('[data-testid="group-card"]');
		expect(groups.length).toBe(2);
	});

	it('groups by sender when sort=SENDER', async () => {
		render(DocumentList, {
			props: {
				items: [
					makeItem({
						id: 'd1',
						sender: {
							id: 's1',
							lastName: 'Schmidt',
							displayName: 'Anna Schmidt',
							personType: 'PERSON',
							familyMember: false
						}
					}),
					makeItem({
						id: 'd2',
						sender: {
							id: 's2',
							lastName: 'Meier',
							displayName: 'Bert Meier',
							personType: 'PERSON',
							familyMember: false
						}
					})
				],
				canWrite: false,
				sort: 'SENDER' as const
			}
		});

		const groupHeaders = document.querySelectorAll('[data-testid="group-header"]');
		expect(groupHeaders.length).toBe(2);
	});

	it('uses "Undatiert" group label for items without documentDate', async () => {
		render(DocumentList, {
			props: { items: [makeItem({ documentDate: null })], canWrite: false }
		});

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

	it('uses "Unbekannter Absender" when sort=SENDER and no sender', async () => {
		render(DocumentList, {
			props: {
				items: [makeItem({ sender: null })],
				canWrite: false,
				sort: 'SENDER' as const
			}
		});

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

	it('renders the result count when total is provided and > 0', async () => {
		render(DocumentList, {
			props: { items: [makeItem()], canWrite: false, total: 42 }
		});

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