const { chromium } = require('playwright');

(async () => {
  console.log('🚀 启动浏览器测试...\n');

  const browser = await chromium.launch({ headless: false, slowMo: 500 });
  const context = await browser.newContext();
  const page = await context.newPage();

  // 基础 URL
  const baseUrl = 'http://localhost:5173';

  const pages = [
    { path: '/#/pages/index/index', name: '首页' },
    { path: '/#/pages/create/index', name: '生成页' },
    { path: '/#/pages/history/index', name: '历史页' },
    { path: '/#/pages/mine/index', name: '我的页' },
    { path: '/#/pages/book-generator/index', name: '书籍生成页' },
    { path: '/#/pages/video-generator/index', name: '视频生成页' },
    { path: '/#/pages/favorites/index', name: '收藏页' },
    { path: '/#/pages/search/index', name: '搜索页' },
    { path: '/#/pages/ai/index', name: 'AI页' },
    { path: '/#/pages/ai-content/index', name: 'AI内容页' },
    { path: '/#/pages/learning-path/index', name: '学习路径页' },
    { path: '/#/pages/album/index?id=1', name: '专辑/书籍详情页' },
  ];

  const errors = [];

  for (const pageInfo of pages) {
    try {
      console.log(`📄 测试页面: ${pageInfo.name}`);
      console.log(`    URL: ${baseUrl}${pageInfo.path}`);

      await page.goto(`${baseUrl}${pageInfo.path}`, { waitUntil: 'networkidle', timeout: 10000 });

      // 等待页面加载
      await page.waitForTimeout(1000);

      // 截图
      const screenshotPath = `screenshot-${pageInfo.name.replace(/\//g, '-')}.png`;
      await page.screenshot({ path: screenshotPath });
      console.log(`   ✅ 页面加载成功，截图已保存: ${screenshotPath}`);

      // 检查页面是否有明显错误
      const pageErrors = await page.evaluate(() => {
        return window.console?.errors || [];
      });

      if (pageErrors.length > 0) {
        console.log(`   ⚠️  页面有 ${pageErrors.length} 个控制台错误`);
      }

      // 尝试点击页面上的按钮
      const buttons = await page.$$('button, .btn, [class*="btn-"], [onclick], [@click]');
      console.log(`   🔘 发现 ${buttons.length} 个可点击元素`);

      // 点击前3个按钮（如果有）
      for (let i = 0; i < Math.min(3, buttons.length); i++) {
        try {
          await buttons[i].click({ timeout: 2000 });
          await page.waitForTimeout(500);
          console.log(`      ✅ 点击了第 ${i + 1} 个按钮`);
        } catch (e) {
          console.log(`      ⚠️  点击第 ${i + 1} 个按钮失败: ${e.message}`);
        }
      }

      console.log('');

    } catch (error) {
      console.log(`   ❌ 页面测试失败: ${error.message}`);
      errors.push({ page: pageInfo.name, error: error.message });
      console.log('');
    }
  }

  // 总结
  console.log('========================================');
  console.log('📊 测试总结:');
  console.log(`   总页面数: ${pages.length}`);
  console.log(`   成功: ${pages.length - errors.length}`);
  console.log(`   失败: ${errors.length}`);

  if (errors.length > 0) {
    console.log('\n❌ 失败的页面:');
    errors.forEach(e => {
      console.log(`   - ${e.page}: ${e.error}`);
    });
  }

  console.log('\n⏸️  浏览器将保持打开10秒，按 Ctrl+C 退出...');
  await page.waitForTimeout(10000);

  await browser.close();
})();
