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

const SPLIT_V1 = 'learnitive:editor-pdf-split:v1';
const SPLIT_V2 = 'learnitive:editor-pdf-split:v2';

test('R14.23.4 ignores the v1 split and only persists v2 after committed interaction', async ({
  page,
}) => {
  await page.setViewportSize({ width: 1440, height: 900 });
  const workspaceName = `split-migration-r14-23-4-${Date.now()}`;
  await createBrowserWorkspace(page, { workspaceName });

  await page.evaluate(
    ({ v1, v2 }) => {
      window.localStorage.setItem(v1, '74');
      window.localStorage.removeItem(v2);
    },
    { v1: SPLIT_V1, v2: SPLIT_V2 },
  );
  await page.reload();

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

  await expect(split).toHaveAttribute('data-editor-split-percent', '60.0');
  await expect(resizer).toHaveAttribute('aria-valuetext', '60% editor, 40% PDF');
  expect(await page.evaluate((key) => window.localStorage.getItem(key), SPLIT_V2)).toBeNull();

  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 expect(resizer).toHaveClass(/is-dragging/);
  await page.mouse.move(splitBox.x + splitBox.width * 0.68, handleBox.y + handleBox.height / 2, {
    steps: 5,
  });
  expect(await page.evaluate((key) => window.localStorage.getItem(key), SPLIT_V2)).toBeNull();
  await page.mouse.up();

  await expect(resizer).not.toHaveClass(/is-dragging/);
  await expect(split).toHaveAttribute('data-editor-split-percent', /^(67|68|69)\./);
  const persistedAfterDrag = await page.evaluate(
    (key) => window.localStorage.getItem(key),
    SPLIT_V2,
  );
  expect(Number(persistedAfterDrag)).toBeGreaterThanOrEqual(67);
  expect(Number(persistedAfterDrag)).toBeLessThanOrEqual(69);

  await resizer.focus();
  await page.keyboard.press('Home');
  await expect(split).toHaveAttribute('data-editor-split-percent', '60.0');
  expect(await page.evaluate((key) => window.localStorage.getItem(key), SPLIT_V2)).toBe('60');

  await page.keyboard.press('Shift+ArrowLeft');
  await expect(split).toHaveAttribute('data-editor-split-percent', '55.0');
  expect(await page.evaluate((key) => window.localStorage.getItem(key), SPLIT_V2)).toBe('55');

  for (let index = 0; index < 20; index += 1) await page.keyboard.press('Shift+ArrowLeft');
  await expect(split).toHaveAttribute('data-editor-split-percent', '30.0');
  for (let index = 0; index < 20; index += 1) await page.keyboard.press('Shift+ArrowRight');
  await expect(split).toHaveAttribute('data-editor-split-percent', '80.0');

  await resizer.dblclick();
  await expect(split).toHaveAttribute('data-editor-split-percent', '60.0');
  expect(await page.evaluate((key) => window.localStorage.getItem(key), SPLIT_V2)).toBe('60');
});

test('R14.23.4 uses compact mobile toolbar labels and accessible compile status/cursors', async ({
  page,
}) => {
  await page.setViewportSize({ width: 390, height: 844 });
  const workspaceName = `mobile-polish-r14-23-4-${Date.now()}`;
  await createBrowserWorkspace(page, { workspaceName });

  const collaborate = page.getByRole('button', { name: 'Collaborate', exact: true });
  const tools = page.getByRole('button', { name: 'Tools', exact: true });
  const preview = page.getByRole('button', { name: 'Preview compiled PDF', exact: true });

  await expect(collaborate).toBeVisible();
  await expect(tools).toBeVisible();
  await expect(page.getByText('Project Tools', { exact: true })).toBeHidden();
  await expect(collaborate.locator('span')).toBeHidden();

  const statusDot = page.getByTestId('interactive-log-status-dot');
  await expect(statusDot).toHaveAttribute('data-compile-status', 'neutral');

  await expect
    .poll(() => tools.evaluate((element) => getComputedStyle(element).cursor))
    .toBe('pointer');
  await expect(preview).toBeDisabled();
  await expect
    .poll(() => preview.evaluate((element) => getComputedStyle(element).cursor))
    .toBe('not-allowed');

  await page.getByRole('button', { name: 'Compile', exact: true }).click();
  const outputPane = page.getByTestId('interactive-output-pane');
  await expect(outputPane).toBeVisible();
  await expect(statusDot).toHaveAttribute('data-compile-status', 'compiling', { timeout: 10_000 });
  await expect(statusDot).toHaveAttribute('data-compile-status', 'success', { timeout: 180_000 });

  const logButton = page.getByTestId('interactive-output-tabs').getByRole('button', { name: /Log/ });
  await expect(logButton).toHaveAccessibleName(/Last compile succeeded/);

  await page.getByRole('button', { name: 'Close PDF and return to editor' }).click();
  const source = page.getByLabel('LaTeX source editor');
  await source.fill([
    '\\documentclass{article}',
    '\\begin{document}',
    '\\definitelyUndefinedR14234Command',
    '\\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(statusDot).toHaveAttribute('data-compile-status', 'failure', { timeout: 180_000 });
  await expect(logButton).toHaveAccessibleName(/Last compile failed/);
});
