/** Marker on injected `<style>` so rules are not duplicated per container. */
export const DOCX_JUSTIFY_MITIGATION_ATTR = 'data-docx-justify-mitigation';

/**
 * docx-preview maps OOXML justified paragraphs to CSS `text-align: justify`. Browsers can
 * then stretch inter-word gaps widely on short lines. Mitigate in HTML/CSS (browser PDF
 * capture) while server-side OOXML normalization (`relax_justified_softbreak_paragraphs_in_docx`)
 * fixes Word/LibreOffice output.
 */
export function injectDocxJustifyMitigationStyles(scope: HTMLElement): void {
  if (scope.querySelector(`style[${DOCX_JUSTIFY_MITIGATION_ATTR}="1"]`)) return;
  const style = document.createElement('style');
  style.setAttribute(DOCX_JUSTIFY_MITIGATION_ATTR, '1');
  style.textContent = `
    [data-docx-capture-root] .docx-wrapper p[style*="text-align: justify"],
    [data-docx-capture-root] .docx-wrapper p[style*="text-align:justify"],
    [data-docx-capture-root] .docx-wrapper p[style*="text-align: distribute"],
    [data-docx-capture-root] .docx-wrapper p[style*="text-align:distribute"],
    [data-docx-capture-root] .docx-wrapper li[style*="text-align: justify"],
    [data-docx-capture-root] .docx-wrapper li[style*="text-align:justify"],
    [data-docx-capture-root] .docx-wrapper td[style*="text-align: justify"],
    [data-docx-capture-root] .docx-wrapper td[style*="text-align:justify"],
    [data-app-form-docx-preview] .docx-wrapper p[style*="text-align: justify"],
    [data-app-form-docx-preview] .docx-wrapper p[style*="text-align:justify"],
    [data-app-form-docx-preview] .docx-wrapper p[style*="text-align: distribute"],
    [data-app-form-docx-preview] .docx-wrapper p[style*="text-align:distribute"],
    [data-app-form-docx-preview] .docx-wrapper li[style*="text-align: justify"],
    [data-app-form-docx-preview] .docx-wrapper li[style*="text-align:justify"],
    [data-app-form-docx-preview] .docx-wrapper td[style*="text-align: justify"],
    [data-app-form-docx-preview] .docx-wrapper td[style*="text-align:justify"] {
      text-align: justify !important;
      text-align-last: start !important;
      text-justify: inter-word !important;
      text-wrap: pretty !important;
      hyphens: auto !important;
      -webkit-hyphens: auto !important;
      overflow-wrap: break-word !important;
      word-break: normal !important;
    }
  `;
  scope.appendChild(style);
}
