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

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

test('R14.22.3 keeps one Sigma toolbar entry, native MathLive menu, movable modal, and insertion modes', async ({ page }) => {
  const workspaceName = `mathlive-r14-22-3-${Date.now()}`;
  await createBrowserWorkspace(page, { workspaceName });
  const source = page.getByLabel('LaTeX source editor');
  await source.fill('\\documentclass{article}\n\\begin{document}\n\\end{document}\n');
  await source.press(saveShortcut);

  const toolbar = page.getByTestId('latex-plugin-toolbar');
  await expect(toolbar.getByRole('button', { name: 'Equation editor', exact: true })).toHaveCount(1);
  await expect(toolbar.getByRole('button', { name: 'Display Math', exact: true })).toHaveCount(0);
  await expect(toolbar.getByRole('button', { name: 'Equation', exact: true })).toHaveCount(0);
  await toolbar.getByRole('button', { name: 'Equation editor', exact: true }).click();

  const editor = page.getByTestId('mathlive-equation-editor');
  const field = editor.locator('math-field');
  await expect(editor).toBeVisible();
  await expect(field).toBeVisible();
  await expect.poll(async () => field.evaluate((element) => {
    const math = element as HTMLElement & { menuItems?: unknown[] };
    return math.menuItems?.length ?? 0;
  })).toBeGreaterThan(0);

  const toggle = field.locator('[part~="menu-toggle"]');
  await expect(toggle).toBeVisible();
  await toggle.click();
  await expect(page.getByRole('menu').last()).toBeVisible();
  await toggle.click();

  const before = await editor.boundingBox();
  if (!before) throw new Error('MathLive editor has no bounding box');
  const handle = page.getByTestId('mathlive-equation-drag-handle');
  const handleBox = await handle.boundingBox();
  if (!handleBox) throw new Error('MathLive drag handle has no bounding box');
  await page.mouse.move(handleBox.x + 20, handleBox.y + 10);
  await page.mouse.down();
  await page.mouse.move(handleBox.x + 100, handleBox.y + 70, { steps: 5 });
  await page.mouse.up();
  const after = await editor.boundingBox();
  if (!after) throw new Error('MathLive editor disappeared after drag');
  expect(Math.abs(after.x - before.x) + Math.abs(after.y - before.y)).toBeGreaterThan(20);
  expect(after.x).toBeGreaterThanOrEqual(0);
  expect(after.y).toBeGreaterThanOrEqual(0);

  await editor.getByRole('button', { name: 'Equation', exact: true }).click();
  await field.evaluate((element) => {
    const math = element as HTMLElement & { value: string };
    math.value = 'x^2+y^2';
    math.dispatchEvent(new Event('input', { bubbles: true }));
  });
  await editor.getByRole('button', { name: 'Apply' }).click();
  await expect(source).toContainText('\\begin{equation}\nx^2+y^2\n\\end{equation}');
});
