/**
 * Decode HTML entities from string
 * Converts &lt; to <, &gt; to >, &amp; to &, etc.
 */
export function decodeHtmlEntities(text: string | null | undefined): string {
  if (!text || typeof text !== "string") return "";

  const entities: { [key: string]: string } = {
    "&lt;": "<",
    "&gt;": ">",
    "&amp;": "&",
    "&quot;": '"',
    "&#039;": "'",
    "&nbsp;": " ",
  };

  let decoded = text;
  for (const [entity, char] of Object.entries(entities)) {
    decoded = decoded.replace(new RegExp(entity, "g"), char);
  }
  return decoded;
}

/**
 * Strip HTML tags from string, keeping only text content
 */
export function stripHtmlTags(html: string | null | undefined): string {
  if (!html || typeof html !== "string") return "";

  // First decode HTML entities
  let text = html;
  
  // Handle encoded HTML entities
  const entityMap: { [key: string]: string } = {
    "&lt;": "<",
    "&gt;": ">",
    "&amp;": "&",
    "&quot;": '"',
    "&#039;": "'",
    "&nbsp;": " ",
  };

  for (const [entity, char] of Object.entries(entityMap)) {
    text = text.replace(new RegExp(entity, "g"), char);
  }

  // Remove all HTML tags including <p>, </p>, <br>, etc.
  text = text.replace(/<[^>]*>/g, "");
  
  // Clean up extra spaces
  text = text.replace(/\s+/g, " ").trim();
  
  return text;
}

/**
 * Clean HTML content - strips tags and decodes entities
 */
export function cleanHtmlContent(html: string | null | undefined): string {
  return stripHtmlTags(html).trim();
}

/**
 * Parse HTML content into paragraphs
 */
export function parseHtmlParagraphs(html: string | null | undefined): string[] {
  if (!html || typeof html !== "string") return [];

  // First decode entities
  let text = decodeHtmlEntities(html);

  // Extract text from <p> tags
  const paragraphs = text.match(/<p[^>]*>([^<]*)<\/p>/gi) || [];

  if (paragraphs.length > 0) {
    return paragraphs
      .map((p) => stripHtmlTags(p))
      .filter((p) => p.trim())
      .map((p) => p.trim());
  }

  // If no paragraphs, split by <br> tags
  const parts = text.split(/<br\s*\/?>/i);
  
  if (parts.length > 1) {
    return parts
      .map((part) => stripHtmlTags(part).trim())
      .filter((part) => part);
  }

  // Fallback: return the whole cleaned text
  const cleaned = stripHtmlTags(text).trim();
  return cleaned ? [cleaned] : [];
}
