/**
 * 调试页面加载问题
 */
const { chromium } = require('playwright');

(async () => {
  const browser = await chromium.launch({
    headless: false,
    channel: 'chrome'
  });

  const page = await browser.newPage();

  // 监听所有控制台消息
  page.on('console', msg => {
    console.log(`[${msg.type()}] ${msg.text()}`);
  });

  // 监听页面错误
  page.on('pageerror', error => {
    console.error(`[PAGE ERROR] ${error.message}`);
    console.error(error.stack);
  });

  // 监听请求
  page.on('request', request => {
    console.log(`[REQUEST] ${request.method()} ${request.url()}`);
  });

  // 监听响应
  page.on('response', response => {
    if (response.status() >= 400) {
      console.error(`[RESPONSE ERROR] ${response.status()} ${response.url()}`);
    }
  });

  console.log('正在访问 http://localhost:3000 ...');
  await page.goto('http://localhost:3000', {
    waitUntil: 'networkidle',
    timeout: 30000
  });

  console.log('\n等待 5 秒...');
  await page.waitForTimeout(5000);

  // 检查 DOM 内容
  const bodyHTML = await page.evaluate(() => {
    return {
      root: document.getElementById('root')?.innerHTML.substring(0, 500),
      bodyText: document.body.innerText.substring(0, 200),
      hasReact: !!window.React,
      scripts: Array.from(document.querySelectorAll('script')).map(s => s.src),
      styles: Array.from(document.querySelectorAll('link[rel="stylesheet"]')).map(s => s.href)
    };
  });

  console.log('\n页面信息:');
  console.log('Root 内容:', bodyHTML.root || '空');
  console.log('Body 文本:', bodyHTML.bodyText || '空');
  console.log('React 存在:', bodyHTML.hasReact);
  console.log('脚本:', bodyHTML.scripts);
  console.log('样式:', bodyHTML.styles);

  // 截图
  await page.screenshot({ path: 'debug-screenshot.png' });
  console.log('\n截图已保存: debug-screenshot.png');

  console.log('\n按 Enter 关闭浏览器...');
  await new Promise(resolve => {
    process.stdin.once('data', resolve);
  });

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