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

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';

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, 120);
        else { window.scrollTo(0, 0); setTimeout(resolve, 400); }
      };
      step();
    });
  });
}

(async () => {
  const browser = await chromium.launch();
  const ctx = await browser.newContext({
    viewport: { width: 1440, height: 900 },
    userAgent: UA,
    deviceScaleFactor: 1.5,
  });
  const page = await ctx.newPage();
  await page.goto(URL, { waitUntil: 'networkidle', timeout: 60000 }).catch(() => {});
  await scrollPass(page);
  await page.waitForTimeout(800);

  const total = await page.evaluate(() => document.body.scrollHeight);
  const vh = 900;
  let idx = 0;
  for (let y = 0; y < total; y += vh) {
    await page.evaluate((yy) => window.scrollTo(0, yy), y);
    await page.waitForTimeout(500);
    idx++;
    const padded = String(idx).padStart(2, '0');
    await page.screenshot({ path: `${OUT}/d-sec-${padded}.png` });
  }
  console.log('total sections:', idx, 'pageHeight:', total);

  // Also dump structural outline for the report
  const outline = await page.evaluate(() => {
    const out = [];
    document.querySelectorAll('section, header, footer, [class*=section i]').forEach((el) => {
      const r = el.getBoundingClientRect();
      const txt = (el.innerText || '').trim().replace(/\s+/g, ' ').slice(0, 90);
      out.push(`${el.tagName} .${(el.className||'').toString().split(' ')[0]} | h=${Math.round(el.offsetHeight)} | ${txt}`);
    });
    return out.join('\n');
  });
  require('fs').writeFileSync(`${OUT}/outline.txt`, outline, 'utf-8');

  // headings outline
  const heads = await page.evaluate(() =>
    [...document.querySelectorAll('h1,h2,h3,h4')]
      .map((h) => `${h.tagName}: ${(h.innerText||'').trim().replace(/\s+/g,' ')}`)
      .join('\n')
  );
  require('fs').writeFileSync(`${OUT}/headings.txt`, heads, 'utf-8');

  await browser.close();
})();
