/**
 * Capture client-side JS errors on app pages (Playwright).
 * Usage: npx tsx scripts/browser-smoke.ts [baseUrl]
 */
import { chromium } from "playwright";

const base = process.argv[2] ?? "http://127.0.0.1:3060";
const pages = [
  "/login",
  "/dashboard",
  "/my-project",
  "/brand-profile",
  "/posting-context",
  "/connected-accounts",
  "/generated-posts",
  "/content-library",
  "/smart-schedule",
  "/live-generation",
  "/automation",
];

async function main() {
  const browser = await chromium.launch({ headless: true });
  const context = await browser.newContext();
  const page = await context.newPage();

  const consoleErrors: string[] = [];
  const pageErrors: string[] = [];

  page.on("console", (msg) => {
    if (msg.type() === "error") {
      consoleErrors.push(`[console] ${msg.text()}`);
    }
  });
  page.on("pageerror", (err) => {
    pageErrors.push(`[pageerror] ${err.message}\n${err.stack ?? ""}`);
  });

  // Demo login
  await page.goto(`${base}/login`, { waitUntil: "networkidle", timeout: 60000 });
  const demoBtn = page.getByRole("button", { name: /demo/i });
  if (await demoBtn.count()) {
    await demoBtn.click();
    await page.waitForURL(/\/(dashboard|my-project)/, { timeout: 30000 }).catch(() => {});
  }

  const results: Array<{ path: string; status: string; errors: string[] }> = [];

  for (const path of pages) {
    consoleErrors.length = 0;
    pageErrors.length = 0;

    const res = await page.goto(`${base}${path}`, {
      waitUntil: "networkidle",
      timeout: 60000,
    });
    await page.waitForTimeout(1500);

    const bodyText = await page.locator("body").innerText().catch(() => "");
    const appError = bodyText.includes("Application error") || bodyText.includes("client-side exception");
    const errors = [...pageErrors, ...consoleErrors];
    const status = res?.status() ?? 0;

    results.push({
      path,
      status: appError ? "CLIENT_CRASH" : status >= 400 ? "HTTP_FAIL" : "OK",
      errors,
    });

    console.log(
      `${appError ? "FAIL" : status === 200 ? "PASS" : "WARN"}\t${path}\tHTTP ${status}${errors.length ? ` — ${errors[0]?.slice(0, 120)}` : ""}`,
    );
  }

  await browser.close();

  const failed = results.filter((r) => r.status !== "OK");
  console.log(`\n=== Browser smoke: ${results.length - failed.length} OK / ${failed.length} failed ===`);
  for (const f of failed) {
    console.log(`\n--- ${f.path} (${f.status}) ---`);
    for (const e of f.errors.slice(0, 5)) console.log(e);
  }

  process.exit(failed.length > 0 ? 1 : 0);
}

main().catch((e) => {
  console.error(e);
  process.exit(2);
});
