import { chromium } from "playwright";
import { preview } from "astro";

const server = await preview({ server: { port: 4399 } });
const base = "http://localhost:4399";
const browser = await chromium.launch();

async function shot(name, { theme = "dark", scrollY = 0, selector = null, path = "/", fullPage = false } = {}) {
  const page = await browser.newPage({
    viewport: { width: 1440, height: 900 },
    deviceScaleFactor: 2,
  });
  await page.addInitScript((t) => {
    try { localStorage.setItem("theme", t); } catch {}
  }, theme);
  await page.goto(base + path, { waitUntil: "networkidle" });
  await page.evaluate(
    (t) => document.documentElement.setAttribute("data-theme", t),
    theme
  );
  if (scrollY) {
    await page.evaluate((y) => window.scrollTo(0, y), scrollY);
    await page.waitForTimeout(400);
  }
  await page.waitForTimeout(2700);
  if (selector) {
    const el = await page.$(selector);
    await el.scrollIntoViewIfNeeded();
    await page.waitForTimeout(2700);
    await el.screenshot({ path: `/tmp/site-${name}.png` });
  } else {
    await page.screenshot({ path: `/tmp/site-${name}.png`, fullPage });
  }
  await page.close();
  console.log("wrote /tmp/site-" + name + ".png");
}

await shot("light-hero", { theme: "light" });
await shot("dark-hero", { theme: "dark" });

await browser.close();
await server.stop();
