/// <reference types="@playwright/test" />
import { test, expect } from '@playwright/test';

const BASE = process.env.PLAYWRIGHT_BASE_URL || 'http://192.168.0.251:13000';

test.describe('Node navigation', () => {
  test('canvas remounts on node change', async ({ page }) => {
    test.setTimeout(60000);

    async function serverReachable() {
      try {
        const res = await page.request.get(new URL('/api/health', BASE).toString(), { timeout: 4000 }).catch(
          () => null as any
        );
        return Boolean(res && (res as any).ok());
      } catch {
        return false;
      }
    }
    if (!(await serverReachable())) test.skip(true, 'Dev server not reachable at ' + BASE);

    const consoleMessages: string[] = [];
    page.on('console', (msg: any) => consoleMessages.push((msg.text() as string) || ''));
    page.on('pageerror', (err: any) => consoleMessages.push('pageerror: ' + ((err.message as string) || 'unknown')));

    await page.goto(`${BASE}/login`);
    const email = process.env.VITE_TEST_TEACHER_EMAIL || 'teacher@test';
    const password = process.env.VITE_TEST_TEACHER_PASSWORD || 'password';
    await page.getByLabel('Email').fill(email);
    await page.getByLabel('Password').fill(password);
    await page.getByRole('button', { name: /sign in|log in/i }).click();
    await page.waitForURL((url: URL) => /\/dashboard|\/node\//.test(url.pathname), { timeout: 12000 });

    const canvas = page.locator('[data-testid="tldraw-canvas"], .tl-container');
    if ((await canvas.count()) === 0) await canvas.first().waitFor({ timeout: 8000 });
    await canvas.first().waitFor({ state: 'visible', timeout: 8000 });

    const nodes = page.locator('a[href*="/node/"]').first();
    if ((await nodes.count()) === 0) test.skip(true, 'No node navigation links found');
    await nodes.click();
    await page.waitForURL((url: URL) => /\/node\/\d+/.test(url.pathname), { timeout: 12000 });

    await expect(canvas.first()).toBeVisible();
    const errorTexts = consoleMessages.some((m) => /error|failed/i.test(m));
    expect(errorTexts).toBe(false);
  });
});
