(function($) {
    'use strict';

    // Wait for the DOM to be ready
    $(document).ready(function() {
        // Initialize Stripe
        const stripe = Stripe(subscription_checkout_data.stripe_key);
        const elements = stripe.elements();
        
        // Create card element
        const cardElement = elements.create('card', {
            style: {
                base: {
                    color: '#32325d',
                    fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
                    fontSmoothing: 'antialiased',
                    fontSize: '16px',
                    '::placeholder': {
                        color: '#aab7c4'
                    }
                },
                invalid: {
                    color: '#fa755a',
                    iconColor: '#fa755a'
                }
            }
        });
        
        // Mount the card element
        cardElement.mount('#card-element');
        
        // Handle form submission
        const form = document.getElementById('subscription-payment-form');
        form.addEventListener('submit', async (event) => {
            event.preventDefault();
            
            // Disable the submit button to prevent multiple submissions
            document.getElementById('submit-payment').disabled = true;
            document.getElementById('payment-processing').style.display = 'block';
            
            // Get customer data
            const customerData = {
                name: document.getElementById('customer_name').value,
                email: document.getElementById('customer_email').value
            };
            
            // Create payment method
            createPaymentMethod(stripe, cardElement, customerData);
        });
        
        // Create a payment method and handle the next steps
        function createPaymentMethod(stripe, cardElement, customerData) {
            stripe.createPaymentMethod({
                type: 'card',
                card: cardElement,
                billing_details: {
                    name: customerData.name,
                    email: customerData.email
                }
            }).then(function(result) {
                if (result.error) {
                    // Show error in the form
                    const errorElement = document.getElementById('card-errors');
                    errorElement.textContent = result.error.message;
                    
                    // Re-enable the submit button
                    document.getElementById('submit-payment').disabled = false;
                    document.getElementById('payment-processing').style.display = 'none';
                } else {
                    // Send the payment method ID to your server
                    processPayment(result.paymentMethod.id, customerData);
                }
            });
        }
        
        // Process the payment on the server
        function processPayment(paymentMethodId, customerData) {
            // Show processing state
            document.getElementById('payment-processing').style.display = 'block';
            
            console.log('Processing payment with method ID:', paymentMethodId);
            console.log('Customer data:', customerData);
            
            // Clear any previous errors
            document.getElementById('card-errors').textContent = '';
            
            $.ajax({
                url: subscription_checkout_data.ajax_url,
                type: 'POST',
                data: {
                    action: 'process_subscription_payment',
                    payment_method_id: paymentMethodId,
                    plan_id: subscription_checkout_data.plan_id,
                    customer_name: customerData.name,
                    customer_email: customerData.email,
                    nonce: subscription_checkout_data.nonce
                },
                success: function(response) {
                    console.log('Payment response:', response);
                    
                    if (response.success) {
                        if (response.data.checkout_url) {
                            // Redirect to Stripe Checkout
                            window.location.href = response.data.checkout_url;
                        } else if (response.data.requires_action) {
                            // Handle 3D Secure authentication
                            if (response.data.redirect_url) {
                                console.log('Redirecting to:', response.data.redirect_url);
                                window.location.href = response.data.redirect_url;
                                return;
                            }
                            
                            console.log('Handling with Stripe.js');
                            handleCardPayment(response.data.client_secret, customerData);
                        } else {
                            // Handle successful payment
                            handlePaymentSuccess(response.data);
                        }
                    } else {
                        console.error('Payment error:', response.data);
                        handlePaymentError(response.data);
                    }
                },
                error: function(xhr, status, error) {
                    console.error('AJAX error:', status, error);
                    console.error('Response:', xhr.responseText);
                    
                    // Try to parse the response to see if it contains HTML
                    var errorMessage = 'An error occurred while processing your payment. Please try again.';
                    
                    if (xhr.responseText) {
                        if (xhr.responseText.indexOf('<') === 0) {
                            errorMessage += ' (Server returned HTML instead of JSON)';
                            // Log the first 200 characters of the response for debugging
                            console.error('Response preview:', xhr.responseText.substring(0, 200));
                        } else {
                            try {
                                var jsonResponse = JSON.parse(xhr.responseText);
                                if (jsonResponse.message) {
                                    errorMessage = jsonResponse.message;
                                }
                            } catch (e) {
                                errorMessage += ' (Error: ' + error + ')';
                            }
                        }
                    }
                    
                    handlePaymentError({
                        message: errorMessage
                    });
                },
                complete: function() {
                    // This will run regardless of success or error
                    console.log('AJAX request completed');
                }
            });
        }
        
        // Handle card payment for 3D Secure or other authentication
        function handleCardPayment(clientSecret, customerData) {
            stripe.confirmCardPayment(clientSecret).then(function(result) {
                if (result.error) {
                    // Show error in payment form
                    handlePaymentError({
                        message: result.error.message
                    });
                } else {
                    // The payment has been processed!
                    if (result.paymentIntent.status === 'succeeded') {
                        // Show success message and redirect
                        handlePaymentSuccess({
                            message: 'Payment successful!',
                            redirect_url: subscription_checkout_data.success_url || '/my-account/'
                        });
                    } else {
                        // Handle other statuses
                        handlePaymentError({
                            message: 'Payment processing failed. Please try again.'
                        });
                    }
                }
            });
        }
        
        // Handle successful payment
        function handlePaymentSuccess(data) {
            // Hide the form
            document.getElementById('subscription-payment-form').style.display = 'none';
            
            // Show success message
            const resultElement = document.getElementById('payment-result');
            resultElement.innerHTML = '<div class="ss-payment-success">' +
                '<h3>Payment Successful!</h3>' +
                '<p>' + (data.message || 'Your subscription has been processed successfully.') + '</p>' +
                '<p><a href="' + data.redirect_url + '" class="ss-button">View Your Subscription</a></p>' +
                '</div>';
            resultElement.style.display = 'block';
            
            // Scroll to the result
            $('html, body').animate({
                scrollTop: $(resultElement).offset().top - 100
            }, 500);
            
            // Redirect after a delay
            setTimeout(function() {
                window.location.href = data.redirect_url;
            }, 5000);
        }
        
        // Handle payment error
        function handlePaymentError(data) {
            // Show error message
            const resultElement = document.getElementById('payment-result');
            resultElement.innerHTML = '<div class="ss-payment-error">' +
                '<h3>Payment Failed</h3>' +
                '<p>' + data.message + '</p>' +
                '<p><button id="try-again" class="ss-button">Try Again</button></p>' +
                '</div>';
            resultElement.style.display = 'block';
            
            // Re-enable the submit button
            document.getElementById('submit-payment').disabled = false;
            document.getElementById('payment-processing').style.display = 'none';
            
            // Scroll to the error
            $('html, body').animate({
                scrollTop: $(resultElement).offset().top - 100
            }, 500);
            
            // Add event listener for try again button
            document.getElementById('try-again').addEventListener('click', function() {
                resultElement.style.display = 'none';
            });
        }
    });
})(jQuery); 