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

const URL = 'https://studiosfeedback.com';
const OUT = '/home/claude/agency-web/audit2';
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';

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

// slow scroll, ~250ms per step, to trigger scroll-driven animations & count-ups
async function slowScroll(page, perStep = 250, frac = 0.55) {
  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 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 });
    });

    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(() => {});

    // two full slow passes so count-ups & per-step reveals reach final state
    await slowScroll(page, 250, 0.55);
    await slowScroll(page, 200, 0.45);

    // fold (top)
    await page.evaluate(() => window.scrollTo(0, 0));
    await page.waitForTimeout(1000);
    await page.screenshot({ path: `${OUT}/${name}-fold.png` });

    // full page in final animated state
    await page.screenshot({ path: `${OUT}/${name}-full.png`, fullPage: true });

    if (name === 'desktop') {
      fs.writeFileSync(`${OUT}/page.html`, await page.content(), 'utf-8');
      const meta = await page.evaluate(() => {
        const out = [];
        document.querySelectorAll('section, header, footer').forEach((el, i) => {
          const r = el.getBoundingClientRect();
          out.push({
            i,
            tag: el.tagName,
            cls: (el.className || '').toString().slice(0, 70),
            top: Math.round(r.top + window.scrollY),
            h: Math.round(r.height),
            txt: (el.innerText || '').replace(/\s+/g, ' ').slice(0, 90),
          });
        });
        return { scrollHeight: document.body.scrollHeight, sections: out };
      });
      fs.writeFileSync(`${OUT}/sections.json`, JSON.stringify(meta, null, 2), 'utf-8');
      console.log('desktop scrollHeight =', meta.scrollHeight, 'sections =', meta.sections.length);
    }
    console.log('captured', name);
    await ctx.close();
  }
  await browser.close();
  console.log('done');
})();
