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

vi.mock('$app/navigation', () => ({
	beforeNavigate: () => {},
	afterNavigate: () => {},
	goto: vi.fn(),
	invalidate: vi.fn(),
	invalidateAll: vi.fn(),
	preloadCode: vi.fn(),
	preloadData: vi.fn(),
	pushState: vi.fn(),
	replaceState: vi.fn(),
	disableScrollHandling: vi.fn(),
	onNavigate: () => () => {}
}));

const { default: GeschichtenListPage } = await import('./+page.svelte');

afterEach(cleanup);

const baseData = (overrides: Record<string, unknown> = {}) => ({
	geschichten: [] as Array<{
		id: string;
		title: string;
		body?: string;
		publishedAt?: string;
		author?: { firstName?: string; lastName?: string };
	}>,
	personFilters: [] as { id?: string; displayName: string }[],
	documentFilter: null,
	canBlogWrite: false,
	drafts: [] as Array<{ id: string; title: string }>,
	...overrides
});

describe('geschichten/+ page', () => {
	it('uses the same directory width as Dokumente/Personen overviews (max-w-7xl)', async () => {
		render(GeschichtenListPage, { props: { data: baseData() } });

		const container = document.querySelector('[class*="mx-auto"]');
		expect(container).not.toBeNull();
		expect(container!.className).toContain('max-w-7xl');
	});

	it('renders the page heading', async () => {
		render(GeschichtenListPage, { props: { data: baseData() } });

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

	it('shows the new-geschichte CTA when canBlogWrite is true', async () => {
		render(GeschichtenListPage, { props: { data: baseData({ canBlogWrite: true }) } });

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

	it('hides the new-geschichte CTA when canBlogWrite is false', async () => {
		render(GeschichtenListPage, { props: { data: baseData({ canBlogWrite: false }) } });

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

	it('renders the no-filter empty state when geschichten and personFilters are empty', async () => {
		render(GeschichtenListPage, { props: { data: baseData() } });

		await expect
			.element(page.getByText('Es gibt noch keine veröffentlichten Geschichten.'))
			.toBeVisible();
	});

	it('renders the for-persons empty state when filters are set but no results', async () => {
		render(GeschichtenListPage, {
			props: {
				data: baseData({ personFilters: [{ id: 'p1', displayName: 'Anna Schmidt' }] })
			}
		});

		await expect
			.element(page.getByText(/Keine Geschichten für Anna Schmidt gefunden/i))
			.toBeVisible();
	});

	it('renders the all-pill as pressed when no filters are set', async () => {
		render(GeschichtenListPage, { props: { data: baseData() } });

		await expect
			.element(page.getByRole('button', { name: /^alle$/i }))
			.toHaveAttribute('aria-pressed', 'true');
	});

	it('marks the all-pill not pressed when person filters are set', async () => {
		render(GeschichtenListPage, {
			props: { data: baseData({ personFilters: [{ id: 'p1', displayName: 'Anna' }] }) }
		});

		await expect
			.element(page.getByRole('button', { name: /^alle$/i }))
			.toHaveAttribute('aria-pressed', 'false');
	});

	it('renders one chip per person filter', async () => {
		render(GeschichtenListPage, {
			props: {
				data: baseData({
					personFilters: [
						{ id: 'p1', displayName: 'Anna Schmidt' },
						{ id: 'p2', displayName: 'Bert Meier' }
					]
				})
			}
		});

		await expect
			.element(page.getByRole('button', { name: /Anna Schmidt aus Filter entfernen/i }))
			.toBeVisible();
		await expect
			.element(page.getByRole('button', { name: /Bert Meier aus Filter entfernen/i }))
			.toBeVisible();
	});

	it('renders one card per geschichte when populated', async () => {
		render(GeschichtenListPage, {
			props: {
				data: baseData({
					geschichten: [
						{
							id: 'g1',
							title: 'Reise nach Berlin',
							body: '<p>Im Jahr 1923...</p>',
							publishedAt: '2026-04-15T10:00:00Z',
							author: { firstName: 'Anna', lastName: 'Schmidt' }
						}
					]
				})
			}
		});

		await expect
			.element(page.getByRole('heading', { level: 2, name: /reise nach berlin/i }))
			.toBeVisible();
	});

	it('authorName falls back to [Unbekannt] when first/last names are missing', async () => {
		render(GeschichtenListPage, {
			props: {
				data: baseData({
					geschichten: [
						{
							id: 'g1',
							title: 'Anonym',
							author: {}
						}
					]
				})
			}
		});

		expect(document.body.textContent).toContain('[Unbekannt]');
	});

	it('authorName renders empty when author is undefined', async () => {
		render(GeschichtenListPage, {
			props: {
				data: baseData({
					geschichten: [{ id: 'g1', title: 'No Author' }]
				})
			}
		});

		// Page renders the title fine, no author string
		expect(document.body.textContent).toContain('No Author');
	});

	it('omits the date when publishedAt is missing', async () => {
		render(GeschichtenListPage, {
			props: {
				data: baseData({
					geschichten: [
						{
							id: 'g1',
							title: 'Draft',
							author: { firstName: 'Anna', lastName: 'Schmidt' }
						}
					]
				})
			}
		});

		// No "·" separator before date when no publishedAt
		const titleHeading = document.querySelector('h2');
		const card = titleHeading?.closest('li');
		expect(card?.textContent).toContain('Anna Schmidt');
		// "·" separator must be absent when there is no publishedAt date
		expect(card?.textContent).not.toContain('·');
	});

	it('omits the body excerpt when body is empty', async () => {
		render(GeschichtenListPage, {
			props: {
				data: baseData({
					geschichten: [
						{
							id: 'g1',
							title: 'No Body',
							body: '',
							author: { firstName: 'Anna', lastName: 'Schmidt' }
						}
					]
				})
			}
		});

		const titleHeading = document.querySelector('h2');
		expect(titleHeading?.textContent).toContain('No Body');
	});

	it('renders the selected-person filter chip when one person filter is active', async () => {
		render(GeschichtenListPage, {
			props: {
				data: baseData({
					personFilters: [{ id: 'p1', displayName: 'Anna' }]
				})
			}
		});

		// The active filter surfaces the person's name somewhere in the filter pill row.
		expect(document.body.textContent).toContain('Anna');
	});
});
