/**
 * Feedback form functionality for plugin deactivation.
 * Updated for new two-modal structure without emojis.
 */

(function(jQuery) {
    var currentModal = null;
    var originalDeactivateHref = null;

    jQuery(document).ready(function() {
        mowcps_initializeForms();
        
        jQuery(document).on('click', 'a[href*="deactivate"]', function(e) {
            var href = jQuery(this).attr('href');
            
            if (href.indexOf('products-sync-for-woocommerce') !== -1) {
                e.preventDefault();
                originalDeactivateHref = href;
                moWcpsShowModal('mowcps-feedback-leaving-modal');
                return false;
            }
        });

        if (window.location.href.indexOf('plugins.php') !== -1) {
            jQuery('<button type="button" style="position: fixed; top: 10px; right: 10px; z-index: 9999; background: #0073aa; color: white; border: none; padding: 5px 10px; cursor: pointer;" onclick="window.moWcpsShowModal(\'mowcps-feedback-leaving-modal\')">Test Modal</button>').appendTo('body');
        }

        jQuery(document).on('click', '.mowcps-feedback-overlay', function(e) {
            if (e.target === this) {
                moWcpsCloseModal(jQuery(this).attr('id'));
            }
        });

        jQuery(document).on('keydown', function(e) {
            if (e.key === 'Escape' && currentModal) {
                moWcpsCloseModal(currentModal);
            }
        });

        // Close button click handler - Fix for cross button not working
        jQuery(document).on('click', '#mowcps-modal-close, .mowcps-feedback-close', function(e) {
            e.preventDefault();
            e.stopPropagation();
            moWcpsCloseModal('mowcps-feedback-leaving-modal');
        });
    });

    // Global functions for modal management
    window.moWcpsShowModal = function(modalId) {
        var modal = document.getElementById(modalId);
        if (modal) {
            modal.classList.add('mowcps-active');
            currentModal = modalId;
            document.body.style.overflow = 'hidden';
            
            // Show form state by default for leaving modal
            if (modalId === 'mowcps-feedback-leaving-modal') {
                setTimeout(function() {
                    moWcpsShowModalState(modalStates.FORM);
                }, 100);
            }
        } else {
        }
    };

    window.moWcpsCloseModal = function(modalId) {
        var modal = document.getElementById(modalId);
        if (modal) {
            modal.classList.remove('mowcps-active');
            document.body.style.overflow = 'auto';
            if (currentModal === modalId) {
                currentModal = null;
            }
        }
    };

    window.moWcpsShowDeactivationModal = function() {
        moWcpsCloseModal('mowcps-feedback-leaving-modal');
        setTimeout(function() {
            moWcpsShowModal('mowcps-feedback-deactivation-modal');
        }, 200);
    };

    window.moWcpsSkipAndDeactivate = function() {
        
        // Add loading state to skip & deactivate button
        var skipBtn = document.querySelector('.mowcps-skip-deactivate-btn');
        if (skipBtn) {
            skipBtn.classList.add('mowcps-loading');
            skipBtn.disabled = true;
            skipBtn.textContent = 'Deactivating...';
        }
        
        // Reset form and helpful resources containers
        try {
            document.getElementById('mowcps-deactivation-form').reset();
        } catch (e) {
        }
        
        // Hide helpful resources container
        var helpfulResources = document.getElementById('mowcps-helpful-resources');
        if (helpfulResources) {
            helpfulResources.style.display = 'none';
        }
        
        // Show the general comments box when form is reset
        var generalCommentsBox = document.querySelector('textarea[name="mo-wcps-feedback-reason"]');
        var generalCommentsGroup = generalCommentsBox ? generalCommentsBox.closest('.mowcps-form-group') : null;
        if (generalCommentsGroup) {
            generalCommentsGroup.style.display = 'block';
        }
        
        // Reset checkboxes to their defaults (modal1=checked, modal2=checked)
        var checkbox1 = document.getElementById('contact-checkbox-modal1');
        var checkbox2 = document.getElementById('contact-checkbox-modal2');
        if (checkbox1) {
            checkbox1.checked = true;
        }
        if (checkbox2) {
            checkbox2.checked = true; // Set to checked by default for 2nd modal
        }
        
        // Close modal immediately
        moWcpsCloseModal('mowcps-feedback-deactivation-modal');
        
        // Small delay to ensure modal closes, then proceed with deactivation
        setTimeout(function() {
            if (originalDeactivateHref) {
                window.location.href = originalDeactivateHref;
            } else {
                // Fallback: try to find deactivation link and click it
                var deactivateLink = document.querySelector('a[href*="products-sync-for-woocommerce"][href*="deactivate"]');
                if (deactivateLink) {
                    deactivateLink.click();
                } else {
                    alert('Plugin will be deactivated. Please refresh the page.');
                    window.location.reload();
                }
            }
        }, 300);
    };

    // Setup guides data based on deactivation reasons
    var setupGuides = {
        'pricing': {
            label: ' Pricing & Discount Options',
            options: [
                { value: 'discount-50', text: ' Get 50% OFF - Limited Time Offer', description: 'Special discount available for new customers. Contact our sales team to get your exclusive 50% discount coupon.' },
                { value: 'free-trial', text: ' Extended Free Trial - 30 Days', description: 'Try all premium features free for 30 days. No credit card required. Perfect to test all functionalities.' },
                { value: 'payment-plan', text: ' Flexible Payment Plans Available', description: 'Split your payment into 3 monthly installments. Pay as low as $X/month instead of the full amount upfront.' },
                { value: 'volume-discount', text: ' Volume Discounts for Multiple Sites', description: 'Save up to 40% when licensing for multiple websites. Perfect for agencies and businesses.' }
            ]
        },
        'too-complex': {
            label: ' Setup & Configuration Help',
            options: [
                { value: 'free-setup', text: ' Free Setup Service - We\'ll Do It For You!', description: 'Our experts will set up and configure the plugin for you completely free. Book a 30-minute setup call.' },
                { value: 'video-tutorials', text: ' Step-by-Step Video Tutorials', description: 'Watch our comprehensive video guides that walk you through every step of the setup process.' },
                { value: 'quick-setup', text: ' 5-Minute Quick Setup Guide', description: 'Follow our simplified setup process that gets you up and running in just 5 minutes.' },
                { value: 'live-chat', text: ' Live Chat Support During Setup', description: 'Get real-time help from our support team while you configure the plugin.' }
            ]
        },
        'missing-features': {
            label: ' Available Features & Roadmap',
            options: [
                { value: 'feature-request', text: ' Request Your Needed Feature', description: 'Tell us what you need! We actively develop features based on user requests. Many requests get implemented within 30 days.' },
                { value: 'hidden-features', text: ' Discover Hidden Features', description: 'You might have missed some powerful features. Let us show you advanced capabilities you may not know about.' },
                { value: 'custom-development', text: ' Custom Development Available', description: 'Need something specific? We offer custom development services to build exactly what your business needs.' },
                { value: 'roadmap', text: ' See Our Development Roadmap', description: 'Check out what\'s coming next! Your needed feature might already be in development.' }
            ]
        },
        'not-working': {
            label: '🔧 Technical Support & Fixes',
            options: [
                { value: 'priority-support', text: ' Priority Technical Support', description: 'Get direct access to our senior developers. We\'ll fix your issue within 24 hours guaranteed.' },
                { value: 'compatibility-check', text: ' Free Compatibility Check', description: 'We\'ll check your site for conflicts and provide a free compatibility report with solutions.' },
                { value: 'debug-session', text: ' Free Debug Session', description: 'Schedule a screen-sharing session where our tech team will debug the issue live on your site.' },
                { value: 'alternative-solution', text: ' Alternative Configuration Options', description: 'There might be different ways to achieve what you need. Let us suggest alternative approaches.' }
            ]
        },
        'found-alternative': {
            label: ' Why Users Choose Us Over Alternatives',
            options: [
                { value: 'comparison-chart', text: ' Feature Comparison Chart', description: 'See a detailed comparison of our features vs. alternatives. We often have more capabilities at better prices.' },
                { value: 'migration-help', text: ' Free Migration Back Anytime', description: 'Changed your mind? We\'ll help you migrate back from any alternative plugin completely free.' },
                { value: 'exclusive-features', text: ' Exclusive Features You Won\'t Find Elsewhere', description: 'Discover unique capabilities that only our plugin offers - features that can save you hours of work.' },
                { value: 'price-match', text: ' Price Match Guarantee', description: 'Found the same features cheaper elsewhere? We\'ll match the price and give you an additional 10% discount.' }
            ]
        },
        'performance': {
            label: ' Performance Optimization Help',
            options: [
                { value: 'performance-audit', text: ' Free Performance Audit', description: 'We\'ll analyze your site and provide a detailed report on how to optimize plugin performance.' },
                { value: 'lightweight-mode', text: ' Enable Lightweight Mode', description: 'Activate our performance-optimized mode that reduces resource usage by up to 60%.' },
                { value: 'caching-guide', text: ' Caching Configuration Guide', description: 'Learn how to properly configure caching to work perfectly with our plugin.' },
                { value: 'server-optimization', text: ' Server Optimization Recommendations', description: 'Get personalized server configuration tips to maximize plugin performance.' }
            ]
        },
        'support': {
            label: ' Improved Support Options',
            options: [
                { value: 'priority-support', text: ' Upgrade to Priority Support', description: 'Get responses within 2 hours and direct access to senior support agents.' },
                { value: 'phone-support', text: ' Schedule a Phone Call', description: 'Sometimes a quick call solves everything! Book a 15-minute call with our support team.' },
                { value: 'dedicated-manager', text: ' Assign Dedicated Account Manager', description: 'Get a dedicated support person who knows your setup and history.' },
                { value: 'support-feedback', text: ' Help Us Improve Support', description: 'Tell us exactly what went wrong so we can improve our support process.' }
            ]
        }
    };

    window.moWcpsShowGuideOptions = function(reason) {
        var container = document.getElementById('mowcps-setup-guide-container');
        var select = document.getElementById('mowcps-setup-guide');
        var inputContainer = document.getElementById('mowcps-guide-input-container');
        
        if (!container || !select) {
            console.error('MOWCPS Feedback: Guide container or select not found');
            return;
        }
        
        // Clear previous options
        select.innerHTML = '<option value="" disabled selected>Select a helpful resource</option>';
        
        // Hide input container when changing reason
        if (inputContainer) {
            inputContainer.style.display = 'none';
        }
        
        if (setupGuides[reason]) {
            // Show the container
            container.style.display = 'block';
            
            // Update label
            var label = container.querySelector('label');
            if (label) {
                label.textContent = setupGuides[reason].label;
            }
            
            // Add options
            setupGuides[reason].options.forEach(function(option) {
                var optionElement = document.createElement('option');
                optionElement.value = option.value;
                optionElement.textContent = option.text;
                optionElement.setAttribute('data-description', option.description);
                select.appendChild(optionElement);
            });
            
        } else {
            // Hide the container for reasons without guides
            container.style.display = 'none';
        }
    };
    
    window.moWcpsShowSimpleInput = function(reason) {
        var container = document.getElementById('mowcps-helpful-resources');
        var content = document.getElementById('mowcps-resources-content');
        
        if (!container || !content) {
            return;
        }
        
        
        // Function to hide/show the general "Any comments?" text box
        var generalCommentsBox = document.querySelector('textarea[name="mo-wcps-feedback-reason"]');
        var generalCommentsGroup = generalCommentsBox ? generalCommentsBox.closest('.mowcps-form-group') : null;
        
        // Reasons that should hide the general comments box (updated for new bracket format)
        var hideGeneralComments = ['[missing features]', '[found alternative]','[performance issues]', '[pricing]', '[not working]', '[temporary]'];
        
        if (generalCommentsGroup) {
            if (hideGeneralComments.includes(reason)) {
                generalCommentsGroup.style.display = 'none';
            } else {
                generalCommentsGroup.style.display = 'block';
            }
        }
        
        var contentHtml = '';
        
        switch(reason) {
            case '[missing features]':
                // 1. Input box with specific text
                contentHtml = '<div class="mowcps-reason-input-box">';
                contentHtml += '<label for="missing-features-input">Please let us know which features you are looking for:</label>';
                contentHtml += '<textarea id="missing-features-input" name="custom-feedback" rows="4" placeholder="Describe the features you need..."></textarea>';
                contentHtml += '</div>';
                break;
                
            case '[not working]':
                // Add helpful resources first
                contentHtml = '<div class="mowcps-guides-container">';
                
                contentHtml += '<div class="mowcps-guides-section">';
                contentHtml += '<h4>🔧 Setup Guide:</h4>';
                contentHtml += '<ul><li><a href="https://plugins.miniorange.com/woocommerce-api-product-sync-with-woocommerce-rest-apis#supplier" target="_blank">WooCommerce API Product Sync Guide</a></li></ul>';
                contentHtml += '</div>';
                
                contentHtml += '<div class="mowcps-video-section">';
                contentHtml += '<h4>📹 Video Tutorial:</h4>';
                contentHtml += '<ul><li><a href="https://www.youtube.com/watch?v=V___9DUoJz8" target="_blank">Setup Tutorial Video</a></li></ul>';
                contentHtml += '</div>';
                
                contentHtml += '<div class="mowcps-expert-message">';
                contentHtml += '<span class="mowcps-bulb-icon">💡</span>';
                contentHtml += '<span>If you are still facing issue, reach out to our expert at apisupport@xecurify.com</span>';
                contentHtml += '</div>';
                
                contentHtml += '</div>'; // Close guides container
                
                // Add custom text box AFTER expert message but BEFORE checkbox
                contentHtml += '<div class="mowcps-reason-input-box">';
                contentHtml += '<label for="not-working-input">Tell us what issue you\'re facing:</label>';
                contentHtml += '<textarea id="not-working-input" name="custom-feedback" rows="4" placeholder="Describe the issue you\'re experiencing..."></textarea>';
                contentHtml += '</div>';
                break;
                
            case '[found alternative]':
                // 3. Input box for alternative
                contentHtml = '<div class="mowcps-reason-input-box">';
                contentHtml += '<label for="alternative-input">Tell us which alternative you are going with?</label>';
                contentHtml += '<textarea id="alternative-input" name="custom-feedback" rows="4" placeholder="Which plugin or solution are you switching to..."></textarea>';
                contentHtml += '</div>';
                break;
                
            case '[temporary]':
                // Custom text box for temporary deactivation
                contentHtml = '<div class="mowcps-reason-input-box">';
                contentHtml += '<label for="temporary-input">Let us know the reason for temporary deactivation:</label>';
                contentHtml += '<textarea id="temporary-input" name="custom-feedback" rows="4" placeholder="Tell us why you need to temporarily deactivate..."></textarea>';
                contentHtml += '</div>';
                break;
                
            case '[performance]':
                // 5. Performance tip message in a container box
                contentHtml = '<div class="mowcps-guides-container">';
                contentHtml += '<div class="mowcps-performance-message">';
                contentHtml += '<span class="mowcps-tip-icon">⚡</span>';
                contentHtml += '<span>Try increase memory limit till 1024M for better performance</span>';
                contentHtml += '</div>';
                contentHtml += '</div>';

                //Input box for performance issues
                contentHtml = '<div class="mowcps-reason-input-box">';
                contentHtml += '<label for="alternative-input">Still facing an issue? Share the details</label>';
                contentHtml += '<textarea id="alternative-input" name="custom-feedback" rows="4" placeholder="provide details of the issue..."></textarea>';
                contentHtml += '</div>';
                break;
                
            case '[pricing]':
                // 6. Budget input box + bulb emoji message
                contentHtml = '<div class="mowcps-reason-input-box">';
                contentHtml += '<label for="budget-input">What\'s your budget?</label>';
                contentHtml += '<textarea id="budget-input" name="custom-feedback" rows="3" placeholder="Let us know your budget..."></textarea>';
                contentHtml += '</div>';
                
                contentHtml += '<div class="mowcps-guides-container">';
                contentHtml += '<div class="mowcps-expert-message">';
                contentHtml += '<span class="mowcps-bulb-icon">💡</span>';
                contentHtml += '<span>We offer good discounts to small businesses</span>';
                contentHtml += '</div>';
                contentHtml += '</div>';
                break;
                
            case '[other]':
                // 7. No setup guides/videos for "other" - hide container
                container.style.display = 'none';
                return;
                
            default:
                container.style.display = 'none';
                return;
        }
        
        content.innerHTML = contentHtml;
        container.style.display = 'block';
    };

    window.moWcpsShowSuccessMessage = function(message) {
        // Always show simple message regardless of input
        document.getElementById('mowcps-success-message').textContent = 'Thank you for your feedback!';
        moWcpsShowModal('mowcps-feedback-success-modal');
        
        // Auto close after 2 seconds (reduced from 3 since no OK button)
        setTimeout(function() {
            moWcpsCloseModal('mowcps-feedback-success-modal');
        }, 2000);
    };

    // Professional Modal State Management
    var modalStates = {
        FORM: 'form',
        LOADING: 'loading', 
        SUCCESS: 'success',
        ERROR: 'error'
    };

    var currentAutoCloseTimer = null;
    var countdownInterval = null;

    // Show specific modal state
    function moWcpsShowModalState(state, errorMessage = '') {
        
        // Hide all states first
        jQuery('#mowcps-form-state').hide();
        jQuery('#mowcps-loading-state').hide();
        jQuery('#mowcps-success-state').hide();
        jQuery('#mowcps-error-state').hide();
        
        // Show requested state with animation
        var targetElement;
        switch(state) {
            case modalStates.FORM:
                targetElement = jQuery('#mowcps-form-state');
                break;
            case modalStates.LOADING:
                targetElement = jQuery('#mowcps-loading-state');
                break;
            case modalStates.SUCCESS:
                targetElement = jQuery('#mowcps-success-state');
                moWcpsStartSuccessTimer(); // Start auto-close timer
                break;
            case modalStates.ERROR:
                targetElement = jQuery('#mowcps-error-state');
                if (errorMessage) {
                    jQuery('#mowcps-error-message').text(errorMessage);
                }
                moWcpsStartErrorTimer(); // Auto-hide error after delay
                break;
        }
        
        if (targetElement) {
            targetElement.addClass('mowcps-state-fade-in').show();
            setTimeout(() => {
                targetElement.removeClass('mowcps-state-fade-in');
            }, 400);
        }
    }

    // Success state with auto-close timer
    function moWcpsStartSuccessTimer() {
        let countdown = 6;
        jQuery('#mowcps-countdown').text(countdown);
        
        countdownInterval = setInterval(() => {
            countdown--;
            jQuery('#mowcps-countdown').text(countdown);
            
            if (countdown <= 0) {
                clearInterval(countdownInterval);
                moWcpsCloseModalWithReset();
            }
        }, 1000);
    }

    // Error state with auto-hide timer
    function moWcpsStartErrorTimer() {
        currentAutoCloseTimer = setTimeout(() => {
            moWcpsShowModalState(modalStates.FORM);
        }, 5000);
    }

    // Close modal and reset to initial state
    function moWcpsCloseModalWithReset() {
        
        // Clear any timers
        if (currentAutoCloseTimer) {
            clearTimeout(currentAutoCloseTimer);
            currentAutoCloseTimer = null;
        }
        if (countdownInterval) {
            clearInterval(countdownInterval);
            countdownInterval = null;
        }
        
        // Reset form
        jQuery('#mowcps-contact-form')[0].reset();
        
        // Close modal
        moWcpsCloseModal('mowcps-feedback-leaving-modal');
        
        // Reset to form state for next time
        setTimeout(() => {
            moWcpsShowModalState(modalStates.FORM);
        }, 300);
    }

    // Show form state (for retry button)
    window.moWcpsShowFormState = function() {
        if (currentAutoCloseTimer) {
            clearTimeout(currentAutoCloseTimer);
            currentAutoCloseTimer = null;
        }
        moWcpsShowModalState(modalStates.FORM);
    };

    // Enhanced form validation
    function moWcpsValidateContactForm() {
        const email = jQuery('#mowcps_person_email').val() ? jQuery('#mowcps_person_email').val().trim() : '';
        const message = jQuery('#mowcps-issue-description').val() ? jQuery('#mowcps-issue-description').val().trim() : '';
        
        
        if (!email) {
            moWcpsShowModalState(modalStates.ERROR, 'Please enter your email address.');
            return false;
        }
        
        if (!moWcpsValidateEmail(email)) {
            moWcpsShowModalState(modalStates.ERROR, 'Please enter a valid email address.');
            return false;
        }
        
        if (!message) {
            moWcpsShowModalState(modalStates.ERROR, 'Please describe your issue or question.');
            return false;
        }
        
        if (message.length < 3) { // Further reduced to 3 characters for better UX
            moWcpsShowModalState(modalStates.ERROR, 'Please write your issue or question.');
            return false;
        }
        
        return true;
    }

    // Email validation helper
    function moWcpsValidateEmail(email) {
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return emailRegex.test(email);
    }

    // Initialize form handlers
    function mowcps_initializeForms() {
        // Contact form (first modal) - Professional state management
        jQuery(document).on('submit', '#mowcps-contact-form', function(e) {
            e.preventDefault();
                        
            // Professional form validation
            if (!moWcpsValidateContactForm()) {
                return; // Validation failed, error state already shown
            }
            
            // Get form data
            const userEmail = jQuery('#mowcps_person_email').val() ? jQuery('#mowcps_person_email').val().trim() : '';
            const issueText = jQuery('#mowcps-issue-description').val() ? jQuery('#mowcps-issue-description').val().trim() : '';
            
            
            // Show loading state
            moWcpsShowModalState(modalStates.LOADING);
            
            // Check if contact checkbox is checked for 1st page
            const contactCheckbox = jQuery('#contact-checkbox-modal1').is(':checked');
            
            // Prepare data for expert contact using professional format
            var expertContactData = {
                reason: 'expert_contact',
                comments: issueText,
                user_email: userEmail,
                custom_feedback: '',
                request_contact: contactCheckbox,
                user_config: contactCheckbox ? getUserConfig() : {}, // Only include config if checkbox is checked
                plugin_version: typeof MOWCPS_VERSION !== 'undefined' ? MOWCPS_VERSION : '1.1.0',
                wp_version: window.wp ? window.wp.version : 'Unknown',
                timestamp: new Date().toISOString(),
                source: 'expert_reach_out_box'
            };
            
            
            // REST API submission with state management
            jQuery.ajax({
                url: window.location.origin + '/wp-json/mowcps/v1/user/feedback',
                method: 'POST',
                dataType: 'json',
                contentType: 'application/json',
                headers: {
                    'X-WP-Nonce': typeof MOWCPSFeedbackData !== 'undefined' ? MOWCPSFeedbackData.restNonce : ''
                },
                data: JSON.stringify(expertContactData),
                timeout: 15000,
                success: function(response) {
                    moWcpsShowModalState(modalStates.SUCCESS);
                },
                error: function(xhr, status, error) {
                    
                    let errorMessage = 'There was an issue sending your message. ';
                    if (xhr.status === 403) {
                        errorMessage += 'Security validation failed. Please refresh the page and try again.';
                    } else if (xhr.status === 500) {
                        errorMessage += 'Server error occurred. Your message may have been sent despite this error.';
                    } else if (xhr.status === 0) {
                        errorMessage += 'Network connection issue. Please check your internet connection.';
                    } else {
                        errorMessage += 'Please try again or contact us directly at apisupport@xecurify.com';
                    }
                    
                    moWcpsShowModalState(modalStates.ERROR, errorMessage);
                }
            });
        });

        // Deactivation reason change handler
        jQuery(document).on('change', '#mowcps-feedback-deactivation-reason', function() {
            var selectedReason = jQuery(this).val();
            moWcpsShowSimpleInput(selectedReason);
            
            // Hide "Any comments?" text box for specific reasons - keep only for "Other"
            var hideAnyComments = [
                '[missing features]',
                '[not working]', 
                '[found alternative]',
                '[temporary]',
                '[performance]',
                '[pricing]'
            ];
            
            if (hideAnyComments.includes(selectedReason)) {
                jQuery('textarea[name="mo-wcps-feedback-reason"]').closest('.mowcps-form-group').hide();
            } else {
                jQuery('textarea[name="mo-wcps-feedback-reason"]').closest('.mowcps-form-group').show();
            }
        });

        // Remove old setup guide handler - no longer needed

        // Deactivation form (second modal) - Submit button requires validation
        jQuery(document).on('submit', '#mowcps-deactivation-form', function(e) {
            e.preventDefault();
            
            // Submit button requires reason selection
            var reason = jQuery('#mowcps-feedback-deactivation-reason').val();
            if (!reason) {
                alert('Please select a reason before submitting your feedback.');
                return;
            }

            // Collect all form data including user config
            var customFeedback = jQuery('textarea[name="custom-feedback"]').val() || '';
            // Only check the checkbox for the current modal (modal2 for deactivation form)
            var contactCheckbox = jQuery('#contact-checkbox-modal2').is(':checked');
                        
            var formData = {
                reason: `Contact Expert: ${reason}`,
                comments: jQuery('textarea[name="mowcps-feedback-reason"]').val() || '',
                custom_feedback: customFeedback,
                user_email: '', // Will fallback to admin email in PHP
                request_contact: contactCheckbox,
                user_config: contactCheckbox ? getUserConfig() : {}, // Include config ONLY if checkbox is checked
                plugin_version: typeof MOWCPS_VERSION !== 'undefined' ? MOWCPS_VERSION : '1.1.0',
                wp_version: window.wp ? window.wp.version : 'Unknown',
                timestamp: new Date().toISOString()
            };

            // Add loading state
            addLoadingState(this);
            
            // REST API submission
            jQuery.ajax({
                url: window.location.origin + '/wp-json/mowcps/v1/user/feedback',
                method: 'POST',
                dataType: 'json',
                contentType: 'application/json',
                headers: {
                    'X-WP-Nonce': typeof MOWCPSFeedbackData !== 'undefined' ? MOWCPSFeedbackData.restNonce : ''
                },
                data: JSON.stringify(formData),
                timeout: 15000,
                success: function(response) {
                    removeLoadingState(document.getElementById('mowcps-deactivation-form'));
                    moWcpsCloseModal('mowcps-feedback-deactivation-modal');
                    
                    if (response && response.success) {
                        moWcpsShowSuccessMessage('✅ Perfect! Your feedback has been sent to our expert team. We\'ll reach out to you soon!');
                    } else {
                        moWcpsShowSuccessMessage('📧 Thank you! Your feedback has been received by our expert team.');
                    }
                    resetForm();
                },
                error: function(xhr, status, error) {
                    removeLoadingState(document.getElementById('mowcps-deactivation-form'));
                    moWcpsCloseModal('mowcps-feedback-deactivation-modal');
                    
                    // Always show positive message to user
                    if (xhr.status === 403) {
                        moWcpsShowSuccessMessage('🔐 Feedback sent! Our expert team has your message and will respond soon.');
                    } else if (xhr.status === 500) {
                        moWcpsShowSuccessMessage('📧 Your feedback has been received! Our experts will review it.');
                    } else {
                        moWcpsShowSuccessMessage('✅ Thank you! Your feedback has been submitted to our expert team.');
                    }
                    resetForm();
                }
            });
        });
        
        // Helper function to reset form and containers
        function resetForm() {
            document.getElementById('mowcps-deactivation-form').reset();
            if (document.getElementById('mowcps-helpful-resources')) {
                document.getElementById('mowcps-helpful-resources').style.display = 'none';
            }
            // Show the general comments box when form is reset
            var generalCommentsBox = document.querySelector('textarea[name="mo-wcps-feedback-reason"]');
            var generalCommentsGroup = generalCommentsBox ? generalCommentsBox.closest('.mowcps-form-group') : null;
            if (generalCommentsGroup) {
                generalCommentsGroup.style.display = 'block';
            }
            // Reset checkboxes to their defaults
            var checkbox1 = document.getElementById('contact-checkbox-modal1');
            var checkbox2 = document.getElementById('contact-checkbox-modal2');
            if (checkbox1) {
                checkbox1.checked = true;
            }
            if (checkbox2) {
                checkbox2.checked = true; // Set to checked by default for 2nd modal
            }
        }
        
        // Function to collect user configuration details
        function getUserConfig() {
            var config = {
                url: window.location.origin,
                userAgent: navigator.userAgent,
                screenResolution: screen.width + 'x' + screen.height,
                browserLanguage: navigator.language,
                timezone: Intl.DateTimeFormat().resolvedOptions().timeZone
            };
            
            // Try to get WordPress and plugin specific info
            if (window.adminpage) {
                config.adminPage = window.adminpage;
            }
            
            if (window.pagenow) {
                config.currentPage = window.pagenow;
            }
            
            return config;
        }
    }

    // Add loading state to form
    function addLoadingState(form) {
        jQuery(form).addClass('mowcps-loading');
        var submitBtn = jQuery(form).find('button[type="submit"]');
        if (submitBtn.length) {
            submitBtn.prop('disabled', true);
            submitBtn.data('original-text', submitBtn.text());
            submitBtn.text('Sending...');
        }
    }

    // Remove loading state from form
    function removeLoadingState(form) {
        jQuery(form).removeClass('mowcps-loading');
        var submitBtn = jQuery(form).find('button[type="submit"]');
        if (submitBtn.length) {
            submitBtn.prop('disabled', false);
            if (submitBtn.data('original-text')) {
                submitBtn.text(submitBtn.data('original-text'));
            }
        }
    }

    // Backward compatibility functions
    window.moWcpsShowModal = window.moWcpsShowModal;
    window.moWcpsHideModal = function() {
        if (currentModal) {
            moWcpsCloseModal(currentModal);
        }
    };

})(jQuery); 

