/**
 * Capture viewport screenshots (not only fullPage) and clip metrics overlay.
 */
import { chromium } from 'playwright';
import { mkdir } from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const outDir = path.join(__dirname, 'screenshots');
const url = process.env.KUTBY_URL || 'http://localhost/wbktby/';

await mkdir(outDir, { recursive: true });

const browser = await chromium.launch({ headless: true });
const context = await browser.newContext({
  viewport: { width: 1440, height: 900 },
  deviceScaleFactor: 1,
  locale: 'ar-SA',
  colorScheme: 'light',
  isMobile: false,
  hasTouch: false,
});
const page = await context.newPage();
await page.goto(url, { waitUntil: 'networkidle', timeout: 60000 });
await page.waitForTimeout(1000);

// Verify zoom/meta
const meta = await page.evaluate(() => {
  const vp = document.querySelector('meta[name="viewport"]');
  return {
    viewportMeta: vp ? vp.getAttribute('content') : null,
    innerWidth: window.innerWidth,
    documentWidth: document.documentElement.clientWidth,
    scrollWidth: document.documentElement.scrollWidth,
    bodyScrollWidth: document.body.scrollWidth,
  };
});
console.log('meta', meta);

await page.screenshot({
  path: path.join(outDir, 'homepage-desktop-viewport.png'),
  fullPage: false,
});
await page.screenshot({
  path: path.join(outDir, 'homepage-desktop.png'),
  fullPage: true,
});

// Tablet + mobile
for (const vp of [
  { name: 'tablet', width: 768, height: 1024 },
  { name: 'mobile', width: 390, height: 844 },
]) {
  await page.setViewportSize({ width: vp.width, height: vp.height });
  await page.waitForTimeout(400);
  await page.screenshot({
    path: path.join(outDir, `homepage-${vp.name}.png`),
    fullPage: true,
  });
  const w = await page.evaluate(() => ({
    inner: window.innerWidth,
    scroll: document.documentElement.scrollWidth,
    container: document.querySelector('.kutby-home .kutby-container')?.getBoundingClientRect().width,
  }));
  console.log(vp.name, w);
}

await browser.close();
console.log('done');
