/**
 * Text Generator Widget JavaScript
 */
(function($) {
    'use strict';
    
    /**
     * Text Generator Widget functionality
     */
    var TextGenerator = {
        
        /**
         * Initialize the widget
         */
        init: function() {
            this.bindEvents();
        },
        
        /**
         * Bind events
         */
        bindEvents: function() {
            $(document).on('click', '.unlockafe-generate-button', this.openModal);
        },
        
        /**
         * Open the text generator modal
         */
        openModal: function(e) {
            e.preventDefault();
            
            var widgetId = $(this).data('widget-id');
            var modalHTML = TextGenerator.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
            TextGenerator.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">Generate Text</h3>';
            html += '<button class="unlockafe-modal-close">&times;</button>';
            html += '</div>';
            html += '<div class="unlockafe-modal-body">';
            
            // Form fields
            html += '<div class="unlockafe-modal-form-group">';
            html += '<label class="unlockafe-modal-label">Topic</label>';
            html += '<input type="text" class="unlockafe-modal-input unlockafe-modal-topic" placeholder="Enter a topic">';
            html += '</div>';
            
            html += '<div class="unlockafe-modal-form-group">';
            html += '<label class="unlockafe-modal-label">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">Tone</label>';
            html += '<select class="unlockafe-modal-select unlockafe-modal-tone">';
            html += '<option value="professional">Professional</option>';
            html += '<option value="casual" selected>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">Additional Instructions (Optional)</label>';
            html += '<textarea class="unlockafe-modal-textarea unlockafe-modal-instructions" placeholder="Any specific instructions for the text generator"></textarea>';
            html += '</div>';
            
            html += '</div>'; // End modal body
            
            html += '<div class="unlockafe-modal-footer">';
            html += '<button class="unlockafe-modal-button unlockafe-modal-cancel">Cancel</button>';
            html += '<button class="unlockafe-modal-button unlockafe-modal-submit" data-widget-id="' + widgetId + '">Generate Text</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() {
                TextGenerator.closeModal();
            });
            
            // Close modal when clicking outside
            $(document).on('click', '.unlockafe-modal-overlay', function(e) {
                if ($(e.target).hasClass('unlockafe-modal-overlay')) {
                    TextGenerator.closeModal();
                }
            });
            
            // Submit form
            $(document).on('click', '.unlockafe-modal-submit', function() {
                TextGenerator.generateText($(this));
            });
        },
        
        /**
         * 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');
        },
        
        /**
         * Generate text based on form inputs
         */
        generateText: function($button) {
            var widgetId = $button.data('widget-id');
            var $modal = $('.unlockafe-modal');
            
            // Check if debug mode is enabled via query parameter, localized setting, or local storage
            var showDebug = false;
            
            // Check URL for debug flag
            if (window.location.href.indexOf('unlockafe_debug=1') > -1) {
                showDebug = true;
                // Save debug preference to localStorage
                if (window.localStorage) {
                    localStorage.setItem('unlockafe_debug_enabled', '1');
                }
            }
            // Check localized setting
            else if (window.unlockafe_text_generator && window.unlockafe_text_generator.debug) {
                showDebug = true;
            }
            // Check localStorage for persistent preference
            else if (window.localStorage && localStorage.getItem('unlockafe_debug_enabled') === '1') {
                showDebug = true;
            }
            
            // Initialize debug variables - these will be null when debug is off
            var debugPanelId = 'unlockafe-visual-debug-' + Date.now();
            var debugPanel = null;
            var debugContent = null;
            
            // Only create the debug panel if debug mode is enabled
            if (showDebug) {
                // Create a debug panel
                debugPanel = $('<div id="' + debugPanelId + '" style="position:fixed; bottom:20px; right:20px; z-index:99999; background:#fff; border:1px solid #ccc; box-shadow:0 0 10px rgba(0,0,0,0.1); padding:15px; width:350px; max-height:60vh; overflow:auto; font-family:monospace; font-size:12px;"></div>');
                var debugTitle = $('<h4 style="margin-top:0; margin-bottom:10px; font-size:14px; border-bottom:1px solid #eee; padding-bottom:5px;">Text Generator Debug</h4>');
                var closeButton = $('<button style="position:absolute; top:5px; right:5px; background:transparent; color:#666; border:none; font-size:16px; line-height:1; cursor:pointer;">&times;</button>');
                var disableButton = $('<button style="position:absolute; top:5px; right:25px; background:transparent; color:#666; border:none; font-size:12px; cursor:pointer;">Disable Debug</button>');
                debugContent = $('<div></div>');
                
                closeButton.on('click', function() {
                    $('#' + debugPanelId).remove();
                });
                
                disableButton.on('click', function() {
                    // Disable debug mode and remove panel
                    if (window.localStorage) {
                        localStorage.setItem('unlockafe_debug_enabled', '0');
                    }
                    $('#' + debugPanelId).remove();
                });
                
                debugPanel.append(debugTitle);
                debugPanel.append(closeButton);
                debugPanel.append(disableButton);
                debugPanel.append(debugContent);
                $('body').append(debugPanel);
                
                // Add message about how to enable debug
                addDebugMessage('Debug mode active. Add ?unlockafe_debug=1 to URL to enable debug mode anytime.', 'info');
            }
            
            // Helper function to add debug messages - works even when debug is disabled
            function addDebugMessage(message, type) {
                // Always add to console for developer access regardless of debug panel visibility
                if (type === 'error') {
                    console.error('Text Generator:', message);
                } else if (type === 'warning') {
                    console.warn('Text Generator:', message);
                } else {
                    console.log('Text Generator:', message);
                }
                
                // Only attempt to add to debug panel if it exists
                if (showDebug && debugContent) {
                    var classname = 'unlockafe-debug-message';
                    if (type) {
                        classname += ' unlockafe-debug-' + type;
                    }
                    var messageElement = $('<div class="' + classname + '"></div>');
                    messageElement.text(message);
                    
                    // Append to debug content
                    debugContent.append(messageElement);
                    
                    // Auto-scroll to bottom
                    if (debugPanel) {
                        debugPanel.scrollTop(debugPanel[0].scrollHeight);
                    }
                }
            }
            
            // Add the modal HTML to debug
            addDebugMessage('Modal HTML:', 'info');
            addDebugMessage($modal.html(), 'info');
            
            // Show all input elements in the modal
            addDebugMessage('Input elements in modal:', 'info');
            var modalInputs = $modal.find('input, select, textarea');
            addDebugMessage('Found ' + modalInputs.length + ' form elements', 'info');
            
            modalInputs.each(function(index) {
                var element = $(this);
                var elementType = element.prop('tagName');
                var elementClass = element.attr('class');
                var elementValue = element.val();
                var elementPlaceholder = element.attr('placeholder') || 'No placeholder';
                addDebugMessage(index + ': ' + elementType + ' - Class: ' + elementClass + ' - Placeholder: "' + elementPlaceholder + '" - Value: "' + elementValue + '"', 'info');
            });
            
            // Try direct value reading
            var directTopic = $modal.find('.unlockafe-modal-topic').val();
            addDebugMessage('Direct topic value: "' + directTopic + '"', 'info');
            
            // Show any values that users are typing
            addDebugMessage('Setting up live value tracking...', 'info');
            $modal.on('input', '.unlockafe-modal-topic', function() {
                addDebugMessage('Topic being typed: "' + $(this).val() + '"', 'success');
            });
            
            // Get values with different approach - HANDLE DUPLICATE INPUTS
            addDebugMessage('⚠️ DUPLICATE INPUTS DETECTED! Attempting to fix...', 'error');
            
            // Find all topic inputs
            var topic = '';
            var allTopicInputs = $modal.find('.unlockafe-modal-topic');
            
            addDebugMessage('Found ' + allTopicInputs.length + ' topic inputs in modal', 'info');
            
            // Strategy: Find the one with a non-empty value first
            allTopicInputs.each(function(index) {
                var currentValue = $(this).val();
                addDebugMessage('Topic input #' + index + ' value: "' + currentValue + '"', 'info');
                
                if (currentValue && currentValue.trim() !== '') {
                    topic = currentValue;
                    addDebugMessage('✅ Found non-empty topic in input #' + index + ': "' + topic + '"', 'success');
                    return false; // Break the each loop
                }
            });
            
            // If still empty, try by placeholder
            if (!topic) {
                $modal.find('input').each(function(index) {
                    if ($(this).attr('placeholder') === 'Enter a topic' && $(this).val()) {
                        topic = $(this).val();
                        addDebugMessage('Found topic by placeholder: "' + topic + '"', 'success');
                        return false; // break
                    }
                });
            }
            
            // Get other values
            var length = $modal.find('.unlockafe-modal-length').val() || 'medium';
            var tone = $modal.find('.unlockafe-modal-tone').val() || 'casual';
            var instructions = $modal.find('.unlockafe-modal-instructions').val() || '';
            
            // Complete advanced debugging checks
            addDebugMessage('--- Topic input summary ---', 'info');
            addDebugMessage('Direct modal topic value: "' + topic + '"', 'info');
            addDebugMessage('Using Topic Length: ' + (topic ? topic.length : 0), 'info');
            addDebugMessage('Length setting: ' + length, 'info');
            addDebugMessage('Tone setting: ' + tone, 'info');
            
            // Trim the topic to handle whitespace correctly
            var originalTopic = topic;
            if (topic) {
                topic = topic.trim();
                addDebugMessage('Topic after trimming: "' + topic + '"', 'info');
                addDebugMessage('Length after trimming: ' + topic.length, 'info');
            }
            
            // Check if topic is empty after trimming - IMPORTANT: NO ALERT HERE FOR TESTING
            if (!topic) {
                addDebugMessage('❌ VALIDATION FAILED: Topic is empty or whitespace only', 'error');
                addDebugMessage('Original value was: "' + originalTopic + '"', 'error');
                
                // Attempt emergency topic value fix
                addDebugMessage('Attempting direct DOM access for topic...', 'info');
                topic = document.querySelector('.unlockafe-modal-topic')?.value || '';
                addDebugMessage('Value from direct DOM: "' + topic + '"', 'info');
                
                if (!topic) {
                    addDebugMessage('❌ EMERGENCY FIX FAILED - CANNOT PROCEED', 'error');
                    // Reset the button but don't close modal to allow user to try again
                    $button.text(originalButtonText);
                    $button.prop('disabled', false);
                    return;
                }
            }
            
            // At this point we should have a valid topic
            addDebugMessage('✅ VALIDATION PASSED: "' + topic + '"', 'success');
            
            // Log additional context
            addDebugMessage('Widget ID: ' + widgetId, 'info');
            
            // Show loading indicator
            var originalButtonText = $button.text();
            $button.html('<span class="unlockafe-loading"></span> Generating...');
            $button.prop('disabled', true);
            
            // Create a structured prompt for OpenAI
            var prompt = 'Create well-structured content about "' + topic + '" for WordPress. ' +
                         'Tone: ' + tone + ', ' +
                         'Length: ' + length;
            
            if (instructions) {
                prompt += '. Additional instructions: ' + instructions;
            }
            
            addDebugMessage('Using prompt: ' + prompt, 'info');
            
            // Get the WordPress AJAX URL
            var ajaxUrl = '';
            if (typeof unlockafe_text_generator !== 'undefined' && unlockafe_text_generator.ajax_url) {
                ajaxUrl = unlockafe_text_generator.ajax_url;
                addDebugMessage('Using AJAX URL from localized script', 'info');
            } else if (typeof ajaxurl !== 'undefined') {
                ajaxUrl = ajaxurl;
                addDebugMessage('Using global ajaxurl variable', 'info');
            } else {
                ajaxUrl = '/wp-admin/admin-ajax.php';
                addDebugMessage('Using fallback AJAX URL path', 'info');
            }
            
            addDebugMessage('AJAX URL: ' + ajaxUrl, 'info');
            
            // Check if we have a nonce - use multiple sources to ensure we find a valid one
            var nonce = '';
            
            // Look for nonce in the localized script data (most reliable)
            if (typeof unlockafe_text_generator !== 'undefined' && unlockafe_text_generator.nonce) {
                nonce = unlockafe_text_generator.nonce;
                addDebugMessage('Using nonce from localized script', 'success');
            }
            // If not available, check for the global variable added via wp_footer
            else if (typeof unlockafe_text_generator_nonce !== 'undefined') {
                nonce = unlockafe_text_generator_nonce;
                addDebugMessage('Using nonce from global variable', 'info');
            }
            // If neither is available, one final check for hidden fields in the DOM
            else if ($('input[name="unlockafe_text_generator_nonce"]').length) {
                nonce = $('input[name="unlockafe_text_generator_nonce"]').val();
                addDebugMessage('Using nonce from hidden field', 'info');
            }
            // If all else fails, log an error but continue with a hardcoded nonce
            else {
                nonce = 'unlockafe_text_generator_nonce';
                addDebugMessage('⚠️ WARNING: Could not find a proper nonce!', 'error');
                addDebugMessage('Please check that the PHP code has properly localized the script', 'error');
            }
            
            // Make the AJAX request
            addDebugMessage('Making AJAX request to WordPress with action: unlockafe_generate_text', 'info');
            addDebugMessage('Nonce value: ' + (nonce ? nonce.substring(0, 6) + '...' : 'MISSING'), nonce ? 'info' : 'error');
            
            $.ajax({
                url: ajaxUrl,
                type: 'POST',
                data: {
                    action: 'unlockafe_generate_text',
                    prompt: prompt,
                    nonce: nonce,
                    debug: showDebug
                },
                success: function(response) {
                    addDebugMessage('Response received!', 'success');
                    addDebugMessage('Raw response: ' + JSON.stringify(response), 'info');
                    
                    // Log WordPress version and server info
                    if (typeof wp !== 'undefined' && wp.version) {
                        addDebugMessage('WordPress version: ' + wp.version, 'info');
                    }
                    
                    if (response.success) {
                        var generatedText = '';
                        
                        if (response.data && response.data.content) {
                            // If we got a structured response with debug info
                            addDebugMessage('Structured response with debug info', 'info');
                            if (response.data.debug) {
                                addDebugMessage('API Provider: ' + response.data.debug.api_provider, 'info');
                                addDebugMessage('Model: ' + response.data.debug.model, 'info');
                            }
                            generatedText = response.data.content;
                        } else {
                            // Simple response
                            generatedText = response.data;
                        }
                        
                        // Apply the generated text
                        addDebugMessage('Updating text content for widget ID: ' + widgetId, 'info');
                        // Only update the specific widget with the matching ID
                        $('.elementor-element-' + widgetId + ' .unlockafe-text-generator-content').html(generatedText);
                        
                        // Update Elementor model if in editor
                        if (window.elementor && widgetId) {
                            try {
                                // Make sure we're only updating the specific widget that was targeted
                                var container = elementor.getContainer(widgetId);
                                if (container) {
                                    var model = container.model;
                                    model.setSetting('placeholder_text', generatedText);
                                    elementor.saver.setFlagEditorChange(true);
                                    addDebugMessage('Updated Elementor model for widget ' + widgetId, 'success');
                                } else {
                                    addDebugMessage('Could not find Elementor container for widget ID: ' + widgetId, 'error');
                                }
                            } catch (e) {
                                addDebugMessage('Error updating Elementor model: ' + e.message, 'error');
                            }
                        }
                    } else {
                        // Handle error with more detailed information
                        addDebugMessage('⚠️ ERROR RESPONSE FROM SERVER', 'error');
                        
                        if (typeof response.data === 'string') {
                            addDebugMessage('Error message: ' + response.data, 'error');
                        } else if (response.data && response.data.message) {
                            addDebugMessage('Error message: ' + response.data.message, 'error');
                            
                            if (response.data.debug) {
                                addDebugMessage('Debug info: ' + JSON.stringify(response.data.debug), 'error');
                            }
                        } else {
                            addDebugMessage('Unknown error format: ' + JSON.stringify(response.data), 'error');
                        }
                        
                        // Show a more user-friendly error on screen
                        if (showDebug) {
                            alert('Error generating text. Please check the debug panel for details.');
                        } else {
                            // More user-friendly error when debug is off
                            var errorMessage = '';
                            
                            if (typeof response.data === 'string') {
                                errorMessage = response.data;
                            } else if (response.data && response.data.message) {
                                errorMessage = response.data.message;
                            } else {
                                errorMessage = 'There was a problem generating text. Please try again.';
                            }
                            
                            alert('Error: ' + errorMessage);
                        }
                    }
                    
                    // Reset button and close modal
                    $button.text(originalButtonText);
                    $button.prop('disabled', false);
                    // Only close the modal if successful, so users can see the debug info on error
                    if (response.success) {
                        TextGenerator.closeModal();
                    }
                },
                error: function(xhr, status, error) {
                    addDebugMessage('⚠️ AJAX ERROR!', 'error');
                    addDebugMessage('Status: ' + status, 'error');
                    addDebugMessage('Error: ' + error, 'error');
                    
                    // Attempt to parse response text if it's JSON
                    var responseText = xhr.responseText || '';
                    addDebugMessage('Response length: ' + responseText.length, 'error');
                    
                    if (responseText.length > 0) {
                        addDebugMessage('First 500 chars of response: ' + responseText.substring(0, 500), 'error');
                        try {
                            var jsonResponse = JSON.parse(responseText);
                            addDebugMessage('Parsed JSON response: ' + JSON.stringify(jsonResponse), 'error');
                        } catch (e) {
                            addDebugMessage('Could not parse response as JSON: ' + e.message, 'error');
                        }
                    }
                    
                    // Try to identify common error patterns
                    if (error === 'Not Found') {
                        addDebugMessage('The AJAX URL may be incorrect or the action not registered', 'error');
                    } else if (xhr.status === 403) {
                        addDebugMessage('Permission denied - check if you are logged in and have proper permissions', 'error');
                    } else if (xhr.status === 0) {
                        addDebugMessage('Network error - check if your server is running', 'error');
                    }
                    
                    // Reset button but keep modal open for debugging
                    $button.text(originalButtonText);
                    $button.prop('disabled', false);
                    
                    // Alert the user
                    alert('Error communicating with the server. Check the debug panel for details.');
                }
            });
        }
    };
    
    // Initialize on document ready
    $(document).ready(function() {
        TextGenerator.init();
    });
    
})(jQuery);
