/**
 * JavaScript equivalent of WordPress wpautop().
 * Converts raw WP post_content lines into proper HTML tags.
 * Groups consecutive plain text lines into <p> paragraphs,
 * while keeping block-level tags (headings, tables, lists, images) completely intact.
 */
export function wpautop(content: string): string {
    if (!content || !content.trim()) return content;

    // Normalize line endings to \n
    let pee = content.replace(/\r\n/g, "\n").replace(/\r/g, "\n");

    // Split into individual lines
    const lines = pee.split("\n");

    const result: string[] = [];
    let currentParagraph: string[] = [];

    // Check if a line starts with an opening block-level tag or self-closing block tag
    const isBlockTag = (line: string): boolean => {
        return /^\s*<(?:table|thead|tbody|tr|td|th|ul|ol|li|div|blockquote|h[1-6]|p|figure|img|hr|section|article|aside|header|footer|nav)/i.test(line);
    };

    // Check if a line starts with a closing block-level tag
    const isBlockEndTag = (line: string): boolean => {
        return /^\s*<\/(?:table|thead|tbody|tr|td|th|ul|ol|li|div|blockquote|h[1-6]|p|figure|img|hr|section|article|aside|header|footer|nav)/i.test(line);
    };

    // Helper to wrap accumulated text lines in a <p> tag
    const flushParagraph = () => {
        if (currentParagraph.length > 0) {
            const text = currentParagraph.join("\n").trim();
            if (text) {
                result.push(`<p>${text.replace(/\n/g, "<br />\n")}</p>`);
            }
            currentParagraph = [];
        }
    };

    for (let line of lines) {
        const trimmed = line.trim();

        if (trimmed === "") {
            // Empty line indicates paragraph break
            flushParagraph();
        } else if (isBlockTag(trimmed) || isBlockEndTag(trimmed)) {
            // Block tag: flush any active paragraph first, then push the tag as-is
            flushParagraph();
            result.push(line);
        } else {
            // Text line: accumulate
            currentParagraph.push(line);
        }
    }

    // Flush any remaining text at the end
    flushParagraph();

    return result.filter(Boolean).join("\n");
}
