import { test, expect, request } from '@playwright/test';

const BASE = process.env.PLAYWRIGHT_BASE_URL || 'http://192.168.0.251:13000';
const TEST_EMAIL = process.env.VITE_TEST_TEACHER_EMAIL;
const TEST_PASSWORD = process.env.VITE_TEST_TEACHER_PASSWORD;

async function serverReachable() {
  try {
    const ctx = await request.newContext();
    const res = await ctx.get(BASE, { timeout: 3000 }).catch(() => null);
    await ctx.dispose();
    return Boolean(res);
  } catch {
    return false;
  }
}

async function login(page) {
  await page.goto(`${BASE}/login`);
  await page.getByLabel('Email').fill(TEST_EMAIL);
  await page.getByLabel('Password').fill(TEST_PASSWORD);
  await page.getByRole('button', { name: 'Login' }).click();
  await page.waitForURL((url) => /\/dashboard|\/node\//.test(url.pathname), { timeout: 15000 });
}

function skipIfUnconfigured() {
  if (!TEST_EMAIL || !TEST_PASSWORD) test.skip(true, 'VITE_TEST_TEACHER_EMAIL / VITE_TEST_TEACHER_PASSWORD not set');
}

test.describe('Transcription toggle', () => {
  test.beforeAll(async () => {
    skipIfUnconfigured();
    const reachable = await serverReachable();
    test.skip(!reachable, `Dev server not reachable at ${BASE}`);
  });

  test('record button toggles isRecording state', async ({ page, context }) => {
    await context.grantPermissions(['microphone']);
    await login(page);
    await page.locator('[data-testid="tldraw-canvas"], .tl-container').waitFor({ timeout: 10000 });
    const recordBtn = page.locator('[data-testid="record-button"], button[aria-label*="ecord" i]').first();
    const btnVisible = await recordBtn.waitFor({ timeout: 5000 }).then(() => true).catch(() => false);
    if (btnVisible) {
      const labelBefore = await recordBtn.getAttribute('aria-label').catch(() => '');
      await recordBtn.click();
      await page.waitForTimeout(1000);
      const labelAfter = await recordBtn.getAttribute('aria-label').catch(() => '');
      expect(labelBefore).not.toEqual(labelAfter);
      await recordBtn.click();
    } else {
      test.skip(true, 'Record button not visible on current node type');
    }
  });
});
