/**
 * Find overflow at a given viewport width.
 */
import { chromium } from 'playwright';

const url = process.env.KUTBY_URL || 'http://localhost/wbktby/';
const width = Number(process.argv[2] || 768);
const height = Number(process.argv[3] || 1024);

const browser = await chromium.launch({ headless: true });
const page = await browser.newPage({
  viewport: { width, height },
  deviceScaleFactor: 1,
});
await page.goto(url, { waitUntil: 'networkidle', timeout: 60000 });

const report = await page.evaluate((docWExpected) => {
  const docW = document.documentElement.clientWidth;
  const offenders = [];
  for (const el of document.querySelectorAll('body *')) {
    const r = el.getBoundingClientRect();
    if (r.width > docW + 1 || r.right > docW + 1 || r.left < -1) {
      offenders.push({
        tag: el.tagName.toLowerCase(),
        cls: (el.className && String(el.className).slice(0, 140)) || '',
        id: el.id || '',
        w: Math.round(r.width),
        left: Math.round(r.left),
        right: Math.round(r.right),
      });
    }
  }
  offenders.sort((a, b) => b.right - a.right || b.w - a.w);
  return {
    expected: docWExpected,
    clientWidth: docW,
    scrollWidth: document.documentElement.scrollWidth,
    top: offenders.slice(0, 30),
  };
}, width);

console.log(JSON.stringify(report, null, 2));
await browser.close();
