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: BriefwechselPage } = await import('./+page.svelte');

afterEach(cleanup);

const baseData = (overrides: Record<string, unknown> = {}) => ({
	filters: { senderId: '', receiverId: '', from: '', to: '', dir: 'DESC' },
	initialValues: { senderName: '', receiverName: '' },
	documents: [],
	canWrite: false,
	...overrides
});

describe('briefwechsel/+ page', () => {
	it('renders the hero when no senderId is set', async () => {
		render(BriefwechselPage, { props: { data: baseData() } });

		// CorrespondenzHero should render
		const inputs = document.querySelectorAll('input');
		expect(inputs.length).toBeGreaterThan(0);
	});

	it('renders the results card when a senderId is set', async () => {
		render(BriefwechselPage, {
			props: {
				data: baseData({
					filters: { senderId: 'p1', receiverId: '', from: '', to: '', dir: 'DESC' },
					initialValues: { senderName: 'Anna Schmidt', receiverName: '' }
				})
			}
		});

		// CorrespondenzPersonBar should render with results context
		await expect.element(page.getByText(/Anna Schmidt/)).toBeVisible();
	});

	it('renders the SinglePersonHintBar when there is a sender but no receiver', async () => {
		render(BriefwechselPage, {
			props: {
				data: baseData({
					filters: { senderId: 'p1', receiverId: '', from: '', to: '', dir: 'DESC' },
					initialValues: { senderName: 'Anna', receiverName: '' }
				})
			}
		});

		// "Alle Briefe von Anna" message from SinglePersonHintBar
		await expect.element(page.getByText(/wähle einen korrespondenten/i)).toBeVisible();
	});

	it('renders the empty results message when documents is empty and a sender is set', async () => {
		render(BriefwechselPage, {
			props: {
				data: baseData({
					filters: { senderId: 'p1', receiverId: '', from: '', to: '', dir: 'DESC' },
					initialValues: { senderName: 'Anna', receiverName: '' }
				})
			}
		});

		await expect.element(page.getByText('Keine Dokumente gefunden.')).toBeVisible();
	});

	it('hides the SinglePersonHintBar when both sender and receiver are set', async () => {
		render(BriefwechselPage, {
			props: {
				data: baseData({
					filters: { senderId: 'p1', receiverId: 'p2', from: '', to: '', dir: 'DESC' },
					initialValues: { senderName: 'Anna', receiverName: 'Bert' }
				})
			}
		});

		await expect.element(page.getByText(/wähle einen korrespondenten/i)).not.toBeInTheDocument();
	});

	it('renders the timeline when documents is non-empty', async () => {
		render(BriefwechselPage, {
			props: {
				data: baseData({
					filters: { senderId: 'p1', receiverId: 'p2', from: '', to: '', dir: 'DESC' },
					initialValues: { senderName: 'Anna', receiverName: 'Bert' },
					documents: [
						{
							id: 'd1',
							title: 'Brief 1',
							documentDate: '1899-04-14',
							sender: { id: 'p1', displayName: 'Anna' },
							receivers: [{ id: 'p2', displayName: 'Bert' }],
							status: 'UPLOADED'
						}
					]
				})
			}
		});

		expect(document.body.textContent).toContain('Brief 1');
	});

	it('writes the senderName to localStorage when sender filter is set on mount', async () => {
		localStorage.removeItem('korrespondenz_recent_persons');
		render(BriefwechselPage, {
			props: {
				data: baseData({
					filters: { senderId: 'p1', receiverId: '', from: '', to: '', dir: 'DESC' },
					initialValues: { senderName: 'Anna Schmidt', receiverName: '' }
				})
			}
		});

		// persistRecentPerson runs in onMount — the persisted entry must include the name.
		await vi.waitFor(() => {
			const stored = localStorage.getItem('korrespondenz_recent_persons');
			expect(stored).toContain('Anna Schmidt');
		});
	});

	it('falls back to an empty recent-persons list when localStorage is malformed', async () => {
		localStorage.setItem('korrespondenz_recent_persons', 'not-json');
		render(BriefwechselPage, {
			props: { data: baseData() }
		});

		// Page still mounts; the malformed entry must not break rendering. The page renders
		// a max-w-7xl container at the root.
		expect(document.querySelector('.max-w-7xl')).not.toBeNull();
		localStorage.removeItem('korrespondenz_recent_persons');
	});

	it('appends the senderName when only sender is set on mount (persistRecentPerson path)', async () => {
		localStorage.removeItem('korrespondenz_recent_persons');
		render(BriefwechselPage, {
			props: {
				data: baseData({
					filters: { senderId: 'p-test', receiverId: '', from: '', to: '', dir: 'DESC' },
					initialValues: { senderName: 'Test Person', receiverName: '' }
				})
			}
		});

		await vi.waitFor(() => {
			const stored = localStorage.getItem('korrespondenz_recent_persons');
			expect(stored).toContain('Test Person');
		});
	});
});
