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

afterEach(cleanup);

const baseProps = {
	title: 'Brief an Helene' as string | null,
	originalFilename: 'brief.pdf' as string | null,
	documentDate: '1923-04-15' as string | null
};

describe('DocumentTopBarTitle', () => {
	it('renders the title as a level-1 heading', async () => {
		render(DocumentTopBarTitle, { props: baseProps });

		await expect
			.element(page.getByRole('heading', { level: 1, name: 'Brief an Helene' }))
			.toBeVisible();
	});

	it('falls back to originalFilename when title is null', async () => {
		render(DocumentTopBarTitle, { props: { ...baseProps, title: null } });

		await expect.element(page.getByRole('heading', { name: 'brief.pdf' })).toBeVisible();
	});

	it('falls back to originalFilename when title is an empty string', async () => {
		render(DocumentTopBarTitle, { props: { ...baseProps, title: '' } });

		await expect.element(page.getByRole('heading', { name: 'brief.pdf' })).toBeVisible();
	});

	it('renders the precision-aware long date when a documentDate is supplied', async () => {
		render(DocumentTopBarTitle, { props: baseProps });

		// '1923-04-15' defaults to DAY precision and renders the honest long German
		// label via formatDocumentDate (Refs #666), not the old short form.
		await expect.element(page.getByText('15. April 1923')).toBeVisible();
	});

	it('omits the date paragraph entirely when documentDate is null', async () => {
		render(DocumentTopBarTitle, { props: { ...baseProps, documentDate: null } });

		expect(document.querySelector('p')).toBeNull();
	});

	it('uses the title (not the originalFilename) for the title attribute when title is set', async () => {
		render(DocumentTopBarTitle, { props: baseProps });

		const heading = (await page
			.getByRole('heading', { name: 'Brief an Helene' })
			.element()) as HTMLElement;
		expect(heading.getAttribute('title')).toBe('Brief an Helene');
	});

	it('uses the originalFilename for the title attribute when title is null', async () => {
		render(DocumentTopBarTitle, { props: { ...baseProps, title: null } });

		const heading = (await page
			.getByRole('heading', { name: 'brief.pdf' })
			.element()) as HTMLElement;
		expect(heading.getAttribute('title')).toBe('brief.pdf');
	});
});
