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

afterEach(cleanup);

const makeDoc = (overrides: Record<string, unknown> = {}) => ({
	id: 'd1',
	title: 'Brief 1923',
	createdAt: '2026-04-15T10:00:00Z',
	updatedAt: '2026-04-15T10:00:00Z',
	sender: { id: 's1', firstName: 'Anna', lastName: 'Schmidt', displayName: 'Anna Schmidt' },
	...overrides
});

describe('ReaderRecentDocs', () => {
	it('renders the heading', async () => {
		render(ReaderRecentDocs, { props: { documents: [] } });

		await expect
			.element(page.getByRole('heading', { name: /zuletzt aktualisiert/i }))
			.toBeVisible();
	});

	it('renders the all-documents link', async () => {
		render(ReaderRecentDocs, { props: { documents: [] } });

		await expect
			.element(page.getByRole('link', { name: /alle dokumente/i }))
			.toHaveAttribute('href', '/documents');
	});

	it('renders the New badge when document was created within the last 7 days', async () => {
		const recentDate = new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString();
		const laterUpdate = new Date(Date.now() - 1 * 24 * 60 * 60 * 1000).toISOString();
		render(ReaderRecentDocs, {
			props: {
				documents: [makeDoc({ createdAt: recentDate, updatedAt: laterUpdate })]
			}
		});

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

	it('hides the New badge when document was created more than 7 days ago', async () => {
		render(ReaderRecentDocs, {
			props: {
				documents: [
					makeDoc({
						createdAt: '2026-04-15T10:00:00Z',
						updatedAt: '2026-04-15T10:00:00Z'
					})
				]
			}
		});

		await expect.element(page.getByText('Neu')).not.toBeInTheDocument();
	});

	it('renders the sender displayName', async () => {
		render(ReaderRecentDocs, { props: { documents: [makeDoc()] } });

		await expect.element(page.getByText('Anna Schmidt')).toBeVisible();
	});

	it('falls back to em-dash when sender is null', async () => {
		render(ReaderRecentDocs, {
			props: { documents: [makeDoc({ sender: null })] }
		});

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

	it('falls back to lastName when displayName is missing', async () => {
		render(ReaderRecentDocs, {
			props: {
				documents: [
					makeDoc({
						sender: { id: 's1', firstName: 'Anna', lastName: 'Schmidt', displayName: null }
					})
				]
			}
		});

		await expect.element(page.getByText(/Schmidt/)).toBeVisible();
	});

	it('renders the document link to /documents/{id}', async () => {
		render(ReaderRecentDocs, { props: { documents: [makeDoc({ id: 'd-42' })] } });

		const links = document.querySelectorAll('a[href^="/documents/"]');
		expect(
			Array.from(links).some((a) => (a as HTMLAnchorElement).href.includes('/documents/d-42'))
		).toBe(true);
	});
});
