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

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

async function createTextFile(page: Page, fileName: string, content: string) {
  const explorer = page.getByTestId('interactive-file-explorer');
  await explorer.getByRole('button', { name: 'New File' }).click();
  const dialog = page.getByRole('dialog', { name: 'Create Project File' });
  await dialog.getByLabel('File name').fill(fileName);
  await dialog.getByRole('button', { name: 'Create' }).click();
  const source = page.getByLabel('LaTeX source editor');
  await source.fill(content);
  await source.press(saveShortcut);
  await expect(page.getByText('Saved', { exact: true })).toBeVisible();
}

async function openCitationDialog(page: Page) {
  const toolbar = page.getByTestId('latex-plugin-toolbar');
  const direct = toolbar.locator('[data-toolbar-item="citation"]');
  if (await direct.count()) await direct.click();
  else {
    await toolbar.getByRole('button', { name: 'More editor commands' }).click();
    await page.locator('[data-toolbar-item="citation"]').click();
  }
  return page.getByRole('dialog', { name: 'References' });
}

test('R29 PM8 keeps citation insertion on the canonical source after the contextual toolbar simplification', async ({ page }) => {
  const workspaceName = `papers-pm8-${Date.now()}`;
  const externalAiRequests: string[] = [];
  page.on('request', (request) => {
    if (/api\.openai\.com|anthropic\.com|generativelanguage\.googleapis\.com|openrouter\.ai/iu.test(request.url())) externalAiRequests.push(request.url());
  });

  await createBrowserWorkspace(page, { workspaceName });
  await createTextFile(page, 'references.bib', [
    '@article{researcher2026browser,',
    '  title = {Browser-Local Reproducible Research},',
    '  author = {Researcher, Ada and Author, Grace},',
    '  year = {2026},',
    '  doi = {10.5555/pm8.1}',
    '}',
    '',
  ].join('\n'));

  await page.getByRole('link', { name: /^main\.tex$/ }).click();
  const source = page.getByLabel('LaTeX source editor');
  await source.fill([
    '\\documentclass{article}',
    '\\begin{document}',
    'Robust local research improves reproducibility. ',
    '\\bibliography{references}',
    '\\end{document}',
    '',
  ].join('\n'));
  await source.press(saveShortcut);
  await expect(page.getByText('Saved', { exact: true })).toBeVisible();

  const dialog = await openCitationDialog(page);
  await expect(dialog.getByText('Browser-Local Reproducible Research')).toBeVisible();
  await dialog.getByText('Browser-Local Reproducible Research').click();
  await dialog.getByRole('button', { name: /Use 1 citation/ }).click();

  await expect(source).toContainText('\\cite{researcher2026browser}');
  await page.getByRole('link', { name: /^references\.bib$/ }).click();
  await expect(page.getByLabel('LaTeX source editor')).toContainText('doi = {10.5555/pm8.1}');
  expect(externalAiRequests).toEqual([]);
});
