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

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

test('project ZIP export and import preserve a real LaTeX project across reload', async ({
  page,
}) => {
  await createBrowserWorkspace(page, { workspaceName: 'zip-source' });
  await page.getByRole('link', { name: /^main\.tex$/ }).click();

  const source = page.getByLabel('LaTeX source editor');
  await source.fill([
    '\\documentclass{article}',
    '\\begin{document}',
    'Portable Learnitive project content.',
    '\\end{document}',
    '',
  ].join('\n'));
  await source.press(SAVE_KEY);
  await expect(source).toContainText('Portable Learnitive project content.');

  await page.getByRole('link', { name: 'Home', exact: true }).click();
  await expect(page.getByTestId('page-ws-home')).toBeVisible();

  const downloadPromise = page.waitForEvent('download');
  await page.getByRole('button', { name: 'Project menu' }).click();
  await page.getByRole('menuitem', { name: 'Download project' }).click();
  const download = await downloadPromise;
  expect(download.suggestedFilename()).toBe('zip-source.zip');
  const downloadPath = await download.path();
  expect(downloadPath).not.toBeNull();
  if (!downloadPath) {
    throw new Error('Project ZIP download did not produce a local file');
  }

  // A new Browser project contains generated main.tex. Importing a whole
  // project is allowed to replace only that untouched bootstrap file.
  await createBrowserWorkspace(page, { workspaceName: 'zip-target' });
  await page.getByRole('link', { name: 'Home', exact: true }).click();
  const fileChooserPromise = page.waitForEvent('filechooser');
  await page.getByRole('button', { name: 'Project menu' }).click();
  await page.getByRole('menuitem', { name: 'Import project…' }).click();
  const fileChooser = await fileChooserPromise;
  await fileChooser.setFiles(downloadPath);

  await expect(page.getByText('Project imported', { exact: true })).toBeVisible();
  await expect(page.getByRole('link', { name: /^main\.tex$/ })).toBeVisible();

  await page.reload({ waitUntil: 'domcontentloaded' });
  await expect(page.getByRole('link', { name: /^main\.tex$/ })).toBeVisible();
  await page.getByRole('link', { name: /^main\.tex$/ }).click();
  await expect(page.getByLabel('LaTeX source editor')).toContainText(
    'Portable Learnitive project content.',
  );
});
