import { test, expect } from '@playwright/test';
import { createEmptyDocument } from './helpers/upload-empty-document.js';

test.describe('Help chip — Read/Edit panel header', () => {
	let docId: string;

	test.beforeAll(async ({ request }) => {
		docId = await createEmptyDocument(request);
	});

	test.afterAll(async ({ request }) => {
		await request.delete(`/api/documents/${docId}`);
	});

	test('opens popover on click, closes on Esc, returns focus to chip', async ({ page }) => {
		await page.goto(`/documents/${docId}`);
		await page.getByRole('button', { name: 'Transkribieren' }).click();

		// Use the accessible label of the HelpPopover trigger (transcription_mode_help_label)
		const helpBtn = page.getByRole('button', { name: 'Lese- und Bearbeitungsmodus' });
		await expect(helpBtn).toBeVisible({ timeout: 5000 });
		await helpBtn.click();

		// Popover should open (role="region", not tooltip — click-triggered panels are regions)
		await expect(page.getByRole('region', { name: 'Lese- und Bearbeitungsmodus' })).toBeVisible();

		// Press Esc
		await page.keyboard.press('Escape');
		await expect(
			page.getByRole('region', { name: 'Lese- und Bearbeitungsmodus' })
		).not.toBeVisible();

		// Focus should have returned to the chip
		await expect(helpBtn).toBeFocused();
	});
});
