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

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

test('R14.10 Chromium ZIP exports import and compile in Firefox', async ({ page, browserName }) => {
  test.skip(process.env.LEARNITIVE_RELEASE_QUALITY !== '1', 'Cross-browser portability is a release-certification gate.');
  test.skip(browserName !== 'chromium', 'The Chromium project drives both browsers exactly once.');
  test.setTimeout(300_000);

  const sourceWorkspace = `cross-browser-source-r14-10-${Date.now()}`;
  await createBrowserWorkspace(page, { workspaceName: sourceWorkspace });
  await page.getByRole('link', { name: /^main\.tex$/ }).click();
  const source = page.getByLabel('LaTeX source editor');
  await source.fill([
    '\\documentclass{article}',
    '\\begin{document}',
    'R14.10 Chromium to Firefox portable project.',
    '\\end{document}',
    '',
  ].join('\n'));
  await source.press(SAVE_KEY);
  await page.getByRole('link', { name: 'Home', exact: true }).click();

  const downloadPromise = page.waitForEvent('download');
  await page.getByRole('button', { name: 'Project menu' }).click();
  await page.getByRole('menuitem', { name: 'Download project' }).click();
  const archive = await downloadPromise;
  const archivePath = await archive.path();
  if (!archivePath) throw new Error('Chromium did not produce the release portability archive');

  const origin = new URL(page.url()).origin;
  const browser = await firefox.launch();
  try {
    const context = await browser.newContext({ baseURL: origin });
    const firefoxPage = await context.newPage();
    const targetWorkspace = `cross-browser-firefox-r14-10-${Date.now()}`;
    await createBrowserWorkspace(firefoxPage, { workspaceName: targetWorkspace });
    await firefoxPage.getByRole('link', { name: 'Home', exact: true }).click();
    await firefoxPage.getByLabel('Import Project ZIP').setInputFiles(archivePath);
    await expect(firefoxPage.getByText('Project imported', { exact: true })).toBeVisible();
    await firefoxPage.getByRole('link', { name: /^main\.tex$/ }).click();
    await expect(firefoxPage.getByLabel('LaTeX source editor')).toContainText(
      'R14.10 Chromium to Firefox portable project.',
    );

    await firefoxPage.getByRole('button', { name: 'Compile', exact: true }).click();
    await expect(firefoxPage.getByTestId('interactive-pdf-preview').locator('canvas')).toBeVisible({ timeout: 120_000 });
    await context.close();
  } finally {
    await browser.close();
  }
});
