$(document).ready(function() {
    var validTaxHeader = false;
    var cartItemsHeader = [];
    var isValidSpecialShippingFeeHeader = false;
    var specialShippingFeeHeader = null;
    modeHeader = getParameterByNameHeader("mode");
    window.addEventListener('doneCountries', function (event, data) {
        if (event.detail && event.detail.countries) {
            countriesHeader = event.detail.countries;
        }
    })
    window.addEventListener('doneCountry', function (event, data) {
        if (event.detail && event.detail.country) {
            countryByIpHeader = event.detail.country;
        }
    })
    function getParameterByNameHeader(name, url) {
        if (!url) url = window.location.href;
        name = name.replace(/[\[\]]/g, '\\$&');
        var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
            results = regex.exec(url);
        if (!results) return null;
        if (!results[2]) return '';
        return decodeURIComponent(results[2].replace(/\+/g, ' '));
    }
    function getCustomerTokenHeader() {
        return new Promise(function (resolve) {
            var url = `/cart/get-customer-token?ignore_localization=1`;
            $.ajax({
                method: "GET",
                url: url,
            }).then(function(response) {
                    let customerToken = null;
                    if (response.status == "successful") {
                        customerToken = response.result;
                    }
                    resolve(customerToken);
                }
            ).catch(function() {
                reject(null);
            });
        });
    }
    async function showExpressCheckout() {
        if (validCountryHeader.includes(countryByIpHeader) && useCheckoutInSidebar) {
            isValidExpressCheckoutHeader = true;
        }
        if (currencyUnitAddToCartHeader != defaultcurrencyUnitAddToCartHeader) {
            isValidExpressCheckoutHeader = false;
        }
        let jsGgDiscount = $('#js-gg-discount').val();
        if (jsGgDiscount == 1 || getParameterByNameHeader("pv2")) {
            isValidExpressCheckoutHeader = false;
        }
        if (modeHeader && modeHeader == "test") {
            isValidExpressCheckoutHeader = true;
            countryByIpHeader = "US";
            keyStripe = keyStripeTest;
        }
        stripeHeader = Stripe(keyStripe, {
            betas: ['ume_beta_1']
        });
        elementsStripeHeader = stripeHeader.elements();
        tokenHeader = await getCustomerTokenHeader();
        if (isMobileHeader) {
            stripeElementStyleHeader = {
                paymentRequestButton: {
                    type: 'default',
                    theme: 'dark',
                    height: '40px',
                    borderRadius: '32px',
                },
            };
        } else {
            stripeElementStyleHeader = {
                paymentRequestButton: {
                    type: 'default',
                    theme: 'dark',
                    height: '40px',
                    borderRadius: '32px',
                },
            };
        }
        isShowExpressCheckout = true;
        if (isValidExpressCheckoutHeader) {
            var paymentRequest = null;
            paymentRequest = stripeHeader.paymentRequest({
                country: countryByIpHeader,
                currency: currencyUnitAddToCartHeader.toLowerCase(),
                total: {
                    label: totalText,
                    amount: formatPriceByCurrency(parseFloat(10), "*"),
                },
                displayItems: [
                    {
                        label: "Ok",
                        amount: formatPriceByCurrency(parseFloat(9), "*"),
                    },
                    {
                        label: transactionFeeText,
                        amount: formatPriceByCurrency(parseFloat(1), "*"),
                    }
                ],
                requestPayerName: true,
                requestPayerEmail: true,
                requestPayerPhone: true,
                requestShipping: true,
            });
            paymentRequest.on('shippingaddresschange', async (event) => {
                // Perform server-side request to fetch shipping options
                await getShippingInfoCart(event.shippingAddress.country);
                await checkTax(event.shippingAddress.country);
                let shippingInfo = shippingInfoByPaymentRequestButtonHeader;
                selectedCountryHeader = event.shippingAddress.country;
                selectedShippingHeader = [];
                for (let index = 0; index < shippingInfoByPaymentRequestButtonHeader.length; index++) {
                    const element = shippingInfoByPaymentRequestButtonHeader[index];
                    for (let i = 0; i < element.shipping_info.length; i++) {
                        const item = element.shipping_info[i];
                        if (item.type == shippingTypeHeader) {
                            selectedShippingHeader.push(item);
                        }
                    }
                }
                let shippingOptions = getShippingOption(shippingInfo, true)
    
                let dataUpdateEvent = getDataUpdateEvent(shippingOptions)
                dataUpdateEvent.status = 'success';
                event.updateWith(dataUpdateEvent);
            });
    
            paymentRequest.on('shippingoptionchange', async (event) => {
                var shippingOption = event.shippingOption;
                shippingTypeHeader = shippingOption.id;
                selectedShippingHeader = [];
                for (let index = 0; index < shippingInfoByPaymentRequestButtonHeader.length; index++) {
                    const element = shippingInfoByPaymentRequestButtonHeader[index];
                    for (let i = 0; i < element.shipping_info.length; i++) {
                        const item = element.shipping_info[i];
                        if (item.type == shippingTypeHeader) {
                            selectedShippingHeader.push(item);
                        }
                    }
                }
                let dataUpdateEvent = getDataUpdateEvent();
                dataUpdateEvent.status = 'success';
                event.updateWith(dataUpdateEvent);
            });
    
            const prButton = elementsStripeHeader.create('paymentRequestButton', {
                paymentRequest,
                style: stripeElementStyleHeader,
            });
    
            (async () => {
                // Check the availability of the Payment Request API first.
                paymentRequest.canMakePayment().then(function(result) {
                    if (result) {
                        prButton.mount('#payment-request-button-sidebar');
                    } else {
                        document.getElementById('payment-request-button-sidebar').style.display = 'none';
                    }
                });
            })();
    
            prButton.on('click', async function(event) {
                let shippingOptions = getShippingOption(shippingInfoByPaymentRequestButtonHeader, true)
    
                let dataUpdateEvent = getDataUpdateEvent(shippingOptions)
    
                paymentRequest.update(dataUpdateEvent);
            })
    
            paymentRequest.on('paymentmethod', async function(event) {
                let data = {
                    payerName: event.payerName,
                    payerEmail: event.payerEmail,
                    payerPhone: event.payerPhone,
                    shippingAddress: event.shippingAddress,
                    paymentMethod: event.paymentMethod,
                }
                var orderData = await processOrder(data, 'product_express');
                //Create payment Intent
                var paymentIntentParams = {
                    url: base_api_url_header + '/stripe/payment-intent',
                    method: 'POST',
                    data: {
                        orderId: orderData.order.id,
                        currency: currencyUnitAddToCartHeader,
                        token: token,
                        email: data.payerEmail.replace(/\s/gm,'')
                    },
                };
                let paymentIntent = null;
                await $.ajax(paymentIntentParams).done(function(result) {
                    paymentIntent = result;
                });

                //Confirm
                stripeHeader.confirmCardPayment(
                    paymentIntent.payment_intent,
                    {payment_method: event.paymentMethod.id},
                    {handleActions: false}
                ).then(function(confirmResult) {
                    if (confirmResult.error) {
                        // Report to the browser that the payment failed, prompting it to
                        // re-show the payment interface, or show an error message and close
                        // the payment interface.
                        alert("Error. Something went wrong. Please try again!");
                        event.complete('fail');
                    } else {
                        // Report to the browser that the confirmation was successful, prompting
                        // it to close the browser payment method collection interface.
                        event.complete('success');
                        // Check if the PaymentIntent requires any actions and if so let Stripe.js
                        if (confirmResult.paymentIntent.status === "requires_action") {
                            // Let Stripe.js handle the rest of the payment flow.
                            stripe.confirmCardPayment(paymentIntent.payment_intent).then(function(result) {
                            if (result.error) {
                                // The payment failed -- ask your customer for a new payment method.
                                alert("Error. Something went wrong. Please try again!");
                            } else {
                                // The payment has succeeded.
                                window.location.replace(orderData.redirect);
                            }
                            });
                        } else {
                            // The payment has succeeded.
                            window.location.replace(orderData.redirect);
                        }
                    }
                });
            });
        }
    }

    async function processOrder(data, paymentType = 'paypal_express') {
        //Create order
        let tokenUserQuery = localStorage.getItem("token_user_query");
        //Build tracking source
        var buildTrackingReqParams = {
            url: '/tracking-order/build-tracking-source?token=' + tokenUserQuery,
            method: 'GET',
        };
        await $.ajax(buildTrackingReqParams).done(function(result) {
            console.log("Done tracking");
        });

        let token = tokenHeader;
        let shippingConfig = {};
        for (let index = 0; index < shippingInfoByPaymentRequestButtonHeader.length; index++) {
            const element = shippingInfoByPaymentRequestButtonHeader[index];
            element.shipping_info.forEach(item => {
                element[item.type] = item;
            });
        }
        if (data.shippingOptions && data.shippingOptions.length > 0) {
            for (let index = 0; index < data.shippingOptions.length; index++) {
                if (data.shippingOptions[index].selected) {
                    shippingTypeHeader = data.shippingOptions[index].id;
                }
            }
        }
        for (let index = 0; index < cartItemHeader.length; index++) {
            const element = cartItemHeader[index];
            for (let i = 0; i < shippingInfoByPaymentRequestButtonHeader.length; i++) {
                const item = shippingInfoByPaymentRequestButtonHeader[i];
                let shippingInfo = item[shippingTypeHeader];
                for (let k = 0; k < item.cart_item_id.length; k++) {
                    const cartItemId = item.cart_item_id[k];
                    shippingConfig[cartItemId] = shippingInfo.id
                }
            }
        }
        let shippingAddress = data.shippingAddress;
        var headers = {
            token: token,
        };
        let billingAddress = null;
        if (data.paymentMethod && data.paymentMethod.billing_details) {
            billingAddress = data.paymentMethod.billing_details;
        } else {
            billingAddress = {
                address: {
                    country: shippingAddress.country,
                    postal_code: shippingAddress.postalCode,
                    city: shippingAddress.city,
                    state: shippingAddress.region,
                    line1: shippingAddress.addressLine && shippingAddress.addressLine[0] ? shippingAddress.addressLine[0] : 'address 1',
                    line2: shippingAddress.addressLine && shippingAddress.addressLine[1] ? shippingAddress.addressLine[1] : '',
                }
            }
        }
        let countryId = 226;
        let countryBilling = 226;
        let hasBilling = false;

        for (const key in countriesHeader) {
            if (Object.hasOwnProperty.call(countriesHeader, key)) {
                const element = countriesHeader[key];
                
                if (element.iso == shippingAddress.country) {
                    countryId = element.id;
                }
                if (billingAddress.address && billingAddress.address.country && element.iso == billingAddress.address.country) {
                    hasBilling = true;
                    countryBilling = element.id;
                }
            }
        }
        if (!hasBilling) {
            countryBilling = countryId;
        }
        let dataOrder = {
            name: data.payerName,
            zipcode: shippingAddress.postalCode ? shippingAddress.postalCode : 0,
            phone: data.payerPhone.replace(/\s/gm,''),
            country: countryId,
            province: null,
            district: null,
            city_name: shippingAddress.city ? shippingAddress.city : "",
            state_name: shippingAddress.region,
            optional_address: shippingAddress.addressLine && shippingAddress.addressLine[1] ? shippingAddress.addressLine[1] : '',
            email: data.payerEmail.replace(/\s/gm,''),
            note: null,
            address: shippingAddress.addressLine && shippingAddress.addressLine[0] ? shippingAddress.addressLine[0] : 'address 1',
            payment_type: paymentType,
            promotion_code: null,
            delivery_note: "",
            shipping_type: shippingTypeHeader,
            discount: 0,
            tips: 0,
            billing_address: JSON.stringify({
                name: billingAddress.name ? billingAddress.name : data.payerName,
                address: billingAddress.address.line1,
                optional_address: billingAddress.address.line2,
                state_name: billingAddress.address.state,
                zip_code: billingAddress.address.postal_code,
                city_name: billingAddress.address.city,
                country: countryBilling,
            }),
            shipping_configuration: JSON.stringify(shippingConfig),
            token: token,
            checkout_source: "sidebar",
            shipping_info: shippingInfoByPaymentRequestButtonHeader,
        };

        if (isValidSpecialShippingFeeHeader && shippingTypeHeader == 'standard' && (specialShippingFeeHeader || specialShippingFeeHeader == 0)) {
            dataOrder.special_shipping_fee = parseFloat(specialShippingFeeHeader);
        }
        if (tokenUserQuery) {
            dataOrder.token_user_query = tokenUserQuery;
        }
        if (validTaxHeader) {
            dataOrder.other_tax_fee = calculateTrumpTaxHeader();
        }
        dataOrder.cjeventCookieHeader = cjeventCookieHeader;
        let orderData = null;
        await order(dataOrder).then(function (result) {
            orderData = result;
        }).catch(function (err) {
            console.error('Augh, there was an error!', err.statusText);
        });
        return orderData;
    }
    function order(dataOrder) {
        dataOrder.service_token = "megaads@123";
        return new Promise((resolve, reject) => {
            let orderData = {};
            const xhr = new XMLHttpRequest();
    
            xhr.open("POST", base_api_url_header + "/api/order");
            xhr.setRequestHeader("Content-Type", "application/json");
            xhr.setRequestHeader("Token", dataOrder.token);
            xhr.send(JSON.stringify(dataOrder));
            xhr.onreadystatechange = function () {
                if (this.readyState === 4 && this.status === 200) {
                    let responseText = this.responseText;
    
                    const orderData = JSON.parse(responseText);
                    resolve(orderData)
                }
            };
        })
    }
    function getShippingOption(shippingInfo, isUpdate = false, type = 'stripe') {
        var shippingOptions = [];
        var shippingData = [];
        for (let index = 0; index < shippingInfo.length; index++) {
            const element = shippingInfo[index];
            element.shipping_info.forEach(item => {
                element[item.type] = item;
                if (!shippingData[item.type]) {
                    shippingData[item.type] = angular.copy(item);
                } else {
                    shippingData[item.type].shipping_fee += item.shipping_fee;
                }
            });
        }
        let types = ["standard", "premium", "express"];
        for (let index = 0; index < shippingInfo.length; index++) {
            for (let i = 0; i < types.length; i++) {
                const type = types[i];
                if (!shippingInfo[index][type]) {
                    delete(shippingData[type]);
                }
            }
        }
        if (isUpdate) {
            selectedShippingHeader = [];
        }
        let hasStandard = false;
        let hasPremium = false;
        for (const key in shippingData) {
            if (shippingData.hasOwnProperty.call(shippingData, key)) {
                const element = shippingData[key];
                if (element.type == 'standard') {
                    hasStandard = true;
                }
                if (element.type == 'premium') {
                    hasPremium = true;
                }
            }
        }
        for (const key in shippingData) {
            if (shippingData.hasOwnProperty.call(shippingData, key)) {
                const element = shippingData[key];
                let minDate = new Date();
                let maxDate = new Date();
                minDate.setDate(minDate.getDate() + parseInt(element.shipping_min_time));
                maxDate.setDate(maxDate.getDate() + parseInt(element.shipping_max_time));
                let textTemplate = betweenFromToText;
                textTemplate = textTemplate.replace('#key', element.name_shipping);
                textTemplate = textTemplate.replace('#from', `${monthNamesHeader[minDate.getMonth()].replace("#date", minDate.getDate())}`);
                textTemplate = textTemplate.replace('#to', `${monthNamesHeader[maxDate.getMonth()].replace("#date", maxDate.getDate())}`);
                if (type == 'stripe') {
                    shippingOptions.push({
                        id: element.type,
                        label: element.name_shipping,
                        detail: textTemplate,
                        amount: formatPriceByCurrency(element.shipping_fee, '*'),
                    });
                } else {
                    shippingOptions.unshift({
                        id: key,
                        label: element.name_shipping,
                        detail: textTemplate,
                        amount: element.shipping_fee,
                        selected: key == shippingTypeHeader,
                    });
                }
                if (isUpdate && element.type == 'standard' && hasStandard) {
                    selectedShippingHeader.push(element);
                    shippingTypeHeader = 'standard';
                }
                if (isUpdate && element.type == 'premium' && !hasStandard && hasPremium) {
                    selectedShippingHeader.push(element);
                    shippingTypeHeader = 'premium';
                }
                if (isUpdate && element.type == 'express' && !hasPremium && !hasStandard) {
                    selectedShippingHeader.push(element);
                    shippingTypeHeader = 'express';
                }
            }
        }
        return shippingOptions;
    }
    
    function getDataUpdateEvent(shippingOptions = null) {
        let amount = getAmount('stripe', shippingOptions);
        let data = {
            total: {
                label: totalText,
                amount: formatPriceByCurrency(amount.productPrice, "*") + formatPriceByCurrency(amount.otherFee, "*") + formatPriceByCurrency(amount.shippingFee, "*") + formatPriceByCurrency(amount.transactionFee, "*"),
            },
            displayItems: [
                {
                    label: subtotalText,
                    amount: formatPriceByCurrency(amount.productPrice, "*"),
                },
                {
                    label: shippingFeeText,
                    amount: formatPriceByCurrency(amount.shippingFee, "*"),
                },
                {
                    label: `${transactionFeeText}`,
                    amount: formatPriceByCurrency(amount.transactionFee, "*"),
                },
            ],
        };
        if (shippingOptions) {
            data.shippingOptions = shippingOptions;
        }
        if (validTaxHeader) {
            data.displayItems.push({
                label: otherFeeTextHeader,
                amount: formatPriceByCurrency(amount.otherFee, "*"),
            });
        }
        return data;
    }

    function getAmount(type = 'stripe', shippingOptions = null) {
        let fee = type == 'stripe' ? stripeFeeHeader : paypalFeeHeader;
        let shippingFee = 0;
        for (let index = 0; index < selectedShippingHeader.length; index++) {
            const element = selectedShippingHeader[index];
            if (element.shipping_fee) {
                shippingFee += element.shipping_fee;
            } else {
                shippingFee += element.amount;
            }
        }
        let result = {
            total: 0,
            transactionFee: 0,
            otherFee: 0,
            productPrice: 0,
            shippingFee: 0,
            designFee: 0,
        };
        for (let index = 0; index < cartItemsHeader.length; index++) {
            const element = cartItemsHeader[index];
            let configurations = JSON.parse(element.configurations);
            if (configurations.design_fee) {
                result.designFee += parseFloat(configurations.design_fee);
            }
        }
        result.totalWithoutShipping = parseFloat(cartAmountHeader);
        if (result.designFee > 0) {
            result.totalWithoutShipping += result.designFee;
        }
        result.total = result.totalWithoutShipping + parseFloat(shippingFee);
        result.transactionFee = decimalAdjust('ceil', fee * result.total / 100);
        result.total += result.transactionFee;
        result.totalWithoutShipping += result.transactionFee;
        result.productPrice = parseFloat(cartAmountHeader);
        result.shippingFee = parseFloat(shippingFee);
        if (typeof useSpecialShippingFee !== "undefined" && useSpecialShippingFee && (selectedCountryHeader == 'US' || selectedCountryHeader == '226')) {
            if (shouldUseNewInterface == 'a') {
                if (result.productPrice >= 50) {
                    specialShippingFeeHeader = shippingFeeByLevel[0];
                }
                if (result.productPrice >= 100) {
                    specialShippingFeeHeader = shippingFeeByLevel[1];
                }
            }
            if (shouldUseNewInterface == 'b') {
                specialShippingFeeHeader = shippingFeeByLevel[0];
                if (result.productPrice >= 80) {
                    specialShippingFeeHeader = shippingFeeByLevel[1];
                }
            }
            let fee = type == 'stripe' ? stripeFeeHeader : paypalFeeHeader;
            if (specialShippingFeeHeader || specialShippingFeeHeader == 0) {
                if (shippingOptions) {
                    for (let index = 0; index < shippingOptions.length; index++) {
                        const element = shippingOptions[index];
                        if (element.id == 'standard') {
                            if (type == 'stripe') {
                                element.amount = formatPriceByCurrency(specialShippingFeeHeader, "*");
                            } else {
                                element.amount = parseFloat(specialShippingFeeHeader);
                            }
                            let shippingType = selectedShippingHeader[0].type ? selectedShippingHeader[0].type : selectedShippingHeader[0].id;
                            if (shippingType == element.id) {
                                isValidSpecialShippingFeeHeader = true;
                                result.shippingFee = parseFloat(specialShippingFeeHeader);
                                result.transactionFee = decimalAdjust('ceil', fee * (result.productPrice + result.shippingFee) / 100);
                                result.totalWithoutShipping = result.productPrice + result.transactionFee + (result.otherFee ? result.otherFee : 0);
                            }
                        }
                    }
                } else {
                    let shippingType = selectedShippingHeader[0].type ? selectedShippingHeader[0].type : selectedShippingHeader[0].id;
                    if (shippingType == 'standard' && (specialShippingFeeHeader || specialShippingFeeHeader == 0)) {
                        isValidSpecialShippingFeeHeader = true;
                        result.shippingFee = parseFloat(specialShippingFeeHeader);
                        result.transactionFee = decimalAdjust('ceil', fee * (result.productPrice + result.shippingFee) / 100);
                        result.totalWithoutShipping = result.productPrice + result.transactionFee + (result.otherFee ? result.otherFee : 0);
                    }
                }
            }
        }
        if (validTaxHeader) {
            result.otherFee = calculateTrumpTaxHeader();
            result.total += parseFloat(result.otherFee);
            result.totalWithoutShipping += parseFloat(result.otherFee);
        }
        return result;
    }

    function calculateTrumpTaxHeader() {
        let shippingFee = 0;
        for (let index = 0; index < selectedShippingHeader.length; index++) {
            const element = selectedShippingHeader[index];
            if (element.shipping_fee) {
                shippingFee += element.shipping_fee;
            } else {
                shippingFee += element.amount;
            }
        }
        if (isValidSpecialShippingFeeHeader && shippingTypeHeader == 'standard' && (specialShippingFeeHeader || specialShippingFeeHeader == 0)) {
            shippingFee = parseFloat(specialShippingFeeHeader);
        }
        let total = cartAmountHeader + parseFloat(shippingFee);
        let tax = decimalAdjust('ceil', total * 0.2);
        return tax;
    }

    $('.cart-more-item').click(function() {
        if (!$('.all-item-cart-container').hasClass('extra-content')) {
            $('.cart-more-text').hide();
            $('.cart-less-text').css('display', 'inline-flex');
            $('.all-item-cart-container').animate({height: $('.all-item-cart-block .product-grid').height() + 46 + 37}, 100);
            $('.all-item-cart-container').addClass('extra-content');
        } else {
            $('.cart-more-text').css('display', 'inline-flex');
            $('.cart-less-text').hide();
            $('.all-item-cart-container').animate({height: 150}, 100);
            $('.all-item-cart-container').removeClass('extra-content');
        }
    });
    $('#show-mini-cart-wrapper').click(function() {
        if (!$(this).is(':checked')){
            $('.cart-more-text').css('display', 'inline-flex');
            $('.cart-less-text').hide();
            $('.all-item-cart-container').animate({height: 150}, 100);
            $('.all-item-cart-container').removeClass('extra-content');
        }
        
    });
    $(window).on("storage", async function (e) {
        let storageEvent = e.originalEvent;
        if (storageEvent.key == "change-cart") {
            getCartItems()
            getShippingInfoCart()
        }
    });
    window.addEventListener('change-cart', function (event, data) {
        if (event.detail) {
            let showCart = typeof event.detail.showCart !== 'undefined' && !event.detail.showCart ? false : true;
            getCartItems(true, showCart)
            getShippingInfoCart()
        }
    });
    
    window.addEventListener('item-relateds', function (event, data) {
        if (event.detail) {
            showRelated(event.detail.relatedProducts)
        }
    });
    
    window.addEventListener('item-add-to-cart', function (event, data) {
        if (event.detail && false) {
            if (event.detail.listAdd && event.detail.listAdd.length > 0) {
                let html = "";
                for (let index = 0; index < event.detail.listAdd.length; index++) {
                    const element = event.detail.listAdd[index];
                    let url = element.url;
                    if (locale != "" && !element.url.includes(locale)) {
                        url = locale + element.url;
                    }
                    if (element.name_variant != "" && element.product_name && element.product_name.includes(", " + element.name_variant)) {
                        element.product_name = element.product_name.replace(", " + element.name_variant, "");
                    }
                    html += 
                    `
                        <div style="min-width: 0px;" class="item-summary-product" >
                            <div class="item-summary-image" >
                                <div class="quantity-badge">
                                    ${element.quantity ? element.quantity : 1}
                                </div>
                                <img class="" src="${getImageCdn(element.image_url, 360, 360, false)}" alt="Discover ${element.product_name}" referrerpolicy="no-referrer" width="80" height="80">
                            </div>
                            <div style="flex: 1 1 0%; min-width: 0px;" class="item-summary-info" >
                                <a class="title-product" href="${url}" target="_blank">${element.product_name}</a>
                                <span class="variant-product">${element.name_variant}</span>
                                <span class="price-product">
                                    <b>${formatPrice(decorePrice(element.price), priceTemplate)}</b>`
                            if (element.high_price && element.high_price > element.price) {
                                html += `<del>${formatPrice(decorePrice(element.high_price), priceTemplate)}</del>`
                            }
                    html += `</span></span>`
                            
                    if (element.configurations) {
                        let configurations = JSON.parse(element.configurations);
                        for (let i in configurations) {
                            if (typeof configurations[i] == 'string' || typeof configurations[i] == 'number') {
                                if (i != 'print_location' && i != 'previewUrl' && i != 'buy_design' && i != 'design_fee') {
                                    html += `<span class="qty-product">${i}: ${configurations[i]}</span>`
                                }
                                if (i == 'print_location' && getByField(printLocationsMiniCartHeader, 'value', configurations[i])) {
                                    html += `<span class="qty-product">${printLocationText + ":"} ${getByField(printLocationsMiniCartHeader, 'value', configurations[i]).name}</span>`
                                }
                            } else if (i == 'config_by_print_location') {
                                html += `<span class="qty-product">${printLocationText + ":"} ${Object.key(configurations[i]).map(text => miniCartTranslateText[text]).join(', ')}</span>`
                            } 
                        }
                    }
                    html += `</div>
                        </div>
                    `;
                }
                $("#mini-cart-header .mini-cart-wrapper").removeClass("mini-cart-wrapper-not-add");
                $("#mini-cart-header .list-add-item").html(html);
                $("#mini-cart-header .list-add-item-wrapper").show();
                $("#show-mini-cart-wrapper").prop("checked", true);
                
                //Check only item
                if ( $('.mini-cart-top .list-add-item').children().length > 1 ) {
                    var heightBottom = viewportHeight - multiItem;
                    $('#mini-cart-header .mini-cart-top').height(multiItem);
                    $('#mini-cart-header .mini-cart-bottom').height(heightBottom);
                    
                } else {                   
                    var heightBottom = viewportHeight - minicart;
                    $('#mini-cart-header .mini-cart-top').height(minicart);
                    $('#mini-cart-header .mini-cart-bottom').height(heightBottom);
                }
                $(".buymore-button").click(function() {
                    $("#show-mini-cart-wrapper").prop("checked", false);
                    $('.cart-more-text').css('display', 'inline-flex');
                    $('.cart-less-text').hide();
                    $('.all-item-cart-container').animate({height: 150}, 100);
                    $('.all-item-cart-container').removeClass('extra-content');
                });
                isScrollBottomSidebar = false;
                isScrollBottomSidebarRecommend = false;
                isTimeOut = false;
            }
            if (event.detail.relatedProducts && event.detail.relatedProducts.length > 0) {
                showRelated(event.detail.relatedProducts)
            }
        }
    });
    function getCartItems(updateRelated = false, showCart = true) {
        $("#mini-cart-header .no-item-cart-wrapper").hide();
        $("#mini-cart-header .no-items-cart").hide();
        $("#mini-cart-header .all-item-in-cart").show();
        $(".item-sidebar-cart-loading").addClass("show");
        var getCartReqParams = {
            url: '/cart/get-cart-items',
            method: 'GET'
        };
        $.ajax(getCartReqParams)
            .done(function(result) {
                if (window.dataLayer && currentRouteName != "finish") {
                    window.cartItems = result;
                    window.dataLayer.push({'event': 'cart_loaded'});
                }
                $(".item-sidebar-cart-loading").removeClass("show");
                if (result.status == 'successful') {
                    var quantity = 0;
                    localStorage.setItem("cart-item", result.result.length);
                    cartAmountHeader = 0;
                    result.result.forEach((element) => {
                        quantity += parseInt(element.quantity);
                        cartAmountHeader += element.price * parseInt(element.quantity);
                        if (element.configurations) {
                            try {
                                let configurations = JSON.parse(element.configurations);
                                if (configurations.edit_url) {
                                    element.url = configurations.edit_url.url;
                                }
                            } catch (error) {
    
                            }
                        }
                    });
                    cartItemsHeader = result.result;
                    $(".js-mini-cart-count").text(parseInt(quantity));
                    if (parseInt(quantity) > 0) {
                        $(".js-mini-cart-count").show();
                    }
                    if (result.result && result.result.length > 0) {
                        cartItemHeader = result.result;
                        if (showCart && currentRouteName != "finish" && currentRouteName != "cart" && currentRouteName != "module::cart::checkout" && currentRouteName != "track-order") {
                            showCartItems(result.result);
                        } else {
                            if (typeof usePaypalExpressCheckout !== 'undefined' && usePaypalExpressCheckout && (currentRouteName == "module::cart::checkout" || currentRouteName == "cart")) {
                                showPaypal();
                            }
                        }
                    } else {
                        $("#mini-cart-header .no-item-cart-wrapper").show();
                        $("#mini-cart-header .no-items-cart").show();
                        $("#mini-cart-header .all-item-in-cart").hide();
                    }
                    if (result.related && result.related.length > 0 && updateRelated) {
                        showRelated(result.related)
                    }
                }
            });
    }
    function updateCartItem(quantity, id) {
        $(".item-sidebar-cart-loading").addClass("show");
        $(".sidebar-quantity-add").attr("disabled", true);
        $(".sidebar-quantity-sub").attr("disabled", true);
        let data = {
            id: id,
            quantity: quantity,
        }
        cartItemHeader.forEach(element => {
            if (element.id == id) {
                data.configurations = element.configurations;
            }
        });
        $.ajax({
            method: "POST",
            url: '/cart/update-cart-item',
            data : data
        }).done(function successCallback(response) {
            if (response.status == 'successful') {
                $(".sidebar-quantity [data-id='" + id + "']").val(quantity);
                $(".quantity-badge[data-id='" + id + "']").text(quantity);
                localStorage.setItem("change-cart", Date.now());
                window.dispatchEvent(new CustomEvent('change-cart', {detail: {showCart: true}}));
            }
            $(".item-sidebar-cart-loading").removeClass("show");
            $(".sidebar-quantity-add").attr("disabled", false);
            $(".sidebar-quantity-sub").attr("disabled", false);
        });
    }
    function removeCartItem(id) {
        $(".item-sidebar-cart-loading").addClass("show");
        $(".sidebar-quantity-add").attr("disabled", true);
        $(".sidebar-quantity-sub").attr("disabled", true);
        $.ajax({
            url: '/cart/remove-cart-item?ids=' + id,
            method: 'DELETE',
        }).done(function successCallback(response) {
            if (response.status == 'successful') {
                localStorage.setItem("change-cart", Date.now());
                window.dispatchEvent(new CustomEvent('change-cart', {detail: {showCart: true}}));
                $(".item-sidebar-cart-loading").removeClass("show");
                $(".sidebar-quantity-add").attr("disabled", false);
                $(".sidebar-quantity-sub").attr("disabled", false);
            }
        });
    }
    function showCartNotRecentlyViewed() {
        let isShowCart = false;
        let lastView = localStorage.getItem("last-viewed");
        if (lastView) {
            const timestampInMilliseconds = Number(lastView);
            const currentTimestamp = Date.now();
            const fiveDaysAgoThreshold = currentTimestamp - 5 * 24 * 60 * 60 * 1000;
            if (timestampInMilliseconds <= fiveDaysAgoThreshold) {
                isShowCart = true;
            }
        }
        if (!isShowCart) {
            getCartItems(true, false);
        } else {
            getCartItems(true, true);
        }
        localStorage.setItem("last-viewed", Date.now());
        setInterval(() => {
            localStorage.setItem("last-viewed", Date.now());
        }, 1000 * 60 * 5);
    }
    showCartNotRecentlyViewed();
    function showCartItems(cartItems) {
        $("#mini-cart-header .all-item-in-cart").html("");
        let html = "";
        for (let index = 0; index < cartItems.length; index++) {
            const element = cartItems[index];
            let url = element.url;
            if (locale != "" && !element.url.includes(locale)) {
                url = locale + element.url;
            }
            if (element.name_variant != "" && element.product_name && element.product_name.includes(", " + element.name_variant)) {
                element.product_name = element.product_name.replace(", " + element.name_variant, "");
            }
            html += 
            `
                <div class="item-content-variants">
                    <div class="item-cart-image-box">
                        <a class="item-cart-image-content" href="${url}">
                            <img class="hs-cart-image" loading="lazy" src="${getImageCdn(element.image_url, 360, 360, false)}" width="70" height="70" alt="Discover ${element.product_name}">
                        </a>
                    </div>
                    <div class="item-cart-description">
                        <div class="item-top">
                            <div class="content-product-and-variant-title">
                                <a href="${url}" class="product-title">${element.product_name}</a>
                                <div class="variant-title">${element.name_variant}</div>`
                                if (element.configurations) {
                                    let configurations = JSON.parse(element.configurations);
                                    for (let i in configurations) {
                                        if (i == 'hire_designer') {
                                            html += `<div class="variant-title">${window.HireDesignerCartText}</div>`
                                        } else if (typeof configurations[i] == 'string' || typeof configurations[i] == 'number') {
                                            if (i != 'print_location' && i != 'previewUrl' && i != 'buy_design' && i != 'design_fee') {
                                                html += `<div class="variant-title">${i}: ${configurations[i]}</div>`
                                            }

                                            if (i == 'print_location' && getByField(printLocationsMiniCartHeader, 'value', configurations[i])) {
                                                html += `<div class="variant-title">${printLocationText + ":"} ${getByField(printLocationsMiniCartHeader, 'value', configurations[i]).name}</div>`
                                            }
                                        } else if (i == 'Preview url') {
                                            html += `<div class="variant-title">${i}: <a href="${configurations[i]['image_url']}" target="_blank">${viewText}</a></div>`
                                        } else if (i == 'config_by_print_location') {
                                            html += `<div class="variant-title">${printLocationText + ": "} ${Object.keys(configurations[i]).map(text => miniCartTranslateText[text]).join(', ')}</div>`
                                        }
                                    }
                                }
                        html += `</div>
                            <div class="item-close cart-sidebar-remove" data-id="${element.id}">
                                <svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" width="16" height="16" x="0" y="0" viewBox="0 0 24 24" style="enable-background:new 0 0 512 512" xml:space="preserve" class="">
                                    <g>
                                        <g data-name="01 align center">
                                            <path d="M22 4h-5V2a2 2 0 0 0-2-2H9a2 2 0 0 0-2 2v2H2v2h2v15a3 3 0 0 0 3 3h10a3 3 0 0 0 3-3V6h2ZM9 2h6v2H9Zm9 19a1 1 0 0 1-1 1H7a1 1 0 0 1-1-1V6h12Z" fill="currentColor" opacity="1" data-original="#000000" class=""></path>
                                            <path d="M9 10h2v8H9zM13 10h2v8h-2z" fill="currentColor" opacity="1" data-original="#000000" class=""></path>
                                        </g>
                                    </g>
                                </svg>
                            </div>
                        </div>
                        <div class="content-quantity-price">
                            <div class="quantity-box">
                                <button class="product-quantity-sub sidebar-quantity-sub" aria-label="Minus" data-id="${element.id}">
                                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" viewBox="0 0 16 16">
                                        <path d="M4 8a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 0 1h-7A.5.5 0 0 1 4 8z"></path>
                                    </svg>
                                </button>
                                <input class="form-control quantity-input sidebar-quantity" type="number" name="quantity" value="${element.quantity}" min="1" max="99" aria-label="product quantity" data-id="${element.id}">
                                <button class="product-quantity-add sidebar-quantity-add" aria-label="Plus" data-id="${element.id}">
                                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" viewBox="0 0 16 16">
                                        <path d="M8 4a.5.5 0 0 1 .5.5v3h3a.5.5 0 0 1 0 1h-3v3a.5.5 0 0 1-1 0v-3h-3a.5.5 0 0 1 0-1h3v-3A.5.5 0 0 1 8 4z"></path>
                                    </svg>
                                </button>
                            </div>
                            <div class="cart-content-price">
                                <span class="price-total">${formatPrice(decorePrice(element.price), priceTemplate)}</span>`
                                if (element.high_price && element.high_price > element.price) {
                                    html += `<span class="compare-at-price">${formatPrice(decorePrice(element.high_price), priceTemplate)}</span>`
                                }
                            html += `
                            </div>
                        </div>
                    </div>
                </div>
            `
        }
        $("#mini-cart-header .mini-cart-wrapper").removeClass("mini-cart-wrapper-not-add");
        $("#mini-cart-header .list-add-item").html(html);
        $("#mini-cart-header .list-add-item-wrapper").show();
        if (cartItems.length > 3) {
            $("#mini-cart-header .action-layout").addClass("show-footer");
        } else {
            $("#mini-cart-header .action-layout").removeClass("show-footer");
        }
        $("#show-mini-cart-wrapper").prop("checked", true);
    
        $(".buymore-button").click(function() {
            $("#show-mini-cart-wrapper").prop("checked", false);
        });
        isScrollBottomSidebar = false;
        isScrollBottomSidebarRecommend = false;
        isTimeOut = false;
        $("#mini-cart-header .all-item-in-cart").html(html);
        $('.layout-content').scrollTop(0);
    
        $(".sidebar-quantity-add").click(function() {
            let quantity = parseInt($(this).siblings(".quantity-input").val());
            let id = $(this).data("id");
            if (quantity < 1000) {
                $(this).siblings(".quantity-input").val(quantity + 1);
                updateCartItem(quantity + 1, id);
            }
        });
        $(".sidebar-quantity-sub").click(function() {
            let quantity = parseInt($(this).siblings(".quantity-input").val());
            let id = $(this).data("id");
            if (quantity > 1) {
                $(this).siblings(".quantity-input").val(quantity - 1);
                updateCartItem(quantity - 1, id);
            }
            if (quantity == 1) {
                removeCartItem(id);
            }
        });
        $(".sidebar-quantity").on("focusin", function() {
            $(".overlay-mini-cart-wrapper-input").show();
        });
        $(".sidebar-quantity").on("focusout", function() {
            $(".overlay-mini-cart-wrapper-input").hide();
        });
        $(".sidebar-quantity").on("change", function() {
            let quantity = parseInt($(this).val());
            if (!quantity) {
                quantity = 1;
                $(this).val(1);
            }
            if (quantity < 0) {
                quantity = 1;
                $(this).val(1);
            }
            
            if (quantity > 1000) {
                quantity = 1000;
                $(this).val(1000);
            }
            let id = $(this).data("id");
            if (quantity == 0) {
                removeCartItem(id);
            } else {
                updateCartItem(quantity, id);
            }
        });
        $(".cart-sidebar-remove").on("click", function() {
            let id = $(this).data("id");
            removeCartItem(id);
            eventRemoveCartInsider(id);

        });
        if (!isShowExpressCheckout) {
            showExpressCheckout();
        }
        if (typeof isShowPaypalExpressCheckout !== 'undefined') {
            showPaypal();
        }
        if (!isValidPaypalExpressCheckout && !isValidExpressCheckoutHeader) {
            $(".split-button-sidebar").hide();
        }

    }

    function eventRemoveCartInsider(id) {
        var localeInsider = 'us';
        if (typeof localePrefix !== 'undefined' && localePrefix !== '') {
            localeInsider = localePrefix;
        }
        let data = {
            type: 'remove_from_cart',
        };
        let item = cartItemHeader.find(item => item.id == id);
        if (item) {
            let {color, size, taxonomy, seller_name} = getSizeAndColorAndTaxonomy(item.cart_item_insider ?? null);
            data.value = {
                id: 'sku-' + item.product_sku_id,
                name: item.product_name,
                groupcode: localeInsider + '-' + item.product_id,
                taxonomy: taxonomy,
                unit_price: parseFloat(item.high_price),
                unit_sale_price: parseFloat(item.price),
                quantity: parseInt(item.quantity),
                url: baseUrl ? baseUrl + item.url : item.url,
                color: color ?? "",
                size: size ?? "",
                product_image_url: item.image_url,
                custom: {
                    merchandiser: seller_name,
                }
            };
            pushEventToInsider(data);
        }
    }

    function pushEventToInsider(data) {
        const newEvent = new CustomEvent('eventInsider', {
            detail: data,
            bubbles: true,
            cancelable: true
        });
        document.dispatchEvent(newEvent);
    }

    function getSizeAndColorAndTaxonomy(dataInsider) {
        let color = '';
        let size = '';
        let taxonomy = [];
        let seller_name = '';
        if (dataInsider) {
            try {
                dataInsider = JSON.parse(dataInsider);
                color = dataInsider.color;
                size = dataInsider.size;
                taxonomy = dataInsider.array_category_name;
                seller_name = dataInsider.seller_name;
            } catch (error) {
            }
        }
        return {color: color, size: size, taxonomy: taxonomy, seller_name: seller_name};
    }

    function showPaypal() {
        if (validCountryHeader.includes(countryByIpHeader) && usePaypalInSidebar) {
            isValidPaypalExpressCheckout = true;
        }
        if (currencyUnitAddToCartHeader != defaultcurrencyUnitAddToCartHeader) {
            isValidPaypalExpressCheckout = false;
        }
        let jsGgDiscount = $('#js-gg-discount').val();
        if (jsGgDiscount == 1) {
            isValidPaypalExpressCheckout = false;
        }
        if (modeHeader && modeHeader == "test") {
            isValidPaypalExpressCheckout = true;
            countryByIpHeader = "US";
        }
        if (isValidPaypalExpressCheckout && !isShowPaypalExpressCheckout) {
            isShowPaypalExpressCheckout = true;
            let style = {
                shape: 'rect',
                height: 40,
                shape: "pill",
                layout: "horizontal",
                tagline: false,
                branding: false
            }
            if (currentRouteName == "module::cart::checkout" || currentRouteName == "cart") {
                style = {
                    shape: "rect",
                    layout: "vertical",
                    tagline: false,
                    branding: false
                }
            }
            paypal.Buttons({
                style: style,
                createOrder: async function(data, actions) {
                    await getShippingInfoCart();
                    if (!tokenHeader) {
                        tokenHeader = await getCustomerTokenHeader();
                    }
                    shippingTypeHeader = "standard";
                    let shippingOptions = getShippingOption(shippingInfoByPaymentRequestButtonHeader, true, 'paypal');
                    let amount = getAmount('paypal', shippingOptions);
                    let orderId = null;
                    await $.ajax({
                        method: 'POST',
                        url: base_api_url_header + '/paypal/express/create',
                        data: JSON.stringify({ 
                            amount: amount.totalWithoutShipping,
                            shippingOptions,
                            service_token: "megaads@123",
                            mode: getParameterByNameHeader("mode")
                        }),
                        headers: {
                            'Content-Type': 'application/json',
                        }
                    }).done(function(response) {
                        orderId = response.order_id;
                        paypalAccountHeader = response.account;
                    });
                    return orderId;
                },
    
                onShippingChange: async function(data, actions) {
                    let shippingOptions = [];
                    let isGetShippingInfo = false;
                    let countryId = null;
                    if (data.shipping_address && data.shipping_address.country_code != selectedCountryHeader) {
                        selectedCountryHeader = data.shipping_address.country_code;
                        isGetShippingInfo = true;
                        await getShippingInfoCart(data.shipping_address.country_code);
                        countryId = data.shipping_address.country_code;
                        await checkTax(data.shipping_address.country_code);
                        shippingOptions = getShippingOption(shippingInfoByPaymentRequestButtonHeader, true, 'paypal');
                    }
                    if (data.selected_shipping_option && data.selected_shipping_option.id && shippingTypeHeader != data.selected_shipping_option.id) {
                        shippingTypeHeader = data.selected_shipping_option.id;
                        selectedShippingHeader = [];
                        selectedShippingHeader.push({
                            id: data.selected_shipping_option.id,
                            shipping_fee: data.selected_shipping_option.amount.value ? data.selected_shipping_option.amount.value : data.selected_shipping_option.amount,
                            name_shipping: data.selected_shipping_option.label,
                        });
                        shippingOptions = getShippingOption(shippingInfoByPaymentRequestButtonHeader, false, 'paypal');
                        isGetShippingInfo = true;
                    }
                    if (isGetShippingInfo) {
                        let amount = getAmount('paypal', shippingOptions);
                        try {
                            const response = await $.ajax({
                                method: 'POST',
                                url: base_api_url_header + '/paypal/express/update-shipping',
                                data: JSON.stringify({
                                    shipping_info: shippingInfoByPaymentRequestButtonHeader,
                                    selected_shipping_option: selectedShippingHeader,
                                    amount: amount.totalWithoutShipping,
                                    order_id: data.orderID, 
                                    shippingOptions, 
                                    account: paypalAccountHeader,
                                    service_token: "megaads@123",
                                    mode: getParameterByNameHeader("mode"),
                                    country: countryId,
                                }),
                                headers: {
                                    'Content-Type': 'application/json',
                                }
                            });
                            if (response.status === 'successful') {
                                return actions.resolve();
                            }
                            console.log(response);
                            throw new Error(response.message || 'Failed to update shipping.');
                        } catch (err) {
                            console.error('Update Shipping Error:', err);
                            return actions.reject('Failed to update shipping: ' + err.message);
                        }
                    }
                    return actions.resolve();
                },       
                onApprove: async function(data, actions) { 
                    return actions.order.get().then(async function(orderData) {
                        let shippingData = orderData.purchase_units[0].shipping;
                        let shipping = {
                            country: shippingData.address.country_code,
                            postalCode: shippingData.address.postal_code,
                            city: shippingData.address.admin_area_2,
                            region: shippingData.address.admin_area_1,
                            addressLine: [
                                shippingData.address.address_line_1,
                                shippingData.address.address_line_2,
                            ]
                        }
                        let payer = orderData.payer;
                        let phone = "000000";
                        if (payer.phone && payer.phone.phone_number && payer.phone.phone_number.national_number) {
                            phone = payer.phone.phone_number.national_number;
                            if (payer.phone.phone_number.country_code) {
                                shipping.country = payer.phone.phone_number.country_code;
                            }
                        }
                        if (phone == "000000" && shippingData.phone_number && shippingData.phone_number.national_number) {
                            phone = shippingData.phone_number.national_number;
                            if (shippingData.phone_number.country_code) {
                                shipping.country = shippingData.phone_number.country_code;
                            }
                        }
                        let data = {
                            payerName: payer.name.given_name + ' ' + payer.name.surname,
                            payerEmail: payer.email_address,
                            payerPhone: phone,
                            shippingAddress: shipping,
                            shippingOptions: shippingData.options && shippingData.options.length > 0 ? shippingData.options : null,
                        }
                        let order = await processOrder(data, "paypal_express");
                        await updateInvoice(order.order.code, orderData.id);
                        let url = base_api_url_header + '/paypal/v2/confirm?customerToken=' + tokenHeader + '&order_code=' + order.order.code + '&token=' + orderData.id + '&ignore_localization=1&type_return=json';
                        if (getParameterByNameHeader("mode") == "test") {
                            url += '&is_sandbox=1';
                        }
                        await $.ajax({
                            method: 'GET',
                            url: url,
                        }).done(function(response) {
                            window.location.href = response.result;
                        });
                    }).catch(function(error) {
                        console.error("Error fetching order details:", error);
                    });
                },
                onError: function(err) {
                    alert('Error: ' + err.message);
                }
            }).render('#paypal-button-container-sidebar');
        }
    }

    async function updateInvoice(orderCode, orderId) {
        await $.ajax({
            method: 'POST',
            url: base_api_url_header + '/paypal/express/update-invoice',
            data: JSON.stringify({
                order_code: orderCode,
                order_id: orderId,
                account: paypalAccountHeader,
                service_token: "megaads@123",
                mode: getParameterByNameHeader("mode")
            }),
            headers: {
                'Content-Type': 'application/json',
            }
        });
    }

    function showRelated(relatedProducts) {
        if (typeof tenancyToken !== 'undefined' && tenancyToken != '') {
            return;
        }
        $("#mini-cart-header .related-items").html("");
        let html = "";
        for (let index = 0; index < relatedProducts.length; index++) {
            const element = relatedProducts[index];
            listRelated.push(element.id);
            let url = element.url;
            if (locale != "" && !element.url.includes(locale)) {
                url = locale + element.url;
            }
            html += buildRelatedItemHtml(element);
        }
        $("#mini-cart-header .related-items").html(html);
        $("#mini-cart-header .related-items-wrapper").show();
    
        showLazyLoadImages();
    }
    
    function showLazyLoadImages() {
    
        const callbackLoaded = function(image) {
            if (image.closest(".has-fancy-loading")) {
                const loadingBlocks = image.closest(".has-fancy-loading").querySelectorAll('span.fancy-loading-block');
                if (loadingBlocks) {
                    for (let i = 0; i < loadingBlocks.length; i++) {
                        loadingBlocks[i].remove();
                    }
                }
            }
        }
    
        const lazyFunction = function(image) 
        {
            if (image.parentElement.tagName === 'PICTURE')
            {
                let sources = image.parentElement.getElementsByTagName('source');
                for (let i = 0; i < sources.length; i++) {
                    sources[i].srcset = sources[i].dataset.srcset;
                }
            } else {
                image.src = image.dataset.src;
            }
    
            image.classList.remove("lazy");
    
            if (image.complete) {
                callbackLoaded(image);
            } else {
                image.addEventListener('load', function(event) {
                    callbackLoaded(event.target);
                });
                image.addEventListener('error', function(event) {
                    callbackLoaded(event.target);
                    console.warn('error load image', image.currentSrc);
                });
            }
    
        }
        const lazyloadImages = document.querySelectorAll("#mini-cart-header .related-items .lazy");
        const imageObserver = new IntersectionObserver(function (entries, observer) {
            entries.forEach(function (entry) {
                if (entry.isIntersecting) {
                    const image = entry.target;
    
                    lazyFunction(image);
                    imageObserver.unobserve(image);
                }
            });
        }, {
            root: null,
            rootMargin: "100px",
            threshold: 0.1
        });
    
        lazyloadImages.forEach(function (image) {
            imageObserver.observe(image);
        });
    }
    
    function decorePrice(price, element) {
        if (element && element.configurations && element.is_flash_sale) {
            let configurations = JSON.parse(element.configurations);
            if (configurations.print_location) {
                let addPrice = buildAddPrice(price, configurations.print_location, element.categoryIds);
                price = parseFloat(price) - addPrice;
            }
        }
        if (priceConfigForMiniCart) {
            price = (parseFloat(price) + parseFloat(priceConfigForMiniCart["adding_price"])) * parseFloat(priceConfigForMiniCart["ratio"]);
            price = decimalAdjust('ceil', price);
        }
    
        return price;
    }
    
    buildAddPrice = (price, type, categoryIds = []) => {
        let retVal = null;
        let locale = prefixLocaleUrlMiniCart == "/" ? "us" : prefixLocaleUrlMiniCart.replace(/\//g, "");
        if (printLocationsPriceMiniCart && printLocationsPriceMiniCart[type]) {
            if (printLocationsPriceMiniCart[type][locale]) {
                let printLocationsPriceByLocale = printLocationsPriceMiniCart[type][locale];
                for (let cateId in printLocationsPriceByLocale.category) {
                    let check = categoryIds.find(id => id == cateId);
                    if (check) {
                        retVal = printLocationsPriceByLocale.category[cateId];
                        break;
                    }
                }
                if (!retVal && printLocationsPriceByLocale.default) {
                    retVal = printLocationsPriceByLocale.default;
                }
            }
        }
        let addPrice = 0;
        if (retVal) {
            if (retVal.type == 'percent') {
                addPrice = parseFloat(price) * retVal.value;
            } else {
                addPrice = retVal.value;
            }
        }
        return addPrice;
    }
    
    function getShippingInfoCart(country = null) {
        return new Promise((resolve, reject) => {
            $.ajax({
                url: "/cart/shipping/info?country=" + country,
            }).done(function(response) {
                if (response.result && response.result.length > 0) {
                    buildShippingInfo(response.result);
                    shippingInfoByPaymentRequestButtonHeader = response.result;
                }
                resolve();
            });
        })
    }

    async function checkTax(country) {
        validTaxHeader = false;
        if (country == "US") {
            await $.ajax({
                url: "/cart/tax-us?country=" + 226,
            }).done(function(response) {
                if (response.status == 'successful') {
                    validTaxHeader = response.result;
                }
            }).catch(function(error) {
            });
        }
    }
    
    function buildShippingInfo(result) {
        let dataShipping = result;
        let htmlFreeShip = "";
        dataShipping.forEach(shipping => {
            shipping.shipping_info.forEach(element => {
                if (element["type"] == "standard") {
                    for (let i = 0; i < element["additional_info"].length; i++) {
                        const info = element["additional_info"][i];
                        if (parseFloat(info.fee_limit) > 0 && parseFloat(info.fee_if_limit) == 0) {
                            htmlFreeShip += `<div style="font-weight: 400 !important; padding: 0 var(--pr-spacing-07)"><span style="font-weight: 500;">Free Shipping</span>` + " on orders over " + `<span style="font-weight: 500;">` + formatPrice(decorePrice(info.fee_limit), priceTemplate) + "</span> " + `(${info.cate_name})</div>`
                        }
                        if (parseFloat(info.adding_fee) == 0 && info.cate_name == "Stickers") {
                            htmlFreeShip += `<div style="font-weight: 400 !important;"><span style="font-weight: 500;">No extra shipping fee</span>` + " for additional items " + `(${info.cate_name})</div>`
                        }
                    }
                }
            });
        });
        if (htmlFreeShip != "") {
            $(".cart-buy-more-sidebar").show();
            $(".cart-buy-more-sidebar").html(htmlFreeShip);
        } else {
            $(".cart-buy-more-sidebar").hide();
        }
    };
    
    function loadMoreRelated() {
        let productId = $("#productId").val();
        let userId = $("#userId").val();
        let url = "/pod/also-available/find?product_id=" + productId;
        $(".also-like-sidebar-cart-loading").show();
        $.ajax({
            method: "GET",
            url: url,
        }).done(function (response) {
            if (response.status == "successful") {
                let html = "";
                for (let index = 0; index < response.result.length; index++) {
                    const element = response.result[index];
                    let url = element.url;
                    if (locale != "" && !element.url.includes(locale)) {
                        url = locale + element.url;
                    }
                    html += buildRelatedItemHtml(element);
                }
                
                $("#mini-cart-header .related-items").append(html);
                $(".also-like-sidebar-cart-loading").hide();
                showLazyLoadImages();
                setTimeout(() => {
                    isTimeOut = true; 
                }, 500);
            }
        });
    }
    
    function buildRelatedItemHtml(element) {
        let url = element.url;
        if (locale != "" && !element.url.includes(locale)) {
            url = locale + element.url;
        }
        let result = `
            <div 
                class="product-item ${isNaN(element.id) ? 'preview-product-item' : '' }"
                ${isNaN(element.id) ? `onclick="genProduct(this, ${element.template_id}, ${element.enable_bulk_create ? 'true' : 'false'})"` : '' }
            >
                ${isNaN(element.id) ? '<div class="search-loading"></div>' : "" }
                <div class="product-item-wrapp">
                    <div class="product-image has-fancy-loading">
                        <a 
                            class="cart-sidebar-product-item-link ${isNaN(element.id) ? 'preview-product-item' : '' }" 
                            href="${!isNaN(element.id) ? `${locale}${element.url}?internal_source=cart-popup-suggestion` : `javascript:void(0)`}"
                        >
                            <picture>
                                <source data-srcset="${getImageCdn(element.image_url, imageSize, imageSize, false)}">
                                <img loading="lazy" class="lazy" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=" alt="Discover ${element.name}" referrerpolicy="no-referrer" width="160" height="160">
                            </picture>
                            <span class="fancy-loading-block animated-background"></span>
                        </a>
                    </div>       
                    <div class="product-info">
                        <a 
                            class="cart-sidebar-product-item-link ${isNaN(element.id) ? 'preview-product-item' : '' }" 
                            href="${!isNaN(element.id) ? `${locale}${element.url}?internal_source=cart-popup-suggestion` : `javascript:void(0)`}">
                            <span class="product-title">${element.name}</span>
                        </a>
                        <span class="minicart-product-price">
                            <b>${formatPrice(decorePrice(element.price), priceTemplate)}</b>
                            ${element.high_price && element.high_price > element.price ? `<del>${formatPrice(decorePrice(element.high_price), priceTemplate)}</del>` : ''}
                        </span>
                    </div>                                                    
                </div> 
            </div>
        `;
    
        return result;
    }
    
    
    function genProduct(element, templateId, enableBulkCreate = false) {
        $(element).addClass('generating');
    
        let productId = $("#productId").val();
        let url = `/pod/also-available/create`;
    
        $.ajax({
            url: url,
            method: "POST",
            data: { product_id: productId, template_id: templateId }
        }).done(response => {
            $(element).removeClass('generating');
            $(element).removeAttr('onclick');
            if (response && response.result && response.result.id) {
                let links = $(element).find('.cart-sidebar-product-item-link');
                for (let link of links) {
                    let redirectUrl = '/product-p' + response.result.id + '?internal_source=also-available-template'
                    if (localePrefix && localePrefix != 'us') {
                        redirectUrl = `/${localePrefix}` + redirectUrl;
                    }
                    $(link).attr('href', redirectUrl);
                }
                if (links.length) {
                    setTimeout(() => {
                        links[0].click();
                        $(links[0])[0].click();
                    }, 300)
                }
                if (enableBulkCreate) {
                    triggerBulkCreate(productId);
                }
            } else {
                toastr.error(errorTryAgainText);
            }
        });
    }
    
    function triggerBulkCreate(productId) {
        $.ajax({
            url: PodAlsoAvailableRestQUrl + `/service/pod/bulk-create-product-from-design?ignore_localization=1`,
            method: "POST",
            data: { from_product_id: productId }
        })
    }
    
    function getRecommendationProduct() {
        $(".also-like-sidebar-cart-loading").show();
        $.ajax({
            url: "/product/recommendation?id=" + $("#productId").val() + "&size=40",
            method: "GET",
        }).done(function (response) {
            if (response.status == "successful") {
                let html = "";
                for (let index = 0; index < response.result.length; index++) {
                    const element = response.result[index];
                    if (listRelated.includes(element.id)) {
                        continue;
                    }
                    html += buildRelatedItemHtml(element);
                }
                $("#mini-cart-header .related-items").append(html);
                $(".also-like-sidebar-cart-loading").hide();
                showLazyLoadImages();
            }
        });
    }
    
    $('.layout-content').on('scroll', function() {
        if (typeof tenancyToken !== 'undefined' && tenancyToken != '') {
            return;
        }
        var heightwd = $('.layout-content').height() + 800;
        if ($(this).scrollTop() >= $(this)[0].scrollHeight - heightwd) {
            if (isTimeOut && isScrollBottomSidebar && !isScrollBottomSidebarRecommend) {
                isScrollBottomSidebarRecommend = true;
                getRecommendationProduct();
            }
            if (!isScrollBottomSidebar && !isScrollBottomSidebarRecommend) {
                isScrollBottomSidebar = true;
                loadMoreRelated();
            }
        }
    });
    function getByField (list, fieldName, value) {
        var retVal = null;
        list.forEach(function (item) {
            if (item[fieldName] == value) {
                retVal = item;
            }
        });
        return retVal;
    };
})