export type DocxTableReflowOptions = {
  /**
   * Wrapper + paginated section rules from `docx-to-pdf-demo.html` (transparent wrapper, page shadows).
   * Use for PDF capture / DocxToPdfViewer only — not for inline form previews.
   */
  pdfPreviewChrome?: boolean;
};

const REFLOW_STYLE_MARKER = 'data-docx-reflow-injected';

/**
 * docx-preview maps Word `w:trHeight` to CSS `height` even when Word uses `hRule="atLeast"`,
 * which should allow rows to grow. Fixed `height` makes wrapped cell text paint over the next row.
 * These overrides force auto row height for raster capture and on-screen preview.
 *
 * Rules are scoped with `data-docx-reflow-root` on `scope` so they do not leak to other docx-previews.
 *
 * @see https://github.com/VolodymyrBaydalka/docxjs (parseTrHeight uses height for atLeast too)
 */
export function injectDocxTableReflowStyles(
  scope: HTMLElement,
  options: DocxTableReflowOptions = {},
): void {
  scope.dataset.docxReflowRoot = '1';
  if (scope.querySelector(`style[${REFLOW_STYLE_MARKER}]`)) return;

  const root = '[data-docx-reflow-root]';
  const { pdfPreviewChrome = false } = options;

  const chrome = pdfPreviewChrome
    ? `
    ${root} .docx-wrapper {
      background: transparent !important;
      padding: 0 !important;
    }
    ${root} section.docx {
      margin: 0 auto 24px !important;
      box-shadow:
        0 1px 2px rgba(0, 0, 0, 0.06),
        0 8px 24px rgba(0, 0, 0, 0.08);
    }
    ${root} section.docx:last-child {
      margin-bottom: 0 !important;
    }
  `
    : '';

  const style = document.createElement('style');
  style.setAttribute(REFLOW_STYLE_MARKER, '');
  style.textContent =
    chrome +
    `
    ${root} .docx-wrapper table tr {
      height: auto !important;
      max-height: none !important;
    }
    ${root} .docx-wrapper table td,
    ${root} .docx-wrapper table th {
      height: auto !important;
      max-height: none !important;
      min-height: 0 !important;
      /* Prevent long unbroken tokens from overflowing/overpainting neighboring content. */
      overflow-wrap: anywhere !important;
      word-break: break-word !important;
    }
  `;
  scope.insertBefore(style, scope.firstChild);
}
