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

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

test.describe('File loading', () => {
  test('loads OBJ file and shows mesh info', async ({ page }) => {
    await page.goto('/');
    await page.locator('canvas').waitFor({ state: 'visible', timeout: 10000 });

    const fileInput = page.locator('#file-input');
    await fileInput.setInputFiles(resolve(__dirname, '../fixtures/cube.obj'));
    await page.waitForTimeout(3000);

    await expect(page.locator('[data-testid="vertex-count"]')).toContainText('8');
    await expect(page.locator('[data-testid="face-count"]')).toContainText('6');
  });

  test('loads STL file and shows correct face count', async ({ page }) => {
    await page.goto('/');
    await page.locator('canvas').waitFor({ state: 'visible', timeout: 10000 });

    const fileInput = page.locator('#file-input');
    await fileInput.setInputFiles(resolve(__dirname, '../fixtures/cube.stl'));
    await page.waitForTimeout(3000);

    await expect(page.locator('[data-testid="face-count"]')).toContainText('12');
  });

  test('loads PLY file', async ({ page }) => {
    await page.goto('/');
    await page.locator('canvas').waitFor({ state: 'visible', timeout: 10000 });

    const fileInput = page.locator('#file-input');
    await fileInput.setInputFiles(resolve(__dirname, '../fixtures/cube.ply'));
    await page.waitForTimeout(3000);

    await expect(page.locator('[data-testid="vertex-count"]')).toContainText('8');
  });
});

test.describe('Render modes', () => {
  test('render mode buttons switch display', async ({ page }) => {
    await page.goto('/');
    await page.locator('canvas').waitFor({ state: 'visible', timeout: 10000 });
    await page.waitForTimeout(1000);

    for (const mode of ['solid', 'flat', 'wireframe', 'points']) {
      await page.click(`[data-testid="mode-${mode}"]`);
      await page.waitForTimeout(300);
      const dataUrl = await page.evaluate(() => document.querySelector('canvas')?.toDataURL() ?? '');
      expect(dataUrl.length).toBeGreaterThan(1000);
    }
  });
});

test.describe('Export', () => {
  test('File menu has export options', async ({ page }) => {
    await page.goto('/');
    await page.click('[data-testid="menu-File"]');
    await expect(page.locator('text=Export Mesh As...').first()).toBeVisible();
  });
});
