import { expect, test } from '@playwright/test';
import { createBrowserWorkspace } from './common';

test('R14.22.2 switches pdfLaTeX between Full / SyncTeX and Fast Preview without stale maps', async ({ page }) => {
  const workspaceName = `synctex-r14-22-2-${Date.now()}`;
  await createBrowserWorkspace(page, { workspaceName });

  const source = page.getByLabel('LaTeX source editor');
  await source.fill([
    '\\documentclass{article}',
    '\\begin{document}',
    'R14.22.2 SyncTeX mode marker.',
    '\\end{document}',
    '',
  ].join('\n'));
  await source.press(process.platform === 'darwin' ? 'Meta+s' : 'Control+s');

  await page.getByRole('button', { name: 'Compiler settings' }).click();
  const mode = page.getByLabel('pdfLaTeX mode');
  await expect(mode).toHaveText(/Full \/ SyncTeX/);
  await page.keyboard.press('Escape');
  await page.getByRole('button', { name: 'Compile', exact: true }).click();
  await expect(page.getByTestId('interactive-pdf-preview').locator('canvas')).toBeVisible({ timeout: 180_000 });
  await expect(page.getByText('SyncTeX ready', { exact: true })).toBeVisible({ timeout: 30_000 });
  await expect(page.getByLabel('Sync editor and PDF scrolling')).toBeEnabled();

  await page.getByRole('button', { name: 'Compiler settings' }).click();
  await mode.click();
  await page.getByRole('option', { name: 'Fast Preview' }).click();
  await page.keyboard.press('Escape');
  await page.getByRole('button', { name: 'Compile', exact: true }).click();
  await expect(page.getByTestId('interactive-pdf-preview').locator('canvas')).toBeVisible({ timeout: 120_000 });
  await expect(page.getByText(/Fast Preview uses SwiftLaTeX/)).toBeVisible();
  await expect(page.getByLabel('Sync editor and PDF scrolling')).toBeDisabled();
  await expect(page.getByLabel('Sync editor and PDF scrolling')).toHaveAttribute('title', /Full \/ SyncTeX/);

  await page.getByRole('button', { name: 'Compiler settings' }).click();
  await mode.click();
  await page.getByRole('option', { name: 'Full / SyncTeX' }).click();
  await page.keyboard.press('Escape');
  await page.getByRole('button', { name: 'Compile', exact: true }).click();
  await expect(page.getByTestId('interactive-pdf-preview').locator('canvas')).toBeVisible({ timeout: 180_000 });
  await expect(page.getByText('SyncTeX ready', { exact: true })).toBeVisible({ timeout: 30_000 });
});
