jQuery(function($) {
    // Initialize Stripe
    var stripe = Stripe(subscription_data.stripe_publishable_key);
    
    $('.subscribe-button').on('click', function() {
        var planId = $(this).data('plan-id');
        var button = $(this);
        var planName = button.closest('.ss-pricing-plan').find('h3').text();
        var planPrice = button.closest('.ss-pricing-plan').find('.ss-price').text().replace(/[^0-9.]/g, '');
        
        // Check if user is logged in
        if (!subscription_data.is_user_logged_in) {
            // User is not logged in, redirect to register page
            window.location.href = subscription_data.register_page_url + '?plan_id=' + planId;
            return;
        } else {
            // Check if user already has this subscription
            $.ajax({
                url: subscription_data.ajax_url,
                type: 'POST',
                data: {
                    action: 'check_user_subscription',
                    plan_id: planId,
                    nonce: subscription_data.nonce
                },
                success: function(response) {
                    if (response.success && response.data.has_subscription) {
                        // User already has this subscription, redirect to account page
                        window.location.href = subscription_data.account_page_url + '?tab=subscriptions';
                    } else {
                        // User is logged in but doesn't have this subscription, proceed with payment
                        proceedWithPayment(planId, button, planName, planPrice);
                    }
                },
                error: function() {
                    // On error, proceed with payment flow
                    proceedWithPayment(planId, button, planName, planPrice);
                }
            });
        }
    });
    
    function proceedWithPayment(planId, button, planName, planPrice) {
        // Disable button and show loading state
        button.prop('disabled', true).addClass('loading').text('Processing...');
        
        // Create RECURRING subscription checkout session with Stripe API
        fetch('https://api.stripe.com/v1/checkout/sessions', {
            method: 'POST',
            headers: {
                'Authorization': 'Bearer ' + subscription_data.stripe_secret_key,
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: new URLSearchParams({
                'payment_method_types[]': 'card',
                'line_items[0][price_data][currency]': 'usd',
                'line_items[0][price_data][product_data][name]': planName,
                'line_items[0][price_data][unit_amount]': Math.round(planPrice * 100),
                'line_items[0][price_data][recurring][interval]': 'month',
                'line_items[0][quantity]': 1,
                'mode': 'subscription',
                'success_url': subscription_data.thank_you_page_url + '?session_id={CHECKOUT_SESSION_ID}',
                'cancel_url': subscription_data.pricing_plans_page_url,
                'client_reference_id': planId,
                'metadata[plan_id]': planId
            })
        })
        .then(response => response.json())
        .then(session => {
            if (session.id) {
                return stripe.redirectToCheckout({ sessionId: session.id });
            } else if (session.error) {
                throw new Error(session.error.message);
            } else {
                throw new Error('Unknown error occurred');
            }
        })
        .then(result => {
            if (result.error) {
                throw new Error(result.error.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Error: ' + error.message);
            button.prop('disabled', false).removeClass('loading').text(subscription_data.subscribe_now_text);
        });
    }
}); 