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

async function selectCodeMirrorText(page: import('@playwright/test').Page, needle: string) {
  await page.locator('.cm-content').evaluate((element, text) => {
    const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT);
    let node = walker.nextNode() as Text | null;
    while (node) {
      const index = node.data.indexOf(text);
      if (index >= 0) {
        const range = document.createRange();
        range.setStart(node, index);
        range.setEnd(node, index + text.length);
        const selection = window.getSelection();
        selection?.removeAllRanges();
        selection?.addRange(range);
        element.dispatchEvent(new Event('selectionchange', { bubbles: true }));
        return;
      }
      node = walker.nextNode() as Text | null;
    }
    throw new Error(`Unable to select ${text}`);
  }, needle);
}

test('BF4.4 keeps review activity and snapshots outside canonical LaTeX source', async ({ page }) => {
  const workspaceName = `review-history-r14-27-2-${Date.now()}`;
  await createBrowserWorkspace(page, { workspaceName });
  const source = page.getByLabel('LaTeX source editor');
  await source.fill('\\documentclass{article}\n\\begin{document}\nA robust local claim.\n\\end{document}\n');

  await selectCodeMirrorText(page, 'robust local claim');
  await page.getByTestId('review-toggle').click();
  await page.getByRole('button', { name: /Add comment/i }).click();
  await page.getByRole('dialog').getByRole('textbox').fill('History should retain this comment.');
  await page.getByRole('dialog').getByRole('button', { name: /Comment|Add/i }).click();

  const sidebar = page.getByTestId('review-sidebar');
  await sidebar.getByRole('tab', { name: 'History' }).click();
  const history = page.getByTestId('review-history-panel');
  await expect(history).toContainText('Comment Created');
  await history.getByRole('button', { name: /Snapshot current file/i }).click();
  await expect(history).toContainText('Snapshot Created');

  await history.getByLabel('Changes since').selectOption('snapshot');
  await history.getByLabel('Type').selectOption('snapshots');
  await expect(history).toContainText('Manual review snapshot');

  await sidebar.getByRole('tab', { name: 'Review' }).click();
  const reviewedSource = await source.inputValue();
  expect(reviewedSource).not.toContain('LEARNITIVE-REVIEW');
  expect(reviewedSource).not.toContain('<###');
});
