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('OFF format', () => {
  test('loads OFF file and shows vertex count', async ({ page }) => {
    await page.goto('/');
    await page.locator('canvas').first().waitFor({ state: 'visible', timeout: 10000 });

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

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

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

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

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

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

    await page.locator('#file-input').setInputFiles(resolve(__dirname, '../fixtures/cube.glb'));
    await page.waitForTimeout(5000);

    // Should have at least 1 layer with vertices
    const layerItems = page.locator('[data-testid="layer-item"]');
    await expect(layerItems.first()).toBeVisible({ timeout: 10000 });
    await expect(page.locator('[data-testid="vertex-count"]')).toBeVisible();
  });
});

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

test.describe('Error messages', () => {
  test('unsupported format shows error', async ({ page }) => {
    await page.goto('/');
    await page.locator('canvas').first().waitFor({ state: 'visible', timeout: 10000 });

    await page.locator('#file-input').setInputFiles({
      name: 'model.abc',
      mimeType: 'application/octet-stream',
      buffer: Buffer.from('fake'),
    });
    await page.waitForTimeout(1000);

    await expect(page.locator('[data-testid="error-toast"]')).toContainText('Unsupported');
  });
});
