var googlePaymentsClient;
var googlePayPaymentInstance;

function initialiseGooglePay(isMiniCartCheckout) {
    var paymentsClient = getGooglePaymentClient();

    braintree.googlePayment.create({
        client: client,
        googlePayVersion: 2,
        googleMerchantId: googleMerchantId // Optional in sandbox; if set in sandbox, this value must be a valid production Google Merchant ID
    }).then(function (googlePaymentInstance) {
        return paymentsClient.isReadyToPay({
            // see https://developers.google.com/pay/api/web/reference/object#IsReadyToPayRequest for all options
            apiVersion: 2,
            apiVersionMinor: 0,
            allowedPaymentMethods: googlePaymentInstance.createPaymentDataRequest().allowedPaymentMethods,
            existingPaymentMethodRequired: true
        }).then(function (isReadyToPay) {
            if (isReadyToPay.result) {
                googlePayPaymentInstance = googlePaymentInstance;

                if (checkGooglePayAvailability()) {
                    $('#googlepay').removeClass(CONST.HIDE);
                    checkSavedPaymentMethods(CONST.GOOGLE_PAY_ACCOUNT, isReadyToPay.result);
                    renderGooglePayButton(paymentsClient, googlePaymentInstance, isMiniCartCheckout);
                } else {
                    renderGooglePayButton(paymentsClient, googlePaymentInstance, isMiniCartCheckout);
                }

            }
        }).catch(function (err) {
            // Handle creation errors
            console.error('An error occurred during creation:', err.message);
        });
    });
}



function setupGooglePayButton(){
    var paymentsClient = getGooglePaymentClient();
    const waitForGooglePayInstance = setInterval(function () {
        if (typeof googlePayPaymentInstance !== "undefined") {
            clearInterval(waitForGooglePayInstance);
            if (googlePayPaymentInstance !== ''){
                renderGooglePayButton(paymentsClient, googlePayPaymentInstance);
            }
        }
    }, 10);


}


function checkGooglePayAvailability() {
    if (typeof paymentMethodsPage != 'undefined' || typeof addPaymentMethodsPage != 'undefined' ||
        typeof accountPaymentInfoPage != 'undefined') {
        return true;
    }
    return false;
}

function renderGooglePayButton(paymentsClient, googlePaymentInstance, isMiniCartCheckout) {
    var buttonContainers = document.getElementsByClassName("google_pay_container");
    var button = handleGooglePayButtonInit(paymentsClient, googlePaymentInstance, isMiniCartCheckout);

    if (typeof paymentMethodsPage == 'undefined' || paymentMethodsPage === '') {
        button.firstChild.className += ' google-pay-button-style';
    } else {
        button.firstChild.className += ' google-pay-mark-button-style';
    }

    Array.from(buttonContainers).forEach(function (item) {
        if (!item.hasChildNodes()) {
            item.appendChild(button);
        }
    });
}

function handleGooglePayButtonInit(paymentsClient, googlePaymentInstance, isMiniCartCheckout) {
    var button;

    if (typeof isMiniCartCheckout == 'undefined') {
        button = paymentsClient.createButton({
            buttonSizeMode:  googlePayButtonConfig?.size,
            buttonType: googlePayButtonConfig?.type,
            onClick: () => onGooglePaymentButtonClicked(paymentsClient, googlePaymentInstance, isMiniCartCheckout)
        });
    } else {
        button = paymentsClient.createButton({
            onClick: () => onGooglePaymentButtonClicked(paymentsClient, googlePaymentInstance, isMiniCartCheckout)
        });
    }

    return button;
}

function getGooglePaymentClient() {
    if (typeof googlePaymentsClient == 'undefined' || googlePaymentsClient === '') {
        var localEnvironment = environment.toUpperCase() === 'PRODUCTION' ? 'PRODUCTION' : 'TEST';
        googlePaymentsClient = new google.payments.api.PaymentsClient({
            environment: localEnvironment
        });
    }
    return googlePaymentsClient;
}

