import { describe, it, expect, vi, afterEach } from 'vitest';
import { cleanup, render } from 'vitest-browser-svelte';
import { page } from 'vitest/browser';
import { goto } from '$app/navigation';
import NotificationDropdown from './NotificationDropdown.svelte';

vi.mock('$app/navigation', () => ({ goto: vi.fn() }));

// Configurable result for the enhance mock — tests that need failure set
// mockFormResult.type = 'failure' before clicking.
const mockFormResult = vi.hoisted(() => ({ type: 'success' as string }));

// Invoke the SubmitFunction and always call the returned result callback with
// mockFormResult so tests can exercise both success and failure branches.
vi.mock('$app/forms', () => ({
	enhance(
		node: HTMLFormElement,
		submit?: (opts: {
			formData: FormData;
		}) => (opts: {
			result: { type: string; data?: Record<string, unknown> };
			update: () => Promise<void>;
		}) => Promise<void>
	) {
		const handler = async (e: Event) => {
			e.preventDefault();
			const cb = submit?.({ formData: new FormData(node) } as never);
			if (typeof cb === 'function') {
				await cb({ result: mockFormResult, update: async () => {} } as never);
			}
		};
		node.addEventListener('submit', handler);
		return { destroy: () => node.removeEventListener('submit', handler) };
	}
}));

afterEach(() => {
	cleanup();
	vi.clearAllMocks();
	mockFormResult.type = 'success'; // reset to default after each test
});

const makeNotification = (overrides: Record<string, unknown> = {}) => ({
	id: 'n1',
	type: 'REPLY' as 'REPLY' | 'MENTION',
	documentId: 'd1',
	documentTitle: 'Brief',
	referenceId: 'c1',
	annotationId: null,
	read: false,
	createdAt: new Date().toISOString(),
	actorName: 'Anna Schmidt',
	...overrides
});

