/**
 * L1 冒烟测试：核心前端页面加载
 * 使用 Playwright 浏览器打开关键页面，验证无控制台错误
 */
import { test, expect } from '@playwright/test';

const FRONTEND_URL = process.env.FRONTEND_URL || 'http://localhost:5173';

/** 核心页面列表（TabBar 页面 + 关键业务页面） */
const CORE_PAGES = [
  { name: '首页', path: '/#/pages/index/index' },
  { name: '生成页', path: '/#/pages/create/index' },
  { name: '书籍生成', path: '/#/pages/book-generator/index' },
  { name: '我的', path: '/#/pages/mine/index' },
  { name: '历史记录', path: '/#/pages/history/index' },
  { name: '播放器', path: '/#/pages/player/index' },
  { name: '会员中心', path: '/#/pages/member/index' },
  { name: '专辑列表', path: '/#/pages/albums/index' },
];

test.describe('核心页面加载测试', () => {
  for (const pageInfo of CORE_PAGES) {
    test(`页面加载: ${pageInfo.name} (${pageInfo.path})`, async ({ page }) => {
      // 收集控制台错误
      const consoleErrors: string[] = [];
      page.on('console', msg => {
        if (msg.type() === 'error') {
          consoleErrors.push(msg.text());
        }
      });

      // 收集页面异常
      const pageErrors: string[] = [];
      page.on('pageerror', err => {
        pageErrors.push(err.message);
      });

      // 打开页面
      await page.goto(`${FRONTEND_URL}${pageInfo.path}`, {
        waitUntil: 'networkidle',
        timeout: 30000,
      });

      // 等待页面渲染
      await page.waitForTimeout(2000);

      // 验证页面标题存在（uni-app 页面至少有一个根元素）
      const appElement = await page.$('#app');
      expect(appElement).not.toBeNull();

      // 验证无严重 JS 错误
      // 注意：一些第三方库（如 uni-app）可能产生非关键警告，这里不视为失败
      const criticalErrors = consoleErrors.filter(
        e => !e.includes('favicon') && !e.includes('preload') && !e.includes('net::ERR')
      );
      const totalErrors = [...criticalErrors, ...pageErrors];

      if (totalErrors.length > 0) {
        console.warn(`  ⚠ ${pageInfo.name} 存在 ${totalErrors.length} 个错误:`);
        totalErrors.forEach(e => console.warn(`    - ${e}`));
      }

      // 截图保存
      await page.screenshot({
        path: `test-results/screenshots/smoke-${pageInfo.name}.png`,
        fullPage: true,
      }).catch(() => {});
    });
  }
});
