import puppeteer from "puppeteer-core";
import { mkdirSync } from "fs";

const OUT = "/home/devuser/work/screenshots";
mkdirSync(OUT, { recursive: true });

const browser = await puppeteer.launch({
  executablePath: "/usr/bin/chromium",
  headless: "new",
  args: [
    "--no-sandbox",
    "--disable-gpu",
    "--window-size=1440,900",
    "--use-gl=angle",
    "--use-angle=swiftshader",
    "--autoplay-policy=no-user-gesture-required",
  ],
  defaultViewport: { width: 1440, height: 900, deviceScaleFactor: 1 },
});

const page = await browser.newPage();
page.on("console", (m) => console.log("PAGE", m.type(), m.text()));
page.on("pageerror", (e) => console.log("ERR", e.message));

async function shot(name) {
  await page.screenshot({ path: `${OUT}/${name}`, type: "png" });
  console.log("saved", name);
}

await page.goto("http://127.0.0.1:5173/", { waitUntil: "networkidle0", timeout: 30000 });
await new Promise((r) => setTimeout(r, 800));
await shot("01-title.png");

await page.click("#sc-boot");
await new Promise((r) => setTimeout(r, 600));
await shot("02-menu.png");

await page.click('[data-act="campaign"]');
await new Promise((r) => setTimeout(r, 400));
await shot("03-campaign.png");

await page.goto("http://127.0.0.1:5173/?fast=1&level=1", {
  waitUntil: "networkidle0",
  timeout: 30000,
});
await new Promise((r) => setTimeout(r, 900));

const laid = await page.evaluate(() => {
  const { game, renderer } = window.__lumina;
  if (!game || !renderer.layout) return { ok: false };
  const L = renderer.layout;
  const cells = [
    [3, 2],
    [3, 3],
    [3, 4],
    [3, 5],
    [3, 6],
    [3, 7],
  ];
  for (const [r, c] of cells) {
    game.queue[0] = "h";
    game.place(r, c);
  }
  return { ok: true, tile: L.tile, bx: L.bx, by: L.by, score: game.score };
});
console.log("laid", laid);
await new Promise((r) => setTimeout(r, 400));
await shot("04-play.png");

await page.evaluate(() => window.__lumina.game.release());
await new Promise((r) => setTimeout(r, 2500));
await shot("05-flow.png");

await new Promise((r) => setTimeout(r, 2500));
await shot("06-results.png");

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