function renderUsBankAccountButton() {

    document.getElementById('business-name-container').hidden = true;
    var usBankAccountButtonContinue = document.getElementById('us-bank-account-button-continue');
    var routingNumberValue = document.getElementById('routing-number');

    braintree.usBankAccount.create({
        client: client
    }, function (err, usBankAccountInstance) {
        if (err) {
            console.error('Error creating Us Bank Account:', err);
            return;
        }
        usBankAccountButtonContinue.addEventListener('click', function () {
            getValuesFromUsBankAccountForm().then((bankDetails) => {
                if (bankDetails == null) {
                    showCustomAbsoluteErrorMessage(ACC.addons.braintreeb2baddon['braintree.message.invalid.usBankAccount']);
                    return;
                }

                var mandateUsBankAccountText = document.getElementById('mandate-text').innerText.trim();

                usBankAccountInstance.tokenize({
                    bankDetails: bankDetails,
                    mandateText: mandateUsBankAccountText
                }, function (tokenizeErr, payload) {
                    if (tokenizeErr) {
                        console.error('An error occurred:', tokenizeErr.message);
                        showCustomAbsoluteErrorMessage(ACC.addons.braintreeb2baddon['braintree.message.invalid.usBankAccount']);
                        if (errorContainsField(tokenizeErr, "routingNumber")) {
                            routingNumberValue.classList.add("error-input");
                        }
                    } else {
                        processUsBankAccountResponse(payload, bankDetails, false);
                    }
                })
            });
        });
    });
    document.getElementById("account-number").addEventListener('input', restrictInput);
    document.getElementById("routing-number").addEventListener('input', restrictInput);
    document.getElementById("billing-postal-code").addEventListener('input', restrictInput);
}

function restrictInput(event) {
    const input = event.target;
    const value = input.value;

    if (input.id === 'billing-postal-code') {
        const numericValue = value.replace(/[^0-9-]/g, '');
        input.value = numericValue;
    } else {
        const numericValue = value.replace(/\D/g, '');
        input.value = numericValue;
    }
}

function processUsBankAccountResponse(response, bankDetails, isMiniCartCheckout) {
    if (typeof addPaymentMethodsPage != 'undefined') {
        var submitForm;
        var parsedDetails = prepareUsBankAccountPayload(response, bankDetails);
        parsedDetails.deviceData = deviceData;
        var realToken = createHiddenParameter("CSRFToken", ACC.config.CSRFToken);
        var usBankAccountDetails = createHiddenParameter("usBankAccountData", JSON.stringify(parsedDetails));

        submitForm = createForm(CONST.US_BANK_ACCOUNT_PAYMENT_FORM_NAME, ACC.config.encodedContextPath + "/my-account/add-us-bank-account-payment-method");
        const shouldSaveAddress = $(CONST.SAVE_ADDRESS_ACH_CHECKBOX).is(HTML.CHECKED);
        submitForm.append(createHiddenParameter('shouldSaveAddress', shouldSaveAddress));

        submitForm.append($(realToken));
        submitForm.append($(usBankAccountDetails));
        submitForm.appendTo('body');
        submitForm.submit();
    } else {
        processExpressCheckoutForm(prepareUsBankAccountPayload(response, bankDetails), false, undefined, isMiniCartCheckout);
    }
}

function prepareUsBankAccountPayload(response, bankDetails) {
    var payloadCopy = {};
    payloadCopy.nonce = response.nonce;
    payloadCopy.details = {};
    payloadCopy.type = response.type;

    payloadCopy.details.accountNumber = bankDetails.accountNumber;
    payloadCopy.details.routingNumber = bankDetails.routingNumber;

    payloadCopy.details.billingAddress = {
        line1: bankDetails.billingAddress.streetAddress,
        line2: bankDetails.billingAddress.extendedAddress,
        city: bankDetails.billingAddress.locality,
        state: bankDetails.billingAddress.region,
        postalCode: bankDetails.billingAddress.postalCode,
        countryCode: 'US',
    };
    if (bankDetails.ownershipType === 'personal') {
        payloadCopy.details.billingAddress.firstName = bankDetails.firstName;
        payloadCopy.details.billingAddress.lastName = bankDetails.lastName;
    } else {
        payloadCopy.details.billingAddress.businessName = bankDetails.businessName;
    }
    return payloadCopy;
}

