/// <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('Transcription toggle', () => {
  test('record and stop preserve segments', 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);

    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 recordButton = page.locator('[data-testid="record-button"], button[aria-label*="record" i], button[aria-label*="Record" i]').first();
    if ((await recordButton.count()) === 0) test.skip(true, 'No transcription record control found');
    const beforeCount = await page.locator('[data-testid="segment"], .segment, .transcription-segment').count();

    await recordButton.click();
    await expect(recordButton).toHaveAttribute('aria-pressed', 'true');
    await recordButton.click();

    const afterCount = await page.locator('[data-testid="segment"], .segment, .transcription-segment').count();
    expect(afterCount).toBeGreaterThanOrEqual(beforeCount);
  });
});
