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

const sourceDocument = String.raw`\documentclass{article}
\usepackage{amsmath}
\usepackage{graphicx}
\begin{document}
R14.7 compiler recovery test.
\[
E=mc^2
\]
\end{document}
`;

test('R14.7 initializes the real browser compiler before compile settings are ready', async ({
  page,
}) => {
  const workspaceName = `compiler-r14-7-ready-${Date.now()}`;
  await createBrowserWorkspace(page, { workspaceName });

  const mainTex = page.getByRole('link', { name: /^main\.tex$/ });
  if (await mainTex.isVisible()) await mainTex.click();
  await expect(page.getByLabel('LaTeX source editor')).toBeVisible();

  await page.getByRole('button', { name: 'Compiler settings' }).click();
  await expect(page.getByText('Browser compiler runtime')).toBeVisible();
  await expect(page.getByText(/Runtime/)).toBeVisible();
});

test('R14.7 compiles amsmath and graphicx with the real package resolver', async ({
  page,
}) => {
  const workspaceName = `compiler-r14-7-packages-${Date.now()}`;
  await createBrowserWorkspace(page, { workspaceName });
  const mainTex = page.getByRole('link', { name: /^main\.tex$/ });
  if (await mainTex.isVisible()) await mainTex.click();

  const source = page.getByLabel('LaTeX source editor');
  await expect(source).toBeVisible();
  await source.fill(sourceDocument);
  await source.press(process.platform === 'darwin' ? 'Meta+s' : 'Control+s');

  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.getByRole('button', { name: 'Download PDF' })).toBeVisible();
  await expect(page.getByText(/Last package/i)).toBeVisible();
});
