/* global wp */

// escape regex special chars
function cleanContent(html) {
    let cleaned = html
        // 1. remove highlight spans
        .replace(
            /<span[^>]*class="[^"]*(wg-span)[^"]*"[^>]*>(.*?)<\/span>/gi,
            "$2"
        )

        .replace(/<span[^>]*style=["'][^"']*text-wrap-mode\s*:\s*nowrap[^"']*["'][^>]*>(.*?)<\/span>/gi, "$1")

        // 2. unescape <img ...>
        .replace(/&lt;img([^&]*)&gt;/gi, (match) => {
            return match.replace(/&lt;/g, "<").replace(/&gt;/g, ">");
        })
        // 3. remove empty block elements
        .replace(/<\/?(div|section|article|header|footer)[^>]*>/gi, '')
        // 4. remove empty cite tags
        .replace(/<cite>\s*<\/cite>/gi, '')
        .trim();

    // 5. Fix malformed blockquotes (add content if empty)
    cleaned = cleaned.replace(
        /<blockquote[^>]*>\s*<\/blockquote>\s*<p>(.*?)<\/p>/gi,
        '<blockquote class="wp-block-quote"><p>$1</p></blockquote>'
    );

    // 6. Normalize <p> tags
    // cleaned = cleaned
    //     .replace(/^<\/p>/i, '')
    //     .replace(/<p>\s*$/i, '')
    //     .replace(/(<\/p>\s*){2,}/gi, '</p>')
    //     .trim();

    return cleaned;
}

// Insert in editor of Wpress
function handleSave(newContent) {
    // Clean and sanitize the content
    let cleanedContent = cleanContent(newContent);
    // Prevent inserting empty or invalid content
    if (!cleanedContent || cleanedContent === "<br>") {
        console.warn("Skipping save: content is empty or just a <br>");
        return;
    }

    // TinyMCE path
    if (window.tinymce && window.tinymce.activeEditor) {
        window.tinymce.activeEditor.setContent(cleanedContent);
        return;
    }
    if (typeof wp !== "undefined" && wp.data) {
        // WordPress block editor path
        guttenbergSync(cleanedContent);
    }
};

// Gutenberg sync
function guttenbergSync(cleanedContent) {

    const { select, dispatch } = wp.data;
    const blocks = select("core/block-editor").getBlocks();

    const convertedBlocks = wp.blocks.rawHandler({ HTML: cleanedContent });

    if (convertedBlocks && convertedBlocks.length > 0) {
        // Replace all blocks at once
        dispatch("core/block-editor").replaceBlocks(
            blocks.map(block => block.clientId),
            convertedBlocks
        );
    }

}

export default handleSave;