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

const selectAll = process.platform === 'darwin' ? 'Meta+a' : 'Control+a';

function longLatexLine(): string {
  return `\\documentclass{article}\n\\begin{document}\n${'Learnitive soft wrapping remains a viewport preference and never rewrites canonical source. '.repeat(40)}\n\\end{document}\n`;
}

test('R14.16 keeps one CodeMirror view while soft wrap toggles and runs the Learnitive toolbar', async ({ page }) => {
  const workspaceName = `source-r14-16-${Date.now()}`;
  await createBrowserWorkspace(page, { workspaceName });

  const source = page.getByLabel('LaTeX source editor');
  const host = page.locator('[data-latex-codemirror]');
  const cmEditor = host.locator('.cm-editor');
  const cmLine = host.locator('.cm-line').first();
  const wrap = page.getByTestId('latex-soft-wrap-toggle');

  await expect(source).toBeVisible();
  await expect(page.getByTestId('latex-plugin-toolbar')).toBeVisible();
  await expect(wrap).toHaveAttribute('aria-pressed', 'true');

  await cmEditor.evaluate((element) => {
    (element as HTMLElement).dataset.r1416Identity = 'same-editor-view';
  });
  await source.fill(longLatexLine());
  await expect(cmLine).toHaveCSS('white-space', 'pre-wrap');

  await wrap.click();
  await expect(wrap).toHaveAttribute('aria-pressed', 'false');
  await expect(cmLine).toHaveCSS('white-space', 'pre');
  await expect(cmEditor).toHaveAttribute('data-r1416-identity', 'same-editor-view');

  await wrap.click();
  await expect(wrap).toHaveAttribute('aria-pressed', 'true');
  await expect(cmLine).toHaveCSS('white-space', 'pre-wrap');
  await expect(cmEditor).toHaveAttribute('data-r1416-identity', 'same-editor-view');

  await source.fill('Toolbar selection');
  await source.press(selectAll);
  await page.getByRole('button', { name: 'Bold', exact: true }).click();
  await expect(source).toContainText('\\textbf{Toolbar selection}');

  await wrap.click();
  await expect(wrap).toHaveAttribute('aria-pressed', 'false');
  await page.reload({ waitUntil: 'domcontentloaded' });
  await expect(page.getByTestId('latex-soft-wrap-toggle')).toHaveAttribute('aria-pressed', 'false');
});
