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

afterEach(cleanup);

const baseData = (overrides: Record<string, unknown> = {}) => ({
	documents: [] as { id: string; title: string }[],
	canWrite: false,
	...overrides
});

describe('enrich/+ page', () => {
	it('renders the page heading', async () => {
		render(EnrichListPage, { props: { data: baseData() } });

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

	it('renders the empty placeholder when there are no documents', async () => {
		render(EnrichListPage, { props: { data: baseData() } });

		await expect.element(page.getByText('Alle Dokumente vollständig')).toBeVisible();
	});

	it('hides the document count and start CTA when the list is empty', async () => {
		render(EnrichListPage, { props: { data: baseData() } });

		await expect
			.element(page.getByRole('link', { name: /überprüfung starten/i }))
			.not.toBeInTheDocument();
	});

	it('renders the count when documents are present', async () => {
		render(EnrichListPage, {
			props: {
				data: baseData({
					documents: [
						{ id: 'd1', title: 'Brief 1' },
						{ id: 'd2', title: 'Brief 2' },
						{ id: 'd3', title: 'Brief 3' }
					]
				})
			}
		});

		await expect.element(page.getByText(/3\s+Dokumente/)).toBeVisible();
	});

	it('points the start CTA to the first document', async () => {
		render(EnrichListPage, {
			props: {
				data: baseData({
					documents: [
						{ id: 'first-doc', title: 'Brief 1' },
						{ id: 'd2', title: 'Brief 2' }
					]
				})
			}
		});

		await expect
			.element(page.getByRole('link', { name: /überprüfung starten/i }))
			.toHaveAttribute('href', '/enrich/first-doc');
	});

	it('renders one row per document with title visible', async () => {
		render(EnrichListPage, {
			props: {
				data: baseData({
					documents: [
						{ id: 'd1', title: 'Tagebucheintrag 1923' },
						{ id: 'd2', title: 'Postkarte aus Berlin' }
					]
				})
			}
		});

		await expect.element(page.getByText('Tagebucheintrag 1923')).toBeVisible();
		await expect.element(page.getByText('Postkarte aus Berlin')).toBeVisible();
	});

	it('renders the bulk-select checkbox per row when canWrite is true', async () => {
		render(EnrichListPage, {
			props: {
				data: baseData({
					canWrite: true,
					documents: [{ id: 'd1', title: 'Brief 1' }]
				})
			}
		});

		const checkbox = document.querySelector('input[type="checkbox"]');
		expect(checkbox).not.toBeNull();
	});

	it('omits the bulk-select checkbox when canWrite is false', async () => {
		render(EnrichListPage, {
			props: {
				data: baseData({
					canWrite: false,
					documents: [{ id: 'd1', title: 'Brief 1' }]
				})
			}
		});

		const checkbox = document.querySelector('li input[type="checkbox"]');
		expect(checkbox).toBeNull();
	});
});