async function getValuesFromUsBankAccountForm() {
    let achBillingSelectorValue = document.getElementById("achBillingAddressSelector")?.selectedOptions[0].value;
    var verified;
    var addressVerified;

    var billingPostalCodeValue;
    var billingLocationValue;
    var billingPostalCodeValue;
    var extendedAddress;
    var region;

    if (achBillingSelectorValue === 'newAddress') {

        billingStreetAddressValue = document.getElementById('billing-street-address');
        billingLocationValue = document.getElementById('billing-locality');
        billingPostalCodeValue = document.getElementById('billing-postal-code');

        addressVerified = achAddressVerification(billingStreetAddressValue, billingLocationValue, billingPostalCodeValue);

        if (addressVerified) {
            billingStreetAddressValue = billingStreetAddressValue.value;
            billingLocationValue = billingLocationValue.value;
            billingPostalCodeValue = billingPostalCodeValue.value;
            extendedAddress = document.getElementById('billing-extended-address').value
            region = document.getElementById('billing-region').value
        }

    } else if (achBillingSelectorValue === 'noAddress') {
        document.getElementById("achBillingAddressSelector").classList.add("error-input");
        addressVerified = false;
    } else {
        let address = await getAddressById(achBillingSelectorValue);
        billingStreetAddressValue = address.line1;
        billingLocationValue = address.town;
        billingPostalCodeValue = address.postalCode;
        extendedAddress = address.line2;
        region = address.region.isocodeShort;

        addressVerified = true;
    }

    var accountNumberValue = document.getElementById('account-number');
    var routingNumberValue = document.getElementById('routing-number');
    var ownerShipTypeValue = document.getElementById('ownership-type');
    var firstNameValue = document.getElementById('first-name');
    var lastNameValue = document.getElementById('last-name');
    var businessNameValue = document.getElementById('business-name');

    verified = dataVerification(accountNumberValue, routingNumberValue, ownerShipTypeValue, firstNameValue, lastNameValue, businessNameValue);

    if (!verified && !addressVerified) {
        return null;
    }

    var bankDetails = {
        accountNumber: accountNumberValue.value,
        routingNumber: routingNumberValue.value,
        accountType: document.getElementById('account-type').value,
        ownershipType: ownerShipTypeValue.value,
        billingAddress: {
            streetAddress: billingStreetAddressValue,
            extendedAddress: extendedAddress,
            locality: billingLocationValue,
            region: region,
            postalCode: billingPostalCodeValue
        }
    };

    if (bankDetails.ownershipType === 'personal') {
        bankDetails.firstName = firstNameValue.value;
        bankDetails.lastName = lastNameValue.value;
    } else {
        bankDetails.businessName = businessNameValue.value;
    }
    return bankDetails;
}

function dataVerification(accountNumberValue, routingNumberValue, ownerShipTypeValue, firstNameValue, lastNameValue, businessNameValue) {

    var dataVerified = true;

    accountNumberValue.classList.remove("error-input");
    routingNumberValue.classList.remove("error-input");
    ownerShipTypeValue.classList.remove("error-input");
    firstNameValue.classList.remove("error-input");
    lastNameValue.classList.remove("error-input");
    businessNameValue.classList.remove("error-input");

    if (accountNumberValue.value.length < 1 || accountNumberValue.value.length > 17) {
        accountNumberValue.classList.add("error-input");
        dataVerified = false;
    }
    if (routingNumberValue.value.length < 8 || routingNumberValue.value.length > 9 || routingNumberValue.value.match(/^[0-9]+$/) == null) {
        routingNumberValue.classList.add("error-input");
        dataVerified = false;
    }

    if (ownerShipTypeValue.value === 'personal') {
        if (firstNameValue.value.length === 0) {
            firstNameValue.classList.add("error-input");
            dataVerified = false;
        }
        if (lastNameValue.value.length === 0) {
            lastNameValue.classList.add("error-input");
            dataVerified = false;
        }
    } else {
        if (businessNameValue.value.length === 0) {
            businessNameValue.classList.add("error-input");
            dataVerified = false;
        }
    }
    return dataVerified;
}

