// tinymce-init.js

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,
        height: 300,                      // Editor height
        width: '100%',                    // Editor width
        menubar: true,                    // Show the menu bar
        branding: true,                   // Show "Powered by Tiny"
        promotion: false,                 // Hide promotion messages
        resize: true,                     // Allow resizing
        statusbar: true,                  // Show status bar
        inline: false,                    // Inline vs classic mode

        language: "es",
        directionality: "ltr",

        // **ADD THESE URL HANDLING OPTIONS**
        relative_urls: false,           // Don't convert URLs to relative
        remove_script_host: false,      // Keep the protocol and domain
        convert_urls: false,            // Don't convert URLs at all
        // **END OF URL HANDLING OPTIONS**

        paste_data_images: true,

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

        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: {
            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",

        automatic_uploads: true,

        images_upload_handler: handleTinyMCEImageUpload,

        // File picker for selecting images from URLs
        file_picker_types: 'image',

        // Optional: Restrict file types
        images_file_types: 'jpg,jpeg,png,gif,webp,bmp,svg',

        // Optional: Set max file size (in bytes) - 5MB example
        images_upload_max_filesize: 5 * 1024 * 1024,

        // Remove paste preprocessing that blocks images
        paste_preprocess: function (plugin, args) {
            // 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 file:// images (we'll handle them in PastePostProcess)
            args.content = args.content.replace(/<img[^>]+src=["']file:\/\/[^"']*["'][^>]*>/gi, '');
        },

        // Block all media/file elements entirely
        invalid_elements: '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 } img { max-width: 100%; height: auto; }",

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

            // Handle paste event to capture clipboard images
            setupTinyMCEPasteHandler(editor);

            // Limit typing based on maxlength
            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 input for maxlength
            editor.on('input', function () {
                var textarea = document.getElementById(editor.id);
                var maxLength = textarea.getAttribute("maxlength");

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

    // Ensure sync before any submit
    var formClientId = (typeof tinyMCEConfig !== 'undefined' && tinyMCEConfig.formClientId)
        ? tinyMCEConfig.formClientId
        : '<%= Page.Form.ClientID %>';
    var f = document.getElementById(formClientId);
    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-initialize TinyMCE after partial postbacks
if (window.Sys && Sys.WebForms && Sys.WebForms.PageRequestManager) {
    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function () {
        initTinyMCE();
    });
}
