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

test('R14.8 edits Visual equations through explicit MathLive Apply', async ({
  page,
}) => {
  const workspaceName = `visual-math-r14-8-${Date.now()}`;
  await createBrowserWorkspace(page, { workspaceName });

  const source = page.getByLabel('LaTeX source editor');
  await expect(source).toBeVisible();
  await source.fill([
    '\\documentclass{article}',
    '\\begin{document}',
    'Energy is $E=mc^2$ and remains source-backed.',
    '\\end{document}',
    '',
  ].join('\n'));
  await source.press(process.platform === 'darwin' ? 'Meta+s' : 'Control+s');

  await page.getByRole('button', { name: 'Visual' }).click();
  const visual = page.locator('.interactive-latex-visual-editor');
  await expect(visual).toBeVisible();
  await page.getByRole('button', { name: 'Edit equation' }).first().click();

  const equationEditor = page.getByTestId('mathlive-equation-editor');
  await expect(equationEditor).toBeVisible();
  const field = equationEditor.locator('math-field');
  await field.evaluate((element) => {
    const math = element as HTMLElement & { value: string };
    math.value = 'E=\\gamma mc^2';
    math.dispatchEvent(new Event('input', { bubbles: true }));
  });
  await equationEditor.getByRole('button', { name: 'Apply' }).click();
  await expect(equationEditor).toBeHidden();

  await page.getByRole('button', { name: 'Source' }).click();
  await expect(source).toContainText('$E=\\gamma mc^2$');
});

test('R14.4 renders selectable PDF.js text, searches it, and keeps SyncTeX separate', async ({
  page,
}) => {
  const workspaceName = `pdf-text-r14-4-${Date.now()}`;
  await createBrowserWorkspace(page, { workspaceName });

  const source = page.getByLabel('LaTeX source editor');
  await source.fill([
    '\\documentclass{article}',
    '\\begin{document}',
    'R14.4 searchable PDF text layer marker.',
    '\\end{document}',
    '',
  ].join('\n'));
  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 });

  const textLayer = page.getByTestId('pdf-text-layer');
  await expect(textLayer).toBeVisible();
  await expect(textLayer.locator('span').filter({ hasText: 'searchable PDF' }).first()).toBeVisible();

  await page.getByRole('button', { name: 'Search PDF' }).click();
  await page.getByLabel('Search compiled PDF').fill('searchable PDF');
  await expect(page.getByTestId('pdf-search-toolbar')).toContainText(/1 \/ 1/);
  await expect(textLayer.locator('.interactive-pdf-search-active')).toBeVisible();
});
