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

test('R14.28.0 terminal shares the Learnitive workspace and opens scientific code files', async ({ page }) => {
  const workspaceName = `terminal-r14-28-0-${Date.now()}`;
  await createBrowserWorkspace(page, { workspaceName });

  await page.getByTestId('terminal-open').click();
  const terminal = page.getByTestId('project-terminal');
  await expect(terminal).toBeVisible();
  const input = page.getByTestId('terminal-input');

  await input.fill('touch analysis.py index.html; mkdir -p results; cat main.tex | head -n 1 > results/header.txt; find .');
  await input.press('Enter');
  await expect(terminal).toContainText('/workspace/analysis.py');
  await expect(terminal).toContainText('/workspace/results/header.txt');

  await input.fill('cat results/header.txt');
  await input.press('Enter');
  await expect(terminal).toContainText('documentclass');

  await terminal.getByRole('button', { name: /analysis\.py/u }).last().click();
  await expect(page.getByTestId('project-code-editor')).toBeVisible();
  await expect(page.getByTestId('project-code-editor')).toContainText('Python');
  const projectEditor = page.getByTestId('project-code-editor');
  const codeMirror = projectEditor.locator('.cm-editor');
  await expect(page.getByTestId('project-word-wrap-toggle')).toHaveAttribute('aria-pressed', 'true');
  await codeMirror.evaluate((element) => { (element as HTMLElement).dataset.sharedToolbarIdentity = 'same'; });
  await page.getByLabel('Python editor').fill('print("word wrap remains a viewport preference " * 20)');
  await expect(projectEditor.locator('.cm-line').first()).toHaveCSS('white-space', 'pre-wrap');

  await page.getByTestId('project-word-wrap-toggle').click();
  await expect(page.getByTestId('project-word-wrap-toggle')).toHaveAttribute('aria-pressed', 'false');
  await expect(codeMirror).toHaveAttribute('data-shared-toolbar-identity', 'same');
  await page.getByTestId('project-source-editor-settings').locator('summary').click();
  await page.getByTestId('project-font-size').selectOption('18');
  await page.getByTestId('project-line-numbers').uncheck();
  await expect(projectEditor.locator('.cm-lineNumbers')).toHaveCount(0);
  await expect(codeMirror).toHaveAttribute('data-shared-toolbar-identity', 'same');

  await terminal.getByRole('button', { name: /index\.html/u }).last().click();
  await expect(page.getByTestId('project-code-editor')).toContainText('HTML');
  await expect(page.getByTestId('project-word-wrap-toggle')).toHaveAttribute('aria-pressed', 'false');
  await page.getByTestId('project-word-wrap-toggle').click();
  await expect(page.getByTestId('project-word-wrap-toggle')).toHaveAttribute('aria-pressed', 'true');

  await expect(page.getByTestId('project-terminal')).toBeVisible();
  await input.fill('pwd');
  await input.press('Enter');
  await expect(terminal).toContainText('/workspace');
});
