const { app, BrowserWindow } = require("electron");
const { writeFile } = require("node:fs/promises");

const urlIndex = process.argv.findIndex((argument) => /^https?:\/\//u.test(argument));
const captureArguments = urlIndex >= 0 ? process.argv.slice(urlIndex) : [];
const [url = "http://127.0.0.1:4173", widthValue = "1440", heightValue = "1000", output = "site-preview.png"] = captureArguments;
const width = Number(widthValue);
const height = Number(heightValue);

app.commandLine.appendSwitch("disable-gpu");
app.commandLine.appendSwitch("disable-dev-shm-usage");

app.whenReady().then(async () => {
  const window = new BrowserWindow({
    width,
    height,
    show: false,
    webPreferences: { sandbox: true },
  });
  await window.loadURL(url);
  await window.webContents.executeJavaScript("window.scrollTo(0, 0)");
  await window.webContents.insertCSS(".reveal { opacity: 1 !important; transform: none !important; transition: none !important; }");
  await new Promise((resolve) => setTimeout(resolve, 1800));
  const image = await window.webContents.capturePage();
  await writeFile(output, image.toPNG());
  await window.close();
  app.quit();
}).catch((error) => {
  process.stderr.write(`${error instanceof Error ? error.stack : String(error)}\n`);
  app.exit(1);
});
