import assert from "node:assert/strict";

const webUrl = process.env.AWP_WEB_URL;
const playwrightModule = process.env.AWP_PLAYWRIGHT_MODULE;
if (!webUrl) throw new Error("AWP_WEB_URL is required");
if (!playwrightModule) throw new Error("AWP_PLAYWRIGHT_MODULE is required");

const { chromium } = await import(playwrightModule);
const browser = await chromium.launch({ headless: true });
try {
  const page = await browser.newPage();
  const consoleErrors: string[] = [];
  page.on("console", (message) => {
    if (message.type() === "error") consoleErrors.push(message.text());
  });
  page.on("pageerror", (error) => consoleErrors.push(error.message));
  const started = performance.now();
  const response = await page.goto(webUrl, { waitUntil: "networkidle" });
  const elapsed = performance.now() - started;
  assert.equal(response?.status(), 200);
  assert.ok(elapsed < 3_000, `UI load took ${Math.round(elapsed)}ms`);
  assert.deepEqual(consoleErrors, []);
  await page.getByRole("heading", { name: "Projects" }).waitFor();
  process.stdout.write(
    `AC-01 PASS: UI loaded in ${Math.round(elapsed)}ms with zero console errors\n`,
  );
} finally {
  await browser.close();
}
