/**
 * Text Generator Widget - Elementor Editor Integration
 * This file is only loaded in the Elementor editor context
 */
(function($) {
    'use strict';
    
    /**
     * Text Generator Editor Integration
     */
    var TextGeneratorEditor = {
        
        /**
         * Initialize the editor integration
         */
        init: function() {
            this.bindEvents();
        },
        
        /**
         * Bind editor events
         */
        bindEvents: function() {
            // Listen for our custom event that will be triggered by the modal submit
            $(document).on('unlockafe:generateText', this.handleGenerateText);
            
            // Override the frontend button click in editor mode
            elementor.channels.editor.on('editor:widget:unlockafe-text-generator:section_general:after:render', function() {
                $('.unlockafe-generate-button').off('click');
                $(document).on('click', '.unlockafe-generate-button', TextGeneratorEditor.openEditorModal);
            });
        },
        
        /**
         * Open the editor modal
         */
        openEditorModal: function(e) {
            e.preventDefault();
            
            var widgetId = $(this).data('widget-id');
            var modalHTML = TextGeneratorEditor.createModalHTML(widgetId);
            
            // Append modal to body
            $('body').append(modalHTML);
            
            // Show the modal with animation
            setTimeout(function() {
                $('.unlockafe-modal-overlay').addClass('active');
            }, 10);
            
            // Bind modal events
            TextGeneratorEditor.bindModalEvents(widgetId);
        },
        
        /**
         * Create the modal HTML
         */
        createModalHTML: function(widgetId) {
            var html = '<div class="unlockafe-modal-overlay">';
            html += '<div class="unlockafe-modal">';
            html += '<div class="unlockafe-modal-header">';
            html += '<h3 class="unlockafe-modal-title">AI Text Generator</h3>';
            html += '<button class="unlockafe-modal-close">&times;</button>';
            html += '</div>';
            html += '<div class="unlockafe-modal-body">';
            
            // Instruction box
            html += '<div class="unlockafe-instruction-box" style="background: #f7f9fb; border-left: 4px solid #4267b2; padding: 12px; margin-bottom: 20px; border-radius: 4px;">';
            html += '<p style="margin: 0; font-size: 14px;">Enter your topic and customize options below to generate high-quality content for your website. The AI will format the output with proper HTML structure.</p>';
            html += '</div>';
            
            // Form fields
            html += '<div class="unlockafe-modal-form-group">';
            html += '<label class="unlockafe-modal-label">What would you like to write about?</label>';
            html += '<input type="text" class="unlockafe-modal-input unlockafe-modal-topic" placeholder="E.g., Benefits of WordPress, Modern Web Design Trends, etc.">';
            html += '</div>';
            
            html += '<div class="unlockafe-modal-form-group">';
            html += '<label class="unlockafe-modal-label">Content Length</label>';
            html += '<select class="unlockafe-modal-select unlockafe-modal-length">';
            html += '<option value="short">Short (100-200 words)</option>';
            html += '<option value="medium" selected>Medium (200-500 words)</option>';
            html += '<option value="long">Long (500+ words)</option>';
            html += '</select>';
            html += '</div>';
            
            html += '<div class="unlockafe-modal-form-group">';
            html += '<label class="unlockafe-modal-label">Content Tone</label>';
            html += '<select class="unlockafe-modal-select unlockafe-modal-tone">';
            html += '<option value="professional" selected>Professional</option>';
            html += '<option value="casual">Casual</option>';
            html += '<option value="formal">Formal</option>';
            html += '<option value="friendly">Friendly</option>';
            html += '<option value="persuasive">Persuasive</option>';
            html += '</select>';
            html += '</div>';
            
            html += '<div class="unlockafe-modal-form-group">';
            html += '<label class="unlockafe-modal-label">Specific Instructions (Optional)</label>';
            html += '<textarea class="unlockafe-modal-textarea unlockafe-modal-instructions" placeholder="Add specific details, angle, or requirements for your content"></textarea>';
            html += '</div>';
            
            // Developer options toggle
            html += '<div class="unlockafe-modal-form-group" style="margin-top: 15px;">';
            html += '<label class="unlockafe-modal-checkbox-label" style="font-size: 14px; display: flex; align-items: center;">';
            html += '<input type="checkbox" class="unlockafe-modal-debug-toggle" style="margin-right: 8px;"> Show debug information (developer option)';
            html += '</label>';
            html += '</div>';
            
            html += '</div>'; // End modal body
            
            html += '<div class="unlockafe-modal-footer">';
            html += '<button class="unlockafe-modal-button unlockafe-modal-cancel" style="background: #f1f3f5; color: #444;">Cancel</button>';
            html += '<button class="unlockafe-modal-button unlockafe-modal-submit" data-widget-id="' + widgetId + '" style="background: #4267b2; color: white;">Generate Content</button>';
            html += '</div>';
            
            html += '</div>'; // End modal
            html += '</div>'; // End overlay
            
            return html;
        },
        
        /**
         * Bind modal events
         */
        bindModalEvents: function(widgetId) {
            // Close modal
            $(document).on('click', '.unlockafe-modal-close, .unlockafe-modal-cancel', function() {
                TextGeneratorEditor.closeModal();
            });
            
            // Close modal when clicking outside
            $(document).on('click', '.unlockafe-modal-overlay', function(e) {
                if ($(e.target).hasClass('unlockafe-modal-overlay')) {
                    TextGeneratorEditor.closeModal();
                }
            });
            
            // Submit form
            $(document).on('click', '.unlockafe-modal-submit', function() {
                var $button = $(this);
                var widgetId = $button.data('widget-id');
                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;
                }
                
                // Trigger generate text
                $(document).trigger('unlockafe:generateText', [widgetId, topic, length, tone, instructions, $button]);
            });
        },
        
        /**
         * Close the modal
         */
        closeModal: function() {
            $('.unlockafe-modal-overlay').removeClass('active');
            
            // Remove modal from DOM after animation
            setTimeout(function() {
                $('.unlockafe-modal-overlay').remove();
            }, 300);
            
            // Unbind modal events
            $(document).off('click', '.unlockafe-modal-close, .unlockafe-modal-cancel');
            $(document).off('click', '.unlockafe-modal-overlay');
            $(document).off('click', '.unlockafe-modal-submit');
        },
        
        /**
         * Handle the generate text event
         */
        handleGenerateText: function(e, widgetId, topic, length, tone, instructions, $button) {
            // Show loading
            var originalButtonText = $button.text();
            $button.html('<span class="unlockafe-loading"></span> Generating...');
            $button.prop('disabled', true);
            
            // Get the current widget model
            var widgetModel = elementor.getPreviewView().collection.findWhere({ id: widgetId }).model;
            
            // Build a clearer, more direct prompt based on the parameters
            var prompt = topic;
            
            // Add length instruction only if it will enhance the result
            if (length === 'long') {
                prompt += '. Please provide a comprehensive and detailed response.';
            } else if (length === 'short') {
                prompt += '. Please provide a concise response.';
            }
            
            // Add tone only if specified
            if (tone && tone !== 'casual') {
                prompt += ' The tone should be ' + tone + '.';
            }
            
            // Add any additional instructions
            if (instructions) {
                prompt += ' ' + instructions;
            }
            
            console.log('Sending prompt to AI:', prompt);
            
            // Check if debug is enabled
            var debugEnabled = $('.unlockafe-modal-debug-toggle').is(':checked');
            var debugInfoId = null;
            var logDebug = function() {}; // Empty function by default
            
            // Only create debug panel if enabled
            if (debugEnabled) {
                // Add a div to the page to show debug info
                debugInfoId = 'unlockafe-debug-info-' + new Date().getTime();
                $('body').append('<div id="' + debugInfoId + '" style="position: fixed; bottom: 10px; right: 10px; z-index: 9999; background: white; border: 1px solid #ccc; padding: 10px; max-width: 500px; max-height: 300px; overflow: auto;"><h4>Text Generator Debug <button onclick="this.parentElement.parentElement.remove()" style="float:right;background:none;border:none;cursor:pointer;font-size:12px;color:#999;">Close</button></h4><pre></pre></div>');
                
                // Add debug log function
                logDebug = function(message) {
                    console.log(message);
                    $('#' + debugInfoId + ' pre').append(message + "\n");
                };
                
                logDebug('Starting text generation request...');
                logDebug('Topic: ' + topic);
                logDebug('Prompt: ' + prompt);
            }
            
            // Make the API request
            TextGeneratorEditor.makeAPIRequest(prompt, debugEnabled).then(function(response) {
                // Update the widget content
                var generatedText = response;
                
                if (!generatedText) {
                    generatedText = 'Error: Unable to generate text. Please try again.';
                    if (debugEnabled) logDebug('ERROR: Empty response received');
                }
                
                if (debugEnabled) {
                    logDebug('SUCCESS: Received response (' + generatedText.length + ' chars)');
                    logDebug('First 100 chars: ' + generatedText.substring(0, 100) + '...');
                }
                
                // Store the current widget model ID for debugging
                var currentWidgetId = widgetModel.get('id');
                if (debugEnabled) {
                    logDebug('Updating widget with ID: ' + currentWidgetId);
                }
                
                // Update only the specific widget model that triggered the text generation
                widgetModel.setSetting('placeholder_text', generatedText);
                
                // Reset and close modal
                $button.text(originalButtonText);
                $button.prop('disabled', false);
                TextGeneratorEditor.closeModal();
                
                // Remove debug info after 30 seconds if it exists
                if (debugEnabled && debugInfoId) {
                    setTimeout(function() {
                        $('#' + debugInfoId).fadeOut(function() {
                            $(this).remove();
                        });
                    }, 30000);
                }
                
            }).catch(function(error) {
                console.error('Error generating text:', error);
                if (debugEnabled) logDebug('ERROR: ' + error.message);
                
                // Show error and reset
                alert('Error generating text: ' + error.message);
                $button.text(originalButtonText);
                $button.prop('disabled', false);
            });
        },
        
        /**
         * Make the API request to the LLM server
         */
        makeAPIRequest: function(prompt, debug) {
            return new Promise(function(resolve, reject) {
                console.log('Making API request with prompt:', prompt);
                
                // Add a timestamp to force a fresh request (avoid caching)
                var timestamp = new Date().getTime();
                
                // Display more detailed debug info in the console
                console.log('=== TEXT GENERATOR DEBUG ===');
                console.log('Ajax URL:', unlockafe_text_generator.ajax_url);
                console.log('Prompt:', prompt);
                console.log('Timestamp:', timestamp);
                
                // AJAX request to our backend proxy
                $.ajax({
                    url: unlockafe_text_generator.ajax_url + '?t=' + timestamp,
                    type: 'POST',
                    data: {
                        action: 'unlockafe_generate_text',
                        prompt: prompt,
                        nonce: unlockafe_text_generator.nonce,
                        debug: debug
                    },
                    timeout: 60000, // 60 second timeout
                    beforeSend: function() {
                        console.log('AJAX request started to: ' + unlockafe_text_generator.ajax_url);
                    },
                    success: function(response) {
                        console.log('AJAX response received:', response);
                        if (response.success) {
                            // If debug info is available, log it
                            if (response.data && response.data.debug) {
                                console.log('API Provider Used:', response.data.debug.api_provider);
                                console.log('Model Used:', response.data.debug.model);
                                
                                // Resolve with just the content
                                resolve(response.data.content);
                            } else {
                                resolve(response.data);
                            }
                        } else {
                            console.error('Error in API response:', response);
                            
                            // If debug info is available in error, log it
                            if (response.data && response.data.debug) {
                                console.error('API Provider:', response.data.debug.api_provider);
                                console.error('API Key Set:', response.data.debug.api_key_set);
                                console.error('Error Details:', response.data.debug.error_details);
                                
                                // Reject with just the message
                                reject(new Error(response.data.message || 'Unknown error occurred'));
                            } else {
                                reject(new Error(response.data || 'Unknown error occurred'));
                            }
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error('AJAX Error:', status, error);
                        console.error('AJAX Response Text:', xhr.responseText);
                        console.error('AJAX Status:', xhr.status);
                        
                        if (status === 'timeout') {
                            reject(new Error('Request timed out. The server took too long to respond. Try a shorter prompt or try again later.'));
                        } else if (xhr.responseJSON && xhr.responseJSON.data) {
                            reject(new Error(xhr.responseJSON.data));
                        } else {
                            reject(new Error('Failed to connect to the server. Please check your network connection and try again.'));
                        }
                    }
                });
            });
        }
    };
    
    // Add some custom CSS for the modal
    $(document).ready(function() {
        // Add custom CSS to improve modal appearance
        $('head').append(`
            <style>
                .unlockafe-modal-overlay {
                    position: fixed;
                    top: 0;
                    left: 0;
                    right: 0;
                    bottom: 0;
                    background-color: rgba(0, 0, 0, 0.5);
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    z-index: 9999;
                    opacity: 0;
                    transition: opacity 0.3s ease;
                }
                
                .unlockafe-modal-overlay.active {
                    opacity: 1;
                }
                
                .unlockafe-modal {
                    background-color: #fff;
                    border-radius: 8px;
                    width: 500px;
                    max-width: 95%;
                    max-height: 90vh;
                    overflow-y: auto;
                    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
                    transform: translateY(20px);
                    transition: transform 0.3s ease;
                }
                
                .unlockafe-modal-overlay.active .unlockafe-modal {
                    transform: translateY(0);
                }
                
                .unlockafe-modal-header {
                    padding: 16px 20px;
                    border-bottom: 1px solid #eee;
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                }
                
                .unlockafe-modal-title {
                    margin: 0;
                    font-size: 18px;
                    color: #333;
                }
                
                .unlockafe-modal-close {
                    background: none;
                    border: none;
                    font-size: 22px;
                    cursor: pointer;
                    color: #999;
                }
                
                .unlockafe-modal-body {
                    padding: 20px;
                }
                
                .unlockafe-modal-form-group {
                    margin-bottom: 16px;
                }
                
                .unlockafe-modal-label {
                    display: block;
                    margin-bottom: 6px;
                    font-weight: 500;
                    color: #333;
                }
                
                .unlockafe-modal-input, 
                .unlockafe-modal-select, 
                .unlockafe-modal-textarea {
                    width: 100%;
                    padding: 10px 12px;
                    border-radius: 4px;
                    border: 1px solid #ddd;
                    font-size: 14px;
                    transition: border-color 0.2s;
                }
                
                .unlockafe-modal-input:focus, 
                .unlockafe-modal-select:focus, 
                .unlockafe-modal-textarea:focus {
                    outline: none;
                    border-color: #4267b2;
                }
                
                .unlockafe-modal-textarea {
                    min-height: 80px;
                    resize: vertical;
                }
                
                .unlockafe-modal-footer {
                    padding: 16px 20px;
                    border-top: 1px solid #eee;
                    display: flex;
                    justify-content: flex-end;
                    gap: 10px;
                }
                
                .unlockafe-modal-button {
                    padding: 10px 16px;
                    border-radius: 4px;
                    border: none;
                    font-size: 14px;
                    cursor: pointer;
                    transition: opacity 0.2s;
                }
                
                .unlockafe-modal-button:hover {
                    opacity: 0.9;
                }
                
                .unlockafe-loading {
                    display: inline-block;
                    width: 12px;
                    height: 12px;
                    border: 2px solid rgba(255,255,255,0.3);
                    border-radius: 50%;
                    border-top-color: #fff;
                    animation: spin 1s linear infinite;
                    margin-right: 8px;
                }
                
                @keyframes spin {
                    to { transform: rotate(360deg); }
                }
            </style>
        `);
        
        // Initialize the editor
        TextGeneratorEditor.init();
    });
    
})(jQuery);
