// ─── Headless browser pool ─────────────────────────────────────────────────────
// Single-instance pool — Vercel serverless gets one browser per invocation.

let _browser: import("puppeteer-core").Browser | null = null;

export async function getBrowser(): Promise<import("puppeteer-core").Browser> {
  if (_browser) return _browser;

  const chromium = (await import("@sparticuz/chromium")).default;
  const puppeteer = await import("puppeteer-core");

  _browser = await puppeteer.default.launch({
    args: [...chromium.args, "--no-sandbox", "--disable-gpu"],
    defaultViewport: { width: 1280, height: 800 },
    executablePath: await chromium.executablePath(),
    headless: true,
  });

  return _browser;
}

export async function closeBrowser(): Promise<void> {
  if (_browser) {
    await _browser.close().catch(() => undefined);
    _browser = null;
  }
}
