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

test('R14.22.4 compiles from Play and routes PDF/log output without losing the last good PDF', async ({
  page,
}) => {
  const workspaceName = `compile-output-r14-22-4-${Date.now()}`;
  await createBrowserWorkspace(page, { workspaceName });

  const compile = page.getByRole('button', { name: 'Compile', exact: true });
  await expect(compile.locator('svg.lucide-play')).toBeVisible();
  await expect(page.getByRole('button', { name: 'Compiler settings' })).toBeVisible();
  await expect(page.locator('svg.lucide-chevrons-right-left')).toHaveCount(0);

  await page.getByRole('button', { name: 'Compiler settings' }).click();
  await expect(page.getByRole('heading', { name: 'Browser LaTeX Compile' })).toBeVisible();
  await page.keyboard.press('Escape');

  await compile.click();
  await expect(page.getByRole('button', { name: 'Compiling LaTeX document' })).toBeVisible();
  const preview = page.getByTestId('interactive-pdf-preview');
  await expect(preview.locator('canvas')).toBeVisible({ timeout: 180_000 });
  await expect(preview.getByRole('button', { name: 'Download compiled PDF' })).toBeEnabled();
  await expect(preview.getByTestId('interactive-output-tabs').getByRole('button', { name: 'PDF' })).toBeVisible();
  await expect(preview.getByTestId('interactive-output-tabs').getByRole('button', { name: 'Log' })).toBeVisible();

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

  const logPane = preview.getByTestId('interactive-compile-log');
  await expect(logPane).toBeVisible({ timeout: 180_000 });
  await expect(logPane).toContainText(/Undefined control sequence|definitelyUndefinedLearnitiveCommand/i);
  await expect(logPane.getByRole('button', { name: 'Copy compiler log' })).toBeEnabled();
  await expect(logPane.getByRole('button', { name: 'Download compiler log' })).toBeEnabled();

  await preview.getByTestId('interactive-output-tabs').getByRole('button', { name: 'PDF' }).click();
  await expect(preview.locator('canvas')).toBeVisible();
  await expect(preview.getByRole('button', { name: 'Download compiled PDF' })).toBeEnabled();
});
