jQuery(document).ready(function($) {
    'use strict';
    
    /**
     * PayPal Integration Object
     */
    window.WPDD_PayPal = {
        
        init: function() {
            if (typeof paypal !== 'undefined') {
                this.renderPayPalButton();
            }
        },
        
        renderPayPalButton: function() {
            var $container = $('#wpdd-paypal-button');
            
            if (!$container.length) {
                return;
            }
            
            var $form = $container.closest('form');
            
            paypal.Buttons({
                createOrder: function(data, actions) {
                    return WPDD_PayPal.createOrder($form);
                },
                
                onApprove: function(data, actions) {
                    return WPDD_PayPal.captureOrder(data.orderID);
                },
                
                onError: function(err) {
                    console.error('PayPal Error:', err);
                    WPDD_PayPal.showError('Payment processing failed. Please try again.');
                },
                
                onCancel: function(data) {
                    WPDD_PayPal.showNotice('Payment was cancelled.', 'info');
                }
                
            }).render('#wpdd-paypal-button');
        },
        
        createOrder: function($form) {
            return new Promise(function(resolve, reject) {
                var formData = $form.serialize();
                
                $.ajax({
                    url: wpdd_paypal.ajax_url,
                    type: 'POST',
                    data: formData + '&action=wpdd_create_paypal_order&nonce=' + wpdd_paypal.nonce,
                    success: function(response) {
                        if (response.success) {
                            resolve(response.data.orderID);
                        } else {
                            reject(new Error(response.data || 'Failed to create PayPal order'));
                        }
                    },
                    error: function(xhr, status, error) {
                        reject(new Error('Network error: ' + error));
                    }
                });
            });
        },
        
        captureOrder: function(orderID) {
            return new Promise(function(resolve, reject) {
                $.ajax({
                    url: wpdd_paypal.ajax_url,
                    type: 'POST',
                    data: {
                        action: 'wpdd_capture_paypal_order',
                        orderID: orderID,
                        nonce: wpdd_paypal.nonce
                    },
                    success: function(response) {
                        if (response.success) {
                            // Redirect to thank you page
                            window.location.href = response.data.redirect_url;
                        } else {
                            reject(new Error(response.data || 'Failed to capture payment'));
                        }
                    },
                    error: function(xhr, status, error) {
                        reject(new Error('Network error: ' + error));
                    }
                });
            });
        },
        
        showError: function(message) {
            this.showNotice(message, 'error');
        },
        
        showNotice: function(message, type) {
            type = type || 'info';
            
            // Remove existing notices
            $('.wpdd-paypal-notice').remove();
            
            var notice = $('<div class="wpdd-paypal-notice wpdd-notice-' + type + '">' +
                          '<p>' + message + '</p>' +
                          '<button class="wpdd-notice-dismiss">&times;</button>' +
                          '</div>');
            
            $('#wpdd-paypal-button').before(notice);
            
            // Auto-dismiss after 5 seconds
            setTimeout(function() {
                notice.fadeOut(function() {
                    notice.remove();
                });
            }, 5000);
            
            // Manual dismiss
            notice.find('.wpdd-notice-dismiss').on('click', function() {
                notice.fadeOut(function() {
                    notice.remove();
                });
            });
        },
        
        validateForm: function($form) {
            var isValid = true;
            var errors = [];
            
            // Check required fields
            $form.find('input[required]').each(function() {
                var $field = $(this);
                var value = $field.val().trim();
                var fieldName = $field.attr('name') || $field.attr('id');
                
                if (!value) {
                    isValid = false;
                    errors.push(fieldName + ' is required');
                    $field.addClass('error');
                } else {
                    $field.removeClass('error');
                }
            });
            
            // Validate email format
            $form.find('input[type="email"]').each(function() {
                var $field = $(this);
                var value = $field.val().trim();
                var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                
                if (value && !emailRegex.test(value)) {
                    isValid = false;
                    errors.push('Please enter a valid email address');
                    $field.addClass('error');
                }
            });
            
            if (!isValid) {
                this.showError(errors.join('<br>'));
            }
            
            return isValid;
        },
        
        showLoadingState: function() {
            $('#wpdd-paypal-button').addClass('wpdd-loading');
        },
        
        hideLoadingState: function() {
            $('#wpdd-paypal-button').removeClass('wpdd-loading');
        },
        
        disableForm: function($form) {
            $form.find('input, select, button').prop('disabled', true);
        },
        
        enableForm: function($form) {
            $form.find('input, select, button').prop('disabled', false);
        }
    };
    
    // Initialize PayPal integration after object definition
    WPDD_PayPal.init();
    
    // Add PayPal-specific styles
    $('<style>')
        .prop('type', 'text/css')
        .html(`
            #wpdd-paypal-button {
                margin: 20px 0;
                min-height: 45px;
            }
            
            .wpdd-paypal-notice {
                padding: 12px 16px;
                margin-bottom: 15px;
                border-radius: 4px;
                position: relative;
            }
            
            .wpdd-notice-success {
                background: #d4edda;
                color: #155724;
                border: 1px solid #c3e6cb;
            }
            
            .wpdd-notice-error {
                background: #f8d7da;
                color: #721c24;
                border: 1px solid #f5c6cb;
            }
            
            .wpdd-notice-info {
                background: #d1ecf1;
                color: #0c5460;
                border: 1px solid #bee5eb;
            }
            
            .wpdd-notice-dismiss {
                position: absolute;
                top: 8px;
                right: 12px;
                background: none;
                border: none;
                font-size: 16px;
                cursor: pointer;
                color: inherit;
                opacity: 0.7;
                padding: 0;
                line-height: 1;
            }
            
            .wpdd-notice-dismiss:hover {
                opacity: 1;
            }
            
            .wpdd-loading {
                position: relative;
                opacity: 0.6;
                pointer-events: none;
            }
            
            .wpdd-loading::after {
                content: '';
                position: absolute;
                top: 50%;
                left: 50%;
                width: 20px;
                height: 20px;
                margin: -10px 0 0 -10px;
                border: 2px solid #ccc;
                border-top: 2px solid #0073aa;
                border-radius: 50%;
                animation: wpdd-paypal-spin 1s linear infinite;
            }
            
            @keyframes wpdd-paypal-spin {
                0% { transform: rotate(0deg); }
                100% { transform: rotate(360deg); }
            }
            
            input.error {
                border-color: #dc3545 !important;
                box-shadow: 0 0 0 0.2rem rgba(220, 53, 69, 0.25) !important;
            }
            
            .wpdd-checkout-section {
                transition: opacity 0.3s;
            }
            
            .wpdd-checkout-section.disabled {
                opacity: 0.5;
                pointer-events: none;
            }
            
            /* PayPal button container responsive */
            @media (max-width: 400px) {
                #wpdd-paypal-button {
                    min-height: 40px;
                }
            }
            
            /* Form validation styling */
            .wpdd-form-row {
                margin-bottom: 15px;
            }
            
            .wpdd-form-row.has-error input {
                border-color: #dc3545;
            }
            
            .wpdd-field-error {
                color: #dc3545;
                font-size: 12px;
                margin-top: 5px;
                display: none;
            }
            
            .wpdd-form-row.has-error .wpdd-field-error {
                display: block;
            }
        `)
        .appendTo('head');
    
    // Form validation enhancement
    $(document).on('blur', '#wpdd-checkout-form input[required]', function() {
        var $field = $(this);
        var $row = $field.closest('.wpdd-form-row');
        var value = $field.val().trim();
        
        if (!value) {
            $row.addClass('has-error');
        } else {
            $row.removeClass('has-error');
        }
    });
    
    // Real-time email validation
    $(document).on('input', '#wpdd-checkout-form input[type="email"]', function() {
        var $field = $(this);
        var $row = $field.closest('.wpdd-form-row');
        var value = $field.val().trim();
        var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        
        if (value && !emailRegex.test(value)) {
            $row.addClass('has-error');
        } else {
            $row.removeClass('has-error');
        }
    });
    
    // Prevent double-submission
    var formSubmitting = false;
    
    $(document).on('submit', '#wpdd-checkout-form', function(e) {
        if (formSubmitting) {
            e.preventDefault();
            return false;
        }
        
        formSubmitting = true;
        
        // Re-enable after 5 seconds as failsafe
        setTimeout(function() {
            formSubmitting = false;
        }, 5000);
    });
});