import { sanitizeRichTextHtml } from '@/lib/customFormHtmlSanitizer';

const DOCX_MIME_TYPE = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';

function ensureEditorFriendlyBlocks(html = '') {
  if (!html) return '';

  const parser = new DOMParser();
  const doc = parser.parseFromString(html, 'text/html');
  const blockSelector = 'p, li, td, th, h1, h2, h3, h4, h5, h6, blockquote, pre';

  doc.body.querySelectorAll(blockSelector).forEach((element) => {
    if (!element.textContent?.trim() && !element.querySelector('img, br, table, ul, ol')) {
      element.innerHTML = '<br>';
    }
  });

  return doc.body.innerHTML.trim();
}

export function isDocxFile(file) {
  if (!file) return false;

  const name = file.name?.toLowerCase() || '';
  return file.type === DOCX_MIME_TYPE || name.endsWith('.docx');
}

export async function convertDocxFileToHtml(file) {
  if (!isDocxFile(file)) {
    throw new Error('Please choose a .docx file.');
  }

  const mammothModule = await import('mammoth/mammoth.browser');
  const mammoth = mammothModule.default || mammothModule;
  const arrayBuffer = await file.arrayBuffer();

  const result = await mammoth.convertToHtml(
    { arrayBuffer },
    {
      ignoreEmptyParagraphs: false,
      includeDefaultStyleMap: true,
      styleMap: [
        "p[style-name='Title'] => h1:fresh",
        "p[style-name='Subtitle'] => h2:fresh",
        "p[style-name='Heading 1'] => h1:fresh",
        "p[style-name='Heading 2'] => h2:fresh",
        "p[style-name='Heading 3'] => h3:fresh",
        "p[style-name='Heading 4'] => h4:fresh",
      ],
    },
  );

  const sanitizedHtml = sanitizeRichTextHtml(result.value || '');
  const normalizedHtml = ensureEditorFriendlyBlocks(sanitizedHtml);

  return {
    html: normalizedHtml || '<p><br></p>',
    messages: result.messages || [],
  };
}
