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

test('R3 keeps compact Source polish while compiler mode stays settings-only and manual', async ({
  page,
}) => {
  const workspaceName = `polish-r14-22-6-${Date.now()}`;
  await page.setViewportSize({ width: 1440, height: 900 });
  await createBrowserWorkspace(page, { workspaceName });
  await page.getByRole('link', { name: /^main\.tex$/ }).click();

  const sourceSection = page.locator('[data-editor-engine="latex-source"]');
  await expect(sourceSection).toHaveClass(/\bpl-2\b/);
  await expect(sourceSection).toHaveClass(/\bmd:pl-2\b/);

  const source = page.getByLabel('LaTeX source editor');
  const liveMarker = `Downloaded from live source ${Date.now()}`;
  await source.press(process.platform === 'darwin' ? 'Meta+ArrowDown' : 'Control+End');
  await source.pressSequentially(`\n% ${liveMarker}`);

  const mainFileLink = page.getByRole('link', { name: /^main\.tex$/ }).first();
  await mainFileLink.click({ button: 'right' });
  const downloadPromise = page.waitForEvent('download');
  await page.getByRole('button', { name: 'Download source' }).click();
  const download = await downloadPromise;
  expect(download.suggestedFilename()).toBe('main.tex');
  const stream = await download.createReadStream();
  if (!stream) throw new Error('Source download stream unavailable');
  const chunks: Buffer[] = [];
  for await (const chunk of stream) chunks.push(Buffer.from(chunk));
  expect(Buffer.concat(chunks).toString('utf8')).toContain(liveMarker);

  await expect(page.getByTestId('interactive-compiler-indicator')).toHaveCount(0);

  const locate = page.getByTestId('latex-source-synctex-locate');
  await expect(locate).toHaveAttribute('data-synctex-state', 'unavailable');
  const unavailableTitle = await locate.getAttribute('title');
  expect(unavailableTitle?.trim().length).toBeGreaterThan(0);

  await page.getByRole('button', { name: 'Compiler settings' }).click();
  await expect(page.getByText('Live PDF preview')).toHaveCount(0);
  await expect(page.getByLabel('Live PDF preview')).toHaveCount(0);
  const pdfMode = page.getByLabel('pdfLaTeX mode');
  await pdfMode.click();
  await page.getByRole('option', { name: /Fast Preview/i }).click();
  await expect(pdfMode).toContainText('Fast Preview');
  await page.keyboard.press('Escape');
});
