import { describe, it, expect, afterEach } from 'vitest';
import { cleanup, render } from 'vitest-browser-svelte';
import { page } from 'vitest/browser';
import TranscriptionColumn from './TranscriptionColumn.svelte';
import type { components } from '$lib/generated/api';

type TranscriptionQueueItemDTO = components['schemas']['TranscriptionQueueItemDTO'];

afterEach(cleanup);

function makeDoc(overrides: Partial<TranscriptionQueueItemDTO> = {}): TranscriptionQueueItemDTO {
	return {
		id: 'doc-1',
		title: 'Test Dokument',
		annotationCount: 0,
		textedBlockCount: 0,
		reviewedBlockCount: 0,
		contributors: [],
		hasMoreContributors: false,
		...overrides
	};
}

describe('TranscriptionColumn', () => {
	it('renders document list when docs are provided', async () => {
		const doc1 = makeDoc({ id: 'doc-1', title: 'Familienbrief' });
		const doc2 = makeDoc({ id: 'doc-2', title: 'Tagebuch Eintrag' });

		render(TranscriptionColumn, { props: { docs: [doc1, doc2], weeklyCount: 0 } });

		await expect.element(page.getByText('Familienbrief')).toBeInTheDocument();
		await expect.element(page.getByText('Tagebuch Eintrag')).toBeInTheDocument();
	});

	it('renders dashed empty state when docs array is empty', async () => {
		render(TranscriptionColumn, { props: { docs: [], weeklyCount: 0 } });

		await expect
			.element(page.getByText('Keine Dokumente warten auf Transkription.'))
			.toBeInTheDocument();
	});

	it('renders progress bar when textedBlockCount > 0', async () => {
		const doc = makeDoc({
			id: 'doc-1',
			title: 'Brief mit Blöcken',
			annotationCount: 4,
			textedBlockCount: 2
		});

		render(TranscriptionColumn, { props: { docs: [doc], weeklyCount: 0 } });

		// The progress text should show "2 / 4 Blöcke"
		await expect.element(page.getByText('2 / 4 Blöcke')).toBeInTheDocument();

		// A progress bar div should exist (the visual bar)
		const progressBar = document.querySelector('.h-1.flex-1');
		expect(progressBar).not.toBeNull();
	});

	it('renders dash placeholder when textedBlockCount is 0', async () => {
		const doc = makeDoc({
			id: 'doc-1',
			title: 'Brief ohne Blöcke',
			annotationCount: 3,
			textedBlockCount: 0
		});

		render(TranscriptionColumn, { props: { docs: [doc], weeklyCount: 0 } });

		// The italic em-dash placeholder should render
		const dashEl = document.querySelector('span.italic');
		expect(dashEl).not.toBeNull();
		expect(dashEl?.textContent?.trim()).toBe('—');
	});

	it('links to /documents/{id}?task=transcribe', async () => {
		const doc = makeDoc({ id: 'xyz-456', title: 'Transkriptions Dokument' });

		render(TranscriptionColumn, { props: { docs: [doc], weeklyCount: 0 } });

		const link = page.getByRole('link', { name: /Transkriptions Dokument/ });
		await expect.element(link).toHaveAttribute('href', '/documents/xyz-456?task=transcribe');
	});
});