describe('NotificationDropdown', () => {
	it('renders the dialog with the bell label', async () => {
		render(NotificationDropdown, {
			props: {
				notifications: [],
				optimisticMarkRead: () => {},
				optimisticMarkAllRead: () => {},
				onClose: () => {}
			}
		});

		await expect.element(page.getByRole('dialog', { name: /benachrichtigungen/i })).toBeVisible();
	});

	it('renders the empty state when there are no notifications', async () => {
		render(NotificationDropdown, {
			props: {
				notifications: [],
				optimisticMarkRead: () => {},
				optimisticMarkAllRead: () => {},
				onClose: () => {}
			}
		});

		await expect.element(page.getByText('Keine neuen Benachrichtigungen')).toBeVisible();
	});

	it('hides the mark-all-read action when the list is empty', async () => {
		render(NotificationDropdown, {
			props: {
				notifications: [],
				optimisticMarkRead: () => {},
				optimisticMarkAllRead: () => {},
				onClose: () => {}
			}
		});

		await expect
			.element(page.getByRole('button', { name: /alle gelesen/i }))
			.not.toBeInTheDocument();
	});

	it('renders the mark-all-read action when notifications are present', async () => {
		render(NotificationDropdown, {
			props: {
				notifications: [makeNotification()],
				optimisticMarkRead: () => {},
				optimisticMarkAllRead: () => {},
				onClose: () => {}
			}
		});

		await expect.element(page.getByRole('button', { name: /alle gelesen/i })).toBeVisible();
	});

	it('renders one item per notification with the reply text for REPLY type', async () => {
		render(NotificationDropdown, {
			props: {
				notifications: [makeNotification({ type: 'REPLY', actorName: 'Bert' })],
				optimisticMarkRead: () => {},
				optimisticMarkAllRead: () => {},
				onClose: () => {}
			}
		});

		await expect
			.element(page.getByText(/Bert hat auf deinen Kommentar geantwortet/i))
			.toBeVisible();
	});

	it('renders the mention text for MENTION type', async () => {
		render(NotificationDropdown, {
			props: {
				notifications: [makeNotification({ type: 'MENTION', actorName: 'Clara' })],
				optimisticMarkRead: () => {},
				optimisticMarkAllRead: () => {},
				onClose: () => {}
			}
		});

		await expect
			.element(page.getByText(/Clara hat dich in einem Kommentar erwähnt/i))
			.toBeVisible();
	});

	it('renders the unread dot only for unread notifications', async () => {
		render(NotificationDropdown, {
			props: {
				notifications: [
					makeNotification({ id: 'n1', read: false }),
					makeNotification({ id: 'n2', read: true })
				],
				optimisticMarkRead: () => {},
				optimisticMarkAllRead: () => {},
				onClose: () => {}
			}
		});

		const unreadDots = document.querySelectorAll('[aria-label="ungelesen"]');
		expect(unreadDots.length).toBe(1);
	});

	it('each notification row is wrapped in a form posting to the dismiss action', async () => {
		render(NotificationDropdown, {
			props: {
				notifications: [makeNotification({ id: 'n42' })],
				optimisticMarkRead: () => {},
				optimisticMarkAllRead: () => {},
				onClose: () => {}
			}
		});

		const form = document.querySelector('form[action="/aktivitaeten?/dismiss-notification"]');
		expect(form).not.toBeNull();
		expect(form?.getAttribute('method')).toBe('POST');
	});

	it('the dismiss form has a hidden notificationId input with the notification id', async () => {
		render(NotificationDropdown, {
			props: {
				notifications: [makeNotification({ id: 'n42' })],
				optimisticMarkRead: () => {},
				optimisticMarkAllRead: () => {},
				onClose: () => {}
			}
		});

		const input = document.querySelector<HTMLInputElement>(
			'form[action="/aktivitaeten?/dismiss-notification"] input[name="notificationId"]'
		);
		expect(input?.value).toBe('n42');
	});

	it('calls optimisticMarkRead with the notification id when a row is submitted', async () => {
		const optimisticMarkRead = vi.fn();
		const n = makeNotification({ id: 'n42', actorName: 'Anna' });
		render(NotificationDropdown, {
			props: {
				notifications: [n],
				optimisticMarkRead,
				optimisticMarkAllRead: () => {},
				onClose: () => {}
			}
		});

		await page.getByRole('button', { name: /Anna hat auf deinen/i }).click();

		expect(optimisticMarkRead).toHaveBeenCalledWith('n42');
	});

	it('the mark-all-read control is a form posting to the mark-all-read action', async () => {
		render(NotificationDropdown, {
			props: {
				notifications: [makeNotification()],
				optimisticMarkRead: () => {},
				optimisticMarkAllRead: () => {},
				onClose: () => {}
			}
		});

		const form = document.querySelector('form[action="/aktivitaeten?/mark-all-read"]');
		expect(form).not.toBeNull();
		expect(form?.getAttribute('method')).toBe('POST');
	});

	it('calls optimisticMarkAllRead when the mark-all-read button is submitted', async () => {
		const optimisticMarkAllRead = vi.fn();
		render(NotificationDropdown, {
			props: {
				notifications: [makeNotification()],
				optimisticMarkRead: () => {},
				optimisticMarkAllRead,
				onClose: () => {}
			}
		});

		await page.getByRole('button', { name: /alle gelesen/i }).click();

		expect(optimisticMarkAllRead).toHaveBeenCalledOnce();
	});

	it('shows a role=alert error banner when mark-all-read returns a failure', async () => {
		mockFormResult.type = 'failure';
		render(NotificationDropdown, {
			props: {
				notifications: [makeNotification()],
				optimisticMarkRead: () => {},
				optimisticMarkAllRead: () => {},
				onClose: () => {}
			}
		});

		await page.getByRole('button', { name: /alle gelesen/i }).click();

		const alert = document.querySelector('[role="alert"]');
		expect(alert).not.toBeNull();
	});

	it('calls onClose when the view-all button is clicked', async () => {
		const onClose = vi.fn();
		render(NotificationDropdown, {
			props: {
				notifications: [],
				optimisticMarkRead: () => {},
				optimisticMarkAllRead: () => {},
				onClose
			}
		});

		await page.getByRole('button', { name: /alle aktivitäten|view all/i }).click();

		expect(onClose).toHaveBeenCalledOnce();
	});

	it('navigates to /aktivitaeten when the view-all button is clicked', async () => {
		render(NotificationDropdown, {
			props: {
				notifications: [],
				optimisticMarkRead: () => {},
				optimisticMarkAllRead: () => {},
				onClose: () => {}
			}
		});

		await page.getByRole('button', { name: /alle aktivitäten|view all/i }).click();

		expect(goto).toHaveBeenCalledWith('/aktivitaeten');
	});

	it('calls onClose before navigating to /aktivitaeten', async () => {
		const callOrder: string[] = [];
		const onClose = vi.fn(() => callOrder.push('close'));
		vi.mocked(goto).mockImplementation(() => {
			callOrder.push('goto');
			return Promise.resolve();
		});
		render(NotificationDropdown, {
			props: {
				notifications: [],
				optimisticMarkRead: () => {},
				optimisticMarkAllRead: () => {},
				onClose
			}
		});

		await page.getByRole('button', { name: /alle aktivitäten|view all/i }).click();

		expect(callOrder).toEqual(['close', 'goto']);
	});

	it('renders MENTION items with the mention verb text', async () => {
		render(NotificationDropdown, {
			props: {
				notifications: [makeNotification({ id: 'm1', type: 'MENTION', actorName: 'Anna' })],
				optimisticMarkRead: () => {},
				optimisticMarkAllRead: () => {},
				onClose: () => {}
			}
		});

		expect(document.body.textContent).toMatch(/erwähnt|mention/i);
	});

	it('renders REPLY items with the reply glyph', async () => {
		render(NotificationDropdown, {
			props: {
				notifications: [makeNotification({ id: 'r1', type: 'REPLY', actorName: 'Bert' })],
				optimisticMarkRead: () => {},
				optimisticMarkAllRead: () => {},
				onClose: () => {}
			}
		});

		// Reply uses the curved-arrow glyph
		expect(document.body.textContent).toMatch(/↩|reply|geantwortet/i);
	});

	it('renders multiple notifications in order', async () => {
		render(NotificationDropdown, {
			props: {
				notifications: [
					makeNotification({ id: 'n1', actorName: 'First' }),
					makeNotification({ id: 'n2', actorName: 'Second' })
				],
				optimisticMarkRead: () => {},
				optimisticMarkAllRead: () => {},
				onClose: () => {}
			}
		});

		const forms = document.querySelectorAll('form[action="/aktivitaeten?/dismiss-notification"]');
		expect(forms.length).toBe(2);
	});

	it('calls onClose and goto with the deep-link URL after a successful dismiss', async () => {
		const onClose = vi.fn();
		const n = makeNotification({
			id: 'n42',
			documentId: 'd1',
			referenceId: 'c1',
			annotationId: null,
			actorName: 'Anna'
		});
		render(NotificationDropdown, {
			props: {
				notifications: [n],
				optimisticMarkRead: () => {},
				optimisticMarkAllRead: () => {},
				onClose
			}
		});

		await page.getByRole('button', { name: /Anna hat auf deinen/i }).click();

		expect(onClose).toHaveBeenCalledOnce();
		expect(goto).toHaveBeenCalledWith('/documents/d1?commentId=c1');
	});

	it('does NOT call onClose or goto when the dismiss action returns a failure', async () => {
		mockFormResult.type = 'failure';
		const onClose = vi.fn();
		const n = makeNotification({ id: 'n99', actorName: 'Bob' });
		render(NotificationDropdown, {
			props: {
				notifications: [n],
				optimisticMarkRead: () => {},
				optimisticMarkAllRead: () => {},
				onClose
			}
		});

		await page.getByRole('button', { name: /Bob hat auf deinen/i }).click();

		expect(onClose).not.toHaveBeenCalled();
		expect(goto).not.toHaveBeenCalled();
	});

	it('calls goto with annotationId appended when the notification has an annotationId', async () => {
		const n = makeNotification({
			id: 'n55',
			documentId: 'd1',
			referenceId: 'c1',
			annotationId: 'a1',
			actorName: 'Eva'
		});
		render(NotificationDropdown, {
			props: {
				notifications: [n],
				optimisticMarkRead: () => {},
				optimisticMarkAllRead: () => {},
				onClose: () => {}
			}
		});

		await page.getByRole('button', { name: /Eva hat auf deinen/i }).click();

		expect(goto).toHaveBeenCalledWith('/documents/d1?commentId=c1&annotationId=a1');
	});
});
