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

afterEach(cleanup);

const makeDoc = (overrides: Record<string, unknown> = {}) => ({
	id: 'd1',
	title: 'Brief 1923',
	updatedAt: '2026-04-15T10:00:00Z',
	...overrides
});

describe('DashboardRecentDocuments', () => {
	it('renders nothing when recentDocs is empty', async () => {
		render(DashboardRecentDocuments, { props: { recentDocs: [] } });

		expect(document.querySelector('[data-testid="dashboard-recent-docs"]')).toBeNull();
	});

	it('renders the heading and one row per doc', async () => {
		render(DashboardRecentDocuments, {
			props: { recentDocs: [makeDoc({ id: 'd1', title: 'A' }), makeDoc({ id: 'd2', title: 'B' })] }
		});

		await expect.element(page.getByRole('heading', { name: /zuletzt aktiv/i })).toBeVisible();
		expect(document.querySelectorAll('[data-testid^="doc-row-"]').length).toBe(2);
	});

	it('renders the title as a link to the document detail', async () => {
		render(DashboardRecentDocuments, { props: { recentDocs: [makeDoc()] } });

		await expect
			.element(page.getByRole('link', { name: 'Brief 1923' }))
			.toHaveAttribute('href', '/documents/d1');
	});

	it('renders the formatted date when updatedAt is present', async () => {
		render(DashboardRecentDocuments, { props: { recentDocs: [makeDoc()] } });

		expect(document.querySelector('[data-testid="doc-date-d1"]')).not.toBeNull();
	});

	it('omits the date when updatedAt is undefined', async () => {
		render(DashboardRecentDocuments, {
			props: { recentDocs: [makeDoc({ updatedAt: undefined })] }
		});

		expect(document.querySelector('[data-testid="doc-date-d1"]')).toBeNull();
	});

	it('renders the stats footnote when stats.totalDocuments is set', async () => {
		render(DashboardRecentDocuments, {
			props: {
				recentDocs: [makeDoc()],
				stats: { totalDocuments: 50, totalPersons: 12 } as unknown as never
			}
		});

		const footnote = document.querySelector('[data-testid="dashboard-stats-footnote"]');
		expect(footnote?.textContent).toContain('50');
		expect(footnote?.textContent).toContain('12');
	});

	it('omits the stats footnote when stats is null', async () => {
		render(DashboardRecentDocuments, { props: { recentDocs: [makeDoc()], stats: null } });

		expect(document.querySelector('[data-testid="dashboard-stats-footnote"]')).toBeNull();
	});
});
