import { renderDocxAsync } from '@/lib/docxPreviewClient';
import { injectDocxJustifyMitigationStyles } from '@/lib/docxJustifyMitigationCss';
import { injectDocxTableReflowStyles } from '@/lib/docxTableReflow';
import html2pdf from 'html2pdf.js';
import type { FillProgressEvent } from './templateTypes';

/**
 * Renders a filled DOCX off-screen and rasterizes to PDF via html2pdf.js.
 * Quality depends on browser; suitable for preview/print-style export.
 */
export async function docxBlobToPdfBlob(
  docx: Blob,
  options?: { onProgress?: (e: FillProgressEvent) => void },
): Promise<Blob> {
  const container = document.createElement('div');
  container.dataset.docxCaptureRoot = '1';
  container.style.position = 'fixed';
  container.style.left = '-12000px';
  container.style.top = '0';
  container.style.width = '210mm';
  container.style.background = '#fff';
  document.body.appendChild(container);

  options?.onProgress?.({ phase: 'converting-to-pdf' });

  try {
    await renderDocxAsync(docx, container, undefined, {
      inWrapper: true,
      breakPages: true,
      experimental: true,
    });

    injectDocxTableReflowStyles(container);
    injectDocxJustifyMitigationStyles(container);

    const pdfBlob = (await html2pdf()
      .set({
        margin: [10, 10, 10, 10],
        filename: 'export.pdf',
        image: { type: 'jpeg', quality: 0.92 },
        html2canvas: { scale: 2, useCORS: true },
        jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' },
        pagebreak: { mode: ['css', 'legacy'] },
      })
      .from(container)
      .outputPdf('blob')) as Blob;
    return pdfBlob;
  } finally {
    document.body.removeChild(container);
  }
}
