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

test('R14.9 real-world Visual editing keeps unsupported LaTeX local and source-safe', async ({ page }) => {
  const workspaceName = `visual-r14-9-${Date.now()}`;
  await createBrowserWorkspace(page, { workspaceName });
  await page.getByRole('link', { name: /^main\.tex$/ }).click();

  const source = page.getByLabel('LaTeX source editor');
  await source.fill([
    '\\documentclass{article}',
    '\\usepackage{amsmath}',
    '\\begin{document}',
    '\\section{Introduction}',
    '',
    'Before \\custommacro{LOCKED} after \\textbf{important} and \\emph{emphasised} with $E=mc^2$.',
    '',
    '\\begin{itemize}',
    '\\item First item',
    '\\item Second \\emph{item}',
    '\\end{itemize}',
    '',
    '\\begin{customenv}',
    'KEEP-RAW-CONTENT',
    '\\end{customenv}',
    '',
    'Editable after environment.',
    '\\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 expect(visual.locator('.interactive-visual-inline-raw')).toContainText('\\custommacro{LOCKED}');
  await expect(visual.locator('.interactive-visual-inline-bold')).toHaveText('important');
  await expect(visual.locator('.interactive-visual-inline-italic').first()).toHaveText('emphasised');
  await expect(visual.locator('.interactive-visual-list-item')).toHaveCount(1);
  await expect(visual.locator('.interactive-visual-raw')).toContainText('KEEP-RAW-CONTENT');
  await expect(visual.locator('.interactive-visual-paragraph').filter({ hasText: 'Editable after environment.' })).toHaveCount(1);

  await visual.locator('.interactive-visual-inline-bold').fill('critical');
  const firstItem = visual.locator('.interactive-visual-list-item').first();
  await firstItem.fill('Updated first item');

  await page.getByRole('button', { name: 'Source' }).click();
  await expect(source).toContainText('\\custommacro{LOCKED}');
  await expect(source).toContainText('\\textbf{critical}');
  await expect(source).toContainText('\\item Updated first item');
  await expect(source).toContainText('\\begin{customenv}\nKEEP-RAW-CONTENT\n\\end{customenv}');
});
