import { afterEach, describe, expect, it, vi } from 'vitest';
import { cleanup, render } from 'vitest-browser-svelte';
import { page, userEvent } from 'vitest/browser';
import { m } from '$lib/paraglide/messages.js';
import JourneyAddBar from './JourneyAddBar.svelte';

afterEach(() => {
	cleanup();
	vi.unstubAllGlobals();
});

describe('JourneyAddBar — interlude flow', () => {
	it('interlude confirm button is natively disabled when text is empty (WCAG 4.1.2)', async () => {
		render(JourneyAddBar, { onAddDocument: vi.fn(), onAddInterlude: vi.fn() });

		await userEvent.click(page.getByText(m.journey_add_interlude()));

		const confirmBtn = page.getByRole('button', {
			name: m.journey_add_interlude_confirm(),
			exact: true
		});
		await expect.element(confirmBtn).toBeDisabled();
	});

	it('confirm becomes enabled after typing text', async () => {
		render(JourneyAddBar, { onAddDocument: vi.fn(), onAddInterlude: vi.fn() });

		await userEvent.click(page.getByText(m.journey_add_interlude()));
		await userEvent.fill(page.getByRole('textbox'), 'Eine schöne Reise');

		const confirmBtn = page.getByRole('button', {
			name: m.journey_add_interlude_confirm(),
			exact: true
		});
		await expect.element(confirmBtn).toBeEnabled();
	});

	it('calls onAddInterlude with text on confirm', async () => {
		const onAddInterlude = vi.fn();
		render(JourneyAddBar, { onAddDocument: vi.fn(), onAddInterlude });

		await userEvent.click(page.getByText(m.journey_add_interlude()));
		await userEvent.fill(page.getByRole('textbox'), 'Reise nach Wien');
		await userEvent.click(
			page.getByRole('button', { name: m.journey_add_interlude_confirm(), exact: true })
		);

		expect(onAddInterlude).toHaveBeenCalledWith('Reise nach Wien');
	});

	it('limits the interlude textarea to 2000 characters', async () => {
		render(JourneyAddBar, { onAddDocument: vi.fn(), onAddInterlude: vi.fn() });

		await userEvent.click(page.getByText(m.journey_add_interlude()));

		await expect.element(page.getByRole('textbox')).toHaveAttribute('maxlength', '2000');
	});
});

describe('JourneyAddBar — document picker', () => {
	it('reveals picker when "Brief hinzufügen" is clicked', async () => {
		vi.stubGlobal(
			'fetch',
			vi.fn().mockResolvedValue({ ok: true, json: vi.fn().mockResolvedValue({ items: [] }) })
		);
		render(JourneyAddBar, { onAddDocument: vi.fn(), onAddInterlude: vi.fn() });

		await userEvent.click(page.getByText(m.journey_add_document()));

		await expect.element(page.getByRole('combobox')).toBeInTheDocument();
	});
});
