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

import DashboardNeedsMetadata from './DashboardNeedsMetadata.svelte';

afterEach(cleanup);

type IncompleteDoc = { id: string; title: string; uploadedAt: string };

function makeDoc(id: string, title: string, uploadedAt = '2026-04-20T12:00:00'): IncompleteDoc {
	return { id, title, uploadedAt };
}

describe('DashboardNeedsMetadata', () => {
	it('renders nothing when topDocs is empty', async () => {
		render(DashboardNeedsMetadata, { topDocs: [], totalCount: 0 });
		const widget = page.getByTestId('dashboard-needs-metadata');
		await expect.element(widget).not.toBeInTheDocument();
	});

	it('shows the widget when topDocs is present', async () => {
		render(DashboardNeedsMetadata, { topDocs: [makeDoc('d1', 'Taufschein')], totalCount: 1 });
		await expect.element(page.getByTestId('dashboard-needs-metadata')).toBeInTheDocument();
	});

	it('renders one link per row pointing at /enrich/{id}', async () => {
		const docs = [makeDoc('d1', 'Taufschein'), makeDoc('d2', 'Heiratsurkunde')];
		render(DashboardNeedsMetadata, { topDocs: docs, totalCount: 2 });
		await expect
			.element(page.getByRole('link', { name: /Taufschein/ }))
			.toHaveAttribute('href', '/enrich/d1');
		await expect
			.element(page.getByRole('link', { name: /Heiratsurkunde/ }))
			.toHaveAttribute('href', '/enrich/d2');
	});

	it('hides the footer link when totalCount is 5 or fewer', async () => {
		const docs = Array.from({ length: 5 }, (_, i) => makeDoc(`d${i}`, `Dok ${i}`));
		render(DashboardNeedsMetadata, { topDocs: docs, totalCount: 5 });
		const footer = page.getByRole('link', { name: /Alle/i });
		await expect.element(footer).not.toBeInTheDocument();
	});

	it('shows the footer link with totalCount when totalCount > 5', async () => {
		const docs = Array.from({ length: 5 }, (_, i) => makeDoc(`d${i}`, `Dok ${i}`));
		render(DashboardNeedsMetadata, { topDocs: docs, totalCount: 12 });
		const footer = page.getByRole('link', { name: /12/ });
		await expect.element(footer).toHaveAttribute('href', '/enrich');
	});

	it('uses totalCount in the footer even when topDocs has fewer items', async () => {
		const docs = [makeDoc('d1', 'Only one')];
		render(DashboardNeedsMetadata, { topDocs: docs, totalCount: 50 });
		await expect.element(page.getByRole('link', { name: /Alle 50/ })).toBeInTheDocument();
	});
});
