const { chromium } = require('playwright');
const OUT = '/home/claude/agency-web/audit2';
const URL = 'https://studiosfeedback.com';
const UA = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36';

async function slowScroll(page, perStep, frac) {
  await page.evaluate(async ({ perStep, frac }) => {
    const step = Math.max(200, Math.round(window.innerHeight * frac));
    for (let y = 0; y < document.body.scrollHeight; y += step) {
      window.scrollTo(0, y);
      await new Promise((r) => setTimeout(r, perStep));
    }
    window.scrollTo(0, document.body.scrollHeight);
    await new Promise((r) => setTimeout(r, 1500));
  }, { perStep, frac });
}

(async () => {
  const b = await chromium.launch();
  const ctx = await b.newContext({ viewport: { width: 1440, height: 900 }, userAgent: UA, deviceScaleFactor: 2 });
  const page = await ctx.newPage();
  await page.goto(URL, { waitUntil: 'networkidle', timeout: 60000 }).catch(() => {});
  await page.keyboard.press('Escape').catch(() => {});
  await slowScroll(page, 250, 0.55);

  const box = await page.evaluate(() => {
    const loop = document.querySelector('section.loop');
    const r = loop.getBoundingClientRect();
    return { top: Math.round(r.top + window.scrollY), h: Math.round(r.height) };
  });
  console.log('loop box', JSON.stringify(box));

  const vh = 900;
  const tiles = Math.ceil(box.h / vh);
  for (let i = 0; i < tiles; i++) {
    const y = box.top + i * vh;
    await page.evaluate((yy) => window.scrollTo(0, yy), y);
    await page.waitForTimeout(900);
    await page.screenshot({ path: `${OUT}/desktop-howitworks-tile${i + 1}.png` });
    console.log('tile', i + 1, 'at y=', y);
  }
  await b.close();
  console.log('done');
})();
