// tinymce-paste-handler.js
function setupTinyMCEPasteHandler(editor) {
    // Handle paste event to capture clipboard images
    editor.on('paste', function (e) {
        var clipboardData = e.clipboardData || window.clipboardData;

        if (!clipboardData) {
            return;
        }

        // Check for image files in clipboard
        var items = clipboardData.items;
        if (items) {
            for (var i = 0; i < items.length; i++) {
                var item = items[i];

                // If it's an image
                if (item.type.indexOf('image') !== -1) {

                    // Prevent default paste
                    e.preventDefault();

                    // Get the image as a file/blob
                    var blob = item.getAsFile();

                    if (blob) {

                        // Save the current cursor position/selection
                        var bookmark = editor.selection.getBookmark(2, true);

                        // Create a unique ID for the placeholder
                        var placeholderId = 'img-placeholder-' + Date.now();

                        // Insert placeholder at current cursor position
                        editor.selection.setContent(
                            '<span id="' + placeholderId + '" style="color: #999; background: #f0f0f0; padding: 2px 8px; border-radius: 3px; display: inline-block;">⏳ Subiendo imagen...</span>'
                        );

                        // Create a BlobInfo-like object for the upload handler
                        var fileName = blob.name || 'clipboard-image-' + Date.now() + '.png';
                        var blobInfo = {
                            id: function () { return 'clipboard_' + Date.now(); },
                            name: function () { return fileName; },
                            filename: function () { return fileName; },
                            blob: function () { return blob; },
                            base64: function () {
                                return new Promise(function (resolve) {
                                    var reader = new FileReader();
                                    reader.onloadend = function () {
                                        resolve(reader.result.split(',')[1]);
                                    };
                                    reader.readAsDataURL(blob);
                                });
                            },
                            blobUri: function () { return URL.createObjectURL(blob); },
                            uri: function () { return URL.createObjectURL(blob); }
                        };

                        // Upload the image
                        handleTinyMCEImageUpload(
                            blobInfo,
                            function (url) {
                                // Find the placeholder element
                                var placeholder = editor.dom.get(placeholderId);

                                if (placeholder) {
                                    // Create the image element
                                    var img = editor.dom.create('img', {
                                        src: url,
                                        alt: 'Pasted image',
                                        style: 'max-width: 100%; height: auto;'
                                    });

                                    // Replace placeholder with image
                                    editor.dom.replace(img, placeholder);

                                    // Trigger change event
                                    editor.fire('change');
                                } else {
                                    // Fallback: if placeholder not found, restore bookmark and insert
                                    editor.selection.moveToBookmark(bookmark);
                                    editor.selection.setContent('<img src="' + url + '" alt="Pasted image" style="max-width: 100%; height: auto;" />');
                                }
                            },
                            function (error) {
                                // Failure: Replace placeholder with error message

                                var placeholder = editor.dom.get(placeholderId);

                                if (placeholder) {
                                    var errorSpan = editor.dom.create('span', {
                                        style: 'color: #d9534f; background: #f2dede; padding: 2px 8px; border-radius: 3px; display: inline-block;'
                                    }, '❌ Error: ' + error);

                                    editor.dom.replace(errorSpan, placeholder);
                                } else {
                                    // Fallback
                                    editor.selection.moveToBookmark(bookmark);
                                    editor.selection.setContent('<span style="color: #d9534f;">❌ Error al subir imagen: ' + error + '</span>');
                                }
                            },
                            function (percent) {
                                // Progress callback
                                var placeholder = editor.dom.get(placeholderId);
                                if (placeholder && percent < 100) {
                                    placeholder.innerHTML = '⏳ Subiendo... ' + Math.round(percent) + '%';
                                }
                            }
                        );
                    }

                    return false; // Stop further processing
                }
            }
        }
    });

    // Handle post-paste to catch file:// images that slipped through
    editor.on('PastePostProcess', function (e) {
        var images = e.node.getElementsByTagName('img');

        for (var i = 0; i < images.length; i++) {
            var img = images[i];
            var src = img.getAttribute('src');

            if (src && src.indexOf('file://') === 0) {
                // Replace with a placeholder
                img.setAttribute('src', 'data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" width="200" height="100"%3E%3Crect fill="%23ddd" width="200" height="100"/%3E%3Ctext x="50%25" y="50%25" text-anchor="middle" dy=".3em" fill="%23999"%3ENo se puede cargar imagen local%3C/text%3E%3C/svg%3E');
                img.setAttribute('alt', 'Imagen local no accesible');
                img.setAttribute('title', 'Por favor, usa el botón de imagen');
            }
        }
    });
}