function achAddressVerification(billingStreetAddressValue, billingLocationValue, billingPostalCodeValue) {

    var addressVerified = true;

    billingStreetAddressValue.classList.remove("error-input");
    billingLocationValue.classList.remove("error-input");
    billingPostalCodeValue.classList.remove("error-input");

    if (billingStreetAddressValue.value.length === 0) {
        billingStreetAddressValue.classList.add("error-input");
        addressVerified = false;
    }
    if (billingLocationValue.value.length === 0) {
        billingLocationValue.classList.add("error-input");
        addressVerified = false;
    }
    if (billingPostalCodeValue.value.length < 5 || billingPostalCodeValue.value.length > 10) {
        billingPostalCodeValue.classList.add("error-input");
        addressVerified = false;
    }

    return addressVerified;

}

function getAddressById(addressId) {
    const url = ACC.config.encodedContextPath + "/my-account/get-address/" + addressId;
    return new Promise(function (resolve, reject) {
        $.get(url).then((address) => {
            resolve(address);
        },
            (error) => {
                reject(error);
            });
    });
}

function showPersonalOrBusinessField(value) {
    if (value === 'business') {
        document.getElementById('first-and-last-name-container').hidden = true;
        document.getElementById('business-name-container').hidden = false;
    } else {
        document.getElementById('first-and-last-name-container').hidden = false;
        document.getElementById('business-name-container').hidden = true;
    }
};

function renderMandatoryTextForUsBankAccount() {

    var accountNumberInput = document.getElementById('account-number');
    var routingNumberInput = document.getElementById('routing-number');
    var ownershipTypeInput = document.getElementById('ownership-type');
    var firstNameInput = document.getElementById('first-name');
    var lastNameInput = document.getElementById('last-name');
    var businessNameInput = document.getElementById('business-name');
    var amount = '';

    var firstNameText = '';
    var lastNameText = '';


    accountNumberInput.addEventListener("keyup", function (event) {
        setValueIntoElements('account-number-text', accountNumberInput.value);
    });

    routingNumberInput.addEventListener("keyup", function (event) {
        setValueIntoElements('routing-number-text', routingNumberInput.value);
    });

    ownershipTypeInput.addEventListener("change", function (event) {
        firstNameInput.value = '';
        lastNameInput.value = '';
        businessNameInput.value = '';
        setValueIntoElements('depository-name-text', '');
    });

    firstNameInput.addEventListener("keyup", function (event) {
        firstNameText = firstNameInput.value;
        setValueIntoElements('depository-name-text', firstNameText + ' ' + lastNameText);
    });

    lastNameInput.addEventListener("keyup", function (event) {
        lastNameText = lastNameInput.value;
        setValueIntoElements('depository-name-text', firstNameText + ' ' + lastNameText);
    });

    businessNameInput.addEventListener("keyup", function (event) {
        setValueIntoElements('depository-name-text', businessNameInput.value);
    });


    changingMessageForUsBankAccount();
}

function changingMessageForUsBankAccount() {
    var savePaymentMethodInput = document.getElementById('savePaymentInfo');
    var savingPart = document.getElementById('for-saving-payment-method');
    var notSavingPart = document.getElementById('for-not-saving-payment-method');

    if (typeof addPaymentMethodsPage == "undefined") {
        savingPart.hidden = true;
        savePaymentMethodInput.addEventListener("change", function (event) {
            if (savePaymentMethodInput.checked) {
                savingPart.hidden = false;
                notSavingPart.hidden = true;
            } else {
                savingPart.hidden = true;
                notSavingPart.hidden = false;
            }
        });
    }
}

function setValueIntoElements(className, text) {
    var elemetByClass = document.getElementsByClassName(className);
    for (var i = 0; i < elemetByClass.length; i++) {
        elemetByClass[i].innerText = text;
    }
}

function errorContainsField(tokenizeErr, fieldName) {
    return tokenizeErr.details.originalError.details.originalError[0].extensions.inputPath[2] == fieldName;
}
