/**
 * ConvesioPay Apple Pay Integration using ConvesioPay's component.createApplePaySession()
 */

(function($) {
    'use strict';

    // ConvesioPay Apple Pay handler
    window.ConvesioPayApplePay = {
        config: window.peachpayConvesioPayApplePay || {},
        component: null,
        applePaySession: null,
        
        /**
         * Initialize Apple Pay
         */
        init: function() {
            
            // Check if Apple Pay is available
            if (!this.isApplePayAvailable()) {
                this.hideApplePayButton();
                return;
            }
            
            this.setupConvesioPayComponent();
        },
        
        /**
         * Check if Apple Pay is available
         */
        isApplePayAvailable: function() {
            // Check if we're in Safari on Apple device
            if (!window.ApplePaySession) {
                return false;
            }
            
            // Check if Apple Pay is available on this device
            return ApplePaySession.canMakePayments();
        },
        
        /**
         * Hide Apple Pay button if not available
         */
        hideApplePayButton: function() {
            $('.wc_payment_method.payment_method_peachpay_convesiopay_applepay').hide();
        },
        
        /**
         * Set up ConvesioPay component for Apple Pay
         */
        setupConvesioPayComponent: function() {
            const self = this;
            
            // Wait for ConvesioPay component to be available
            this.waitForConvesioPayComponent(function() {
                self.initializeConvesioPayApplePay();
            });
            
            // Set up payment method selection handler
            $(document).on('click', '.payment_method_peachpay_convesiopay_applepay input[type="radio"]', function() {
                if ($(this).is(':checked')) {
                    self.createApplePaySession();
                }
            });
        },
        
        /**
         * Wait for ConvesioPay component to be available
         */
        waitForConvesioPayComponent: function(callback) {
            if (window.convesioPayComponent && typeof window.convesioPayComponent.createApplePaySession === 'function') {
                this.component = window.convesioPayComponent;
                callback();
            } else {
                setTimeout(() => {
                    this.waitForConvesioPayComponent(callback);
                }, 500);
            }
        },
        
        /**
         * Initialize ConvesioPay Apple Pay integration
         */
        initializeConvesioPayApplePay: function() {
            
            // Set up component change event listeners
            this.component.on('change', (event) => {
                this.handleComponentChange(event);
            });
            
        },
        
        /**
         * Create Apple Pay session using ConvesioPay's component.createApplePaySession()
         */
        createApplePaySession: async function() {
            
            if (!this.component) {
                return;
            }
            
            // Get order details from WooCommerce checkout
            const orderData = this.getOrderData();
            
            if (!orderData.isValid) {
                this.showError('Unable to get order details for Apple Pay');
                return;
            }
            
            try {
                
                // Create Apple Pay session using ConvesioPay's method (NEW FLOW - no orderNumber)
                // orderNumber is removed to use the new token-based flow where payment is created after order exists
                this.applePaySession = await this.component.createApplePaySession({
                    integration: this.config.integration_name || 'default_integration',
                    returnUrl: window.location.href,
                    // orderNumber: REMOVED - new flow creates payment after order exists
                    amount: orderData.amount, // In minor units (cents)
                    currency: orderData.currency,
                    email: orderData.email,
                    name: orderData.name,
                    billingAddress: orderData.billingAddress,
                    shippingAddress: orderData.shippingAddress,
                    lineItems: orderData.lineItems
                });
                
                
                // Apple Pay session is now ready, customer can proceed with payment
                this.setupCheckoutIntegration();
                
            } catch (error) {
                this.showError('Failed to initialize Apple Pay: ' + error.message);
            }
        },
        
        /**
         * Get order data for ConvesioPay Apple Pay session
         */
        getOrderData: function() {
            const orderData = {
                isValid: false,
                orderNumber: this.generateOrderNumber(),
                amount: 0,
                currency: 'USD',
                email: '',
                name: '',
                billingAddress: null,
                shippingAddress: null,
                lineItems: null
            };
            
            // Get order total (convert to minor units - cents)
            const total = this.getOrderTotal();
            if (!total) {
                return orderData;
            }
            orderData.amount = Math.round(total * 100); // Convert to cents
            
            // Get currency
            orderData.currency = this.getOrderCurrency();
            
            // Get customer details from checkout form
            const customerData = this.getCustomerData();
            if (!customerData.email || !customerData.name) {
                return orderData;
            }
            
            orderData.email = customerData.email;
            orderData.name = customerData.name;
            orderData.billingAddress = customerData.billingAddress;
            orderData.shippingAddress = customerData.shippingAddress;
            
            // Get line items
            orderData.lineItems = this.getLineItems();
            
            orderData.isValid = true;
            return orderData;
        },
        
        /**
         * Get order total in dollars
         */
        getOrderTotal: function() {
            // Try to get from WooCommerce checkout
            const totalElement = $('.order-total .woocommerce-Price-amount, .woocommerce-checkout-review-order-total .woocommerce-Price-amount');
            if (totalElement.length) {
                const totalText = totalElement.first().text().replace(/[^0-9.]/g, '');
                return parseFloat(totalText) || 0;
            }
            
            return 0;
        },
        
        /**
         * Get order currency
         */
        getOrderCurrency: function() {
            // Try to get from WooCommerce global
            if (typeof wc_checkout_params !== 'undefined' && wc_checkout_params.currency) {
                return wc_checkout_params.currency;
            }
            
            // Fallback to USD
            return 'USD';
        },
        
        /**
         * Generate unique order number
         */
        generateOrderNumber: function() {
            const timestamp = Date.now();
            const random = Math.floor(Math.random() * 1000);
            return `APPLEPAY-${timestamp}-${random}`;
        },
        
        /**
         * Get customer data from checkout form
         */
        getCustomerData: function() {
            return {
                email: $('#billing_email').val() || $('#account_email').val() || '',
                name: `${$('#billing_first_name').val() || ''} ${$('#billing_last_name').val() || ''}`.trim() || 'Customer',
                billingAddress: this.getBillingAddress(),
                shippingAddress: this.getShippingAddress()
            };
        },
        
        /**
         * Get billing address from checkout form
         */
        getBillingAddress: function() {
            const address1 = $('#billing_address_1').val();
            const address2 = $('#billing_address_2').val();
            const city = $('#billing_city').val();
            const state = $('#billing_state').val();
            const postcode = $('#billing_postcode').val();
            const country = $('#billing_country').val();
            
            if (!address1 || !city) {
                return null;
            }
            
            return {
                address1: address1,
                address2: address2,
                city: city,
                state: state,
                postcode: postcode,
                country: country
            };
        },
        
        /**
         * Get shipping address from checkout form
         */
        getShippingAddress: function() {
            // Check if shipping to different address
            const shipToDifferent = $('#ship-to-different-address-checkbox').is(':checked');
            
            if (!shipToDifferent) {
                return this.getBillingAddress(); // Use billing address
            }
            
            const address1 = $('#shipping_address_1').val();
            const address2 = $('#shipping_address_2').val();
            const city = $('#shipping_city').val();
            const state = $('#shipping_state').val();
            const postcode = $('#shipping_postcode').val();
            const country = $('#shipping_country').val();
            
            if (!address1 || !city) {
                return this.getBillingAddress(); // Fallback to billing
            }
            
            return {
                address1: address1,
                address2: address2,
                city: city,
                state: state,
                postcode: postcode,
                country: country
            };
        },
        
        /**
         * Get line items from order review
         */
        getLineItems: function() {
            const lineItems = [];
            
            $('.woocommerce-checkout-review-order-table .cart_item').each(function() {
                const $item = $(this);
                const name = $item.find('.product-name').text().trim();
                const quantity = $item.find('.product-quantity').text().replace(/[^0-9]/g, '') || '1';
                const total = $item.find('.product-total .woocommerce-Price-amount').text().replace(/[^0-9.]/g, '');
                
                if (name && total) {
                    lineItems.push({
                        name: name,
                        quantity: parseInt(quantity),
                        amount: Math.round(parseFloat(total) * 100) // Convert to cents
                    });
                }
            });
            
            return lineItems.length > 0 ? lineItems : null;
        },
        
        /**
         * Handle ConvesioPay component change events (NEW TOKEN-BASED FLOW)
         */
        handleComponentChange: function(event) {
            
            if (event.type === 'ready') {
            } else if (event.type === 'applepay' && event.isSuccessful) {
                // NEW FLOW: On successful device confirmation, extract token from event.token
                // Payment will NOT be automatically created - backend will create it with secret key
                this.handleApplePayToken(event);
            } else if (event.type === 'payment_succeeded') {
                this.handlePaymentSuccess(event);
            } else if (event.type === 'payment_failed') {
                this.handlePaymentFailure(event);
            } else if (event.type === 'error') {
                this.handleComponentError(event);
            }
        },
        
        /**
         * Setup checkout integration
         */
        setupCheckoutIntegration: function() {
            const self = this;
            
            // Apple Pay session is created, now integrate with WooCommerce checkout
            $(document).on('submit', 'form.checkout', function(e) {
                if ($('.payment_method_peachpay_convesiopay_applepay input[type="radio"]').is(':checked')) {
                    // ConvesioPay Apple Pay session will handle the payment
                    // The component will trigger payment events that we handle above
                    return true; // Allow normal form submission
                }
            });
        },
        
        /**
         * Handle ApplePay token from device confirmation (NEW TOKEN-BASED FLOW)
         */
        handleApplePayToken: function(event) {
            // Extract token from event (NEW FLOW: token is provided but payment not created yet)
            const paymentToken = event.token 
                || event.paymentData?.token 
                || event.data?.token 
                || null;
            
            if (!paymentToken) {
                this.showError('Apple Pay authorization successful but token is missing. Please try again.');
                return;
            }
            
            // Store token globally for backend to use when creating payment
            window.convesiopayPaymentToken = paymentToken;
            window.convesiopayApplePayPaymentData = {
                paymentMethod: 'applepay',
                token: paymentToken,
                amount: event.paymentData?.amount || this.getOrderData().amount,
                currency: event.paymentData?.currency || this.getOrderData().currency,
                status: 'authorized' // Device authorized, payment will be created by backend
            };
            
            // Continue with normal checkout flow - backend will create payment with token
            this.completeCheckout();
        },
        
        /**
         * Handle payment success
         */
        handlePaymentSuccess: function(event) {
            
            // Store the payment token from ConvesioPay
            if (event.paymentToken) {
                window.convesiopayPaymentToken = event.paymentToken;
            }
            
            // Continue with normal checkout flow
            this.completeCheckout();
        },
        
        /**
         * Handle payment failure
         */
        handlePaymentFailure: function(event) {
            const errorMessage = event.error?.message || 'Apple Pay payment failed';
            this.showError(errorMessage);
            this.resetCheckoutForm();
        },
        
        /**
         * Handle component error
         */
        handleComponentError: function(event) {
            const errorMessage = event.error?.message || 'Apple Pay component error';
            this.showError(errorMessage);
        },
        
        /**
         * Show error message
         */
        showError: function(message) {
            // Show WooCommerce-style error
            $('.woocommerce-notices-wrapper').first().html(
                '<div class="woocommerce-error" role="alert">' + 
                '<strong>Apple Pay Error:</strong> ' + message +
                '</div>'
            );
            
            // Scroll to top to show error
            $('html, body').animate({
                scrollTop: $('.woocommerce-error').offset().top - 100
            }, 500);
        },
        
        /**
         * Complete checkout after Apple Pay success
         */
        completeCheckout: function() {
            
            // The ConvesioPay component has handled the Apple Pay payment
            // Now continue with normal WooCommerce checkout flow
            $('form.checkout').submit();
        },
        
        /**
         * Reset checkout form
         */
        resetCheckoutForm: function() {
            // Remove loading states and re-enable form
            $('body').removeClass('processing');
            $('.woocommerce-checkout').removeClass('processing').unblock();
            $('form.checkout').removeClass('processing').unblock();
        }
    };
    
    // Initialize when document is ready
    $(document).ready(function() {
        if (window.peachpayConvesioPayApplePay && window.peachpayConvesioPayApplePay.is_available) {
            window.ConvesioPayApplePay.init();
        }
    });
    
})(jQuery);