;(function($) {
    "use strict";
    
    // Define a unique identifier prefix for our clipboard data
    const HTMEGA_CLIPBOARD_PREFIX = 'htmega_elementor_data:';

   // Detect Firefox browser
   const isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;

    function getTimestamp() {
        return new Date().getTime();
    }
    
    function generateOperationId() {
        return 'htmega_' + getTimestamp() + '_' + Math.random().toString(36).substr(2, 9);
    }

    function getUniqueId(elements) {
        if (!elements || !Array.isArray(elements)) return elements;
        
        elements.forEach(function(item) {
            if (!item) return;
            // Generate a new ID for the element
            item.id = elementorCommon.helpers.getUniqueId();
            // Process child elements recursively if they exist
            if (item.elements && Array.isArray(item.elements) && item.elements.length > 0) {
                getUniqueId(item.elements);
            }
        });
        return elements;
    }

    function importContent(newWidget, elementCode, container) {
        
        // Create a deep copy to avoid modification issues
        const elementCodeCopy = JSON.parse(JSON.stringify(elementCode));
        
        // Check for media elements
        var hasMedia = /\.(png|jpg|jpeg|svg|gif|webp|tiff|psd|raw|bmp|heif)/gi.test(JSON.stringify(elementCodeCopy));

        if (hasMedia) {
            
            var model = { 
                elType: newWidget.elType,
                settings: elementCodeCopy.settings
            };
            
            if (newWidget.widgetType) {
                model.widgetType = newWidget.widgetType;
            }

            try {
                var widgetSelector = $e.run('document/elements/create', {
                    container: container,
                    model: model
                });

                $.ajax({
                    url: htmegacrosscp.ajaxurl,
                    method: 'POST',
                    data: {
                        action: 'htmega_copy_paste_data',
                        data: JSON.stringify(elementCodeCopy),
                        security: htmegacrosscp.nonce,
                    },
                    beforeSend: function() {
                        widgetSelector.view.$el.append('<div id="htmega-import-process" style="text-align:center;">Importing images..</div>');
                    }
                }).done(function(response) {
                    if (response.success && response.data && response.data[0]) {
                        var data = response.data[0];                        
                        var finalModel = {
                            elType: data.elType,
                            settings: data.settings
                        };
                        
                        if ('widget' === data.elType) {
                            finalModel.widgetType = data.widgetType;
                        } else if (data.elements) {
                            finalModel.elements = data.elements;
                        }
                        
                        // Delete the temporary element and create the real one
                        setTimeout(function() {
                            try {
                                $e.run('document/elements/delete', { 
                                    container: widgetSelector 
                                });
                                
                                $e.run('document/elements/create', {
                                    model: finalModel,
                                    container: container
                                });
                                
                            } catch (err) {
                                console.error('Error creating final element:', err);
                            }
                            
                            $('#htmega-import-process').remove();
                        }, 500);
                    } else {
                        console.error('Invalid response data', response);
                        $('#htmega-import-process').text('Import failed: Invalid data');
                    }
                }).fail(function(error) {
                    console.error('AJAX import failed:', error);
                    $('#htmega-import-process').text('Import failed');
                    elementor.notifications.showToast({
                        message: 'Import failed: Network error'
                    });
                });
            } catch (err) {
                console.error('Error creating temporary element:', err);
                elementor.notifications.showToast({
                    message: 'Import failed: ' + err.message
                });
            }
        } else {
            
            try {
                // For direct import, make sure we have all required properties
                var finalModel = {
                    elType: newWidget.elType,
                    settings: elementCodeCopy.settings || {}
                };
                
                // Add elements if exists
                if (newWidget.elements) {
                    finalModel.elements = newWidget.elements;
                }
                
                // Add widgetType for widgets
                if (newWidget.elType === 'widget' && newWidget.widgetType) {
                    finalModel.widgetType = newWidget.widgetType;
                }
                
                $e.run("document/elements/create", {
                    model: finalModel,
                    container: container
                });
                
            } catch (err) {
                console.error('Direct import error:', err);
                elementor.notifications.showToast({
                    message: 'Import failed: ' + err.message
                });
            }
        }
    }

    function processImport(newElement, element) {
        try {
            
            // Get target element type
            var getElementType = element.model.get("elType");
            
            // Normalize the data structure
            var elementType, elementCode;
            
            if (typeof newElement.elementCode === 'object') {
                elementType = newElement.elementCode.elType;
                elementCode = newElement.elementCode;
            } else {
                elementType = newElement.elType;
                elementCode = newElement;
            }
            
            // Create the new widget structure
            var newWidget = {
                elType: elementType,
                settings: elementCode.settings || {}
            };
            
            // Add widget type for widgets
            if (elementType === 'widget' && newElement.elementType) {
                newWidget.widgetType = newElement.elementType;
            }
            
            // Add elements array for containers, sections, columns
            if (elementCode.elements && ['container', 'section', 'column'].includes(elementType)) {
                newWidget.elements = getUniqueId(elementCode.elements);
            }
            
            // Determine the container to insert into
            var container;
            
            switch (elementType) {
                case 'container':
                    container = elementor.getPreviewContainer();
                    break;
                    
                case 'section':
                    container = elementor.getPreviewContainer();
                    break;
                    
                case 'column':
                    switch (getElementType) {
                        case 'widget':
                            container = element.getContainer().parent.parent;
                            break;
                        case 'column':
                            container = element.getContainer().parent;
                            break;
                        case 'section':
                            container = element.getContainer();
                            break;
                        default:
                            container = elementor.getPreviewContainer();
                    }
                    break;
                    
                case 'widget':
                    switch (getElementType) {
                        case 'widget':
                            container = element.getContainer().parent;
                            break;
                        case 'column':
                            container = element.getContainer();
                            break;
                        case 'section':
                            if (element.children && element.children.findByIndex(0)) {
                                container = element.children.findByIndex(0).getContainer();
                            } else {
                                // Fallback if no column is found
                                container = element.getContainer();
                                // Try to create a column if needed
                                if (container.model.get('elType') === 'section') {
                                    var columnModel = {
                                        id: elementorCommon.helpers.getUniqueId(),
                                        elType: 'column',
                                        settings: {},
                                        elements: []
                                    };
                                    var columnContainer = $e.run('document/elements/create', {
                                        container: container,
                                        model: columnModel
                                    });
                                    container = columnContainer;
                                }
                            }
                            break;
                        default:
                            container = element.getContainer();
                    }
                    break;
                    
                default:
                    elementor.notifications.showToast({
                        message: 'Unknown element type: ' + elementType
                    });
                    return;
            }
            
            if (!container) {
                throw new Error('Could not determine container for insertion');
            }
            importContent(newWidget, elementCode, container);
            
        } catch (error) {
            console.error('Process import error:', error);
            elementor.notifications.showToast({
                message: 'Error processing element: ' + error.message
            });
        }
    }

    // The rest of your code (HTMegaManageData, clipboard functions, etc.) remains unchanged
    
    // Copy and paste code handling, storage methods, etc.
    // ...

    // Add this function to help fix any data structure issues before importing
    function sanitizeElementData(data) {
        if (!data) return data;
        
        try {
            // If it's a string, parse it
            if (typeof data === 'string') {
                data = JSON.parse(data);
            }
            
            // Make sure elementCode exists if in the expected format
            if (data.elementCode) {
                // Fix missing properties
                if (!data.elementCode.settings) {
                    data.elementCode.settings = {};
                }
                
                // Make sure elements is an array if needed
                if (data.elementCode.elType !== 'widget' && !data.elementCode.elements) {
                    data.elementCode.elements = [];
                }
                
                // Make sure widgetType exists for widgets
                if (data.elementCode.elType === 'widget' && !data.elementCode.widgetType && data.elementType) {
                    data.elementCode.widgetType = data.elementType;
                }
            }
            
            return data;
        } catch (e) {
            console.error('Data sanitization error:', e);
            return data;
        }
    }

    /**
     * Check if browser supports the required clipboard APIs
     */
    function isClipboardSupported() {
        return Boolean(navigator.clipboard && navigator.clipboard.writeText && navigator.clipboard.readText);
    }

    
    /**
     * Enhanced clipboard handling with Firefox-specific logic
     */
    const clipboardManager = {
        // Check if browser supports the Clipboard API
        isSupported: function() {
            return Boolean(navigator.clipboard && navigator.clipboard.writeText && navigator.clipboard.readText);
        },
        
        // Write data to clipboard with special Firefox handling
        writeToClipboard: function(data, successCallback, errorCallback) {
            // For Firefox, prioritize execCommand for cross-domain support
            if (isFirefox) {
                const success = this.writeWithExecCommand(data);
                if (success) {
                    // Also try the standard method as backup
                    if (this.isSupported()) {
                        navigator.clipboard.writeText(data)
                    }
                    
                    // Store in server for cross-domain retrieval
                    serverStorage.store(data, function(id) {
                    });
                    
                    if (successCallback) successCallback();
                    return;
                }
            }
            
            // Regular clipboard API approach for other browsers
            if (this.isSupported()) {
                navigator.clipboard.writeText(data)
                    .then(() => {
                        if (successCallback) successCallback();
                    })
                    .catch((err) => {
                        console.error('Clipboard API write failed:', err);
                        
                        // Try fallback
                        const success = this.writeWithExecCommand(data);
                        if (success) {
                            if (successCallback) successCallback();
                        } else if (errorCallback) {
                            errorCallback(err);
                        }
                    });
            } else {
                // Fallback for browsers without Clipboard API
                const success = this.writeWithExecCommand(data);
                if (success) {
                    if (successCallback) successCallback();
                } else if (errorCallback) {
                    errorCallback(new Error('Clipboard write not supported'));
                }
            }
        },
        
        // Fallback method using document.execCommand
        writeWithExecCommand: function(data) {
            try {
                // Create a temporary textarea element
                const textarea = document.createElement('textarea');
                textarea.value = data;
                
                // Position off-screen but available
                textarea.style.position = 'fixed';
                textarea.style.left = '-9999px';
                textarea.style.top = '0';
                
                document.body.appendChild(textarea);
                textarea.focus();
                textarea.select();
                
                // Execute copy command
                const success = document.execCommand('copy');
                
                // Clean up
                document.body.removeChild(textarea);
                return success;
            } catch (e) {
                console.error('ExecCommand clipboard write failed:', e);
                return false;
            }
        },
        
        // Read from clipboard - Firefox special handling
        readFromClipboard: function(successCallback, errorCallback) {
            // For Firefox cross-domain, don't even try clipboard API first
            if (isFirefox) {
                serverStorage.retrieve(function(serverData) {
                    if (serverData) {
                        if (successCallback) successCallback(serverData);
                        return;
                    }
                    
                    // Try execCommand fallback for Firefox
                    const fallbackData = clipboardManager.readWithExecCommand();
                    if (fallbackData && fallbackData.startsWith(HTMEGA_CLIPBOARD_PREFIX)) {
                        if (successCallback) successCallback(fallbackData);
                        return;
                    }
                    
                    // Last resort - try clipboard API
                    if (clipboardManager.isSupported()) {
                        navigator.clipboard.readText()
                            .then(data => {
                                if (successCallback) successCallback(data);
                            })
                            .catch(err => {
                                if (errorCallback) errorCallback(err);
                            });
                    } else if (errorCallback) {
                        errorCallback(new Error('No clipboard data available'));
                    }
                });
                return;
            }
            
            // For non-Firefox browsers, use standard approach
            if (this.isSupported()) {
                navigator.clipboard.readText()
                    .then(data => {
                        if (successCallback) successCallback(data);
                    })
                    .catch(err => {
                        console.error('Clipboard read failed:', err);
                        
                        // Try fallbacks
                        const fallbackData = this.readWithExecCommand();
                        if (fallbackData) {
                            if (successCallback) successCallback(fallbackData);
                        } else {
                            // Try server as last resort
                            serverStorage.retrieve(function(serverData) {
                                if (serverData) {
                                    if (successCallback) successCallback(serverData);
                                } else if (errorCallback) {
                                    errorCallback(err);
                                }
                            });
                        }
                    });
            } else {
                // Fallback for browsers without Clipboard API
                const data = this.readWithExecCommand();
                if (data) {
                    if (successCallback) successCallback(data);
                } else {
                    // Try server as last resort
                    serverStorage.retrieve(function(serverData) {
                        if (serverData) {
                            if (successCallback) successCallback(serverData);
                        } else if (errorCallback) {
                            errorCallback(new Error('Clipboard read not supported'));
                        }
                    });
                }
            }
        },
        
        // Read from clipboard using execCommand
        readWithExecCommand: function() {
            try {
                // Create a temporary contenteditable div
                const div = document.createElement('div');
                div.contentEditable = true;
                
                // Position it for better Firefox support
                div.style.position = 'fixed';
                div.style.left = '0';
                div.style.top = '0';
                div.style.opacity = '0';
                div.style.width = '10px';
                div.style.height = '10px';
                
                document.body.appendChild(div);
                div.focus();
                
                // Execute paste command
                const success = document.execCommand('paste');
                const data = div.innerText || div.textContent || '';
                
                // Clean up
                document.body.removeChild(div);
                
                return data;
            } catch (e) {
                console.error('ExecCommand clipboard read failed:', e);
                return '';
            }
        }
    };


    /**
     * Store the data directly in memory as fallback
     */
    var memoryStorage = {
        data: null,
        timestamp: 0,
        operationId: '',
        set: function(data, operationId) {
            this.data = data;
            this.timestamp = getTimestamp();
            this.operationId = operationId;
        },
        get: function() {
            return {
                data: this.data,
                timestamp: this.timestamp,
                operationId: this.operationId
            };
        }
    };

    // Add a server-based storage mechanism for cross-domain persistence
    var serverStorage = {
        store: function(data, callback) {
            // Store in a global memory location for cross-function access
            window.htmegaClipboardTempStorage = data;
            // Always report success
            if (callback) callback('memory-only');
        },
        
        retrieve: function(callback) {
            if (window.htmegaClipboardTempStorage && callback) {
                callback(window.htmegaClipboardTempStorage);
            } else if (callback) {
                callback(null);
            }
        }
    };
    

    /**
     * Enhanced HTMegaManageData object with clipboard API support
     */
    var HTMegaManageData = {
        copy: function(element, menutypekey) {
            try {
                // Generate a unique operation ID for this copy operation
                const operationId = generateOperationId();
                
                var copiedData = {
                    elementType: menutypekey == "widget" ? element.model.get("widgetType") : null,
                    elementCode: element.model.toJSON(),
                    timestamp: getTimestamp(),
                    operationId: operationId,
                    domain: window.location.hostname
                };
                
                // Create a JSON string with additional metadata
                const jsonData = JSON.stringify(copiedData);
                
                // Create clipboard data with prefix
                var clipboardData = HTMEGA_CLIPBOARD_PREFIX + jsonData;
                
                // Store in memory for immediate fallback
                memoryStorage.set(jsonData, operationId);
                window.htmegaClipboardTempStorage = clipboardData;
                
                // Store in localStorage for additional fallback
                try {
                    localStorage.setItem('htmega-cp-element', jsonData);
                    localStorage.setItem('htmega-cp-timestamp', getTimestamp());
                    localStorage.setItem('htmega-cp-operationid', operationId);
                } catch (e) {
                    console.log('localStorage fallback failed:', e);
                }
                
                // Use clipboard manager for writing
                clipboardManager.writeToClipboard(
                    clipboardData,
                    function() {
                        elementor.notifications.showToast({
                            message: elementor.translate('Element Copied!')
                        });
                    },
                    function(error) {
                        console.error('Clipboard write error:', error);
                        elementor.notifications.showToast({
                            message: elementor.translate('Element Copied! (Memory mode)')
                        });
                    }
                );
            } catch (e) {
                console.error('Copy error:', e);
                elementor.notifications.showToast({
                    message: elementor.translate('Copy failed: ' + e.message)
                });
            }
        },
        paste: function(element) {
            
            // For Firefox, try memory directly first
            if (isFirefox && window.htmegaClipboardTempStorage) {
                try {
                    const clipboardText = window.htmegaClipboardTempStorage;
                    
                    if (clipboardText && clipboardText.startsWith(HTMEGA_CLIPBOARD_PREFIX)) {
                        // Extract the JSON data
                        var jsonStr = clipboardText.substring(HTMEGA_CLIPBOARD_PREFIX.length);
                        
                        var parsedData = JSON.parse(jsonStr);
                        parsedData = sanitizeElementData(parsedData);
                        
                        // Process the element
                        processImport(parsedData, element);
                        elementor.notifications.showToast({
                            message: elementor.translate('Element Pasted!')
                        });
                        return;
                    }
                } catch (e) {
                    console.error('Memory paste failed:', e);
                    // Fall through to normal paste flow
                }
            }
            
            // Regular clipboard flow for non-Firefox or if memory approach failed
            clipboardManager.readFromClipboard(
                function(clipboardText) {
                    if (clipboardText && clipboardText.startsWith(HTMEGA_CLIPBOARD_PREFIX)) {
                        // Extract the JSON data
                        var jsonStr = clipboardText.substring(HTMEGA_CLIPBOARD_PREFIX.length);
                        
                        try {
                            var parsedData = JSON.parse(jsonStr);
                            
                            // Process the element
                            processImport(parsedData, element);
                            elementor.notifications.showToast({
                                message: elementor.translate('Element Pasted!')
                            });
                        } catch (e) {
                            console.error('JSON parse error:', e);
                            tryMemoryFallback();
                        }
                    } else {
                        tryMemoryFallback();
                    }
                },
                function(error) {
                    console.error('Clipboard read error:', error);
                    tryMemoryFallback();
                }
            );
            
            // Try memory and localStorage as last resorts
            function tryMemoryFallback() {
                // Try memory fallback
                var memoryData = memoryStorage.get();
                if (memoryData && memoryData.data) {
                    try {
                        var parsedData = JSON.parse(memoryData.data);
                        parsedData = sanitizeElementData(parsedData);
                        
                        processImport(parsedData, element);
                        elementor.notifications.showToast({
                            message: elementor.translate('Element Pasted!')
                        });
                        return;
                    } catch (e) {
                        console.error('Memory data parse error:', e);
                    }
                }
                
                // Try localStorage as last resort
                try {
                    var storedData = localStorage.getItem('htmega-cp-element');
                    if (storedData) {
                        var parsedData = JSON.parse(storedData);
                        parsedData = sanitizeElementData(parsedData);
                        
                        processImport(parsedData, element);
                        elementor.notifications.showToast({
                            message: elementor.translate('Element Pasted!')
                        });
                    } else {
                        elementor.notifications.showToast({
                            message: elementor.translate('No element found to paste')
                        });
                    }
                } catch (e) {
                    console.error('localStorage fallback error:', e);
                    elementor.notifications.showToast({
                        message: elementor.translate('Paste failed: Could not retrieve element data')
                    });
                }
            }
        }
    };

    function prepareMenuItem(groups, element, menutypekey) {
        var index = _.findIndex(groups, function(element) {
            return 'clipboard' === element.name;
        });

        if (index === -1) {
            // If clipboard group not found, add to the beginning
            index = 0;
        }

        groups.splice(index + 1, 0, {
            name: "htmega_" + (menutypekey || "element"),
            actions: [
                {
                    name: 'htmega_copy',
                    title: htmegacrosscp.copy,
                    icon: 'eicon-clone',
                    callback: function() {
                        HTMegaManageData.copy(element, menutypekey);
                    }
                },
                {
                    name: 'htmega_paste',
                    title: htmegacrosscp.paste,
                    icon: 'eicon-copy',
                    callback: function() {
                        HTMegaManageData.paste(element);
                    }
                },
            ]
        });
        return groups;
    }

    elementor.hooks.addFilter('elements/widget/contextMenuGroups', function(groups, element) {
        return prepareMenuItem(groups, element, 'widget');
    });

    elementor.hooks.addFilter('elements/section/contextMenuGroups', function(groups, element) {
        return prepareMenuItem(groups, element, 'section');
    });

    elementor.hooks.addFilter('elements/column/contextMenuGroups', function(groups, element) {
        return prepareMenuItem(groups, element, 'column');
    });
    
    elementor.hooks.addFilter('elements/container/contextMenuGroups', function(groups, element) {
        return prepareMenuItem(groups, element);
    });

    // Add clipboard permission helper
    $(document).ready(function() {
        // Check and request clipboard permissions if needed
        setTimeout(function() {
            if (isClipboardSupported() && 
                $('body').hasClass('elementor-editor-active')) {
                
                // Try a test read to see if we have permissions
                navigator.clipboard.readText()
                    .then(function() {
                        try {
                            localStorage.setItem('htmega_clipboard_permission', 'granted');
                        } catch(e) {}
                    })
                    .catch(function(err) {
                        
                        // Check if we've shown the dialog before
                        try {
                            if (localStorage.getItem('htmega_clipboard_dialog_shown')) {
                                return;
                            }
                            localStorage.setItem('htmega_clipboard_dialog_shown', 'true');
                        } catch(e) {}
                        
                        // Create a permission request dialog
                        var permissionDialog = $(
                            '<div class="htmega-clipboard-permission">' + 
                            '<p><strong>HTMega Cross-Domain Copy Paste</strong> needs clipboard access.</p>' +
                            '<p>Click "Grant Access" below and then click "Allow" when your browser asks for permission.</p>' +
                            '<button class="elementor-button elementor-button-success">Grant Access</button>' +
                            '<button class="elementor-button dismiss">Dismiss</button>' +
                            '</div>'
                        );
                        
                        // Add styles
                        var styles = $('<style>' +
                            '.htmega-clipboard-permission {' +
                            '  position: fixed;' +
                            '  top: 50%;' +
                            '  left: 50%;' +
                            '  transform: translate(-50%, -50%);' +
                            '  background: white;' +
                            '  padding: 20px;' +
                            '  border-radius: 5px;' +
                            '  box-shadow: 0 0 10px rgba(0,0,0,0.2);' +
                            '  z-index: 9999;' +
                            '  max-width: 350px;' +
                            '  text-align: center;' +
                            '}' +
                            '.htmega-clipboard-permission button {' +
                            '  margin: 5px;' +
                            '}' +
                            '</style>'
                        );
                        
                        $('body').append(styles).append(permissionDialog);
                        
                        // Grant access button
                        permissionDialog.find('.elementor-button-success').on('click', function() {
                            navigator.clipboard.readText()
                                .then(function() {
                                    permissionDialog.remove();
                                    styles.remove();
                                    
                                    try {
                                        localStorage.setItem('htmega_clipboard_permission', 'granted');
                                    } catch(e) {}
                                    
                                    elementor.notifications.showToast({
                                        message: 'Clipboard access granted! Cross-domain copy-paste is now available.'
                                    });
                                })
                                .catch(function(err) {
                                    console.error('Clipboard permission error:', err);
                                    permissionDialog.html(
                                        '<p><strong>Clipboard permission denied</strong></p>' +
                                        '<p>Please enable clipboard access in your browser settings and then reload this page.</p>' +
                                        '<p>In Chrome: Site Settings > Permissions > Clipboard</p>' +
                                        '<button class="elementor-button">Dismiss</button>'
                                    );
                                    
                                    permissionDialog.find('button').on('click', function() {
                                        permissionDialog.remove();
                                        styles.remove();
                                    });
                                });
                        });
                        
                        // Dismiss button
                        permissionDialog.find('.dismiss').on('click', function() {
                            permissionDialog.remove();
                            styles.remove();
                        });
                    });
            }
        }, 2000);
    });

})(jQuery);