/**
 * Express Checkout Functionality
 * Handles the display and interaction of express payment methods across all templates
 */

jQuery(function($) {
    'use strict';

    const ExpressCheckout = {
        
        /**
         * Initialize express checkout functionality
         */
        init: function() {
            this.detectExpressMethods();
            this.handleExpressPaymentButtons();
            this.initResponsiveHandling();
            
            // Re-initialize when checkout updates
            $(document.body).on('updated_checkout', this.onCheckoutUpdated.bind(this));
        },

        /**
         * Detect if any express payment methods are available
         */
        detectExpressMethods: function() {
            const $expressSection = $('.ckfylt25-express-checkout-section');
            const $expressMethods = $('.ckfylt25-express-payment-methods');
            
            if ($expressSection.length === 0) {
                return;
            }

            // Check for various express payment method indicators
            const hasExpressMethods = this.hasPayPalExpress() || 
                                    this.hasGooglePay() || 
                                    this.hasApplePay() || 
                                    this.hasAmazonPay() ||
                                    this.hasStripeExpress();

            if (!hasExpressMethods) {
                $expressSection.hide();
                $('.ckfylt25-express-checkout-separator').hide();
            } else {
                $expressSection.show();
                $('.ckfylt25-express-checkout-separator').show();
                this.enhanceExpressButtons();
            }
        },

        /**
         * Check for PayPal Express Checkout
         */
        hasPayPalExpress: function() {
            return $('.paypal-express-checkout').length > 0 ||
                   $('[id*="paypal"]').length > 0 ||
                   $('.wc-gateway-ppcp').length > 0 ||
                   $('.paypal-button').length > 0;
        },

        /**
         * Check for Google Pay
         */
        hasGooglePay: function() {
            return $('.google-pay-button').length > 0 ||
                   $('[id*="google-pay"]').length > 0 ||
                   $('.gpay-button').length > 0;
        },

        /**
         * Check for Apple Pay
         */
        hasApplePay: function() {
            return $('.apple-pay-button').length > 0 ||
                   $('[id*="apple-pay"]').length > 0 ||
                   $('.applepay-button').length > 0;
        },

        /**
         * Check for Amazon Pay
         */
        hasAmazonPay: function() {
            return $('.amazon-pay-button').length > 0 ||
                   $('[id*="amazon"]').length > 0 ||
                   $('.amazonpay-button').length > 0;
        },

        /**
         * Check for Stripe Express Payments
         */
        hasStripeExpress: function() {
            return $('.stripe-express-checkout').length > 0 ||
                   $('.payment-request-button').length > 0 ||
                   $('.wc-stripe-express-checkout').length > 0;
        },

        /**
         * Enhance express payment buttons with consistent styling
         */
        enhanceExpressButtons: function() {
            const $buttons = $('.ckfylt25-express-payment-methods button, .ckfylt25-express-payment-methods .payment_method');
            
            $buttons.each(function() {
                const $button = $(this);
                
                // Add consistent classes
                $button.addClass('ckfylt25-express-button');
                
                // Identify button type by content or class
                const buttonText = $button.text().toLowerCase();
                const buttonClass = $button.attr('class') || '';
                
                if (buttonText.includes('paypal') || buttonClass.includes('paypal')) {
                    $button.addClass('ckfylt25-express-paypal');
                } else if (buttonText.includes('google') || buttonClass.includes('google')) {
                    $button.addClass('ckfylt25-express-google');
                } else if (buttonText.includes('apple') || buttonClass.includes('apple')) {
                    $button.addClass('ckfylt25-express-apple');
                } else if (buttonText.includes('amazon') || buttonClass.includes('amazon')) {
                    $button.addClass('ckfylt25-express-amazon');
                }
            });
        },

        /**
         * Handle express payment button interactions
         */
        handleExpressPaymentButtons: function() {
            $(document).on('click', '.ckfylt25-express-button', function(e) {
                const $button = $(this);
                
                // Add loading state
                $button.addClass('ckfylt25-express-loading');
                $button.prop('disabled', true);
                
                // Reset after 5 seconds if no redirect happens
                setTimeout(function() {
                    $button.removeClass('ckfylt25-express-loading');
                    $button.prop('disabled', false);
                }, 5000);
            });

            // Handle express payment completion
            $(document.body).on('checkout_error', function() {
                $('.ckfylt25-express-button').removeClass('ckfylt25-express-loading').prop('disabled', false);
            });
        },

        /**
         * Handle responsive behavior
         */
        initResponsiveHandling: function() {
            const handleResize = () => {
                const $expressSection = $('.ckfylt25-express-checkout-section');
                
                if ($(window).width() < 768) {
                    $expressSection.addClass('ckfylt25-express-mobile');
                } else {
                    $expressSection.removeClass('ckfylt25-express-mobile');
                }
            };

            $(window).on('resize', handleResize);
            handleResize(); // Initial call
        },

        /**
         * Handle checkout update events
         */
        onCheckoutUpdated: function() {
            // Re-detect methods after checkout updates
            setTimeout(() => {
                this.detectExpressMethods();
            }, 100);
        },

        /**
         * Move express buttons to the correct container
         */
        moveExpressButtons: function() {
            const $expressContainer = $('.ckfylt25-express-payment-methods');
            
            if ($expressContainer.length === 0) {
                return;
            }

            // Look for PayPal buttons outside our container
            $('.paypal-express-checkout, .wc-gateway-ppcp .payment_box').each(function() {
                if (!$(this).closest('.ckfylt25-express-payment-methods').length) {
                    $(this).appendTo($expressContainer);
                }
            });

            // Look for Stripe express buttons
            $('.payment-request-button, .wc-stripe-express-checkout').each(function() {
                if (!$(this).closest('.ckfylt25-express-payment-methods').length) {
                    $(this).appendTo($expressContainer);
                }
            });
        }
    };

    // Initialize when DOM is ready
    ExpressCheckout.init();

    // Also initialize when checkout scripts are loaded
    $(document.body).on('checkout_loaded', function() {
        ExpressCheckout.init();
    });

    // Make available globally for debugging
    window.CKFYLT25ExpressCheckout = ExpressCheckout;
});