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", "image", "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 image 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: 'image 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",

        // File/image upload
        //images_upload_url: "/upload",
        automatic_uploads: false,
        file_picker_types: "image",
        file_picker_callback: function (callback, value, meta) {
            let input = document.createElement("input");
            input.setAttribute("type", "file");
            input.onchange = function () {
                let file = this.files[0];
                let reader = new FileReader();
                reader.onload = function () {
                    callback(reader.result, { alt: file.name });
                };
                reader.readAsDataURL(file);
            };
            input.click();
        },

        // 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);
                }
            });
        }
    });

    // 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();
    });
}
