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

test('R14.2 exposes truthful compiler capabilities and disables missing engines', async ({
  page,
}) => {
  const workspaceName = `compiler-r14-2-${Date.now()}`;
  await createBrowserWorkspace(page, { workspaceName });

  await page.getByRole('button', { name: 'Compiler settings' }).click();
  await expect(page.getByText(/TeX Live bundle/)).toBeVisible();

  const status = await page.evaluate(async () => {
    const response = await fetch('/compiler/status.json', { cache: 'no-store' });
    return response.json() as Promise<{
      engines: Record<'pdflatex' | 'xelatex' | 'lualatex', { available: boolean }>;
    }>;
  });
  const engine = page.getByRole('combobox', { name: 'Compiler engine' });
  await expect(engine).toBeVisible();
  await engine.click();
  const pdf = page.getByRole('option', { name: /pdfLaTeX/ });
  const xe = page.getByRole('option', { name: /XeLaTeX/ });
  const lua = page.getByRole('option', { name: /LuaLaTeX/ });
  await expect(pdf).toBeEnabled();
  if (status.engines.xelatex.available) await expect(xe).toBeEnabled();
  else await expect(xe).toBeDisabled();
  if (status.engines.lualatex.available) await expect(lua).toBeEnabled();
  else await expect(lua).toBeDisabled();
});

test('R14.2 compiles the Research Paper template with the bundled package core', async ({
  page,
}) => {
  const workspaceName = `compiler-template-r14-2-${Date.now()}`;
  await page.goto('/');
  if (await page.getByRole('dialog').isVisible()) await page.keyboard.press('Escape');

  await page.getByRole('button', { name: 'Browse Templates' }).click();
  const dialog = page.getByTestId('interactive-template-dialog');
  await dialog.getByRole('button', { name: /Research Paper/ }).click();
  await dialog.getByLabel('Project name').fill(workspaceName);
  await dialog.getByRole('button', { name: 'Create Project' }).click();

  await expect(page.getByLabel('LaTeX source editor')).toBeVisible();
  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();
});
