const { app, BrowserWindow } = require("electron");

const target = process.argv.find((argument) => /^https?:\/\//u.test(argument)) ?? "http://127.0.0.1:4173";
const widths = [375, 768, 1024, 1440];

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

app.whenReady().then(async () => {
  for (const width of widths) {
    const window = new BrowserWindow({ width, height: 900, show: false, webPreferences: { sandbox: true } });
    await window.loadURL(target);
    await new Promise((resolve) => setTimeout(resolve, 1000));
    const report = await window.webContents.executeJavaScript(`(() => {
      const downloads = [...document.querySelectorAll('[data-download-link]')];
      const unnamedButtons = [...document.querySelectorAll('button')].filter((button) => {
        const text = button.textContent.trim();
        return !text && !button.getAttribute('aria-label');
      }).length;
      return {
        viewport: document.documentElement.clientWidth,
        scrollWidth: document.documentElement.scrollWidth,
        brokenImages: [...document.images].filter((image) => !image.complete || image.naturalWidth === 0).length,
        downloads: downloads.length,
        exeDownloads: downloads.filter((link) => link.href.endsWith('.exe')).length,
        disabledDownloads: downloads.filter((link) => link.getAttribute('aria-disabled') === 'true').length,
        unnamedButtons,
        hasMain: Boolean(document.querySelector('main')),
        hasH1: Boolean(document.querySelector('h1')),
        offenders: [...document.querySelectorAll('body *')].map((element) => {
          const rect = element.getBoundingClientRect();
          return { tag: element.tagName, className: element.className, left: Math.round(rect.left), right: Math.round(rect.right), width: Math.round(rect.width) };
        }).filter((item) => item.left < -1 || item.right > document.documentElement.clientWidth + 1).slice(0, 6),
      };
    })()`);
    await window.close();

    const errors = [];
    if (report.scrollWidth > report.viewport + 1) errors.push(`horizontal overflow ${report.scrollWidth - report.viewport}px (${JSON.stringify(report.offenders)})`);
    if (report.brokenImages > 0) errors.push(`${report.brokenImages} broken image(s)`);
    if (report.downloads < 1 || report.exeDownloads !== report.downloads) errors.push("download links are not all direct EXE files");
    if (report.disabledDownloads > 0) errors.push(`${report.disabledDownloads} download link(s) still disabled after release loading`);
    if (report.unnamedButtons > 0) errors.push(`${report.unnamedButtons} unnamed button(s)`);
    if (!report.hasMain || !report.hasH1) errors.push("missing main landmark or H1");
    if (errors.length > 0) throw new Error(`${width}px: ${errors.join(", ")}`);
    process.stdout.write(`${width}px OK · ${report.downloads} direct EXE CTAs · no horizontal overflow\n`);
  }
  app.quit();
}).catch((error) => {
  process.stderr.write(`${error instanceof Error ? error.stack : String(error)}\n`);
  app.exit(1);
});
