import type { Options } from 'docx-preview';

type DocxPreviewMod = typeof import('docx-preview');

let modPromise: Promise<DocxPreviewMod> | null = null;

function loadDocxPreview(): Promise<DocxPreviewMod> {
  if (!modPromise) {
    modPromise = import('docx-preview');
  }
  return modPromise;
}

/**
 * Lazy-loads docx-preview in the browser. Top-level static imports of
 * docx-preview can fail in some Vite/SSR setups or when jszip interop breaks;
 * a dynamic import defers loading until preview/PDF export runs.
 */
export async function renderDocxAsync(
  data: Blob | ArrayBuffer,
  bodyContainer: HTMLElement,
  styleContainer: HTMLElement | undefined,
  userOptions?: Partial<Options>,
): Promise<unknown> {
  const mod = await loadDocxPreview();
  const buf = data instanceof Blob ? await data.arrayBuffer() : data;
  return mod.renderAsync(buf, bodyContainer, styleContainer, userOptions);
}
