/**
 * Text Generator Module for Elementor Editor
 */
(function($) {
    'use strict';
    
    /**
     * Text Generator Module for Elementor
     */
    var TextGeneratorModule = {
        modal: null,
        currentWidget: null,
        currentEditor: null,
        
        /**
         * Initialize the module
         */
        init: function() {
            // Wait for Elementor to be fully loaded
            $(window).on('elementor:init', function() {
                TextGeneratorModule.initEditor();
            });
            
            // Bind events immediately
            this.bindEvents();
        },
        
        /**
         * Initialize editor
         */
        initEditor: function() {
            // Check if elementor is defined
            if (typeof elementor === 'undefined') {
                console.log('Elementor not found, Text Generator Module not initialized');
                return;
            }
            
            console.log('Text Generator Module initialized');
            
            // Add Generate Text button to regular text editor controls
            elementor.hooks.addFilter('elements/widget/contextMenuGroups', this.addGenerateTextMenuItem);
            
            // Watch for our custom widget being rendered
            elementor.channels.editor.on('section:activated', function(sectionName, editor) {
                var currentEditedElement = editor.getOption('editedElementView');
                
                // Only run for our widget or text editors
                if (currentEditedElement && 
                    (currentEditedElement.model.get('widgetType') === 'text-editor' || 
                     currentEditedElement.model.get('widgetType') === 'unlockafe-text-generator')) {
                    
                    // Add our button if it doesn't exist
                    if ($('.unlockafe-generate-text-button').length === 0) {
                        var $editorPanel = $('.elementor-control-editor, .elementor-control-placeholder_text');
                        
                        if ($editorPanel.length > 0) {
                            var $button = $('<div class="elementor-control elementor-control-separator-default">' +
                                '<div class="elementor-control-content">' +
                                '<div class="elementor-control-field">' +
                                '<div class="elementor-control-input-wrapper">' +
                                '<button class="elementor-button elementor-button-success unlockafe-generate-text-button" data-widget-id="' + currentEditedElement.model.id + '">' +
                                '<i class="eicon-text" aria-hidden="true"></i> ' +
                                'Generate Text with AI' +
                                '</button>' +
                                '</div>' +
                                '</div>' +
                                '</div>' +
                                '</div>');
                            
                            $editorPanel.after($button);
                        }
                    }
                }
            });
        },
        
        /**
         * Bind events
         */
        bindEvents: function() {
            // Use document on for delegated events
            $(document).on('click', '.unlockafe-generate-text-button', this.openModal.bind(this));
            $(document).on('click', '.unlockafe-modal-close, .unlockafe-modal-cancel, .dialog-close-button', this.closeModal.bind(this));
            $(document).on('click', '.unlockafe-modal-submit', this.handleGenerateText.bind(this));
            
            // Debug click handler
            $(document).on('click', '.unlockafe-generate-text-button', function() {
                console.log('Generate Text button clicked');
            });
        },
        
        /**
         * Add Generate Text menu item to context menu
         */
        addGenerateTextMenuItem: function(groups, element) {
            // Only add for text editor widgets
            if (element.options.widgetType === 'text-editor' || element.options.widgetType === 'unlockafe-text-generator') {
                groups.push({
                    name: 'unlockafe_text_generator',
                    actions: [{
                        name: 'generate_text',
                        title: 'Generate Text with AI',
                        callback: function() {
                            TextGeneratorModule.openModal(element);
                        }
                    }]
                });
            }
            
            return groups;
        },
        
        /**
         * Open the modal
         */
        openModal: function(event) {
            // Log for debugging
            console.log('Opening modal', event);
            
            // Get widget ID
            var widgetId;
            
            if (event && event.target) {
                // If triggered by click
                widgetId = $(event.target).closest('.unlockafe-generate-text-button').data('widget-id');
                if (!widgetId && $(event.target).data('widget-id')) {
                    widgetId = $(event.target).data('widget-id');
                }
            } else if (event && event.id) {
                // If called from context menu
                widgetId = event.id;
            }
            
            console.log('Widget ID:', widgetId);
            
            if (!widgetId) {
                console.error('No widget ID found');
                return;
            }
            
            // Get the container
            this.currentWidget = elementor.getContainer(widgetId);
            
            if (!this.currentWidget) {
                console.error('Could not find widget container');
                return;
            }
            
            // Get the editor
            var widgetType = this.currentWidget.model.get('widgetType');
            console.log('Widget type:', widgetType);
            
            if (widgetType === 'text-editor') {
                this.currentEditor = 'editor';
            } else if (widgetType === 'unlockafe-text-generator') {
                this.currentEditor = 'placeholder_text';
            } else {
                console.error('Unsupported widget type');
                return;
            }
            
            // Create and open the modal
            var modalHTML = $('#tmpl-unlockafe-text-generator-modal').html();
            
            if (!modalHTML) {
                console.error('Modal template not found');
                alert('Modal template not found. Please refresh the page and try again.');
                return;
            }
            
            this.modal = elementor.dialogsManager.createWidget('lightbox', {
                id: 'unlockafe-text-generator-modal',
                message: modalHTML,
                headerMessage: 'Generate Text with AI',
                closeButton: true,
                closeButtonClass: 'eicon-close',
                position: {
                    my: 'center',
                    at: 'center'
                },
                onShow: function() {
                    // Focus on topic input
                    setTimeout(function() {
                        $('.unlockafe-modal-topic').focus();
                    }, 100);
                }
            });
            
            this.modal.show();
        },
        
        /**
         * Close the modal
         */
        closeModal: function() {
            if (this.modal) {
                this.modal.hide();
            }
        },
        
        /**
         * Handle generate text button click
         */
        handleGenerateText: function() {
            if (!this.currentWidget || !this.currentEditor) {
                console.error('No widget or editor selected');
                return;
            }
            
            // Get form data
            var topic = $('.unlockafe-modal-topic').val();
            var length = $('.unlockafe-modal-length').val();
            var tone = $('.unlockafe-modal-tone').val();
            var instructions = $('.unlockafe-modal-instructions').val();
            
            // Validate
            if (!topic) {
                alert('Please enter a topic');
                return;
            }
            
            // Show loading
            var $submitButton = $('.unlockafe-modal-submit');
            var originalButtonText = $submitButton.text();
            $submitButton.html('<i class="eicon-loading eicon-animation-spin" aria-hidden="true"></i> Generating...');
            $submitButton.prop('disabled', true);
            
            // Build the prompt
            var prompt = 'Generate a ' + length + ' text about "' + topic + '" with a ' + tone + ' tone.';
            
            if (instructions) {
                prompt += ' Additional instructions: ' + instructions;
            }
            
            // For testing, use a mock response
            var mockResponse = 'This is a sample generated text about "' + topic + '" with a ' + tone + ' tone. The length is ' + length + '.';
            mockResponse += ' This is just a placeholder for testing the integration. In the actual implementation, this text would be generated by the LLM API.';
            
            // Update the editor content with mock response for testing
            setTimeout(function() {
                // Update the widget content
                TextGeneratorModule.currentWidget.settings.setExternalChange(
                    TextGeneratorModule.currentEditor, 
                    mockResponse
                );
                
                // Close the modal
                TextGeneratorModule.closeModal();
                
                // Reset button
                $submitButton.html(originalButtonText);
                $submitButton.prop('disabled', false);
                
                // Alert for testing
                alert('Text has been generated and inserted! (Mock response for testing)');
            }, 1000);
            
            /* Uncomment this for actual API integration
            // Make the API request
            this.makeAPIRequest(prompt).then(function(response) {
                // Update the editor content
                var generatedText = response;
                
                if (!generatedText) {
                    generatedText = 'Error: Unable to generate text. Please try again.';
                }
                
                // Update the widget content
                TextGeneratorModule.currentWidget.settings.setExternalChange(
                    TextGeneratorModule.currentEditor, 
                    generatedText
                );
                
                // Close the modal
                TextGeneratorModule.closeModal();
                
                // Reset button
                $submitButton.html(originalButtonText);
                $submitButton.prop('disabled', false);
                
            }).catch(function(error) {
                console.error('Error generating text:', error);
                
                // Show error
                alert('Error generating text: ' + error.message);
                
                // Reset button
                $submitButton.html(originalButtonText);
                $submitButton.prop('disabled', false);
            });
            */
        },
        
        /**
         * Make API request to generate text
         */
        makeAPIRequest: function(prompt) {
            return new Promise(function(resolve, reject) {
                $.ajax({
                    url: unlockafe_text_generator_module.ajax_url,
                    type: 'POST',
                    data: {
                        action: 'unlockafe_generate_text',
                        prompt: prompt,
                        nonce: unlockafe_text_generator_module.nonce
                    },
                    success: function(response) {
                        if (response.success) {
                            resolve(response.data);
                        } else {
                            reject(new Error(response.data || 'Unknown error'));
                        }
                    },
                    error: function(xhr, status, error) {
                        reject(new Error(error));
                    }
                });
            });
        }
    };
    
    // Initialize on document ready
    $(document).ready(function() {
        TextGeneratorModule.init();
    });
    
    // Make it globally accessible for debugging
    window.TextGeneratorModule = TextGeneratorModule;
    
})(jQuery);
