// Render the two-page media kit to PDF via headless Chromium.
// Same approach as audits/render-pdf.mjs in the wallet monorepo.
//
//   npm i playwright && npx playwright install chromium
//   node render-pdf.mjs                  # English
//   node render-pdf.mjs es               # Spanish
//   node render-pdf.mjs all              # both
//
// Also warns, per sheet, if content overlaps that sheet's footer — the layout is
// rigid A4 boxes with overflow:hidden, so a spill would otherwise go unnoticed.

import { chromium } from 'playwright'
import { fileURLToPath } from 'url'
import { dirname, join } from 'path'
import { existsSync, readdirSync } from 'fs'
import { homedir } from 'os'

const here = dirname(fileURLToPath(import.meta.url))

// Playwright pins one Chromium build per release. If the pinned build isn't
// downloaded but some other one is sitting in the cache, use that instead of
// making the user pull another 150 MB.
function cachedChromium() {
  const cache = join(homedir(), '.cache', 'ms-playwright')
  if (!existsSync(cache)) return undefined
  const builds = readdirSync(cache)
    .filter(d => d.startsWith('chromium-'))
    .sort((a, b) => Number(b.split('-')[1]) - Number(a.split('-')[1]))
  for (const b of builds) {
    const exe = join(cache, b, 'chrome-linux64', 'chrome')
    if (existsSync(exe)) return exe
  }
  return undefined
}

const TARGETS = {
  en: { html: 'media-kit-en.html', pdf: 'BVCC-Agent-Wallet-Media-Kit.pdf' },
  es: { html: 'media-kit-es.html', pdf: 'BVCC-Agent-Wallet-Media-Kit-ES.pdf' },
}

const arg = (process.argv[2] || 'en').toLowerCase()
const picked = arg === 'all' ? ['en', 'es'] : [arg]

const exe = cachedChromium()
const browser = await chromium.launch(exe ? { executablePath: exe } : {})

for (const key of picked) {
  const t = TARGETS[key]
  if (!t) {
    console.error(`unknown target "${key}" — use en, es or all`)
    continue
  }

  const page = await browser.newPage()
  await page.goto('file://' + join(here, t.html), { waitUntil: 'networkidle' })
  // Google Fonts land after networkidle often enough to matter for pagination.
  await page.evaluate(() => document.fonts.ready)

  // Measure in print media, not screen. The documents carry @media screen rules so
  // they can be previewed in a browser (scrollable, centred sheets); measuring in
  // screen media would check a layout that never reaches the PDF.
  await page.emulateMedia({ media: 'print' })

  // Each .page is a fixed-height A4 box with overflow:hidden, so scrollHeight never
  // grows and cannot reveal a spill — content just silently overlaps the footer.
  // So check every sheet: does its content end above its own footer?
  const sheets = await page.evaluate(() =>
    [...document.querySelectorAll('.page')].map((pg, i) => {
      const foot = pg.querySelector('footer, .contd')
      const footTop = foot ? foot.getBoundingClientRect().top : pg.getBoundingClientRect().bottom
      let lowest = 0
      let worst = ''
      for (const el of pg.querySelector('.body').querySelectorAll(':scope > *')) {
        const r = el.getBoundingClientRect()
        if (r.height && r.bottom > lowest) {
          lowest = r.bottom
          worst = (el.querySelector('h2')?.textContent || el.tagName).trim()
        }
      }
      return { n: i + 1, lowest: Math.round(lowest), footTop: Math.round(footTop), worst }
    })
  )
  let spilled = false
  for (const s of sheets) {
    if (s.lowest > s.footTop) {
      spilled = true
      console.warn(
        `  ⚠ ${t.html} page ${s.n}: content overlaps the footer by ${s.lowest - s.footTop}px. ` +
        `Last section is "${s.worst}" — cut something there.`
      )
    } else {
      console.log(`  page ${s.n}: ${s.footTop - s.lowest}px of clearance above the footer`)
    }
  }
  if (!spilled && sheets.length) console.log(`  ${sheets.length} page(s), all fitting`)

  await page.pdf({
    path: join(here, t.pdf),
    format: 'A4',
    printBackground: true,
    preferCSSPageSize: true,
    margin: { top: '0', bottom: '0', left: '0', right: '0' },
    displayHeaderFooter: false,
  })
  await page.close()
  console.log('PDF written:', t.pdf)
}

await browser.close()
