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

import ChronikErrorCard from './ChronikErrorCard.svelte';

afterEach(cleanup);

describe('ChronikErrorCard', () => {
	it('renders the default error message', async () => {
		render(ChronikErrorCard, { onRetry: vi.fn() });
		await expect
			.element(page.getByText('Die Aktivitäten konnten nicht geladen werden.'))
			.toBeInTheDocument();
	});

	it('renders the retry button with the expected label', async () => {
		render(ChronikErrorCard, { onRetry: vi.fn() });
		await expect.element(page.getByText('Erneut versuchen')).toBeInTheDocument();
	});

	it('renders a custom message when provided', async () => {
		render(ChronikErrorCard, { onRetry: vi.fn(), message: 'Netzwerkfehler' });
		await expect.element(page.getByText('Netzwerkfehler')).toBeInTheDocument();
	});

	it('calls onRetry when the retry button is clicked', async () => {
		const onRetry = vi.fn();
		render(ChronikErrorCard, { onRetry });
		const btn = (await page.getByText('Erneut versuchen').element()) as HTMLElement;
		btn.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true }));
		expect(onRetry).toHaveBeenCalledTimes(1);
	});

	it('has role="alert" on the wrapper', async () => {
		render(ChronikErrorCard, { onRetry: vi.fn() });
		const alert = document.querySelector('[role="alert"]');
		expect(alert).not.toBeNull();
	});
});
