/// <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('Canvas mount', () => {
  test('login and show lesson canvas', async ({ page }) => {
    test.setTimeout(60000);
    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 });

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

    const canvasVisible = page
      .locator('[data-testid="tldraw-canvas"], .tl-container')
      .waitFor({ timeout: 8000 })
      .then(() => true)
      .catch(() => false);

    expect((await canvasVisible)).toBe(true);
    await expect(page.getByText(/error|failed to load/i).first()).toBeHidden();
  });
});
