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

const SAVE_KEY = process.platform === 'darwin' ? 'Meta+s' : 'Control+s';

test('R14.6 keeps one persistent Source session across 50 Source/Visual switches', async ({
  page,
}) => {
  const workspaceName = `latex-session-r14-6-${Date.now()}`;
  await createBrowserWorkspace(page, { workspaceName });

  const source = page.getByLabel('LaTeX source editor');
  await expect(source).toBeVisible();
  await source.fill([
    '\\documentclass{article}',
    '\\begin{document}',
    '\\section{Persistent session}',
    'Source persistence 123 with inline math $E=mc^2$.',
    '\\end{document}',
    '',
  ].join('\n'));
  await source.press(SAVE_KEY);

  // This marker lives on the actual CodeMirror content DOM node. If Source is
  // unmounted/recreated by a mode switch, the marker disappears.
  await source.evaluate((element) => {
    element.setAttribute('data-r14-6-source-instance', 'persistent');
  });

  const scroller = page.locator('.cm-scroller').first();
  await scroller.evaluate((element) => {
    element.scrollTop = 24;
  });

  for (let index = 0; index < 50; index += 1) {
    await page.getByRole('button', { name: 'Visual' }).click();
    await expect(page.locator('[data-interactive-latex-view="visual"]')).toBeVisible();
    await page.getByRole('button', { name: 'Source' }).click();
    await expect(source).toBeVisible();
    await expect(source).toHaveAttribute(
      'data-r14-6-source-instance',
      'persistent',
    );
  }

  await expect(source).toContainText('Source persistence 123');
  await expect(source).toContainText('$E=mc^2$');
});

test('R14.6 applies Visual edits to the same canonical Source session', async ({
  page,
}) => {
  const workspaceName = `latex-session-edit-r14-6-${Date.now()}`;
  await createBrowserWorkspace(page, { workspaceName });

  const source = page.getByLabel('LaTeX source editor');
  await source.fill([
    '\\documentclass{article}',
    '\\begin{document}',
    '\\section{Original heading}',
    '',
    'Editable paragraph.',
    '\\end{document}',
    '',
  ].join('\n'));
  await source.press(SAVE_KEY);

  await page.getByRole('button', { name: 'Visual' }).click();
  const heading = page.locator('.interactive-visual-heading').first();
  await expect(heading).toBeVisible();
  await heading.fill('Visual persistence 456');

  await page.getByRole('button', { name: 'Source' }).click();
  await expect(source).toContainText('\\section{Visual persistence 456}');

  await page.getByRole('button', { name: 'Visual' }).click();
  await page.getByRole('button', { name: 'Source' }).click();
  await expect(source).toContainText('\\section{Visual persistence 456}');
});
