(function($) {
    'use strict';

    const WalletUpProPayments = {
        debug: true,
        currentAmount: null,
        currentMethod: null,
        animationTimeout: null,
        observer: null, // For observing the form
        amountObserver: null, // Separate observer for amount changes
        containerSelector: '.wallet-up-wpforms-methods-container',
        displaySelector: '#wallet-up-wpforms-qr-display',
        paymentTypeFieldSelector: 'input[name="wpforms[fields][20]"]', // IMPORTANT:  Update [20] if your field ID is different

        init: function() {
            this.container = $(this.containerSelector);
            this.display = $(this.displaySelector);

            if (!this.container.length) {
                this.log('Payment methods container not found (initial)');
                // We'll find it later with the observer.
            }

            this.bindEvents();
            this.setupInitialObserver(); // Observe the *form* for initial changes
            this.checkLocalization();
        },

        log: function(message, data = null) {
            if (this.debug && console && console.log) {
                console.log('WalletUpPro:', message, data || '');
            }
        },

        checkLocalization: function() {
            if (typeof window.walletUpWPForms === 'undefined') {
                console.error('WalletUpProWPForms is not defined. Check PHP script localization.');
            } else {
                console.log('walletUpWPForms:', window.walletUpWPForms);
            }
        },

        bindEvents: function() {
            try {
                // Method selection (event delegation - important for dynamic content)
                $(document).on('click', this.containerSelector + ' .wallet-up-wpforms-method', this.handleMethodSelection.bind(this));

                // Handle page navigation in multi-page forms
                $(document).on('click', '.wpforms-pagebreak-button', this.onPageChange.bind(this));

                this.log('Events bound successfully');
            } catch (error) {
                this.log('Error binding events:', error);
            }
        },

        // Observe the *form* initially to find the WalletUpPro container
        setupInitialObserver: function() {
            const wpformsForm = $(this.paymentTypeFieldSelector).closest('form'); // Observe the *form*
            if (wpformsForm.length) {
                this.initialObserver = new MutationObserver(this.handleInitialContainer.bind(this));
                const config = { childList: true, subtree: true }; // Watch for nodes being added/removed
                this.initialObserver.observe(wpformsForm[0], config);
                this.log('Initial MutationObserver set up on form');
            } else {
                this.log('Initial MutationObserver could not find parent form');
            }
        },

        // Callback for the initial observer - runs when the container is first added
        handleInitialContainer: function(mutations) {
            for (const mutation of mutations) {
                if (mutation.type === 'childList') {
                    for (const node of mutation.addedNodes) {
                        if ($(node).hasClass('wallet-up-wpforms-methods-container') || $(node).find('.wallet-up-wpforms-methods-container').length) {
                            this.container = $(this.containerSelector); // Get the *new* container
                            this.display = $(this.displaySelector);     // Get the *new* display
                            this.setupAmountObserver(); // Set up the observer for amount changes
                            this.handleAmountChange();  // Initialize the UI based on current state
                            this.initialObserver.disconnect(); // Stop observing the form (we don't need it anymore)
                            this.initialObserver = null;
                            this.log('WalletUpPro container found, initialized');
                            return; // Exit the loop once found
                        }
                    }
                }
            }
        },

        // Sets up the observer for the amount display
        setupAmountObserver: function() {
            const $totalDisplay = $('.wpforms-payment-total');
            if ($totalDisplay.length) {
                if (this.amountObserver) {
                    this.amountObserver.disconnect(); // Disconnect any existing observer
                }
                this.amountObserver = new MutationObserver(this.handleAmountChange.bind(this));
                const config = { characterData: true, subtree: true, childList: true };
                this.amountObserver.observe($totalDisplay[0], config);
                this.log('MutationObserver set up for .wpforms-payment-total');
            } else {
                this.log('MutationObserver could NOT be set up for .wpforms-payment-total');
            }
        },


        handleMethodSelection: function(e) {
            e.preventDefault();

            if (this.container.hasClass('disabled')) {
                this.log('Selection blocked - container disabled');
                return;
            }

            const $method = $(e.currentTarget);
            const methodId = $method.data('method');
            const amount = this.getAmount();

            if (!amount) {
                alert(this.getI18nString('invalidAmount', 'Please enter a valid payment amount.'));
                return;
            }

            $('.wallet-up-wpforms-method').removeClass('selected');
            $method.addClass('selected');

            if (this.currentMethod !== methodId) {
                this.currentMethod = methodId;
                this.generateQR(methodId, amount);
            }
        },

        // Handles changes to the payment amount (and payment type selection)
        handleAmountChange: function(mutations = null) {
            if (this.debounceTimeout) {
                clearTimeout(this.debounceTimeout);
            }

            this.debounceTimeout = setTimeout(() => {
                const amount = this.getAmount();
                const isPaymentType3 = $(this.paymentTypeFieldSelector + ':checked').val() === '3'; // Check *current* value

                this.container.toggleClass('disabled', amount <= 0);

                if (isPaymentType3) { // Show if WalletUpPro is selected
                    this.container.stop(true, true).slideDown(250, () => {
                        this.container.css('display', 'grid');
                    });

                    if (amount > 0 && this.currentAmount !== amount) {
                        this.currentAmount = amount;
                        const $selected = $('.wallet-up-wpforms-method.selected');
                        if ($selected.length) {
                            this.generateQR(this.currentMethod, amount);
                        }
                    }
                } else { // Hide if WalletUpPro is NOT selected
                    this.container.stop(true, true).slideUp(200);
                    this.display.empty();
                    this.currentAmount = null;
                    this.currentMethod = null;
                }

                this.log('Amount changed:', amount);
            }, 100); // 100ms debounce
        },

        // Handles changes to the payment *type* selection
        handlePaymentTypeChange: function(e) {
            const isWalletUpProSelected = $(e.target).val() === '3';
            this.container.toggleClass('wallet-up-active', isWalletUpProSelected); // Add/remove class
            this.handleAmountChange(); // Use handleAmountChange to manage visibility
        },

        getAmount: function() {
            let amount = 0;
            const $totalDisplay = $('.wpforms-payment-total');

            if ($totalDisplay.length) {
                let text = $totalDisplay.text().trim();
                const match = text.match(/[\d.,]+/);
                if (match) {
                    let numStr = match[0].replace(/,/g, '');
                    amount = parseFloat(numStr);
                }

                if (!isNaN(amount)) {
                    amount = parseFloat(amount.toFixed(2)); // Ensure 2 decimal places
                }

                if (isNaN(amount) || amount <= 0) {
                    amount = 0;
                }
            } else {
                this.log('No payment total display found');
            }

            return amount;
        },

        getI18nString: function(key, defaultValue) {
            return window.walletUpWPForms?.i18n?.[key] || defaultValue;
        },

        generateQR: function(methodId, amount) {
            if (!methodId || amount <= 0) {
                this.log('Invalid QR parameters:', { methodId, amount });
                return;
            }

            this.display.html(`<div class="generating">${this.getI18nString('generating', 'Generating QR code...')}</div>`);

            if (this.activeRequest) {
                this.activeRequest.abort(); // Cancel any ongoing request
            }

            const nonce = window.walletUpWPForms?.nonce;
            if (!nonce) {
                this.log('Nonce missing for AJAX call');
                this.display.html(`<div class="error">${this.getI18nString('error', 'Error: Security token not found.')}</div>`);
                return;
            }

            const data = {
                action: 'wallet_up_wpforms_generate_qr',
                method: methodId,
                amount: amount,
                nonce: nonce
            };

            this.log('Generating QR:', data);

            this.activeRequest = $.ajax({
                url: window.walletUpWPForms?.ajaxUrl || '',
                type: 'POST',
                data: data,
                success: (response) => {
                    if (response.success && response.data.html) {
                        this.display.fadeOut(200, () => {
                            // Add the QR code and the instructions.
                            this.display.html(response.data.html + `
                                <div class="wallet-up-account-prompt">
                                   <p>You Elected to pay with Wallet Up Checkout. Provide the account name you used to complete the transaction.<br><br>
                                    <strong>Zelle, Cashapp, Venmo, paypal.me, WalupPay or Meta Pay</strong> Account </p>
                                   <input type="text" name="wallet_up_account_name" id="wallet_up_account_name" placeholder="Enter account name" required>
                                </div>
                            `).fadeIn(200);
                        });
                        this.log('QR generated successfully');
                    } else {
                        const error = response.data?.message || this.getI18nString('error', 'Error generating QR code');
                        this.display.fadeOut(200, () => { // Fade out, then in
                            this.display.html(`<div class="error">${error}</div>`).fadeIn(200);
                        });
                        this.log('QR generation failed:', error);
                    }
                    this.activeRequest = null;
                },
                error: (xhr, status, error) => {
                    const errorMessage = this.getI18nString('ajaxError', 'Error generating QR code.  Please try again.');
                    this.display.fadeOut(200, () => { // Fade out, then in
                        this.display.html(`<div class="error">${errorMessage}</div>`).fadeIn(200);
                    });
                    this.log('AJAX error:', { status, error, responseText: xhr.responseText });
                }
            });
        },

        onPageChange: function() {
            // Re-establish observer and update UI on page changes
            this.setupAmountObserver();
            this.handleAmountChange();
        }
    };

    $(document).ready(function() {
        WalletUpProPayments.init();
    });

})(jQuery);