function initTinyMCE() {
    var selector = 'textarea.texto-enriquecido';

    // Remove any prior instance (useful if this control is re-rendered)
    tinymce.remove(); // clear existing editors to avoid duplicates

    tinymce.init({
        selector: selector,
        branding: true,
        height: 300,                      // Editor height
        width: '100%',                    // Editor width
        menubar: true,                    // Show the menu bar
        branding: false,                  // Hide "Powered by Tiny"
        promotion: false,                 // Hide promotion messages
        resize: true,                     // Allow resizing
        statusbar: true,                  // Show status bar
        //skin: "oxide-dark",               // Theme skin
        //content_css: "dark",              // Content theme
        inline: false,                    // Inline vs classic mode

        // Language & direction
        language: "en",
        directionality: "ltr",

        // Plugins
        plugins: [
            "advlist", "autolink", "lists", "link", "charmap", "preview",
            "anchor", "searchreplace", "visualblocks", "code", "fullscreen",
            "insertdatetime", "table", "help", "wordcount", "emoticons",
            "autosave"
        ],

        // Toolbar buttons
        toolbar: [
            "undo redo bold italic underline strikethrough forecolor backcolor fontfamily fontsize blocks",
            "alignleft aligncenter alignright alignjustify bullist numlist outdent indent emoticons charmap removeformat code link table | fullscreen preview help"
        ],

        // Menu items
        menu: {
            file: { title: 'File', items: 'newdocument restoredraft | preview | print ' },
            edit: { title: 'Edit', items: 'undo redo | cut copy paste | selectall | searchreplace' },
            view: { title: 'View', items: 'code visualaid visualchars visualblocks | spellchecker | fullscreen' },
            insert: { title: 'Insert', items: 'link template codesample inserttable | charmap emoticons hr' },
            format: { title: 'Format', items: 'bold italic underline strikethrough superscript subscript codeformat | styles blocks fontfamily fontsize align lineheight | forecolor backcolor removeformat' },
            tools: { title: 'Tools', items: 'spellchecker wordcount' },
            table: { title: 'Table', items: 'inserttable | cell row column | tableprops deletetable' },
            help: { title: 'Help', items: 'help' }
        },

        // Autosave
        autosave_interval: "30s",
        autosave_prefix: "tinymce-autosave-{path}{query}-{id}-",
        autosave_restore_when_empty: true,
        autosave_retention: "20m",

        // Disable image upload completely
        automatic_uploads: false,

        // **PREVENT ANY FILES/MEDIA FROM BEING PASTED**
        paste_preprocess: function (plugin, args) {
            // Remove all img tags
            args.content = args.content.replace(/<img[^>]*>/gi, '');
            // Remove video tags
            args.content = args.content.replace(/<video[^>]*>.*?<\/video>/gi, '');
            // Remove audio tags
            args.content = args.content.replace(/<audio[^>]*>.*?<\/audio>/gi, '');
            // Remove iframe tags
            args.content = args.content.replace(/<iframe[^>]*>.*?<\/iframe>/gi, '');
            // Remove embed tags
            args.content = args.content.replace(/<embed[^>]*>/gi, '');
            // Remove object tags
            args.content = args.content.replace(/<object[^>]*>.*?<\/object>/gi, '');
            // Remove source tags
            args.content = args.content.replace(/<source[^>]*>/gi, '');
            // Remove base64 data (images, videos, etc)
            args.content = args.content.replace(/data:[^;]+;base64[^"'\s]*/gi, '');
        },

        // Block all media/file elements entirely
        invalid_elements: 'img,video,audio,iframe,embed,object,source',

        // Style formats
        style_formats: [
            { title: "Bold text", inline: "b" },
            { title: "Red text", inline: "span", styles: { color: "#ff0000" } },
            { title: "Red header", block: "h1", styles: { color: "#ff0000" } },
            { title: "Table styles" },
            { title: "Table row 1", selector: "tr", classes: "tablerow1" }
        ],

        // Font & sizes
        font_size_formats: "8pt 10pt 12pt 14pt 18pt 24pt 36pt",
        font_family_formats: "Arial=arial,helvetica,sans-serif; Courier New=courier new,courier,monospace; Times New Roman=times new roman,times; Verdana=verdana,geneva",

        // Custom content CSS
        content_style: "body { font-family:Helvetica,Arial,sans-serif; font-size:14px }",

        // Maxlength enforcement added here
        setup: function (editor) {
            // Sync content back to <textarea>
            editor.on('change keyup paste', function () {
                tinymce.triggerSave();
            });

            // Limit typing based on maxlength (plain text only)
            editor.on('keydown', function (e) {
                var textarea = document.getElementById(editor.id);
                var maxLength = textarea.getAttribute("maxlength");

                if (maxLength) {
                    var content = editor.getContent({ format: 'text' });
                    var length = content.length;

                    var allowedKeys = [8, 46, 37, 38, 39, 40, 67, 86]; // backspace, delete, arrows, copy, paste

                    if (length >= maxLength && !allowedKeys.includes(e.keyCode)) {
                        e.preventDefault();
                        e.stopPropagation();
                    }
                }
            });

            // Handle pasted content
            editor.on('paste', function () {
                var textarea = document.getElementById(editor.id);
                var maxLength = textarea.getAttribute("maxlength");

                if (maxLength) {
                    setTimeout(function () {
                        var content = editor.getContent({ format: 'text' });
                        if (content.length > maxLength) {
                            var trimmed = content.substring(0, maxLength);
                            editor.setContent(trimmed);
                        }
                    }, 0);
                }
            });

            // Additional safeguard: Remove any img tags that somehow get inserted
            editor.on('NodeChange', function () {
                var images = editor.dom.select('img');
                if (images.length > 0) {
                    images.forEach(function (img) {
                        editor.dom.remove(img);
                    });
                }
            });
        }
    });

    // Ensure sync before any submit (covers buttons outside this control)
    var f = document.getElementById('<%= Page.Form.ClientID %>');
    if (f && !f.__tinymceSyncAttached) {
        f.addEventListener('submit', function () {
            if (window.tinymce) tinymce.triggerSave();
        });
        f.__tinymceSyncAttached = true;
    }
}

// Run it when page loads
document.addEventListener("DOMContentLoaded", initTinyMCE);

// Re-inicializar TinyMCE después de cada postback parcial
if (window.Sys && Sys.WebForms && Sys.WebForms.PageRequestManager) {
    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function () {
        initTinyMCE();
    });
}
