// 交付前视觉 QA：四档视口全页截图 + 横向溢出检测 + og.png（1200×630 英雄屏视口截图）
// 用法：node scripts/qa-shots.mjs <baseUrl>（需先在 dist 目录起本地静态服务）
import { chromium } from 'playwright';
import { mkdirSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';

const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const base = process.argv[2] ?? 'http://127.0.0.1:8710/';
const viewports = [
  [375, 812],
  [768, 1024],
  [1280, 900],
  [1920, 1080],
];
mkdirSync(resolve(root, 'QA'), { recursive: true });

const browser = await chromium.launch();
const report = [];

for (const [w, h] of viewports) {
  const ctx = await browser.newContext({ viewport: { width: w, height: h } });
  const page = await ctx.newPage();
  await page.goto(base, { waitUntil: 'networkidle' });
  await page.waitForTimeout(300);
  const metrics = await page.evaluate(() => {
    const doc = document.documentElement;
    const overflowEls = [];
    for (const el of document.querySelectorAll('body *')) {
      const r = el.getBoundingClientRect();
      if (r.width > 0 && (r.right > window.innerWidth + 1 || r.left < -1)) {
        overflowEls.push(`${el.tagName.toLowerCase()}.${String(el.className && el.className.split(' ')[0])} right=${Math.round(r.right)} left=${Math.round(r.left)}`);
      }
    }
    return { scrollWidth: doc.scrollWidth, innerWidth: window.innerWidth, overflowEls: overflowEls.slice(0, 8) };
  });
  await page.screenshot({ path: resolve(root, `QA/shot-${w}x${h}.png`), fullPage: true });
  report.push({ viewport: `${w}x${h}`, ...metrics });
  await ctx.close();
}

// og 图：1200×630 视口直出英雄屏（导航 + 英雄区完整入画，不做整页）
const ogCtx = await browser.newContext({ viewport: { width: 1200, height: 630 }, deviceScaleFactor: 1 });
const ogPage = await ogCtx.newPage();
await ogPage.goto(base, { waitUntil: 'networkidle' });
await ogPage.waitForTimeout(300);
await ogPage.screenshot({ path: resolve(root, 'public/og.png') });
const ogMetrics = await ogPage.evaluate(() => {
  const hero = document.querySelector('.hero');
  const stack = document.querySelector('.stack');
  return {
    heroBottom: Math.round(hero.getBoundingClientRect().bottom),
    stackBottom: Math.round(stack.getBoundingClientRect().bottom),
    viewportH: window.innerHeight,
  };
});
report.push({ viewport: 'og-1200x630', ...ogMetrics });
await ogCtx.close();

await browser.close();
console.log(JSON.stringify(report, null, 2));
