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

(async () => {
  const root = path.resolve(__dirname, '..');
  const outDir = path.join(root, 'deliverables');
  const sectionDir = path.join(outDir, 'sections_v03');
  const files = fs.readdirSync(sectionDir).filter(f => f.endsWith('.png')).sort();
  const cards = files.map(f => {
    const title = f.replace('.png', '');
    const src = 'file://' + path.join(sectionDir, f);
    return `<figure><div class="label">${title}</div><img src="${src}" /></figure>`;
  }).join('');
  const html = `<!doctype html><html><head><meta charset="utf-8"><style>
    body{margin:0;background:#ede6d8;font-family:-apple-system,BlinkMacSystemFont,"PingFang SC",sans-serif;color:#302f2e;}
    .wrap{width:1600px;padding:42px 44px 54px;box-sizing:border-box;}
    h1{font-size:38px;margin:0 0 28px;letter-spacing:.04em;}
    .grid{display:grid;grid-template-columns:repeat(4,1fr);gap:24px;align-items:start;}
    figure{margin:0;background:#fffaf1;border:1px solid rgba(189,133,55,.22);border-radius:22px;overflow:hidden;box-shadow:0 16px 36px rgba(48,47,46,.12);}
    .label{font-size:22px;font-weight:700;padding:14px 18px;background:#302f2e;color:#f7f6f2;}
    img{display:block;width:100%;height:auto;}
  </style></head><body><div class="wrap"><h1>渚咖咖啡杯详情页 v03 分段总览</h1><div class="grid">${cards}</div></div></body></html>`;
  const browser = await chromium.launch({ channel: 'chrome', headless: true });
  const page = await browser.newPage({ viewport: { width: 1600, height: 2400 }, deviceScaleFactor: 1 });
  await page.setContent(html, { waitUntil: 'load' });
  await page.evaluate(async () => {
    await Promise.all(Array.from(document.images).map(img => img.complete ? true : new Promise(resolve => { img.onload = img.onerror = resolve; })));
  });
  const out = path.join(outDir, '渚咖咖啡杯_详情页_v03_sections_overview.jpg');
  await page.screenshot({ path: out, fullPage: true, type: 'jpeg', quality: 88 });
  await browser.close();
  console.log(out);
})();