function onGooglePaymentButtonClicked(paymentsClient, googlePayPaymentInstance, isMiniCartCheckout) {
    var paymentDataRequest = getGooglePaymentDataRequest(googlePayPaymentInstance, isMiniCartCheckout);

    // See all available options at https://developers.google.com/pay/api/web/reference/object
    var cardPaymentMethod = paymentDataRequest.allowedPaymentMethods[0];
    paymentDataRequest.emailRequired = true;
    cardPaymentMethod.parameters.billingAddressRequired = true;
    cardPaymentMethod.parameters.billingAddressParameters = {
        format: 'FULL',
        phoneNumberRequired: true
    };

    if (((typeof paymentMethodsPage == 'undefined' || paymentMethodsPage === '')
        && (typeof addPaymentMethodsPage == 'undefined' || addPaymentMethodsPage === ''))
        || (typeof isMiniCartCheckout != 'undefined')) {

        paymentDataRequest.shippingAddressRequired = true;
    }

    var googlePayPaymentData;

    paymentsClient.loadPaymentData(paymentDataRequest).then(function (paymentData) {
        googlePayPaymentData = paymentData;
        return googlePayPaymentInstance.parseResponse(paymentData);
    }).then(function (result) {
        var threeDSecureFlowForCurrentPage = ACC.threeDSecure.is3DSecureEnabledForGooglePay();
        if (result.details.isNetworkTokenized === false && threeDSecureFlowForCurrentPage) {
          if (ACC.threeDSecure.isExpressCheckoutPage()) {
            ACC.threeDSecure.verifyGooglePayBy3DSecureOnExpressCheckout(
              result,
              googlePayPaymentData,
              isMiniCartCheckout
            );
          } else {
            ACC.threeDSecure.verifyGooglePayBy3DSecure(
                result,
                googlePayPaymentData,
                isMiniCartCheckout
            );
          }
        } else {
          processGooglePayResponse(result, googlePayPaymentData, isMiniCartCheckout);
        }
    }).catch(function (err) {
        // Handle errors
        console.error('An error occurred:', err.message);
    });
}

function getGooglePaymentDataRequest(googlePayPaymentInstance, isMiniCartCheckout) {
    var paymentDataRequest;

    if ((typeof addPaymentMethodsPage != 'undefined') && (typeof isMiniCartCheckout == 'undefined')){
        paymentDataRequest = googlePayPaymentInstance.createPaymentDataRequest({
            transactionInfo: {
                countryCode: googlePayCountryCode,
                currencyCode: currency,
                totalPriceStatus: 'FINAL',
                totalPrice: '0.0'
            }
        });
    }else {
        paymentDataRequest = googlePayPaymentInstance.createPaymentDataRequest({
            transactionInfo: {
                countryCode: googlePayCountryCode,
                currencyCode: currency,
                totalPriceStatus: 'FINAL',
                totalPrice: amount
            }
        });
    }
    return paymentDataRequest;
}


function processGooglePayResponse(response, googlePayPaymentData, isMiniCartCheckout) {

    var payload = convertGoogleDataToPayloadObject(response, googlePayPaymentData, isMiniCartCheckout);

    processExpressCheckoutForm(payload, false, undefined, isMiniCartCheckout);
}


function convertGoogleDataToPayloadObject(response, googlePayPaymentData, isMiniCartCheckout) {
    var payloadCopy = {};
    payloadCopy.nonce = response.nonce;
    payloadCopy.details = {};
    payloadCopy.cardDetails = {};
    payloadCopy.type = response.type;
    payloadCopy.details.email = googlePayPaymentData.email;

    payloadCopy.cardDetails.lastFour = response.details.lastFour;
    payloadCopy.cardDetails.cardType = response.details.cardType;

    payloadCopy.details.phone = googlePayPaymentData.paymentMethodData.info.billingAddress.phoneNumber;
    payloadCopy.details.billingAddress = {
        recipientName: googlePayPaymentData.paymentMethodData.info.billingAddress.name,
        line1: googlePayPaymentData.paymentMethodData.info.billingAddress.address1,
        line2: googlePayPaymentData.paymentMethodData.info.billingAddress.address2,
        city: googlePayPaymentData.paymentMethodData.info.billingAddress.locality,
        state: googlePayPaymentData.paymentMethodData.info.billingAddress.administrativeArea.toUpperCase(),
        postalCode: googlePayPaymentData.paymentMethodData.info.billingAddress.postalCode,
        countryCode: googlePayPaymentData.paymentMethodData.info.billingAddress.countryCode.toUpperCase()
    };

    if ((typeof paymentMethodsPage == 'undefined' && typeof addPaymentMethodsPage == 'undefined') || (typeof isMiniCartCheckout != 'undefined')) {
        var namesShipping = googlePayPaymentData.shippingAddress.name.split(' ');
        payloadCopy.details.firstName = namesShipping[0];
        payloadCopy.details.lastName = namesShipping[1];

        payloadCopy.details.shippingAddress = {
            recipientName: googlePayPaymentData.shippingAddress.name,
            line1: googlePayPaymentData.shippingAddress.address1,
            line2: googlePayPaymentData.shippingAddress.address2,
            city: googlePayPaymentData.shippingAddress.locality,
            state: googlePayPaymentData.shippingAddress.administrativeArea.toUpperCase(),
            postalCode: googlePayPaymentData.shippingAddress.postalCode,
            countryCode: googlePayPaymentData.shippingAddress.countryCode.toUpperCase()
        };
    }

    return payloadCopy;
}
