import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { expect, test } from '@playwright/test';
import { createBrowserWorkspace } from './common';

const fixture = path.resolve(
  path.dirname(fileURLToPath(import.meta.url)),
  '../fixtures/interactive-source-project.zip',
);

test('browser Git initializes, commits project files, and persists history', async ({
  page,
}) => {
  const workspaceName = `git-project-${Date.now()}`;
  await createBrowserWorkspace(page, { workspaceName });
  await page.getByLabel('Import Project ZIP').setInputFiles(fixture);

  await page.getByRole('button', { name: 'Git', exact: true }).click();
  await expect(page.getByRole('heading', { name: 'Browser Git' })).toBeVisible();
  await page.getByRole('button', { name: 'Initialize Git' }).click();

  await expect(page.getByText('main.tex', { exact: true })).toBeVisible();
  await page.getByRole('button', { name: 'Stage all' }).click();
  await page.getByLabel('Author name').fill('Learnitive Test');
  await page.getByLabel('Author email').fill('test@learnitive.local');
  await page.getByLabel('Commit message').fill('Initial LaTeX project');
  await page.getByRole('button', { name: 'Commit', exact: true }).click();

  await page.keyboard.press('Escape');
  await page.getByRole('link', { name: /^main\.tex$/ }).click();
  const source = page.getByLabel('LaTeX source editor');
  await source.fill('\\documentclass{article}\nChanged after commit.\n');
  await source.press(process.platform === 'darwin' ? 'Meta+s' : 'Control+s');

  await page.getByRole('button', { name: 'Git', exact: true }).click();
  const changedRow = page.getByText('main.tex', { exact: true }).locator('..');
  await changedRow.getByRole('button', { name: 'Diff', exact: true }).click();
  await expect(page.getByRole('dialog').locator('pre')).toContainText(
    '+ Changed after commit.',
  );

  await page.getByRole('button', { name: 'History', exact: true }).click();
  await expect(page.getByText('Initial LaTeX project', { exact: true })).toBeVisible();

  await page.keyboard.press('Escape');
  await page.reload({ waitUntil: 'domcontentloaded' });
  await page.getByRole('button', { name: 'Git', exact: true }).click();
  await page.getByRole('button', { name: 'History', exact: true }).click();
  await expect(page.getByText('Initial LaTeX project', { exact: true })).toBeVisible();
});
