/**
 * Formats status update text bodies for professional display.
 * Handles line breaks, trimming, and empty states.
 * 
 * @param {string} text - The raw text content
 * @param {number} [maxLength=0] - Optional max length for truncation (0 = no truncation)
 * @returns {string|null} - Formatted HTML string or null
 */
export const formatStatusUpdateText = (text, maxLength = 0) => {
  if (!text || typeof text !== 'string' || !text.trim()) {
    return null;
  }

  let content = text.trim();

  // Handle truncation if requested
  if (maxLength > 0 && content.length > maxLength) {
    content = content.substring(0, maxLength).trim() + '...';
  }

  // Split by newlines and filter empty lines to avoid excessive spacing
  const lines = content.split(/\r\n|\r|\n/).filter(line => line.trim() !== '');

  if (lines.length === 0) return null;

  // Create HTML string instead of JSX
  const lineElements = lines.map((line, index) => `<p key="${index}" class="min-h-[1.2em]">${escapeHtml(line)}</p>`).join('');
  
  return `<div class="text-sm text-slate-600 space-y-1 mt-2 p-3 bg-slate-50 rounded-md border border-slate-100 font-normal leading-relaxed">${lineElements}</div>`;
};

/**
 * Helper to simply clean text for PDF or raw string usage
 */
export const cleanReportText = (text) => {
  if (!text) return '';
  return text.replace(/<[^>]*>/g, '').trim();
};

/**
 * Escapes HTML special characters to prevent injection
 */
const escapeHtml = (text) => {
  const map = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#039;'
  };
  return text.replace(/[&<>"']/g, char => map[char]);
};
