import { test, expect } from '@playwright/test';
import { resolve, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';

const __dirname = dirname(fileURLToPath(import.meta.url));

async function loadCube(page: import('@playwright/test').Page) {
  await page.locator('#file-input').setInputFiles(resolve(__dirname, '../fixtures/cube.obj'));
  await page.waitForTimeout(3000);
}

test.describe('Mesh Stats Dialog', () => {
  test('opens and shows correct stats', async ({ page }) => {
    await page.goto('/');
    await page.locator('canvas').first().waitFor({ state: 'visible', timeout: 10000 });
    await loadCube(page);

    await page.click('[data-testid="mesh-stats-btn"]');
    await expect(page.locator('[data-testid="mesh-stats-dialog"]')).toBeVisible();
    await expect(page.locator('[data-testid="stats-vertices"]')).toContainText('Vertices');
    await expect(page.locator('[data-testid="stats-closed"]')).toContainText('Closed');
    await expect(page.locator('[data-testid="stats-euler"]')).toContainText('2');
    await expect(page.locator('[data-testid="stats-nm-edges"]')).toContainText('0');
  });

  test('close button works', async ({ page }) => {
    await page.goto('/');
    await page.locator('canvas').first().waitFor({ state: 'visible', timeout: 10000 });
    await loadCube(page);

    await page.click('[data-testid="mesh-stats-btn"]');
    await expect(page.locator('[data-testid="mesh-stats-dialog"]')).toBeVisible();
    await page.click('[data-testid="close-dialog"]');
    await expect(page.locator('[data-testid="mesh-stats-dialog"]')).not.toBeVisible();
  });

  test('auto-repair runs successfully', async ({ page }) => {
    await page.goto('/');
    await page.locator('canvas').first().waitFor({ state: 'visible', timeout: 10000 });
    await loadCube(page);

    await page.click('[data-testid="mesh-stats-btn"]');
    await page.click('[data-testid="auto-repair"]');
    await page.waitForTimeout(1000);

    await expect(page.locator('[data-testid="stats-nm-edges"]')).toContainText('0');
    await expect(page.locator('[data-testid="stats-degenerate"]')).toContainText('0');
  });
});

test.describe('Repair Filters', () => {
  test('Repair filters accessible from Filters menu', async ({ page }) => {
    await page.goto('/');
    await page.click('[data-testid="menu-Filters"]');
    await page.locator('[data-testid="menu-bar"]').locator('text=Cleaning and Repairing').click();
    await expect(page.locator('text=Fill Holes').first()).toBeVisible();
    await expect(page.locator('text=Auto-Repair All').first()).toBeVisible();
  });

  test('Cleaning and Repairing in Filters menu', async ({ page }) => {
    await page.goto('/');
    await page.click('[data-testid="menu-Filters"]');
    await expect(page.locator('text=Cleaning and Repairing').first()).toBeVisible();
  });
});
