jQuery(document).ready(function($) {

    let collectJS = null;

    nmipay_log_error("[nmi-checkout.js] Script initialization: DOM is "+document.readyState);
    //var checkout_form = jQuery('form.checkout');

    jQuery('#wc-nmipay-cc-form').css('display', 'none');
    
    var checkout_form = jQuery("form.checkout, form#order_review, form#add_payment_method");

    // Validation function
	function isValidAmount(value) {
		return typeof value === 'number' && !isNaN(value) && value > 0;
	}

    // Enhanced cart total update function for traditional checkout
    function updateNMICartTotal() {

        console.log('[nmi-checkout.js] updateNMICartTotal(): CollectJS configuration completed for block checkout '+collectJS);

        // Comprehensive selector strategy for traditional checkout
        const selectors = [
            // Primary selectors
            '.order-total bdi',
            '.order-total .woocommerce-Price-amount',
            '.order-total .amount',
            
            // Alternative selectors
            '.cart-subtotal .amount',
            '.order-total .woocommerce-Price-amount bdi',
            '.order-total strong .amount',
            
            // Fallback selectors
            '[data-block-name="woocommerce/checkout-totals-block"] .wc-block-formatted-money-amount',
            '.wc-block-components-totals-footer-item-total .wc-block-formatted-money-amount',
            
            // Generic total selectors
            '[class*="total"] [class*="amount"]',
            '[class*="order-total"] [class*="amount"]'
        ];
        
        let foundTotal = false;
        
        for (const selector of selectors) {
            const elements = document.querySelectorAll(selector);
            for (const element of elements) {
                const text = element.textContent.trim();
                const total = parseFloat(text.replace(/[^\d.-]/g, ''));
                
                if (isValidAmount(total) && total > 0) {
                    nmi_info.cart_total = total;
                    console.log('[nmi-checkout.js] updateNMICartTotal(): Updated nmi_info.cart_total using selector:', selector, total);
                    nmipay_log_error('[nmi-checkout.js] updateNMICartTotal(): Updated nmi_info.cart_total: ' + total);
                    foundTotal = true;
                    break;
                }
            }
            if (foundTotal) break;
        }
        
        if (!foundTotal) {
            console.log('[nmi-checkout.js] updateNMICartTotal(): No valid total found, nmi_info.cart_total unchanged');
            nmipay_log_error('[nmi-checkout.js] updateNMICartTotal(): No valid total found for nmi_info.cart_total');
        }
    }

    // Setup traditional checkout total updates
    function setupTraditionalCheckoutTotalUpdates() {
        // 1. Event-based updates
        jQuery(document.body).on('updated_checkout updated_cart_totals', function() {
            console.log('[nmi-checkout.js] setupTraditionalCheckoutTotalUpdates(): Checkout updated, updating cart total');
            nmipay_log_error('[nmi-checkout.js] setupTraditionalCheckoutTotalUpdates(): Checkout updated, updating cart total');
            updateNMICartTotal();
        });
        
        // 2. Form field monitoring
        jQuery(document).on('change input blur', 'input[name*="coupon"], select[name*="shipping"], input[name*="shipping"], input[name*="billing"], select[name*="billing"]', function() {
            console.log('[nmi-checkout.js] setupTraditionalCheckoutTotalUpdates(): Form field changed, updating cart total');
            nmipay_log_error('[nmi-checkout.js] setupTraditionalCheckoutTotalUpdates(): Form field changed, updating cart total');
            updateNMICartTotal();
        });
        
        // 3. Additional WooCommerce events
        jQuery(document.body).on('applied_coupon removed_coupon', function() {
            console.log('[nmi-checkout.js] setupTraditionalCheckoutTotalUpdates(): Coupon applied/removed, updating cart total');
            nmipay_log_error('[nmi-checkout.js] setupTraditionalCheckoutTotalUpdates(): Coupon applied/removed, updating cart total');
            updateNMICartTotal();
        });
        
        // 4. Shipping method changes
        jQuery(document).on('change', 'input[name*="shipping_method"], select[name*="shipping_method"]', function() {
            console.log('[nmi-checkout.js] setupTraditionalCheckoutTotalUpdates(): Shipping method changed, updating cart total');
            nmipay_log_error('[nmi-checkout.js] setupTraditionalCheckoutTotalUpdates(): Shipping method changed, updating cart total');
            updateNMICartTotal();
        });
        /*
        // 5. DOM observer for total changes
        function setupTotalObserver() {
            const orderTotalContainer = document.querySelector('.order-total, .cart-subtotal, .woocommerce-checkout-review-order');
            if (!orderTotalContainer) {
                console.log('[nmi-checkout.js] setupTraditionalCheckoutTotalUpdates(): Total container not found for observer');
                return;
            }
            
            const observer = new MutationObserver(function(mutations) {
                mutations.forEach(function(mutation) {
                    if (mutation.type === 'childList' || mutation.type === 'characterData') {
                        console.log('[nmi-checkout.js] setupTraditionalCheckoutTotalUpdates(): DOM mutation detected, updating cart total');
                        nmipay_log_error('[nmi-checkout.js] setupTraditionalCheckoutTotalUpdates(): DOM mutation detected, updating cart total');
                        updateNMICartTotal();
                    }
                });
            });
            
            observer.observe(orderTotalContainer, {
                childList: true,
                subtree: true,
                characterData: true
            });
            
            console.log('[nmi-checkout.js] setupTraditionalCheckoutTotalUpdates(): Total observer setup complete');
            nmipay_log_error('[nmi-checkout.js] setupTraditionalCheckoutTotalUpdates(): Total observer setup complete');
        }*/
        
        // 6. Initial update (one-time)
        updateNMICartTotal();
        
        // Setup observer
        //setupTotalObserver();
        
        console.log('[nmi-checkout.js] setupTraditionalCheckoutTotalUpdates(): Traditional checkout total updates setup complete');
        nmipay_log_error('[nmi-checkout.js] setupTraditionalCheckoutTotalUpdates(): Traditional checkout total updates setup complete');
    }


    function getBrowserName() {
        var userAgent = navigator.userAgent;
    
        if ((/Opera|OPR\//).test(userAgent)) {
            return 'Opera';
        } else if (/Edg/.test(userAgent)) {
            return 'Microsoft Edge';
        } else if (/Chrome/.test(userAgent) && !/Edg/.test(userAgent)) {
            return 'Chrome';
        } else if (/Safari/.test(userAgent) && !/Chrome/.test(userAgent)) {
            return 'Safari';
        } else if (/Firefox/.test(userAgent)) {
            return 'Firefox';
        } else if (/MSIE|Trident/.test(userAgent)) {
            return 'Internet Explorer';
        }
    
        return 'Unknown';
    }

    function nmipay_log_error( error_message ) {

        console.log(error_message);

        $.ajax({
            type: 'POST',
            url: woocommerce_params.ajax_url,
            data: {
            action: 'log_nmipay_ajax_errors',
            error: error_message
            },
            success: function(response) {
                //console.log(response);
            },
            error: function(error) {
                console.log('[nmi-checkout.js] nmipay_log_error(): AJAX error:', error);
            }
        });
        
    }

    function nmi_wallets_log_error( error_message ) {

        $.ajax({
            type: 'POST',
            url: nmi_wallets_params.ajax_url,
            data: {
            action: 'log_nmi_wallets_ajax_errors',
            error: error_message,
            nonce: nmi_wallets_params.log_errors_nonce
            },
            success: function(response) {
                //console.log(response);
            },
            error: function(error) {
                console.log('[nmi-checkout.js] nmi_wallets_log_error(): AJAX error:', error);
            }
        });

        console.log('[nmi-checkout.js] nmi_wallets_log_error(): ' + error_message);
        
    }

    function submit_error( error_message ) {

        try{
            CollectJS.closePaymentRequest();
        }catch{
            console.log('[nmi-checkout.js] submit_error(): Clearing Payment Request.');
        }

        $( '.woocommerce-NoticeGroup-checkout, .woocommerce-error, .woocommerce-message' ).remove();
        checkout_form.prepend( '<div class="woocommerce-NoticeGroup woocommerce-NoticeGroup-checkout">' + error_message + '</div>' ); // eslint-disable-line max-len
        checkout_form.removeClass( 'processing' ).unblock();
        checkout_form.find( '.input-text, select, input:checkbox' ).trigger( 'validate' ).trigger( 'blur' );
        scroll_to_notices();
        $( document.body ).trigger( 'checkout_error' , [ error_message ] );

        nmipay_log_error( error_message );
    }

    function scroll_to_notices() {
        var scrollElement = $( '.woocommerce-NoticeGroup-updateOrderReview, .woocommerce-NoticeGroup-checkout' );

        if ( ! scrollElement.length ) {
            scrollElement = $( 'form.checkout' );
        }

        // Check if the form is found
        if (scrollElement.length > 0) {
            // Scroll the form into view
            scrollElement[0].scrollIntoView({ behavior: 'auto' }); // You can use 'auto' instead of 'smooth' for instant scrolling
        }


    }


    function trigger_nmi_checkout(nmi_info) {


        if ( jQuery('#payment_method_robust_nmi_gateway').is(':checked')/* && nmi_info.fields_loaded == '0'*/){

            console.log('[nmi-checkout.js] trigger_nmi_checkout(): ##########################################################################################')

            var browserName = getBrowserName();

            nmipay_log_error('[nmi-checkout.js] trigger_nmi_checkout(): ' + browserName);

            nmipay_log_error('[nmi-checkout.js] trigger_nmi_checkout(): Doing Checkout');

            nmipay_log_error('[nmi-checkout.js] trigger_nmi_checkout(): Empty Fields');
            jQuery.unblockUI();

            console.log('[nmi-checkout.js] trigger_nmi_checkout(): inline');

            try{
                collectJS = CollectJS.configure({
                    "variant" : "inline",
                    "styleSniffer" : "true",
                    "fields": {
                        "ccnumber": {
                            "selector": "#nmi-ccnumber",
                            "title": "Card Number",
                            "placeholder": "0000 0000 0000 0000",
                        },
                        "ccexp": {
                            "selector": "#nmi-ccexp",
                            "title": "Card Expiration",
                            "placeholder": "00 / 00"
                        },
                        "cvv": {
                            "display": "required",
                            "selector": "#nmi-cvv",
                            "title": "CVV Code",
                            "placeholder": "***"
                        },
                    },
                    //"variant": "inline",
                    'validationCallback' : function(field, status, message) {
                        if (status) {
                            var message = field + " is OK: " + message;
                            //nmi_error[field] = '';
                        } else {
                            if( field == 'ccnumber' ){
                                field = 'Card Number'
                            }
                            if( field == 'ccexp' ){
                                field = 'Expiration'
                            }
                            if( field == 'cvv' ){
                                field = 'CVV Code'
                            }
                            nmi_info.errors += '<div class="woocommerce-error" role="alert">Message: '+field + " " + message+'</div>';
                            if( nmi_info.submitted == '1' ){
                                submit_error( nmi_info.errors );
                            }
                            jQuery.unblockUI();
                            try{
                                CollectJS.closePaymentRequest();
                            }catch{
                                console.log('[nmi-checkout.js] trigger_nmi_checkout(): Clearing Payment Request.');
                            }
                            jQuery('#wc-robust_nmi_gateway-cc-form').css('display', 'block');
                        }
                        nmipay_log_error(message);
                    },
                    'callback' : function(response) {

                        nmipay_log_error('[nmi-checkout.js] trigger_nmi_checkout(): Callback '+ JSON.stringify(response));


                        if( !nmi_info.inline_card ){

                            jQuery.blockUI(
                                { 
                                message: 'Please wait while your order is being processed.',
                                    css: {
                                    padding:        0, 
                                    margin:         0, 
                                    //width:          '360px',
                                    //height:          '400px',
                                    textAlign:      'center', 
                                    color:          '#000', 
                                    border:         '3px solid #aaa', 
                                    backgroundColor:'#fff', 
                                    cursor:         'wait',
                                    top:             '20%',
                                },
                                }
                            );

                        }

                        jQuery('#wc-robust_nmi_gateway-cc-form').css('display', 'none');

                        // Initialize variables
                        let bdi_total = 0;
                        let wpa_total = 0;
                        let currentTotal = 0;

                        try {
                            bdi_total = parseFloat(jQuery('.order-total bdi').text().replace(/[^\d\.]/g, ''));
                            if (isValidAmount(bdi_total)) {
                                nmi_info.cart_total = bdi_total;
                                console.log('[nmi-checkout.js] trigger_nmi_checkout(): Using bdi_total:', bdi_total);
                            } else {
                                throw new Error('Invalid bdi_total');
                            }
                        } catch (error) {
                            try {
                                wpa_total = parseFloat(jQuery('.order-total .woocommerce-Price-amount').text().replace(/[^\d\.]/g, ''));
                                if (isValidAmount(wpa_total)) {
                                    nmi_info.cart_total = wpa_total;
                                    console.log('[nmi-checkout.js] trigger_nmi_checkout(): Using wpa_total:', wpa_total);
                                } else {
                                    throw new Error('Invalid wpa_total');
                                }
                            } catch (error) {
                                nmipay_log_error('[nmi-checkout.js] trigger_nmi_checkout(): ' + error);

                                // Fallback to wc_checkout_params
                                if (typeof wc_checkout_params !== 'undefined' && wc_checkout_params.total_price) {
                                    const total = parseFloat(wc_checkout_params.total_price);
                                    if (isValidAmount(total)) {
                                        nmi_info.cart_total = total;
                                        console.log('[nmi-checkout.js] trigger_nmi_checkout(): Using wc_checkout_params total:', total);
                                    } else {
                                        // Fallback to .order-total .amount element
                                        const totalElement = document.querySelector('.order-total .amount');
                                        if (totalElement) {
                                            currentTotal = parseFloat(totalElement.textContent.replace(/[^\d.-]/g, ''));
                                            if (isValidAmount(currentTotal)) {
                                                nmi_info.cart_total = currentTotal;
                                                console.log('[nmi-checkout.js] trigger_nmi_checkout(): Using totalElement:', currentTotal);
                                            } else {
                                                console.log('[nmi-checkout.js] trigger_nmi_checkout(): Invalid cart total from totalElement.');
                                            }
                                        } else {
                                            console.log('[nmi-checkout.js] trigger_nmi_checkout(): Cart total element not found.');
                                        }
                                    }
                                } else {
                                    console.log('[nmi-checkout.js] trigger_nmi_checkout(): wc_checkout_params not available.');
                                }
                            }
                        }

                        // Update cart total using enhanced method before final validation
                        updateNMICartTotal();
                        
                        // Final validation and logging
                        if (isValidAmount(nmi_info.cart_total)) {
                            console.log('[nmi-checkout.js] trigger_nmi_checkout(): Final valid cart total:', nmi_info.cart_total);
                        } else {
                            console.log('[nmi-checkout.js] trigger_nmi_checkout(): No valid cart total found, setting to 0.');
                            nmi_info.cart_total = 0;
                        }

                        nmipay_log_error('[nmi-checkout.js] trigger_nmi_checkout(): Cart Amount: ' + nmi_info.cart_total);
                        nmipay_log_error('[nmi-checkout.js] trigger_nmi_checkout(): BDI Amount: ' + bdi_total);
                        nmipay_log_error('[nmi-checkout.js] trigger_nmi_checkout(): WPA Amount: ' + wpa_total);




                        if( nmi_info.public_key != '' && nmi_info.enable_3dsecure == 'yes' ){

                            const options = {
                                paymentToken: response.token,
                                currency: nmi_info.currency_code,
                                amount: parseFloat(nmi_info.cart_total),
                                email: jQuery('#billing_email').val(),
                                phone: jQuery('#billing_phone').val(),
                                city: jQuery('#billing_city').val(),
                                //state: jQuery('#billing_state').val(),
                                address1: jQuery('#billing_address_1').val(),
                                //country: jQuery('#billing_country').val(),
                                firstName: jQuery('#billing_first_name').val(),
                                lastName: jQuery('#billing_last_name').val(),
                                postalCode: jQuery('#billing_postcode').val()
                            };

                            const gateway = Gateway.create(nmi_info.public_key);
                            const threeDS = gateway.get3DSecure();


                            const threeDSecureInterface = threeDS.createUI(options);
                            

                            nmipay_log_error('[nmi-checkout.js] trigger_nmi_checkout(): 3DS options '+ JSON.stringify(options));

                            // Create modal popup for 3DS challenge
                            const modalId = 'nmi-3ds-modal';
                            let modal = document.getElementById(modalId);
                            
                            if (!modal) {
                                modal = document.createElement('div');
                                modal.id = modalId;
                                modal.style.cssText = `
                                    position: fixed;
                                    top: 0;
                                    left: 0;
                                    width: 100%;
                                    height: 100%;
                                    background: rgba(0, 0, 0, 0.5);
                                    z-index: 999999;
                                    display: flex;
                                    align-items: center;
                                    justify-content: center;
                                `;
                                
                                const modalContent = document.createElement('div');
                                modalContent.style.cssText = `
                                    background: white;
                                    padding: 20px;
                                    border-radius: 8px;
                                    max-width: 90%;
                                    max-height: 90%;
                                    overflow: auto;
                                    position: relative;
                                `;
                                
                                const closeButton = document.createElement('button');
                                closeButton.innerHTML = '×';
                                closeButton.style.cssText = `
                                    position: absolute;
                                    top: 10px;
                                    right: 15px;
                                    background: none;
                                    border: none;
                                    font-size: 24px;
                                    cursor: pointer;
                                    color: #666;
                                `;
                                closeButton.onclick = function() {
                                    modal.style.display = 'none';
                                    threeDSecureInterface.unmount();
                                    jQuery.unblockUI();
                                    jQuery('#wc-robust_nmi_gateway-cc-form').css('display', 'block');
                                    submit_error('<div class="woocommerce-error" role="alert">3D Secure authentication cancelled</div>');
                                };
                                
                                const title = document.createElement('h3');
                                title.textContent = '3D Secure Authentication';
                                title.style.cssText = `
                                    margin: 0 0 20px 0;
                                    color: #333;
                                    font-size: 18px;
                                `;
                                
                                const challengeContainer = document.createElement('div');
                                challengeContainer.id = 'nmi-3ds-challenge-popup';
                                challengeContainer.style.cssText = `
                                    min-height: 400px;
                                    min-width: 400px;
                                `;
                                
                                modalContent.appendChild(closeButton);
                                modalContent.appendChild(title);
                                modalContent.appendChild(challengeContainer);
                                modal.appendChild(modalContent);
                                document.body.appendChild(modal);
                            }

                            // Show modal and hide form
                            modal.style.display = 'flex';
                            jQuery('#wc-robust_nmi_gateway-cc-form').css('display', 'none');
                            jQuery.unblockUI();
                            
                            // Start 3DS challenge in the modal
                            threeDSecureInterface.start('#nmi-3ds-challenge-popup');
                            
                                threeDSecureInterface.on('challenge', function(e) {
                                nmipay_log_error('[nmi-checkout.js] trigger_nmi_checkout(): 3DS Challenge started');
                                nmipay_log_error('[nmi-checkout.js] trigger_nmi_checkout(): 3DS Challenge: ' + JSON.stringify(e));
                                });


                            threeDSecureInterface.on('_debug', function(e) {
                                nmipay_log_error('[nmi-checkout.js] trigger_nmi_checkout(): debug');
                                nmipay_log_error('[nmi-checkout.js] trigger_nmi_checkout(): debug'+ JSON.stringify(e));

                                // Hide modal
                                modal.style.display = 'none';
                                threeDSecureInterface.unmount();

                                jQuery('#wc-robust_nmi_gateway-cc-form').css('display', 'block');
                                jQuery('#place_order').attr('disabled', false);
                                submit_error( '<div class="woocommerce-error" role="alert">Message: '+e.message +'</div>' );
                                jQuery('.nmipay_payment_token').remove();
                                jQuery('.nmipay_payment_3ds').remove();
                                jQuery.unblockUI();
                            });


                            threeDSecureInterface.on('complete', function(e) {
                                
                                nmipay_log_error('[nmi-checkout.js] trigger_nmi_checkout(): 3DS Complete'+ JSON.stringify(response));
                                nmipay_log_error('[nmi-checkout.js] trigger_nmi_checkout(): 3DS Complete'+ JSON.stringify(e));
                                
                                // Hide modal
                                modal.style.display = 'none';
                                threeDSecureInterface.unmount();
                                
                                checkout_form.append("<input type='text' class='nmipay_payment_token' name='nmipay_payment_token' value='" + JSON.stringify(response) + "'/>");
                                checkout_form.append("<input type='text' class='nmipay_payment_3ds' name='nmipay_payment_3ds' value='" + JSON.stringify(e) + "'/>");
                                checkout_form.submit();
                                jQuery('.nmipay_payment_token').remove();
                                jQuery('.nmipay_payment_3ds').remove();
                                jQuery.unblockUI();
                                jQuery('#wc-robust_nmi_gateway-cc-form').css('display', 'block');

                            });

                            threeDSecureInterface.on('failure', function(e) {
                                nmipay_log_error('[nmi-checkout.js] trigger_nmi_checkout(): failure');
                                nmipay_log_error('[nmi-checkout.js] trigger_nmi_checkout(): failure'+ JSON.stringify(e));

                                // Hide modal
                                modal.style.display = 'none';
                                threeDSecureInterface.unmount();

                                jQuery('#wc-robust_nmi_gateway-cc-form').css('display', 'block');
                                jQuery('#place_order').attr('disabled', false);
                                submit_error( '<div class="woocommerce-error" role="alert">3D Secure authentication failed: '+e.message +'</div>' );
                                jQuery('.nmipay_payment_token').remove();
                                jQuery('.nmipay_payment_3ds').remove();
                                jQuery.unblockUI();
                                
                                // Prevent form submission by stopping the payment process
                                return false;
                            });

                            gateway.on('error', function (e) {
                                nmipay_log_error('[nmi-checkout.js] trigger_nmi_checkout(): Error');
                                nmipay_log_error('[nmi-checkout.js] trigger_nmi_checkout(): Error'+ JSON.stringify(e));

                                // Hide modal
                                modal.style.display = 'none';
                                threeDSecureInterface.unmount();

                                submit_error( '<div class="woocommerce-error" role="alert">3D Secure authentication failed: '+e.message +'</div>' );
                                jQuery('.nmipay_payment_token').remove();
                                jQuery('.nmipay_payment_3ds').remove();
                                jQuery.unblockUI();
                                jQuery('#wc-robust_nmi_gateway-cc-form').css('display', 'block');
                                
                                // Prevent form submission by stopping the payment process
                                return false;
                            });

                        }else{

                            ////////////////////////////////////////////////////////////////////////////////////
                            nmipay_log_error('[nmi-checkout.js] trigger_nmi_checkout(): Normal Complete');

                            nmipay_log_error('[nmi-checkout.js] trigger_nmi_checkout(): Normal Complete '+ JSON.stringify(response));

                            checkout_form.append("<input type='text' class='nmipay_payment_token' name='nmipay_payment_token' value='" + JSON.stringify(response) + "'/>");
                            checkout_form.submit();
                            jQuery('.nmipay_payment_token').remove();
                            jQuery('.nmipay_payment_3ds').remove();
                            jQuery.unblockUI();
                            jQuery('#wc-robust_nmi_gateway-cc-form').css('display', 'block');
                            ////////////////////////////////////////////////////////////////////////////////////

                        }
                    },
                    'timeoutDuration' : 60000,
                    'timeoutCallback' : function () {

                        message = 'Transaction has timed out. Please try again.';

                        nmipay_log_error('[nmi-checkout.js] trigger_nmi_checkout(): ' + message);

                        submit_error( '<div class="woocommerce-error" role="alert">Message: '+message +'</div>' );

                        jQuery('.nmipay_payment_token').remove();
                        jQuery('.nmipay_payment_3ds').remove();
                        jQuery.unblockUI();
                        jQuery('#wc-robust_nmi_gateway-cc-form').css('display', 'block');


                    },
                    "fieldsAvailableCallback" : function () {
                        
                        jQuery.unblockUI();
                        
                        console.log("[nmi-checkout.js] trigger_nmi_checkout(): Collect.js loaded the fields onto the form");

                        nmipay_log_error('[nmi-checkout.js] trigger_nmi_checkout(): Collect.js loaded the fields onto the form');

                        
                        if (jQuery('#nmi-ccnumber iframe').length > 0) {

                            nmipay_log_error('[nmi-checkout.js] trigger_nmi_checkout(): CC Number field is loaded.');

                            nmi_info.fields_loaded = '1';

                        }

                        
                        if (jQuery('#nmi-ccexp iframe').length > 0) {

                            nmipay_log_error('[nmi-checkout.js] trigger_nmi_checkout(): CC Expiry field is loaded.');

                            nmi_info.fields_loaded = '1';

                        }

                        
                        if (jQuery('#nmi-cvv iframe').length > 0) {

                            nmipay_log_error('[nmi-checkout.js] trigger_nmi_checkout(): CC CVV field is loaded.');

                            nmi_info.fields_loaded = '1';

                        }
                    
                    }

                });
                
            } catch (error) {
                console.error('[nmi-checkout.js] trigger_nmi_checkout(): Error configuring CollectJS:', error);
                if (componentMounted.current) {
                    setError('Failed to initialize payment fields: ' + error.message);
                    setIsLoading(false);
                } else if (error.message && (error.message.includes('PaymentRequestAbstraction') || 
                    error.message.includes('Could not create PaymentRequestAbstraction'))) { // Handle PaymentRequestAbstraction errors specifically
                    console.warn('[nmi-checkout.js] trigger_nmi_checkout(): NMI Wallets: PaymentRequestAbstraction error caught and handled:', error.message);
                    logError('NMI Wallets: PaymentRequestAbstraction error - ' + error.message);
                } else {
                    console.error('[nmi-checkout.js] trigger_nmi_checkout(): Error configuring CollectJS:', error);
                    logError('CollectJS configuration error: ' + error.message);
                }
            }

        }
            
    }


    if (/iPad|iPhone|iPod/.test(navigator.userAgent)) {

        // Apple Pay button handling removed - handled by nmi-wallets.js
    
        // Apple Pay button hover handling removed - handled by nmi-wallets.js

    }

    // Google Pay button handling removed - handled by nmi-wallets.js

    jQuery('form.checkout').on('checkout_place_order_robust_nmi_gateway', function( e ) { 
        nmipay_log_error('[nmi-checkout.js] Form handler: checkout_place_order_robust_nmi_gateway');
        return nmipay_process_card();
    });	

    jQuery('form#order_review').submit(function(){
        nmipay_log_error('[nmi-checkout.js] Form handler: order_review');
        return nmipay_process_card();
    });

    jQuery('form#add_payment_method').submit(function(){
        nmipay_log_error('[nmi-checkout.js] Form handler: order_add_method');
        return nmipay_process_card();
    });

    jQuery("form.checkout, form#order_review, form#add_payment_method").on('change', '.nmipay-creditcard, .nmipay-cvv, .nmipay-expdatemonth, .nmipay-expdateyear, .nmipay-account, .nmipay-bankcode, .nmipay-accname', function( e ) {
        jQuery('.woocommerce_error, .woocommerce_message, .nmipay_payment_token, .nmipay_payment_3ds').remove();
    });


    function nmipay_process_card() {

        console.log('[nmi-checkout.js] nmipay_process_card(): CollectJS configuration completed for block checkout '+CollectJS.configure);


        nmipay_log_error('[nmi-checkout.js] nmipay_process_card(): nmipay_process_card called');
        nmipay_log_error('[nmi-checkout.js] nmipay_process_card(): Payment method checked: ' + jQuery('#payment_method_robust_nmi_gateway').is(':checked'));
        nmipay_log_error('[nmi-checkout.js] nmipay_process_card(): Payment token length: ' + jQuery('input.nmipay_payment_token').length);
        nmipay_log_error('[nmi-checkout.js] nmipay_process_card(): Payment 3DS length: ' + jQuery('input.nmipay_payment_3ds').length);

        if ( jQuery('#payment_method_robust_nmi_gateway').is(':checked') &&  jQuery( 'input.nmipay_payment_token' ).length == 0 &&  jQuery( 'input.nmipay_payment_3ds' ).length == 0 ) {

            nmipay_log_error('[nmi-checkout.js] nmipay_process_card(): submit');         
            
            let missingFields = [];

            // Iterate over each required billing field
            jQuery('.woocommerce-billing-fields .validate-required').each(function() {
                let $field = $(this);
                let inputValue = $field.find('input, select').val();
                if (!inputValue || inputValue.trim() === '') {
                    // Get field label for better error messages
                    let fieldLabel = $field.find('label').text().trim().replace('*','');
                    missingFields.push(fieldLabel);
                }
            });
    
            if (missingFields.length) {

                let missingFieldsStr = missingFields.join(', ');

                submit_error( '<div class="woocommerce-error" role="alert">Please fill in the following required billing fields before proceeding: <b>' + missingFieldsStr +'</b></div>' );
    
                return false;
            
            
            }else if ( jQuery('#terms').length && !jQuery('#terms').is(':checked')) {
                // Check if the 'terms' input exists
                
                // Alert the user or display an error message
                submit_error( '<div class="woocommerce-error" role="alert">Please accept the terms and conditions before proceeding.</div>' );
    
                return false;

            }else{

                let selectedToken = jQuery("input[name='wc-nmipay-payment-token']:checked").val();
                nmipay_log_error('[nmi-checkout.js] nmipay_process_card(): Selected token value: ' + selectedToken);
                nmipay_log_error('[nmi-checkout.js] nmipay_process_card(): Is token numeric: ' + !isNaN(selectedToken));

                if( !isNaN(selectedToken) ){

                    nmipay_log_error('[nmi-checkout.js] nmipay_process_card(): Vault Card Checkout');
                                        
                    return true;
    
                }else{
    
                    nmi_info.submitted = '1';
                    nmi_info.errors = '';
    
                    nmipay_log_error('[nmi-checkout.js] nmipay_process_card(): New Card Checkout');
    
                    if( nmi_info.inline_card ){
    
                        jQuery.blockUI(
                            {
                                message: 'Please wait while your order is being processed.',
                                css: {
                                    padding:        0, 
                                    margin:         0, 
                                    //width:          '360px',
                                    //height:          '400px',
                                    textAlign:      'center', 
                                    color:          '#000', 
                                    border:         '3px solid #aaa', 
                                    backgroundColor:'#fff', 
                                    cursor:         'wait',
                                    top:             '20%',
                                },
                                
                            }
    
                        );
    
                    }
                    CollectJS.startPaymentRequest();
                    return false;
                }

            }
                    
        } else {
            nmipay_log_error('[nmi-checkout.js] nmipay_process_card(): Payment method not checked or tokens already present');
        }
        return true;
    };


    function load_elements(){

        nmipay_log_error("[nmi-checkout.js] load_elements(): Final DOM is "+document.readyState);

        // Setup traditional checkout total updates
        setupTraditionalCheckoutTotalUpdates();

        var tokens = jQuery('input[name="wc-nmipay-payment-token"]').length;
        var selected_token = jQuery('input[name="wc-nmipay-payment-token"]:checked').val();
        
        nmipay_log_error('[nmi-checkout.js] load_elements(): Tokens count: ' + tokens);
        nmipay_log_error('[nmi-checkout.js] load_elements(): Selected token: ' + selected_token);
        
        jQuery( document.body ).on( 'updated_checkout', function() {
            nmipay_log_error('[nmi-checkout.js] load_elements(): updated_checkout');

            if (selected_token && selected_token !== 'new') {
                nmipay_log_error('[nmi-checkout.js] load_elements(): wc-nmipay-payment-token-old');
                jQuery('#wc-robust_nmi_gateway-cc-form').css('display', 'none');
            }else{
                jQuery('#wc-robust_nmi_gateway-cc-form').css('display', 'block');
                trigger_nmi_checkout(nmi_info);
            }

        });

        jQuery( document.body ).on( 'payment_method_selected', function() {
            nmipay_log_error('[nmi-checkout.js] load_elements(): payment_method_selected');
            if ( jQuery('#payment_method_robust_nmi_gateway').is(':checked')  ){
                if (selected_token && selected_token !== 'new') {
                    nmipay_log_error('[nmi-checkout.js] load_elements(): wc-nmipay-payment-token-old');
                    jQuery('#wc-robust_nmi_gateway-cc-form').css('display', 'none');
                }else{
                    jQuery('#wc-robust_nmi_gateway-cc-form').css('display', 'block');
                    trigger_nmi_checkout(nmi_info);
                }
            
            }
        });


        if ( jQuery('#payment_method_robust_nmi_gateway').is(':checked')  ){
            if (selected_token && selected_token !== 'new') {
                nmipay_log_error('[nmi-checkout.js] load_elements(): wc-nmipay-payment-token-old');
                jQuery('#wc-robust_nmi_gateway-cc-form').css('display', 'none');
            }else{
                jQuery('#wc-robust_nmi_gateway-cc-form').css('display', 'block');
                trigger_nmi_checkout(nmi_info);
            }
        }

        
        if (jQuery('body').hasClass('woocommerce-add-payment-method')) {
            if (selected_token && selected_token !== 'new') {
                nmipay_log_error('[nmi-checkout.js] load_elements(): wc-nmipay-payment-token-old');
                jQuery('#wc-robust_nmi_gateway-cc-form').css('display', 'none');
            }else{
                jQuery('#wc-robust_nmi_gateway-cc-form').css('display', 'block');
                trigger_nmi_checkout(nmi_info);
            }
        }


        jQuery( 'form.woocommerce-checkout' ).on( 'click change', 'input[name="wc-nmipay-payment-token"]', function() {
            if ( jQuery( '#payment_method_robust_nmi_gateway' ).is( ':checked' ) && ( ! jQuery( 'input[name="wc-nmipay-payment-token"]:checked' ).length || 'new' === jQuery( 'input[name="wc-nmipay-payment-token"]:checked' ).val() ) && ! jQuery( '#nmi-card-number-element' ).children().length ) {
                nmipay_log_error('[nmi-checkout.js] load_elements(): wc-nmipay-payment-token-new');
                jQuery('#wc-robust_nmi_gateway-cc-form').css('display', 'block');
                trigger_nmi_checkout(nmi_info);
            }

            if ( ( ! jQuery( 'input[name="wc-nmipay-payment-token"]:checked' ).length || 'new' != jQuery( 'input[name="wc-nmipay-payment-token"]:checked' ).val() ) && ! jQuery( '#nmi-card-number-element' ).children().length ) {
                nmipay_log_error('[nmi-checkout.js] load_elements(): wc-nmipay-payment-token-old');
                jQuery('#wc-robust_nmi_gateway-cc-form').css('display', 'none');
            }

        });
        
    }

    function checkReadyState() {
        if (document.readyState === 'complete') {
            clearInterval(intervalId);
            console.log('[nmi-checkout.js] checkReadyState(): Document is fully loaded.');
            // Place your code here that should run after the document is fully loaded
            load_elements();
        } else {
            console.log('[nmi-checkout.js] checkReadyState(): Document is not yet fully loaded, current state:', document.readyState);
        }
    }
    
    // Set an interval to check the readyState every 100 milliseconds
    var intervalId = setInterval(checkReadyState, 200);
  
});