jQuery(function($) {
    const $displayContainer = $('#wallet-up-payment-display');
    const $methodSelect = $('#wallet_up_payment_method');
    const loadingHtml = '<div class="loading">' + walletUpCheckout.i18n.loading + '</div>';
    
    function initializePaymentDisplay() {
        if (!$displayContainer.length || !$methodSelect.length) {
            return;
        }

        function loadPaymentDisplay() {
            const methodId = $methodSelect.val();
            if (!methodId) return;

            $displayContainer.html(loadingHtml);

            $.ajax({
                url: walletUpCheckout.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'wallet_up_wc_payment_display',
                    methodId: methodId,
                    amount: walletUpCheckout.amount,
                    nonce: walletUpCheckout.nonce,
                    context: 'checkout'
                },
                success: function(response) {
                    if (response.success && response.data?.html) {
                        $displayContainer.html(response.data.html);
                        initializePaymentTracking();
                    } else {
                        console.error('Invalid payment display response:', response);
                        $displayContainer.html(
                            '<div class="woocommerce-error">' + 
                            walletUpCheckout.i18n.error + 
                            '</div>'
                        );
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Payment display error:', {
                        status: xhr.status,
                        statusText: xhr.statusText,
                        responseText: xhr.responseText,
                        error: error
                    });
                    $displayContainer.html(
                        '<div class="woocommerce-error">' + 
                        walletUpCheckout.i18n.error + 
                        '</div>'
                    );
                }
            });
        }

        function initializePaymentTracking() {
            $('.wallet-up-qr-link').on('click', function(e) {
                const methodId = $(this).closest('.wallet-up-payment-display').data('method');
                if (!methodId) return;

                $.ajax({
                    url: walletUpCheckout.ajaxUrl,
                    type: 'POST',
                    data: {
                        action: 'wallet_up_track_usage',
                        type: 'click',
                        method: methodId,
                        nonce: walletUpCheckout.nonce,
                        context: 'checkout'
                    }
                });
            });
        }

        // Initialize display and handle changes
        $methodSelect.on('change', loadPaymentDisplay);
        loadPaymentDisplay();

        // Track impressions
        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    const $display = $(entry.target);
                    const methodId = $display.data('method');
                    if (!methodId) return;

                    $.ajax({
                        url: walletUpCheckout.ajaxUrl,
                        type: 'POST',
                        data: {
                            action: 'wallet_up_track_usage',
                            type: 'impression',
                            method: methodId,
                            nonce: walletUpCheckout.nonce,
                            context: 'checkout'
                        }
                    });

                    observer.unobserve(entry.target);
                }
            });
        }, {
            threshold: 0.5
        });

        // Observe payment displays for impressions
        $displayContainer.find('.wallet-up-payment-display').each(function() {
            observer.observe(this);
        });
    }

    // Initialize on document ready
    initializePaymentDisplay();

    // Re-initialize on checkout update
    $(document.body).on('updated_checkout', function() {
        initializePaymentDisplay();
    });

    // Handle payment form submission
    $('form.checkout').on('checkout_place_order_wallet_up', function() {
        if (!$methodSelect.val()) {
            alert(walletUpCheckout.i18n.selectMethod);
            return false;
        }
        return true;
    });
});