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

afterEach(cleanup);

const makeStory = (overrides: Record<string, unknown> = {}) => ({
	id: 'g1',
	title: 'Reise nach Berlin',
	body: '<p>Brief text content</p>',
	publishedAt: '2026-04-15T10:00:00Z',
	updatedAt: '2026-04-15T10:00:00Z',
	...overrides
});

describe('ReaderRecentStories', () => {
	it('renders nothing when stories is empty', async () => {
		render(ReaderRecentStories, { props: { stories: [] } });

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

	it('renders the heading and one row per story', async () => {
		render(ReaderRecentStories, {
			props: {
				stories: [
					makeStory({ id: 'g1', title: 'Story 1' }),
					makeStory({ id: 'g2', title: 'Story 2' })
				]
			}
		});

		await expect.element(page.getByRole('heading', { name: /neue geschichten/i })).toBeVisible();
		await expect.element(page.getByText('Story 1')).toBeVisible();
		await expect.element(page.getByText('Story 2')).toBeVisible();
	});

	it('renders the link to /geschichten in the header', async () => {
		render(ReaderRecentStories, { props: { stories: [makeStory()] } });

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

	it('renders the story link to /geschichten/{id}', async () => {
		render(ReaderRecentStories, { props: { stories: [makeStory({ id: 'g-42' })] } });

		const links = document.querySelectorAll('a[href^="/geschichten/"]');
		const detailLinks = Array.from(links).filter((a) =>
			(a as HTMLAnchorElement).href.includes('/geschichten/g-42')
		);
		expect(detailLinks.length).toBe(1);
	});

	it('renders the body excerpt when present', async () => {
		render(ReaderRecentStories, {
			props: { stories: [makeStory({ body: '<p>Once upon a time in 1923</p>' })] }
		});

		await expect.element(page.getByText(/Once upon a time in 1923/)).toBeVisible();
	});

	it('omits the excerpt paragraph when body is empty', async () => {
		render(ReaderRecentStories, {
			props: { stories: [makeStory({ body: '' })] }
		});

		const paragraphs = document.querySelectorAll('p');
		expect(paragraphs.length).toBe(0);
	});
});
