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

afterEach(cleanup);

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

const baseModel = (overrides: Partial<SenderModel> = {}): SenderModel =>
	({
		id: 'm1',
		personId: '123e4567-e89b-12d3-a456-426614174000',
		correctedLinesAtTraining: 100,
		createdAt: '2026-01-01T00:00:00Z',
		updatedAt: '2026-04-01T00:00:00Z',
		cer: 0.05,
		accuracy: 0.95,
		...overrides
	}) as SenderModel;

describe('OcrModelsTable — null/em-dash branches', () => {
	it('renders em-dash when cer is null', async () => {
		render(OcrModelsTable, {
			senderModels: [baseModel({ cer: null as unknown as undefined })],
			personNames: {}
		});

		const tds = document.querySelectorAll('tbody td');
		const cerCell = tds[1] as HTMLTableCellElement;
		expect(cerCell.textContent?.trim()).toBe('—');
	});

	it('renders em-dash when accuracy is null', async () => {
		render(OcrModelsTable, {
			senderModels: [baseModel({ accuracy: null as unknown as undefined })],
			personNames: {}
		});

		const tds = document.querySelectorAll('tbody td');
		const accuracyCell = tds[2] as HTMLTableCellElement;
		expect(accuracyCell.textContent?.trim()).toBe('—');
	});

	it('renders cer as percentage when set', async () => {
		render(OcrModelsTable, {
			senderModels: [baseModel({ cer: 0.0432 })],
			personNames: {}
		});

		const tds = document.querySelectorAll('tbody td');
		const cerCell = tds[1] as HTMLTableCellElement;
		expect(cerCell.textContent?.trim()).toBe('4.3%');
	});

	it('renders accuracy as percentage when set', async () => {
		render(OcrModelsTable, {
			senderModels: [baseModel({ accuracy: 0.967 })],
			personNames: {}
		});

		const tds = document.querySelectorAll('tbody td');
		const accuracyCell = tds[2] as HTMLTableCellElement;
		expect(accuracyCell.textContent?.trim()).toBe('96.7%');
	});

	it('renders the corrected-lines training count as raw number', async () => {
		render(OcrModelsTable, {
			senderModels: [baseModel({ correctedLinesAtTraining: 247 })],
			personNames: {}
		});

		expect(document.body.textContent).toContain('247');
	});

	it('renders multiple models as separate rows', async () => {
		render(OcrModelsTable, {
			senderModels: [
				baseModel({ id: 'm1', personId: 'p1' }),
				baseModel({ id: 'm2', personId: 'p2' })
			],
			personNames: { p1: 'Anna', p2: 'Bertha' }
		});

		const rows = document.querySelectorAll('tbody tr');
		expect(rows.length).toBe(2);
	});
});
