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

afterEach(cleanup);

const baseProps = {
	doc: { id: 'd1', filePath: null, contentType: null, fileHash: null },
	fileUrl: '',
	isLoading: false,
	error: '',
	transcribeMode: false,
	blockNumbers: {},
	annotationReloadKey: 0,
	activeAnnotationId: null,
	annotationsDimmed: false,
	flashAnnotationId: null,
	onAnnotationClick: () => {}
};

describe('DocumentViewer', () => {
	it('renders the loading spinner and label when isLoading is true', async () => {
		render(DocumentViewer, { props: { ...baseProps, isLoading: true } });

		await expect.element(page.getByText('Lade Dokument...')).toBeVisible();
	});

	it('renders the error message when error is set', async () => {
		render(DocumentViewer, { props: { ...baseProps, error: 'Datei nicht verfügbar' } });

		await expect.element(page.getByText('Datei nicht verfügbar')).toBeVisible();
	});

	it('shows the direct-download link in the error state when filePath is present', async () => {
		render(DocumentViewer, {
			props: {
				...baseProps,
				doc: { ...baseProps.doc, filePath: 'docs/scan.pdf' },
				error: 'Render failed'
			}
		});

		await expect
			.element(page.getByRole('link', { name: /direkter download/i }))
			.toHaveAttribute('href', '/api/documents/d1/file');
	});

	it('hardens the target=_blank download link with rel=noopener noreferrer (CWE-1022)', async () => {
		render(DocumentViewer, {
			props: {
				...baseProps,
				doc: { ...baseProps.doc, filePath: 'docs/scan.pdf' },
				error: 'Render failed'
			}
		});

		await expect
			.element(page.getByRole('link', { name: /direkter download/i }))
			.toHaveAttribute('rel', 'noopener noreferrer');
	});

	it('omits the direct-download link in the error state when filePath is null', async () => {
		render(DocumentViewer, { props: { ...baseProps, error: 'Render failed' } });

		await expect
			.element(page.getByRole('link', { name: /direkter download/i }))
			.not.toBeInTheDocument();
	});

	it('renders the no-scan placeholder when filePath is null and there is no error', async () => {
		render(DocumentViewer, { props: baseProps });

		await expect.element(page.getByText('Kein Scan vorhanden')).toBeVisible();
	});

	it('renders an <img> for non-PDF content types when fileUrl is present', async () => {
		render(DocumentViewer, {
			props: {
				...baseProps,
				doc: { ...baseProps.doc, filePath: 'docs/x.jpg', contentType: 'image/jpeg' },
				fileUrl: '/api/documents/d1/file'
			}
		});

		const img = await page.getByRole('img', { name: /original-scan/i }).element();
		expect(img.getAttribute('src')).toBe('/api/documents/d1/file');
	});
});
