import * as pdfjsLib from 'pdfjs-dist/build/pdf';
import pdfjsWorker from 'pdfjs-dist/build/pdf.worker.min.js?url';

pdfjsLib.GlobalWorkerOptions.workerSrc = pdfjsWorker;

export async function renderExamPdfPages(container: HTMLElement, bytes: Uint8Array) {
  container.innerHTML = '';
  const pdf = await pdfjsLib.getDocument({ data: bytes }).promise;
  const pad = 16;
  const width = container.clientWidth || container.parentElement?.clientWidth || 900;
  const maxWidth = Math.max(360, width - pad * 2);

  for (let pageNum = 1; pageNum <= pdf.numPages; pageNum += 1) {
    const page = await pdf.getPage(pageNum);
    const base = page.getViewport({ scale: 1 });
    const scale = Math.min(1.6, maxWidth / base.width);
    const viewport = page.getViewport({ scale });

    const wrap = document.createElement('div');
    wrap.className = 'exam-pdf-page-wrap';
    const canvas = document.createElement('canvas');
    canvas.className = 'exam-pdf-page';
    canvas.width = viewport.width;
    canvas.height = viewport.height;
    wrap.appendChild(canvas);
    container.appendChild(wrap);

    await page.render({
      canvasContext: canvas.getContext('2d')!,
      viewport,
    }).promise;
  }
}
