import { chromium } from 'playwright';
import { mkdir } from 'node:fs/promises';
import path from 'node:path';

const baseURL = process.env.PROTOTYPE_URL || 'http://127.0.0.1:5174/';
const outDir = path.resolve('qa', 'artifacts');
await mkdir(outDir, { recursive: true });

const browser = await chromium.launch({
  headless: true,
  executablePath: process.env.BROWSER_PATH || 'C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe',
});

const page = await browser.newPage({ viewport: { width: 390, height: 844 }, deviceScaleFactor: 1 });
const errors = [];
page.on('console', (message) => { if (message.type() === 'error') errors.push(message.text()); });
page.on('pageerror', (error) => errors.push(error.message));

try {
  await page.goto(baseURL, { waitUntil: 'networkidle' });
  await page.evaluate(() => localStorage.removeItem('running-ai-prd-v1'));
  await page.reload({ waitUntil: 'networkidle' });

  const layout = await page.evaluate(() => ({
    viewport: window.innerWidth,
    contentWidth: document.documentElement.scrollWidth,
    dockVisible: getComputedStyle(document.querySelector('.demo-dock')).display !== 'none',
  }));
  if (layout.contentWidth > layout.viewport + 1) throw new Error(`mobile horizontal overflow: ${layout.contentWidth}px`);
  if (layout.dockVisible) throw new Error('demo dock should be hidden at mobile width');

  await page.keyboard.press('Tab');
  const focusVisible = await page.evaluate(() => ['BUTTON', 'A', 'INPUT', 'TEXTAREA'].includes(document.activeElement?.tagName || ''));
  if (!focusVisible) throw new Error('keyboard focus did not reach an interactive element');

  await page.screenshot({ path: path.join(outDir, 'mobile-home.png'), fullPage: true });
  await page.getByRole('button', { name: '训练', exact: true }).click();
  await page.locator('.page-header strong').filter({ hasText: '训练中心' }).waitFor();
  await page.screenshot({ path: path.join(outDir, 'mobile-training.png'), fullPage: true });

  await page.getByRole('button', { name: '营养', exact: true }).click();
  await page.locator('.page-header strong').filter({ hasText: '营养' }).waitFor();
  await page.screenshot({ path: path.join(outDir, 'mobile-nutrition.png'), fullPage: true });

  await page.getByRole('button', { name: '我的', exact: true }).click();
  await page.locator('.page-header strong').filter({ hasText: '我的' }).waitFor();
  await page.screenshot({ path: path.join(outDir, 'mobile-profile.png'), fullPage: true });

  if (errors.length) throw new Error(`browser errors: ${errors.join(' | ')}`);
  console.log(JSON.stringify({ ok: true, checks: ['390px 无横向溢出', '移动端隐藏 Demo 面板', '键盘焦点可达', '四个一级页无控制台错误'] }, null, 2));
} catch (error) {
  console.error(JSON.stringify({ ok: false, error: String(error), browserErrors: errors }, null, 2));
  process.exitCode = 1;
} finally {
  await browser.close();
}
