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

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

const VIEWPORTS = [
  ['desktop', 1440, 900],
  ['mobile', 390, 844],
];

async function scrollPass(page) {
  await page.evaluate(async () => {
    await new Promise((resolve) => {
      let y = 0;
      const step = () => {
        window.scrollTo(0, y);
        y += 500;
        if (y < document.body.scrollHeight) {
          setTimeout(step, 130);
        } else {
          window.scrollTo(0, 0);
          setTimeout(resolve, 400);
        }
      };
      step();
    });
  });
}

(async () => {
  const browser = await chromium.launch();
  for (const [name, w, h] of VIEWPORTS) {
    const ctx = await browser.newContext({
      viewport: { width: w, height: h },
      userAgent: UA,
      deviceScaleFactor: 2,
    });
    const page = await ctx.newPage();
    await page.goto(URL, { waitUntil: 'networkidle', timeout: 60000 }).catch(async () => {
      await page.goto(URL, { waitUntil: 'load', timeout: 60000 });
    });

    // dismiss consent / popups
    for (const sel of [
      'text=/^(accept|aceptar|agree|ok|entendido|got it)/i',
      "[id*='cookie' i] button",
      "[class*='consent' i] button",
    ]) {
      try { await page.locator(sel).first().click({ timeout: 700 }); } catch (e) {}
    }
    await page.keyboard.press('Escape').catch(() => {});

    await scrollPass(page);
    await page.waitForTimeout(1200);

    // above the fold
    await page.screenshot({ path: `${OUT}/${name}-fold.png` });
    // full page
    await page.screenshot({ path: `${OUT}/${name}-full.png`, fullPage: true });

    if (name === 'desktop') {
      fs.writeFileSync(`${OUT}/page.html`, await page.content(), 'utf-8');
      const bh = await page.evaluate(() => document.body.scrollHeight);
      console.log('desktop body scrollHeight =', bh);
    }
    console.log(`captured ${name}`);
    await ctx.close();
  }
  await browser.close();
})();
