let workerConfigured = false

async function loadPdfJs() {
  if (typeof window === "undefined") {
    throw new Error("PDF thumbnails require a browser environment")
  }
  const pdfjs = await import("pdfjs-dist")
  if (!workerConfigured) {
    pdfjs.GlobalWorkerOptions.workerSrc = new URL(
      "pdfjs-dist/build/pdf.worker.min.mjs",
      import.meta.url
    ).toString()
    workerConfigured = true
  }
  return pdfjs
}

/** First-page raster thumb for mail PDF attachments (client only). */
export async function renderMailPdfThumb(blob: Blob, maxWidth = 360): Promise<string> {
  const { getDocument } = await loadPdfJs()
  const data = await blob.arrayBuffer()
  const task = getDocument({ data })
  const pdf = await task.promise
  try {
    const page = await pdf.getPage(1)
    const baseViewport = page.getViewport({ scale: 1 })
    const scale = Math.min(2, Math.max(0.2, maxWidth / baseViewport.width))
    const viewport = page.getViewport({ scale })
    const canvas = document.createElement("canvas")
    canvas.width = Math.ceil(viewport.width)
    canvas.height = Math.ceil(viewport.height)
    const ctx = canvas.getContext("2d")
    if (!ctx) throw new Error("canvas unavailable")
    await page.render({ canvasContext: ctx, viewport, canvas }).promise
    const thumbBlob = await new Promise<Blob>((resolve, reject) => {
      canvas.toBlob(
        (b) => (b ? resolve(b) : reject(new Error("pdf thumb encode failed"))),
        "image/jpeg",
        0.86
      )
    })
    return URL.createObjectURL(thumbBlob)
  } finally {
    await pdf.cleanup()
  }
}
