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

test('R14.22.5 resizes the desktop editor/PDF split and preserves the ratio', async ({
  page,
}) => {
  await page.setViewportSize({ width: 1440, height: 900 });
  const workspaceName = `split-r14-22-5-${Date.now()}`;
  await createBrowserWorkspace(page, { workspaceName });

  const split = page.getByTestId('interactive-split-workspace');
  const editor = page.getByTestId('interactive-editor-pane');
  const output = page.getByTestId('interactive-output-pane');
  const resizer = page.getByRole('separator', {
    name: 'Resize editor and PDF panes',
  });

  await expect(split).toHaveAttribute('data-editor-split-percent', '60.0');
  await expect(editor).toBeVisible();
  await expect(output).toBeVisible();
  await expect(resizer).toBeVisible();

  const splitBox = await split.boundingBox();
  const handleBox = await resizer.boundingBox();
  if (!splitBox || !handleBox) throw new Error('Resizable workspace did not receive layout boxes.');

  await page.mouse.move(handleBox.x + handleBox.width / 2, handleBox.y + handleBox.height / 2);
  await page.mouse.down();
  await page.mouse.move(splitBox.x + splitBox.width * 0.7, handleBox.y + handleBox.height / 2, {
    steps: 8,
  });
  await page.mouse.up();
  await expect(split).toHaveAttribute('data-editor-split-percent', /^(69|70|71)\./);

  const persisted = await split.getAttribute('data-editor-split-percent');
  await page.waitForTimeout(180);
  await page.reload();
  await expect(page.getByTestId('interactive-split-workspace')).toHaveAttribute(
    'data-editor-split-percent',
    persisted ?? '70.0',
  );

  const restoredResizer = page.getByRole('separator', {
    name: 'Resize editor and PDF panes',
  });
  await restoredResizer.dblclick();
  await expect(page.getByTestId('interactive-split-workspace')).toHaveAttribute(
    'data-editor-split-percent',
    '60.0',
  );

  await restoredResizer.focus();
  await page.keyboard.press('ArrowLeft');
  await expect(page.getByTestId('interactive-split-workspace')).toHaveAttribute(
    'data-editor-split-percent',
    '58.0',
  );
});

test('R14.22.5 mobile compile opens output and closing returns to the mounted editor', async ({
  page,
}) => {
  await page.setViewportSize({ width: 390, height: 844 });
  const workspaceName = `mobile-output-r14-22-5-${Date.now()}`;
  await createBrowserWorkspace(page, { workspaceName });

  const editorPane = page.getByTestId('interactive-editor-pane');
  const outputPane = page.getByTestId('interactive-output-pane');
  const source = page.getByLabel('LaTeX source editor');
  const sourceDomId = await source.evaluate((node) => {
    const marker = `interactive-editor-${Date.now()}`;
    node.setAttribute('data-r14-22-5-editor-instance', marker);
    return marker;
  });

  await expect(editorPane).toBeVisible();
  await expect(outputPane).toBeHidden();
  await expect(page.getByTestId('interactive-editor-pdf-resizer')).toBeHidden();

  await page.getByRole('button', { name: 'Compile', exact: true }).click();
  await expect(outputPane).toBeVisible();
  await expect(editorPane).toBeHidden();

  const preview = page.getByTestId('interactive-pdf-preview');
  await expect(preview.locator('canvas')).toBeVisible({ timeout: 180_000 });
  const firstPage = preview.getByTestId('pdf-page-surface');
  await expect(firstPage).toHaveAttribute('data-pdf-canvas-status', 'ready');
  await expect(firstPage).not.toHaveAttribute('data-pdf-canvas-status', 'error');
  await expect(
    preview.getByTestId('interactive-output-tabs').getByRole('button', { name: 'PDF' }),
  ).toBeVisible();

  await preview.getByRole('button', { name: 'Close PDF and return to editor' }).click();
  await expect(editorPane).toBeVisible();
  await expect(outputPane).toBeHidden();
  await expect(source).toHaveAttribute('data-r14-22-5-editor-instance', sourceDomId);

  const reopen = page.getByRole('button', { name: 'Preview compiled PDF' });
  await expect(reopen).toBeEnabled();
  await reopen.click();
  await expect(outputPane).toBeVisible();
  await expect(preview.locator('canvas')).toBeVisible();

  await preview.getByRole('button', { name: 'Close PDF and return to editor' }).click();
  await source.fill([
    '\\documentclass{article}',
    '\\begin{document}',
    '\\definitelyUndefinedMobileCommand',
    '\\end{document}',
    '',
  ].join('\n'));
  await source.press(process.platform === 'darwin' ? 'Meta+s' : 'Control+s');
  await page.getByRole('button', { name: 'Compile', exact: true }).click();

  await expect(outputPane).toBeVisible();
  await expect(preview.getByTestId('interactive-compile-log')).toBeVisible({ timeout: 180_000 });
  await expect(preview.getByTestId('interactive-compile-log')).toContainText(
    /Undefined control sequence|definitelyUndefinedMobileCommand/i,
  );
});
