/**
 * Decodes HTML entities in a string (e.g., &amp; -> &, &nbsp; -> ' ')
 * Uses a browser-native approach safe for the React environment.
 * Handles named entities, hex entities, and decimal entities.
 * @param {string} html 
 * @returns {string}
 */
export const decodeHtml = (html) => {
    if (!html) return "";
    try {
        const txt = document.createElement("textarea");
        txt.innerHTML = html;
        return txt.value;
    } catch (e) {
        console.warn("HTML decoding failed", e);
        return html;
    }
};

/**
 * Strips HTML tags from a string, converting common block elements to newlines
 * to preserve document structure (e.g., <p> and <br> become line breaks).
 * @param {string} html 
 * @returns {string}
 */
export const stripHtml = (html) => {
    if (!html) return "";

    // Convert block tags to newlines
    let text = html.replace(/<br\s*\/?>/gi, "\n");
    text = text.replace(/<\/p>/gi, "\n");
    text = text.replace(/<\/div>/gi, "\n");
    text = text.replace(/<\/li>/gi, "\n");
    text = text.replace(/<\/tr>/gi, "\n"); 
    text = text.replace(/<\/h[1-6]>/gi, "\n");
    
    // Remove all other HTML tags
    text = text.replace(/<[^>]+>/g, "");

    return text;
};

/**
 * Normalizes whitespace:
 * - Replaces non-breaking spaces with regular spaces
 * - Removes zero-width characters (which can cause PDF rendering glitches)
 * - Trims excessive whitespace from ends of lines
 * - Collapses runs of spaces/tabs into single spaces within lines
 * @param {string} text 
 * @returns {string}
 */
export const normalizeWhitespace = (text) => {
    if (!text) return "";
    
    // Replace non-breaking spaces with normal spaces
    let result = text.replace(/\u00A0/g, " ");
    result = result.replace(/&nbsp;/g, " ");
    
    // Remove zero-width characters
    result = result.replace(/[\u200B-\u200D\uFEFF]/g, "");

    // Normalize whitespace on each line (collapse multiple spaces to one, trim ends)
    result = result
        .split("\n")
        .map((line) => line.replace(/[ \t]+/g, " ").trimEnd())
        .join("\n");

    return result;
};

/**
 * Main utility to clean text for PDF generation.
 * Combines stripping HTML, decoding entities, and normalizing whitespace.
 * Ensures strict output consistency for PDF text content.
 * @param {string} content 
 * @returns {string}
 */
export const cleanText = (content) => {
    if (!content) return "";
    if (typeof content !== 'string') return String(content);
    
    // 1. Strip HTML tags (converts blocks to newlines)
    let text = stripHtml(content);
    
    // 2. Decode Entities (converts &amp; to &, etc)
    text = decodeHtml(text);
    
    // 3. Normalize Whitespace (clean up spaces and invisible chars)
    text = normalizeWhitespace(text);
    
    // 4. Collapse excessive blank lines (more than 2 newlines becomes 2)
    // This preserves paragraph separation but removes huge gaps
    text = text.replace(/\n{3,}/g, "\n\n");
    
    return text.trim();
};