/**
 * Xeep Onboarding Form JavaScript
 * Debug Version with Enhanced Event Handling
 */

(function($) {
    'use strict';
    
    // ===== DEBUG MODE - Enable WordPress Debug Logging =====
    var DEBUG = true;
    function debugLog(message, data) {
        if (DEBUG) {
            if (data !== undefined) {
                console.log('[XEEP DEBUG] ' + message, data);
            } else {
                console.log('[XEEP DEBUG] ' + message);
            }
        }
    }
    
    // ===== GLOBAL STATE =====
    // Make selectedServices globally accessible
    window.xeepSelectedServices = window.xeepSelectedServices || [];
    
    debugLog('Script loaded. jQuery version:', $.fn.jquery);
    debugLog('Initial selectedServices:', window.xeepSelectedServices);
    
    // ===== SERVICE SELECTION HANDLER (STANDALONE - OUTSIDE document.ready) =====
    // This ensures the handler is bound even if Elementor loads widgets dynamically
    
    function handleServiceClick($btn) {
        var serviceId = String($btn.attr('data-service-id') || $btn.data('service-id'));
        var serviceName = $btn.attr('data-service-name') || $btn.data('service-name');
        var servicePrice = parseFloat($btn.attr('data-service-price') || $btn.data('service-price')) || 0;
        var textAdd = $btn.attr('data-text-add') || $btn.data('text-add') || 'Add to Cart';
        var textRemove = $btn.attr('data-text-remove') || $btn.data('text-remove') || 'Remove';
        
        debugLog('=== SERVICE BUTTON CLICKED ===');
        debugLog('Service ID:', serviceId);
        debugLog('Service Name:', serviceName);
        debugLog('Service Price:', servicePrice);
        debugLog('Current cart:', window.xeepSelectedServices);
        
        if (!serviceId || serviceId === 'undefined') {
            debugLog('ERROR: Invalid service ID!');
            console.error('[XEEP] Invalid service ID on button:', $btn[0]);
            return false;
        }
        
        // Find if service already in cart
        var existingIndex = -1;
        for (var i = 0; i < window.xeepSelectedServices.length; i++) {
            if (String(window.xeepSelectedServices[i].service_id) === serviceId) {
                existingIndex = i;
                break;
            }
        }
        
        debugLog('Existing index in cart:', existingIndex);
        
        if (existingIndex >= 0) {
            // Remove from cart
            window.xeepSelectedServices.splice(existingIndex, 1);
            $btn.text(textAdd).removeClass('selected');
            $btn.closest('.xeep-service-card').removeClass('service-selected');
            debugLog('REMOVED from cart:', serviceName);
        } else {
            // Add to cart
            window.xeepSelectedServices.push({
                service_id: serviceId,
                service_name: serviceName,
                price: servicePrice,
                qty: 1,
                status: 'pending'
            });
            $btn.text(textRemove).addClass('selected');
            $btn.closest('.xeep-service-card').addClass('service-selected');
            debugLog('ADDED to cart:', serviceName);
        }
        
        debugLog('Updated cart:', window.xeepSelectedServices);
        
        // Update order summary
        updateOrderSummary();
        
        return true;
    }
    
    // ===== ORDER SUMMARY UPDATE FUNCTION =====
    function updateOrderSummary() {
        debugLog('Updating order summary...');
        
        var itemsContainer = $('#order-summary-items');
        var totalEl = $('.xeep-order-total');
        var checkoutContainer = $('.xeep-checkout');
        var emptyText = checkoutContainer.data('empty-text') || 'No services selected';
        
        debugLog('Found items container:', itemsContainer.length);
        debugLog('Found total element:', totalEl.length);
        
        // Clear existing items
        itemsContainer.empty();
        
        if (window.xeepSelectedServices.length === 0) {
            itemsContainer.html(
                '<div class="xeep-order-empty">' +
                    '<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">' +
                        '<circle cx="9" cy="21" r="1"/>' +
                        '<circle cx="20" cy="21" r="1"/>' +
                        '<path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"/>' +
                    '</svg>' +
                    '<p>' + emptyText + '</p>' +
                '</div>'
            );
            totalEl.text('₦0.00');
            debugLog('Cart is empty, showing empty state');
        } else {
            var total = 0;
            window.xeepSelectedServices.forEach(function(service, index) {
                total += service.price;
                var itemHtml = 
                    '<div class="xeep-order-item" data-index="' + index + '">' +
                        '<span class="xeep-order-item-name">' + service.service_name + '</span>' +
                        '<span class="xeep-order-item-price">' + xeepFormatCurrency(service.price) + '</span>' +
                        '<button type="button" class="xeep-order-item-remove" data-service-id="' + service.service_id + '" title="Remove">' +
                            '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">' +
                                '<line x1="18" y1="6" x2="6" y2="18"></line>' +
                                '<line x1="6" y1="6" x2="18" y2="18"></line>' +
                            '</svg>' +
                        '</button>' +
                    '</div>';
                itemsContainer.append(itemHtml);
            });
            
            totalEl.text(xeepFormatCurrency(total));
            debugLog('Updated total:', total);
        }
        
        // Enable/disable payment buttons
        var hasItems = window.xeepSelectedServices.length > 0;
        $('.xeep-pay-paystack, .xeep-pay-flutterwave, .xeep-pay-offline').prop('disabled', !hasItems);
        debugLog('Payment buttons enabled:', hasItems);
    }
    
    // Make updateOrderSummary globally accessible
    window.xeepUpdateOrderSummary = updateOrderSummary;
    
    // ===== BIND EVENT HANDLER USING MULTIPLE METHODS FOR MAXIMUM COMPATIBILITY =====
    
    // Method 1: Direct document-level delegation (most reliable)
    $(document).on('click.xeepService', '.xeep-add-service', function(e) {
        debugLog('Event triggered via $(document).on()');
        e.preventDefault();
        e.stopPropagation();
        handleServiceClick($(this));
        return false;
    });
    
    // Method 2: Also bind on body as fallback
    $('body').on('click.xeepService', '.xeep-add-service', function(e) {
        debugLog('Event triggered via $("body").on()');
        e.preventDefault();
        e.stopPropagation();
        handleServiceClick($(this));
        return false;
    });
    
    debugLog('Service button event handlers bound');
    
    // ===== ELEMENTOR FRONTEND INTEGRATION =====
    // Re-bind events when Elementor widgets are loaded/reloaded
    $(window).on('elementor/frontend/init', function() {
        debugLog('Elementor frontend init detected');
        
        if (typeof elementorFrontend !== 'undefined') {
            elementorFrontend.hooks.addAction('frontend/element_ready/widget', function($element) {
                debugLog('Elementor widget ready:', $element.data('widget_type'));
                
                // Check if this is our services widget
                if ($element.find('.xeep-add-service').length > 0) {
                    debugLog('Services widget detected, buttons found:', $element.find('.xeep-add-service').length);
                }
            });
        }
    });
    
    // ===== DOCUMENT READY - FORM AND OTHER FUNCTIONALITY =====
    $(document).ready(function() {
        debugLog('Document ready fired');
        
        const form = $('#xeep-onboarding-form');
        let currentStep = 1;
        let aiKeywords = [];
        
        // Log all service buttons found
        var serviceButtons = $('.xeep-add-service');
        debugLog('Service buttons found on page:', serviceButtons.length);
        serviceButtons.each(function(index) {
            debugLog('Button ' + index + ':', {
                id: $(this).attr('data-service-id'),
                name: $(this).attr('data-service-name'),
                price: $(this).attr('data-service-price')
            });
        });
        
        // ===== Step navigation =====
        $(document).on('click', '.xeep-btn-next', function() {
            if (validateStep(currentStep)) {
                goToStep(currentStep + 1);
            }
        });
        
        $(document).on('click', '.xeep-btn-prev', function() {
            goToStep(currentStep - 1);
        });
        
        // Sidebar step navigation
        $(document).on('click', '.xeep-step-item', function() {
            const step = parseInt($(this).data('step'));
            if (step < currentStep || validateStep(currentStep)) {
                goToStep(step);
            }
        });
        
        function goToStep(step) {
            $('.xeep-form-step').removeClass('active');
            $(`.xeep-form-step[data-step="${step}"]`).addClass('active');
            
            $('.xeep-step-item').removeClass('active completed');
            $('.xeep-step-item').each(function() {
                const itemStep = parseInt($(this).data('step'));
                if (itemStep < step) {
                    $(this).addClass('completed');
                } else if (itemStep === step) {
                    $(this).addClass('active');
                }
            });
            
            currentStep = step;
            
            const totalSteps = $('.xeep-form-step').length;
            const progress = Math.round((step / totalSteps) * 100);
            $('.xeep-progress-fill').css('width', progress + '%');
            $('.xeep-progress-text').text(progress + '%');
            
            $('html, body').animate({
                scrollTop: $('.xeep-onboarding-container').offset().top - 20
            }, 300);
        }
        
        // Initialize progress bar if form exists
        if (form.length > 0) {
            goToStep(1);
        }
        
        function validateStep(step) {
            const stepEl = $(`.xeep-form-step[data-step="${step}"]`);
            const requiredFields = stepEl.find('[required]');
            let valid = true;
            
            requiredFields.each(function() {
                if (!$(this).val()) {
                    $(this).addClass('error');
                    valid = false;
                } else {
                    $(this).removeClass('error');
                }
            });
            
            if (!valid) {
                alert('Please fill in all required fields');
            }
            
            return valid;
        }
        
        // ===== Business Name Toggle Switch =====
        $('#xeep-business-name-toggle').on('change', function() {
            const isAiMode = $(this).is(':checked');
            if (isAiMode) {
                $('#xeep-ai-business-name-container').slideDown(200);
                $('#xeep-manual-business-name-container').slideUp(200);
                $('.xeep-toggle-label-manual').removeClass('active');
                $('.xeep-toggle-label-ai').addClass('active');
            } else {
                $('#xeep-ai-business-name-container').slideUp(200);
                $('#xeep-manual-business-name-container').slideDown(200);
                $('.xeep-toggle-label-manual').addClass('active');
                $('.xeep-toggle-label-ai').removeClass('active');
            }
        });
        
        // Name style selection
        let selectedNameStyle = 'modern';
        $(document).on('click', '.xeep-name-style-btn', function() {
            $('.xeep-name-style-btn').removeClass('active');
            $(this).addClass('active');
            selectedNameStyle = $(this).data('style');
        });
        
        // ===== AI Keywords Management =====
        const keywordInput = $('#xeep-keyword-input');
        const keywordsTags = $('#xeep-keywords-tags');
        const keywordsHidden = $('#ai_keywords');
        
        function updateKeywordsDisplay() {
            keywordsTags.empty();
            aiKeywords.forEach(function(keyword, index) {
                const tag = $(
                    '<span class="xeep-keyword-tag">' +
                        keyword +
                        '<button type="button" class="xeep-keyword-remove" data-index="' + index + '">&times;</button>' +
                    '</span>'
                );
                keywordsTags.append(tag);
            });
            keywordsHidden.val(aiKeywords.join(','));
        }
        
        function addKeyword(keyword) {
            keyword = keyword.trim().toLowerCase();
            if (keyword && !aiKeywords.includes(keyword) && aiKeywords.length < 5) {
                aiKeywords.push(keyword);
                updateKeywordsDisplay();
            }
        }
        
        keywordInput.on('keydown', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                addKeyword($(this).val());
                $(this).val('');
            }
        });
        
        $(document).on('click', '.xeep-keyword-remove', function() {
            const index = $(this).data('index');
            aiKeywords.splice(index, 1);
            updateKeywordsDisplay();
        });
        
        $(document).on('click', '.xeep-keyword-suggestion', function() {
            addKeyword($(this).data('keyword'));
        });
        
        // ===== AI Business Name Generation =====
        $(document).on('click', '#xeep-generate-names', function() {
            const btn = $(this);
            const container = $('#xeep-name-suggestions');
            const loadingEl = $('#xeep-ai-loading');
            
            if (aiKeywords.length === 0) {
                alert('Please add at least one keyword to generate names');
                return;
            }
            
            btn.prop('disabled', true).addClass('loading');
            container.empty();
            loadingEl.show();
            
            animateLoadingSteps();
            
            $('#name_style').val(selectedNameStyle);
            
            const formData = {
                keywords: aiKeywords,
                name_style: selectedNameStyle,
                business_description: $('textarea[name="business_description"]').val(),
                industry: $('select[name="business_industry"]').val(),
                max_results: 8,
                deep_research: true
            };
            
            $.ajax({
                url: xeepData.restUrl + 'suggest-names-advanced',
                method: 'POST',
                contentType: 'application/json',
                beforeSend: function(xhr) {
                    xhr.setRequestHeader('X-WP-Nonce', xeepData.nonce);
                },
                data: JSON.stringify(formData),
                success: function(response) {
                    displayAdvancedNameSuggestions(response);
                },
                error: function(xhr) {
                    container.html('<div class="xeep-error">Failed to generate suggestions. Please try again.</div>');
                },
                complete: function() {
                    btn.prop('disabled', false).removeClass('loading');
                    loadingEl.hide();
                    resetLoadingSteps();
                }
            });
        });
        
        function animateLoadingSteps() {
            const steps = ['generate', 'research', 'verify'];
            let index = 0;
            
            const interval = setInterval(function() {
                if (index >= steps.length) {
                    clearInterval(interval);
                    return;
                }
                
                $(`.xeep-loading-step[data-step="${steps[index]}"]`).addClass('active');
                
                const statusMessages = {
                    'generate': 'Generating creative names with AI...',
                    'research': 'Researching web for existing usage...',
                    'verify': 'Verifying uniqueness...'
                };
                $('#xeep-loading-status').text(statusMessages[steps[index]]);
                
                index++;
            }, 1500);
        }
        
        function resetLoadingSteps() {
            $('.xeep-loading-step').removeClass('active');
        }
        
        function displayAdvancedNameSuggestions(suggestions) {
            const container = $('#xeep-name-suggestions');
            container.empty();
            
            if (!suggestions || suggestions.length === 0) {
                container.html('<p class="xeep-no-results">No unique names found. Try different keywords.</p>');
                return;
            }
            
            suggestions.forEach(function(suggestion, index) {
                const uniquenessClass = getUniquenessClass(suggestion.uniqueness_score);
                const card = $(
                    '<div class="xeep-name-card xeep-name-card-advanced" style="animation-delay: ' + (index * 0.1) + 's">' +
                        '<div class="xeep-name-header">' +
                            '<h4>' + suggestion.name + '</h4>' +
                            '<span class="xeep-uniqueness-badge ' + uniquenessClass + '">' +
                                suggestion.uniqueness_score + '% Unique' +
                            '</span>' +
                        '</div>' +
                        '<p class="xeep-rationale">' + suggestion.rationale + '</p>' +
                        (suggestion.web_research ? 
                            '<div class="xeep-research-status">' +
                                '<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">' +
                                    '<path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/>' +
                                    '<polyline points="22 4 12 14.01 9 11.01"/>' +
                                '</svg>' +
                                '<span>' + suggestion.web_research + '</span>' +
                            '</div>' : '') +
                        '<button type="button" class="xeep-btn xeep-btn-sm xeep-select-business-name" data-name="' + suggestion.name + '">' +
                            'Use This Name' +
                        '</button>' +
                    '</div>'
                );
                
                container.append(card);
            });
        }
        
        function getUniquenessClass(score) {
            if (score >= 90) return 'xeep-uniqueness-excellent';
            if (score >= 70) return 'xeep-uniqueness-good';
            if (score >= 50) return 'xeep-uniqueness-fair';
            return 'xeep-uniqueness-low';
        }
        
        // Select AI-generated business name
        $(document).on('click', '.xeep-select-business-name', function() {
            const name = $(this).data('name');
            $('input[name="business_name"]').val(name);
            
            $('input[name="business_name_method"][value="manual"]').prop('checked', true).trigger('change');
            
            $('.xeep-select-business-name').removeClass('selected').text('Use This Name');
            $(this).addClass('selected').text('Selected ✓');
        });
        
        // ===== Domain Check =====
        let domainCheckTimeout;
        $('input[name="preferred_domain_input"]').on('input', function() {
            clearTimeout(domainCheckTimeout);
            const input = $(this).val();
            
            if (input.length > 2) {
                domainCheckTimeout = setTimeout(function() {
                    checkDomainAvailability(input);
                }, 500);
            }
        });
        
        $(document).on('click', '#xeep-check-domain', function() {
            const domain = $('input[name="preferred_domain_input"]').val();
            if (domain) {
                checkDomainAvailability(domain);
            }
        });
        
        function checkDomainAvailability(domain) {
            const resultsContainer = $('#xeep-domain-results');
            resultsContainer.html('<div class="xeep-loading">Checking availability...</div>');
            
            $.ajax({
                url: xeepData.restUrl + 'check-domain',
                method: 'GET',
                data: { domain: domain },
                success: function(response) {
                    displayDomainResults(response);
                },
                error: function() {
                    resultsContainer.html('<div class="xeep-error">Failed to check domain</div>');
                }
            });
        }
        
        function displayDomainResults(results) {
            const container = $('#xeep-domain-results');
            container.empty();
            
            if (Array.isArray(results)) {
                results.forEach(function(domain) {
                    const item = $('<div class="xeep-domain-result">');
                    item.append('<span class="domain-name">' + domain.domain + '</span>');
                    item.append('<span class="domain-price">' + xeepFormatCurrency(domain.price_hint) + '</span>');
                    
                    if (domain.available) {
                        item.append('<span class="xeep-badge xeep-badge-success">Available</span>');
                        item.append('<button type="button" class="xeep-btn-sm xeep-select-domain" data-domain="' + domain.domain + '">Select</button>');
                    } else {
                        item.append('<span class="xeep-badge xeep-badge-danger">Not Available</span>');
                    }
                    
                    container.append(item);
                });
            }
        }
        
        // Domain selection
        $(document).on('click', '.xeep-select-domain', function() {
            const domain = $(this).data('domain');
            $('#selected_domain').val(domain);
            $('input[name="preferred_domain_input"]').val(domain.split('.')[0]);
            
            $('.xeep-select-domain').removeClass('selected').text('Select');
            $(this).addClass('selected').text('Selected ✓');
            
            $(this).closest('.xeep-domain-result').addClass('selected');
        });
        
        // ===== Remove item from order summary =====
        $(document).on('click', '.xeep-order-item-remove', function(e) {
            e.preventDefault();
            const serviceId = String($(this).data('service-id'));
            debugLog('Removing item from order summary:', serviceId);
            
            // Find and remove from selectedServices
            var index = -1;
            for (var i = 0; i < window.xeepSelectedServices.length; i++) {
                if (String(window.xeepSelectedServices[i].service_id) === serviceId) {
                    index = i;
                    break;
                }
            }
            
            if (index >= 0) {
                window.xeepSelectedServices.splice(index, 1);
            }
            
            // Update the service card button
            const serviceBtn = $('.xeep-add-service[data-service-id="' + serviceId + '"]');
            const textAdd = serviceBtn.attr('data-text-add') || serviceBtn.data('text-add') || 'Add to Cart';
            serviceBtn.text(textAdd).removeClass('selected');
            serviceBtn.closest('.xeep-service-card').removeClass('service-selected');
            
            updateOrderSummary();
        });
        
        // ===== Offline Payment Modal =====
        $(document).on('click', '.xeep-pay-offline', function(e) {
            e.preventDefault();
            
            if (window.xeepSelectedServices.length === 0) {
                alert('Please select at least one service');
                return;
            }
            
            $('#xeep-offline-payment-modal').addClass('active');
        });
        
        // Close offline payment modal
        $(document).on('click', '.xeep-modal-close, .xeep-modal-overlay', function(e) {
            if (e.target === this) {
                $('#xeep-offline-payment-modal').removeClass('active');
            }
        });
        
        // Copy bank details
        $(document).on('click', '.xeep-copy-btn', function() {
            const text = $(this).data('copy');
            navigator.clipboard.writeText(text).then(function() {
                const btn = $(this);
                const originalText = btn.text();
                btn.text('Copied!');
                setTimeout(function() {
                    btn.text(originalText);
                }, 2000);
            }.bind(this));
        });
        
        // Confirm offline payment
        $(document).on('click', '#xeep-confirm-offline-payment', function() {
            const btn = $(this);
            btn.prop('disabled', true).text('Processing...');
            submitOrder('offline');
        });
        
        // ===== Payment Methods =====
        $(document).on('click', '.xeep-pay-paystack', function(e) {
            e.preventDefault();
            if (window.xeepSelectedServices.length === 0) {
                alert('Please select at least one service');
                return;
            }
            submitOrder('paystack');
        });
        
        $(document).on('click', '.xeep-pay-flutterwave', function(e) {
            e.preventDefault();
            if (window.xeepSelectedServices.length === 0) {
                alert('Please select at least one service');
                return;
            }
            submitOrder('flutterwave');
        });
        
        function submitOrder(paymentMethod) {
            const formData = new FormData(form[0]);
            formData.append('services', JSON.stringify(window.xeepSelectedServices));
            formData.append('payment_method', paymentMethod);
            
            $.ajax({
                url: xeepData.restUrl + 'submit-order',
                method: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                beforeSend: function(xhr) {
                    xhr.setRequestHeader('X-WP-Nonce', xeepData.nonce);
                },
                success: function(response) {
                    if (response.payment_url) {
                        window.location.href = response.payment_url;
                    } else if (response.redirect_url) {
                        window.location.href = response.redirect_url;
                    } else if (response.order_id) {
                        $('#xeep-offline-payment-modal').removeClass('active');
                        alert('Order submitted successfully! Order ID: ' + response.order_id);
                    }
                },
                error: function(xhr) {
                    alert('Failed to submit order. Please try again.');
                    $('#xeep-confirm-offline-payment').prop('disabled', false).text('I Have Made the Payment');
                }
            });
        }
        
        // ===== Form Submission =====
        form.on('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            formData.append('services', JSON.stringify(window.xeepSelectedServices));
            
            $.ajax({
                url: xeepData.restUrl + 'submit-onboarding',
                method: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                beforeSend: function(xhr) {
                    xhr.setRequestHeader('X-WP-Nonce', xeepData.nonce);
                },
                success: function(response) {
                    if (response.redirect_url) {
                        window.location.href = response.redirect_url;
                    }
                },
                error: function(xhr) {
                    alert('Failed to submit form. Please try again.');
                }
            });
        });
        
        // Initialize order summary
        updateOrderSummary();
        
        debugLog('Document ready complete. Total service buttons:', $('.xeep-add-service').length);
    });
    
    // ===== Helper function for currency formatting =====
    window.xeepFormatCurrency = function(amount) {
        return '₦' + parseFloat(amount).toLocaleString('en-NG', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
    };
    
    // ===== NATIVE EVENT LISTENER AS ULTIMATE FALLBACK =====
    // This uses vanilla JS to ensure event binding works even if jQuery delegation fails
    document.addEventListener('click', function(e) {
        var target = e.target;
        
        // Check if clicked element or parent is the add service button
        var btn = target.closest('.xeep-add-service');
        if (btn) {
            console.log('[XEEP DEBUG] Native click handler triggered');
            e.preventDefault();
            e.stopPropagation();
            handleServiceClick($(btn));
        }
    }, true); // Use capture phase
    
    console.log('[XEEP DEBUG] Native event listener added');
    
})(jQuery);
