jQuery(function($) {
    const WalletUpProCheckout = {
        init: function() {
            this.form = $('form.checkout, form#order_review');
            this.blockUI = {
                message: null,
                overlayCSS: {
                    background: '#fff',
                    opacity: 0.6
                }
            };

            this.initializeElements();
            this.initEvents();
            this.maybeInitializeDisplay();
        },

        initializeElements: function() {
            this.submitButton = this.form.find('#place_order');
            this.methodContainer = $('#wallet-up-checkout-container');
            this.methodInput = $('#wallet_up_payment_method');
            this.methodRadio = $('#payment_method_wallet_up');
        },

        initEvents: function() {
            // Payment method selection
            $(document.body).on('change', 'input[name="payment_method"]', () => {
                this.maybeInitializeDisplay();
            });

            // Form submission
            this.form.on('checkout_place_order_wallet_up', () => {
                return this.validatePayment();
            });

            // Checkout update
            $(document.body).on('updated_checkout', () => {
                this.maybeInitializeDisplay();
            });

            // Payment method selection in container
            this.methodContainer.on('click', '.wallet-up-method-item', (e) => {
                const methodId = $(e.currentTarget).data('method');
                if (methodId) {
                    this.methodInput.val(methodId);
                    $('.wallet-up-method-item').removeClass('selected');
                    $(e.currentTarget).addClass('selected');
                    this.loadPaymentDisplay(methodId);
                }
            });
        },

        maybeInitializeDisplay: function() {
            if (this.methodRadio.is(':checked') && 
                this.methodContainer.length && 
                window.walletUpCheckout) {
                this.initializeDisplay();
            }
        },

        initializeDisplay: function() {
            const methods = window.walletUpCheckout.methods;
            if (!methods || Object.keys(methods).length === 0) {
                return;
            }

            // Select first method by default if none selected
            if (!this.methodInput.val()) {
                const firstMethod = Object.keys(methods)[0];
                this.methodInput.val(firstMethod);
                this.loadPaymentDisplay(firstMethod);
            } else {
                this.loadPaymentDisplay(this.methodInput.val());
            }
        },

        loadPaymentDisplay: async function(methodId) {
            if (!methodId || !window.walletUpCheckout) return;

            try {
                this.methodContainer.block(this.blockUI);

                const response = await $.ajax({
                    url: window.walletUpCheckout.ajaxUrl,
                    type: 'POST',
                    data: {
                        action: 'wallet_up_get_payment_display',
                        method: methodId,
                        amount: window.walletUpCheckout.amount,
                        nonce: window.walletUpCheckout.nonces.payment
                    }
                });

                if (response.success && response.data?.html) {
                    $('#wallet-up-payment-display').html(response.data.html);
                } else {
                    throw new Error(response.data?.message || 'Failed to load payment display');
                }

            } catch (error) {
                this.showError(error.message || 'Error loading payment display');
            } finally {
                this.methodContainer.unblock();
            }
        },

        validatePayment: function() {
            if (!this.methodInput.val()) {
                this.showError('Please select a payment method.');
                return false;
            }

            return true;
        },

        showError: function(message) {
            $('.woocommerce-error, .woocommerce-message').remove();

            const errorHtml = `
                <div class="woocommerce-error">
                    ${message}
                </div>
            `;

            this.form.prepend(errorHtml);

            // Scroll to error
            $('html, body').animate({
                scrollTop: $('.woocommerce-error').offset().top - 100
            }, 500);

            this.form.unblock();
        }
    };

    // Initialize checkout
    WalletUpProCheckout.init();
});

// Block registration
registerBlockType('wallet-up-pro/payment-method', {
    title: 'WalletUpPro Payment Method',
    icon: 'money',
    category: 'woocommerce',
    attributes: {
        settings: {
            type: 'object',
            default: {}
        }
    },
    edit: ({ attributes, setAttributes }) => {
        return createElement(CheckoutBlock, {
            settings: window.walletUpBlockData || {},
            isEditor: true,
            onMethodSelect: (methodId) => {
                // Store selected method
                const newSettings = {
                    ...attributes.settings,
                    selectedMethod: methodId
                };
                setAttributes({ settings: newSettings });
            }
        });
    },
    save: ({ attributes }) => {
        return createElement(CheckoutBlock, {
            settings: attributes.settings,
            isEditor: false
        });
    }
});