var { __ } = wp.i18n;

jQuery(function ($) {
    // Utility function for XSS protection - defined at top level for reusability
    function escapeHTML(str) {
        if (typeof str !== 'string') return str;
        return str
            .replace(/&/g, "&amp;")
            .replace(/</g, "&lt;")
            .replace(/>/g, "&gt;")
            .replace(/"/g, "&quot;")
            .replace(/'/g, "&#039;");
    }
    if (window.history.replaceState) {
        window.history.replaceState(null, null, window.location.href);
    }
    /**
     * Object to handle Anet payment forms.
     */
    var anet_accept = {
        validationErrors: [], // Store validation error messages
        echeckValidationErrors: [], // Store eCheck validation error messages
        init: function () {
            // checkout page
            if ($('form.woocommerce-checkout').length) {
                this.form = $('form.woocommerce-checkout');
            }
            //normal card
            $('form.woocommerce-checkout')
                .on(
                    'checkout_place_order_anet',
                    this.onSubmit
                )
            $('form.woocommerce-checkout')
                .on(
                    'checkout_place_order_anet_echeck',
                    this.onSubmit
                );
            //pay order page
            if ($('form#order_review').length) {
                this.form = $('form#order_review');
            }
            $('form#order_review')
                .on(
                    'submit',
                    this.onSubmit
                )
            //payment method page
            if ($('form#add_payment_method').length) {
                this.form = $('form#add_payment_method');
            }
            //store card
            $('form#add_payment_method')
                .on(
                    'submit',
                    this.onSubmit
                )
            $(document)
                .on('change',
                    '#anet-credit-card-form :input, #anet-echeck-form :input',
                    function () {
                        anet_accept.onCCFormChange();
                    }
                )
                .on(
                    'anetError',
                    this.onError
                )
                .on(
                    'checkout_error',
                    this.clearToken
                );
            
            // Clear aria-invalid on focus for eCheck fields
            $(document).on('focus', '#anet-echeck-routing-number, #anet-echeck-account-number, #anet-echeck-account-name, #anet-echeck-bank-account-type', function () {
                $(this).removeAttr('aria-invalid');
            });
        },
        isAnetPayment: function () {
            return $('#payment_method_anet').is(':checked') && (!$('input[name="wc-anet-payment-token"]:checked').length || 'new' === $('input[name="wc-anet-payment-token"]:checked').val());
        },
        isAneteCheckChosen: function () {
            return $('#payment_method_anet_echeck').is(':checked') && (!$('input[name="wc-anet_echeck-payment-token"]:checked').length || 'new' === $('input[name="wc-anet_echeck-payment-token"]:checked').val());
        },
        hasToken: function () {
            return (0 < $('input.anet_nonce').length) && (0 < $('input.anet_data_descriptor').length);
        },
        block: function () {
            anet_accept.form.block({
                message: null,
                overlayCSS: {
                    background: '#fff',
                    opacity: 0.6
                }
            });
        },
        unblock: function () {
            try {
                anet_accept.form.unblock();
            } catch (error) {
                console.error('Error unblocking form via form.unblock():', error);
            }
            // Additional aggressive unblocking for add payment method page
            try {
                $('form#add_payment_method').unblock();
                $('form.woocommerce-checkout').unblock();
                $('form#order_review').unblock();
            } catch (error) {
                console.error('Error unblocking individual forms:', error);
            }
            // Nuclear option - remove all blockUI elements
            $('.blockUI').remove();
            $('.blockMsg').remove();
            $('.blockElement').removeClass('blockElement');
            $('body').removeClass('blockUI-disabled');
            $('form').removeClass('processing');
        },
        // Common error display and unblocking function
        displayErrorAndUnblock: function (errorContent, scrollToError) {
            scrollToError = scrollToError !== false; // Default to true
            var errorDisplayed = false;
            // Convert string HTML to jQuery object if needed, with sanitization
            var $errorContent;
            if (typeof errorContent === 'string') {
                // For Client Potential XSS - Create element safely 
                var cleanText = escapeHTML(errorContent);
                $errorContent = $('<div class="woocommerce_error woocommerce-error wc-anet-error"></div>');
                $errorContent.text(cleanText);
            } else {
                // Already a jQuery object
                $errorContent = errorContent;
            }
            // finding the container based on form type ( CC / echeck )
            if (anet_accept.isAnetPayment()) {  // CC errors
                // Credit card errors - check if we're on actual checkout page
                var checkoutWrapper = $('.woocommerce-billing-fields__field-wrapper_credit_card');
                var isActuallyCheckoutPage = $('form.woocommerce-checkout').length > 0 && $('body').hasClass('woocommerce-checkout');
                if (checkoutWrapper.length > 0 && checkoutWrapper.is(':visible') && isActuallyCheckoutPage) {
                    checkoutWrapper.prepend($errorContent);
                    errorDisplayed = true;
                } else if ($('#anet-card-number').length > 0) {
                    // Add payment method page - use parent container approach
                    var parentContainer = $('#anet-card-number').closest('fieldset, .payment_box, form');
                    if (parentContainer.length > 0) {
                        parentContainer.prepend($errorContent);
                        errorDisplayed = true;
                    } else {
                        // Fallback to form row method
                        $('#anet-card-number').closest('.form-row').before($errorContent);
                        errorDisplayed = true;
                    }
                }
            } else if (anet_accept.isAneteCheckChosen()) {   // eCheck errors              
                var echeckWrapper = $('.woocommerce-billing-fields__field-wrapper_echeck');
                var isActuallyCheckoutPage = $('form.woocommerce-checkout').length > 0 && $('body').hasClass('woocommerce-checkout');
                if (echeckWrapper.length > 0 && echeckWrapper.is(':visible') && isActuallyCheckoutPage) {
                    echeckWrapper.prepend($errorContent);
                    errorDisplayed = true;
                } else if ($('#anet-echeck-routing-number').length > 0) {
                    // Add payment method page - use parent container approach
                    var parentContainer = $('#anet-echeck-routing-number').closest('fieldset, .payment_box, form');
                    if (parentContainer.length > 0) {
                        parentContainer.prepend($errorContent);
                        errorDisplayed = true;
                    } else {
                        // Fallback to form row method
                        $('#anet-echeck-routing-number').closest('.form-row').before($errorContent);
                        errorDisplayed = true;
                    }
                }
            }
            // Error display at the top of the current form
            if (!errorDisplayed && anet_accept.form) {
                anet_accept.form.prepend($errorContent);
                errorDisplayed = true;
            }
            // Scroll to error message
            if (scrollToError && $('.wc-anet-error').length > 0) {
                $('html, body').animate({
                    scrollTop: $('.wc-anet-error').offset().top - 100
                }, 500);
            }
            // Immediate unblock
            anet_accept.unblock();
            // Delayed additional unblock to ensure overlay is completely removed
            setTimeout(function () {
                $('.blockUI').remove();
                $('.blockMsg').remove();
                $('.blockElement').removeClass('blockElement');
                $('body').removeClass('blockUI-disabled');
                $('form').removeClass('processing');
                try {
                    $('form#add_payment_method').unblock();
                    $('form.woocommerce-checkout').unblock();
                    $('form#order_review').unblock();
                } catch (error) {
                    console.error('Delayed unblock error:', error);
                }
            }, 100);
        },
        onError: function (e, responseObject) {
            var message = responseObject.response.text;
            // Remove existing error messages
            $('.wc-anet-error', '.anet_nonce').remove();
            $('.wc-anet-error', '.anet_data_descriptor').remove();
            // For Client Potential XSS - Create error message safely without using .html()
            var $errorMessages = $('<div>', {
                class: 'woocommerce_error woocommerce-error wc-anet-error'
            });
            // Create text node for the error message and append it
            var errorDiv = document.createElement('div');
            errorDiv.textContent = message;
            $errorMessages.append(errorDiv);
            
            anet_accept.displayErrorAndUnblock($errorMessages);
        },
        onSubmit: function (e) {
            var authData = {};
            var secureData = {};
            // Check network connectivity before processing
            if (!navigator.onLine) {
                e.preventDefault();
                e.stopImmediatePropagation();
                var networkErrorMsg = __('You appear to be offline. Please check your internet connection and try again.', 'authorize-net-payments-for-woocommerce');
                anet_accept.displayErrorAndUnblock(networkErrorMsg);
                return false;
            }
            if (anet_accept.isAnetPayment() && !anet_accept.hasToken()) {
                e.preventDefault();
                // Clear any existing errors first
                $('.wc-anet-error').remove();
                // Re-run all validations
                $('[data-anet="card-number"]').trigger('blur');
                $('[data-anet="card-cvc"]').trigger('blur');
                $('[data-anet="expiry-month"]').trigger('blur');
                $('[data-anet="expiry-year"]').trigger('blur');
                // Check if any field is invalid - only for credit card fields
                if (anet_accept.hasInvalidCreditCardFields()) {
                    // Use specific validation errors if available
                    var errorMessages = anet_accept.validationErrors || [__('Please correct the highlighted credit card fields.', 'authorize-net-payments-for-woocommerce')];
                    var $errorMessages = $('<ul>', {
                        class: 'woocommerce_error woocommerce-error wc-anet-error'
                    });
                    // Create list items for each error message
                    var errorHtml = '';
                    for (var k = 0; k < errorMessages.length; k++) {
                        if (typeof errorMessages[k] === 'string') {
                            errorHtml += '<li>' + escapeHTML(errorMessages[k]) + '</li>';
                        }
                    }
                    $errorMessages.html(errorHtml);
                    anet_accept.displayErrorAndUnblock($errorMessages);
                    // Stop form submission
                    e.preventDefault();
                    e.stopPropagation();
                    e.stopImmediatePropagation();
                    return false;
                }
                anet_accept.block();
                // Read card data from fields using data-anet selectors (NOT name attributes)
                // This ensures we're explicitly reading from tokenization-only fields
                card = $('[data-anet="card-number"]').val(),
                    cvc = $('[data-anet="card-cvc"]').val(),
                    expires = {
                        month: $('[data-anet="expiry-month"]').val(),
                        year: $('[data-anet="expiry-year"]').val()
                    };
                first_name = $('#billing_first_name').length ? $('#billing_first_name').val() : anet_params_cc.billing_first_name,
                last_name = $('#billing_last_name').length ? $('#billing_last_name').val() : anet_params_cc.billing_last_name;
                authData.clientKey = anet_params_cc.client_key;
                authData.apiLoginID = anet_params_cc.login_id;
                var cardData = {};
                cardData.cardNumber = card.replace(/\s/g, '');
                cardData.month = expires.month.toString();
                cardData.year = expires.year.toString().slice(-2);
                cardData.cardCode = cvc;
                if (first_name && last_name) {
                    cardData.fullName = first_name + anet_params.anet_space + last_name;
                }
                // CVV validation
                var amexRegex = /^3[47][0-9]{13}$/;
                var cvvRegex = amexRegex.test(cardData.cardNumber) ? /^\d{4}$/ : /^\d{3}$/;
                if (!cvc || !cvvRegex.test(cvc)) {
                    $('.wc-anet-error').remove();
                    var errorMsg = amexRegex.test(cardData.cardNumber)
                        ? __('Please enter a valid 4-digit CVV for American Express.', 'authorize-net-payments-for-woocommerce')
                        : __('Please enter a valid 3-digit CVV.', 'authorize-net-payments-for-woocommerce');
                    var messageText = errorMsg;
                    var $errorMessages = $('<ul>', {
                        class: 'woocommerce_error woocommerce-error wc-anet-error'
                    });
                    // For Client Potential XSS - Create the entire HTML structure as a string with escaped content
                    if (typeof messageText === 'string') {
                        // Create the list item with escaped text
                        $errorMessages.html('<li>' + escapeHTML(messageText) + '</li>');
                    } else {
                        console.warn('Unexpected message type:', typeof messageText, messageText);
                        $errorMessages.html('<li>' + escapeHTML(__('An unexpected error occurred.', 'authorize-net-payments-for-woocommerce')) + '</li>'); // Safe fallback
                    }
                    anet_accept.displayErrorAndUnblock($errorMessages);
                    return false;
                }
                secureData.authData = authData;
                secureData.cardData = cardData;
                Accept.dispatchData(secureData, anet_accept.responseHandler);
                // Prevent form submitting
                return false;
            }
            else if (anet_accept.isAneteCheckChosen() && !anet_accept.hasToken()) {
                e.preventDefault();
                $('.wc-anet-error').remove();
                // Trigger validations
                $('[data-anet="routing-number"]').trigger('blur');
                $('[data-anet="account-number"]').trigger('blur');
                $('[data-anet="account-name"]').trigger('blur');
                $('[data-anet="account-type"]').trigger('blur');
                // Check for invalid fields - only for eCheck fields
                if (anet_accept.hasInvalidEcheckFields()) {
                    // Use specific validation errors if available
                    var errorMessages = anet_accept.echeckValidationErrors || [__('Please correct the highlighted eCheck fields.', 'authorize-net-payments-for-woocommerce')];
                    var $errorMessages = $('<ul>', {
                        class: 'woocommerce_error woocommerce-error wc-anet-error'
                    });
                    // Create list items for each error message
                    var errorHtml = '';
                    for (var k = 0; k < errorMessages.length; k++) {
                        if (typeof errorMessages[k] === 'string') {
                            errorHtml += '<li>' + escapeHTML(errorMessages[k]) + '</li>';
                        }
                    }
                    $errorMessages.html(errorHtml);
                    anet_accept.displayErrorAndUnblock($errorMessages);
                    // Stop form submission
                    e.preventDefault();
                    e.stopPropagation();
                    e.stopImmediatePropagation();
                    return false;
                }
                anet_accept.block();
                // Read eCheck data from fields using data-anet selectors (NOT name attributes)
                // This ensures we're explicitly reading from tokenization-only fields
                var routing_number = $('[data-anet="routing-number"]').val(),
                    account_number = $('[data-anet="account-number"]').val(),
                    account_name = $('[data-anet="account-name"]').val(),
                    account_type = $('[data-anet="account-type"]').val();
                first_name = $('#billing_first_name').length ? $('#billing_first_name').val() : anet_echeck_params.billing_first_name,
                    last_name = $('#billing_last_name').length ? $('#billing_last_name').val() : anet_echeck_params.billing_last_name;
                authData.clientKey = anet_echeck_params.client_key;
                authData.apiLoginID = anet_echeck_params.login_id;
                var bankData = {};
                bankData.accountNumber = account_number;
                bankData.routingNumber = routing_number;
                bankData.nameOnAccount = account_name;
                bankData.accountType = account_type;
                if (bankData.nameOnAccount === '' && first_name && last_name) {
                    bankData.nameOnAccount = first_name + anet_params.anet_space + last_name;
                }
                secureData.authData = authData;
                secureData.bankData = bankData;
                Accept.dispatchData(secureData, anet_accept.responseHandler);
                // Prevent form submitting
                return false;
            }
            else {
                // Allow normal form submission for saved payment methods or other scenarios
                return true;
            }
        },
        onCCFormChange: function () {
            $('.wc-anet-error, .anet_nonce').remove();
            $('.wc-anet-error, .anet_data_descriptor').remove();
        },
        responseHandler: function (response) {
            if (anet_params.anet_error === response.messages.resultCode) {
                // Handle errors from Accept.js
                var i = 0;
                // Collect all error messages first
                var errorMessagesArray = [];
                while (i < response.messages.message.length) {
                    console.error('Accept.js API Error:', response.messages.message[i].code + ": " + response.messages.message[i].text);
                    var messageText = response.messages.message[i].text;
                    // For Client Potential XSS - Collect escaped messages in an array
                    if (typeof messageText === 'string') {
                        errorMessagesArray.push(escapeHTML(messageText));
                    } else {
                        console.warn('Unexpected message type:', typeof messageText, messageText);
                        errorMessagesArray.push('An unexpected error occurred.');
                    }
                    i = i + 1;
                }
                // Create the error messages container
                var $errorMessages = $('<div>', {
                    class: 'woocommerce_error woocommerce-error wc-anet-error'
                });
                // Create text nodes for each error message and append them
                for (var j = 0; j < errorMessagesArray.length; j++) {
                    var errorDiv = document.createElement('div');
                    errorDiv.textContent = errorMessagesArray[j];
                    $errorMessages.append(errorDiv);
                }
                // Use centralized error handling for API errors
                anet_accept.displayErrorAndUnblock($errorMessages, 'API validation error');
                return false;
            }
            else {
                // Handle successful tokenization
                anet_accept.paymentFormUpdate(response.opaqueData);
            }
        },
        paymentFormUpdate: function (opaqueData) {
            // Insert the token into the form so it gets submitted to the server
            var $nonceInput = $('<input>', {
                type: 'hidden',
                class: 'anet_nonce',
                name: 'anet_nonce',
                value: opaqueData.dataValue
            });
            var $descriptorInput = $('<input>', {
                type: 'hidden',
                class: 'anet_data_descriptor',
                name: 'anet_data_descriptor',
                value: opaqueData.dataDescriptor
            });
            anet_accept.form.append($nonceInput);
            anet_accept.form.append($descriptorInput);
            // Network monitoring for form submission
            anet_accept.startNetworkMonitoring();
            // Submit the form
            anet_accept.form.submit();
        },
        // Network monitoring - covers all scenarios
        startNetworkMonitoring: function () {
            var self = this;
            // Combined timeout + network monitoring
            this.networkTimeout = setTimeout(function () {
                self.handleNetworkIssue(__('Processing timeout - please check your connection and try again.', 'authorize-net-payments-for-woocommerce'));
            }, 30000);
            // Listen for network offline event
            window.addEventListener('offline', this.networkHandler = function () {
                self.handleNetworkIssue(__('Connection lost during processing - please check your internet connection.', 'authorize-net-payments-for-woocommerce'));
            });
        },
        // Handle any network issue with single function
        handleNetworkIssue: function (message) {
            // Cleanup all monitoring
            if (this.networkTimeout) {
                clearTimeout(this.networkTimeout);
                this.networkTimeout = null;
            }
            if (this.networkHandler) {
                window.removeEventListener('offline', this.networkHandler);
                this.networkHandler = null;
            }
            anet_accept.displayErrorAndUnblock(message);
        },
        clearToken: function () {
            $('.anet_nonce').remove();
            $('.anet_data_descriptor').remove();
        },
        // Function to detect card type from card number
        getCardType: function (cardNumber) {
            var cleanNumber = cardNumber.replace(/\D/g, '');
            // Visa
            if (/^4/.test(cleanNumber)) {
                return 'visa';
            }
            // Mastercard
            if (/^5[1-5]|^2[2-7]/.test(cleanNumber)) {
                return 'mastercard';
            }
            // American Express
            if (/^3[47]/.test(cleanNumber)) {
                return 'amex';
            }
            // Discover
            if (/^(6011|622(12[6-9]|1[3-9][0-9]|[2-8][0-9]{2}|9[0-1][0-9]|92[0-5]|64[4-9])|65)/.test(cleanNumber)) {
                return 'discover';
            }
            // JCB
            if (/^35(2[89]|[3-8][0-9])/.test(cleanNumber)) {
                return 'jcb';
            }
            // Diners Club
            if (/^3[0689]/.test(cleanNumber)) {
                return 'diners-club';
            }
            return 'unknown';
        },
        // Function to check if card type is allowed
        isCardTypeAllowed: function (cardType, allowedTypes) {
            if (!allowedTypes || 0 === allowedTypes.length) {
                return false; // If no card types configured, don't allow any
            }
            return allowedTypes.indexOf(cardType) !== -1;
        },
        // Function to check for invalid credit card fields only
        hasInvalidCreditCardFields: function () {
            var isValid = true;
            var errors = [];
            // Check card number
            var cardNumber = $('[data-anet="card-number"]').val();
            var cleanCardNumber = cardNumber ? cardNumber.replace(/\s/g, '') : '';
            if (!cleanCardNumber || !/^\d{13,19}$/.test(cleanCardNumber)) {
                $('#anet-card-number-div').addClass('woocommerce-invalid woocommerce-invalid-required-field');
                $('#anet-card-number-div').removeClass('woocommerce-validated');
                errors.push(__('Please enter a valid credit card number.', 'authorize-net-payments-for-woocommerce'));
                isValid = false;
            } else {
                // Additional validation using Luhn algorithm
                if (!anet_accept.isValidCardNumber(cleanCardNumber)) {
                    $('#anet-card-number-div').addClass('woocommerce-invalid woocommerce-invalid-required-field');
                    $('#anet-card-number-div').removeClass('woocommerce-validated');
                    errors.push(__('Please enter a valid credit card number.', 'authorize-net-payments-for-woocommerce'));
                    isValid = false;
                } else {
                    // Card type validation - check if card type is allowed
                    var cardType = anet_accept.getCardType(cleanCardNumber);
                    var allowedCardTypes = anet_params_cc.allowed_card_types || [];
                    if (!anet_accept.isCardTypeAllowed(cardType, allowedCardTypes)) {
                        $('#anet-card-number-div').addClass('woocommerce-invalid woocommerce-invalid-required-field');
                        $('#anet-card-number-div').removeClass('woocommerce-validated');
                        if (!allowedCardTypes || allowedCardTypes.length === 0) {
                            errors.push(__('No card types have been configured in admin. Please contact support.', 'authorize-net-payments-for-woocommerce'));
                        } else {
                            errors.push(__('This card type is not accepted. Please use a different card.', 'authorize-net-payments-for-woocommerce'));
                        }
                        isValid = false;
                    } else {
                        $('#anet-card-number-div').removeClass('woocommerce-invalid woocommerce-invalid-required-field');
                        $('#anet-card-number-div').addClass('woocommerce-validated');
                    }
                }
            }
            // Check CVV
            var cvc = $('[data-anet="card-cvc"]').val();
            var amexRegex = /^3[47][0-9]{13}$/;
            var expectedCvcLength = amexRegex.test(cleanCardNumber) ? 4 : 3;
            var cvcRegex = new RegExp('^\\d{' + expectedCvcLength + '}$');
            if (!cvc || !cvcRegex.test(cvc)) {
                $('#anet-card-cvc-div').addClass('woocommerce-invalid woocommerce-invalid-required-field');
                $('#anet-card-cvc-div').removeClass('woocommerce-validated');
                var cvcErrorMsg = amexRegex.test(cleanCardNumber)
                    ? __('Please enter a valid 4-digit CVV for American Express.', 'authorize-net-payments-for-woocommerce')
                    : __('Please enter a valid 3-digit CVV.', 'authorize-net-payments-for-woocommerce');
                errors.push(cvcErrorMsg);
                isValid = false;
            } else {
                $('#anet-card-cvc-div').removeClass('woocommerce-invalid woocommerce-invalid-required-field');
                $('#anet-card-cvc-div').addClass('woocommerce-validated');
            }
            // Check expiry month and year together to prevent past dates
            var expiryMonth = $('[data-anet="expiry-month"]').val();
            var expiryYear = $('[data-anet="expiry-year"]').val();
            var currentDate = new Date();
            var currentYear = currentDate.getFullYear();
            var currentMonth = currentDate.getMonth() + 1; // getMonth() returns 0-11, so add 1
            var monthValue = parseInt(expiryMonth);
            var yearValue = parseInt(expiryYear);
            // Handle 2-digit years
            if (yearValue < 100) {
                yearValue += 2000;
            }
            // Validate month range
            if (!expiryMonth || expiryMonth === '' || monthValue < 1 || monthValue > 12) {
                $('#anet-card-expiry-month-div').addClass('woocommerce-invalid woocommerce-invalid-required-field');
                $('#anet-card-expiry-month-div').removeClass('woocommerce-validated');
                errors.push(__('Please select a valid expiry month.', 'authorize-net-payments-for-woocommerce'));
                isValid = false;
            }
            // Validate year range
            if (!expiryYear || expiryYear === '' || yearValue < currentYear || yearValue > currentYear + 20) {
                $('#anet-card-expiry-year-div').addClass('woocommerce-invalid woocommerce-invalid-required-field');
                $('#anet-card-expiry-year-div').removeClass('woocommerce-validated');
                if (yearValue < currentYear) {
                    errors.push(__('Expiry year cannot be in the past.', 'authorize-net-payments-for-woocommerce'));
                } else if (yearValue > currentYear + 20) {
                    errors.push(__('Expiry year is too far in the future.', 'authorize-net-payments-for-woocommerce'));
                } else {
                    errors.push(__('Please select a valid expiry year.', 'authorize-net-payments-for-woocommerce'));
                }
                isValid = false;
            }
            // If both month and year are valid individually, check if the combination is in the past
            if (expiryMonth && expiryYear && monthValue >= 1 && monthValue <= 12 && yearValue >= currentYear) {
                // Check if the expiry date is in the past
                if (yearValue < currentYear || (yearValue === currentYear && monthValue < currentMonth)) {
                    $('#anet-card-expiry-month-div').addClass('woocommerce-invalid woocommerce-invalid-required-field');
                    $('#anet-card-expiry-year-div').addClass('woocommerce-invalid woocommerce-invalid-required-field');
                    $('#anet-card-expiry-month-div').removeClass('woocommerce-validated');
                    $('#anet-card-expiry-year-div').removeClass('woocommerce-validated');
                    errors.push(__('Credit card expiry date cannot be in the past.', 'authorize-net-payments-for-woocommerce'));
                    isValid = false;
                } else {
                    // Both month and year are valid and not in the past
                    $('#anet-card-expiry-month-div').removeClass('woocommerce-invalid woocommerce-invalid-required-field');
                    $('#anet-card-expiry-month-div').addClass('woocommerce-validated');
                    $('#anet-card-expiry-year-div').removeClass('woocommerce-invalid woocommerce-invalid-required-field');
                    $('#anet-card-expiry-year-div').addClass('woocommerce-validated');
                }
            }
            // Store errors for later use
            anet_accept.validationErrors = errors;
            return !isValid;
        },
        // Luhn algorithm validation for credit card numbers
        isValidCardNumber: function (cardNumber) {
            var sum = 0;
            var alternate = false;
            for (var i = cardNumber.length - 1; i >= 0; i--) {
                var digit = parseInt(cardNumber.charAt(i), 10);
                if (alternate) {
                    digit *= 2;
                    if (digit > 9) {
                        digit = (digit % 10) + 1;
                    }
                }
                sum += digit;
                alternate = !alternate;
            }
            return (sum % 10 === 0);
        },
        // Function to check for invalid eCheck fields only
        hasInvalidEcheckFields: function () {
            var isValid = true;
            var errors = [];
            // Check routing number
            var routingNumber = $('[data-anet="routing-number"]').val();
            if (!routingNumber || !/^\d{9}$/.test(routingNumber)) {
                $('#anet-bank-routing-number-div').addClass('woocommerce-invalid woocommerce-invalid-required-field');
                $('#anet-bank-routing-number-div').removeClass('woocommerce-validated');
                $('#anet-echeck-routing-number').attr('aria-invalid', 'true');
                if (!routingNumber) {
                    errors.push(__('Please enter your bank routing number.', 'authorize-net-payments-for-woocommerce'));
                } else {
                    errors.push(__('Routing number must be exactly 9 digits.', 'authorize-net-payments-for-woocommerce'));
                }
                isValid = false;
            } else {
                $('#anet-bank-routing-number-div').removeClass('woocommerce-invalid woocommerce-invalid-required-field');
                $('#anet-bank-routing-number-div').addClass('woocommerce-validated');
                $('#anet-echeck-routing-number').attr('aria-invalid', 'false');
            }
            // Check account number
            var accountNumber = $('[data-anet="account-number"]').val();
            if (!accountNumber || !/^\d{5,17}$/.test(accountNumber)) {
                $('#anet-bank-account-number-div').addClass('woocommerce-invalid woocommerce-invalid-required-field');
                $('#anet-bank-account-number-div').removeClass('woocommerce-validated');
                $('#anet-echeck-account-number').attr('aria-invalid', 'true');
                if (!accountNumber) {
                    errors.push(__('Please enter your bank account number.', 'authorize-net-payments-for-woocommerce'));
                } else {
                    errors.push(__('Account number must be between 5 and 17 digits.', 'authorize-net-payments-for-woocommerce'));
                }
                isValid = false;
            } else {
                $('#anet-bank-account-number-div').removeClass('woocommerce-invalid woocommerce-invalid-required-field');
                $('#anet-bank-account-number-div').addClass('woocommerce-validated');
                $('#anet-echeck-account-number').attr('aria-invalid', 'false');
            }
            // Check account name
            var accountName = $('[data-anet="account-name"]').val();
            if (!accountName || !/^[a-zA-Z\s]{2,}$/.test(accountName)) {
                $('#anet-bank-account-name-div').addClass('woocommerce-invalid woocommerce-invalid-required-field');
                $('#anet-bank-account-name-div').removeClass('woocommerce-validated');
                $('#anet-echeck-account-name').attr('aria-invalid', 'true');
                if (!accountName) {
                    errors.push(__('Please enter the name on the account.', 'authorize-net-payments-for-woocommerce'));
                } else {
                    errors.push(__('Account name must contain only letters and spaces, minimum 2 characters.', 'authorize-net-payments-for-woocommerce'));
                }
                isValid = false;
            } else {
                $('#anet-bank-account-name-div').removeClass('woocommerce-invalid woocommerce-invalid-required-field');
                $('#anet-bank-account-name-div').addClass('woocommerce-validated');
                $('#anet-echeck-account-name').attr('aria-invalid', 'false');
            }
            // Check account type
            var accountType = $('[data-anet="account-type"]').val();
            if (!accountType || accountType === '') {
                $('#anet-bank-account-type-div').addClass('woocommerce-invalid woocommerce-invalid-required-field');
                $('#anet-bank-account-type-div').removeClass('woocommerce-validated');
                $('#anet-echeck-bank-account-type').attr('aria-invalid', 'true');
                errors.push(__('Please select an account type.', 'authorize-net-payments-for-woocommerce'));
                isValid = false;
            } else {
                $('#anet-bank-account-type-div').removeClass('woocommerce-invalid woocommerce-invalid-required-field');
                $('#anet-bank-account-type-div').addClass('woocommerce-validated');
                $('#anet-echeck-bank-account-type').attr('aria-invalid', 'false');
            }
            // Store errors for later use
            anet_accept.echeckValidationErrors = errors;
            return !isValid;
        }
    };
    anet_accept.init();
});
