window.doneLoadAddToCartScript = true;
var cartCheckChoosingSize = false;
var cartCustomizeIframeURL = "";
var cartCustomilyIframe = null;
var cartIframePopup = null;
var validTax = false;
var productInsider = typeof product !== 'undefined' ? product : null;

//lắng nghe event buildDataVariantChangeInsider
window.addEventListener('buildDataVariantChangeInsider', function (event) {
    productInsider = event.detail;
});

async function cartHandleAddToCart(btnElement) {
    if (document.querySelector('#js-is-multiple-size')) {
        await cartHandleAddAllToCart(btnElement);
        return;
    }
    let isValid = document.querySelector('#js-sku-chosen[default-sku-id=""]');
    if (typeof checkSizeBeforeAddToCart !== 'undefined' && typeof checkSizeBeforeAddToCart === 'function') {
        isValid = await checkSizeBeforeAddToCart();
        if (!isValid) {
            cartCheckChoosingSize = true;
        }
    }

    window.dispatchEvent(new CustomEvent('check_size_add_to_cart', { detail: {isValid} }));

    // validate add to cart
    let validated = true;
    try {
        if (typeof window.validateAddToCart !== 'undefined' && window.validateAddToCart.length) {
            for (let i = 0; i < window.validateAddToCart.length; i++) {
                if (typeof window.validateAddToCart[i] === 'function') {
                    let result = await window.validateAddToCart[i]();
                    if (validated && !result) {
                        validated = false;
                    }
                }
            }
        }
    } catch (e) {
        console.warn(e);
    }

    window.dispatchEvent(new CustomEvent('validate_add_to_cart', { detail: {validated} }));

    if (!isValid || !validated) {

        if (!validated && $('#notice-option-input')) {
            $('#notice-option-input').prop('checked', true);
        }

        return;
    }
    if (typeof beforeAddToCart !== 'undefined' && typeof beforeAddToCart === 'function') {
        await beforeAddToCart();
    }
    if (window.dataLayer) {
        window.dataLayer.push({'event': 'add_to_cart'});
        window.dataLayer.push({
            'dr_event_type': 'add_to_cart',
            'event':'dynamic_remarketing'
        });
    }
    let self = $(btnElement);
    self.attr("disabled", "disabled");
    self.addClass("is-loading");
    self.find(".add-to-cart-content").hide();
    self.find(".added-to-cart-content").show();
    self.find(".loading-content").show();

    let productId = $("#productId").val(),
        skuId = $("#productSkuId").val(),
        sizeInsider = $("#size-insider").val(),
        colorInsider = $("#color-insider").val(),
        sellerNameInsider = $("#seller-name-insider").val(),
        isOption = $("#isOption").val(),
        quantityAddCart = $("#quantity").val() || 1,
        configurations = $("#configurations").val(),
        productVariantOptions = $("#productVariantOptions").val(),
        recommendation = $("#product-recommendation").val(),
        imageUrl = $("#imageUrl").val(),
        buyMorePrice = $("#js-buy-more-price").val(),
        imageFile = document.getElementById('imageFile');
    
    const formData = new FormData();
    formData.append('productId', productId);
    formData.append('productSkuId', skuId);
    formData.append('quantity', quantityAddCart);
    formData.append('productVariantOptions', productVariantOptions);
    formData.append('_token', csrfToken);
    let tokenUserQuery = localStorage.getItem('token_user_query');
    if (tokenUserQuery) {
        formData.append('token_user_query', tokenUserQuery);
    }
    if (imageFile && imageFile.files && imageFile.files.length) {
        formData.append('imageFile', imageFile.files[0]);
    } else if (imageUrl) {
        formData.append('imageUrl', imageUrl);
    }
    if (buyMorePrice > 0) {
        if (configurations != '') {
            config = JSON.parse(configurations);
        } else {
            config = {};
        }
        config.price_by_quantity = {
            price: buyMorePrice,
        };
        configurations = JSON.stringify(config);
    }
    if (configurations && configurations.length) {
        formData.append('configurations', configurations);
    }

    if (recommendation) {
        formData.append('recommendation', recommendation);
    }

    //xử lý lấy thông tin tên danh mục của sản phẩm
    let arrayCategoryName = [];
    if (typeof product !== 'undefined') {
        arrayCategoryName = product.array_category_name
    }
    let dataInsider = {
        array_category_name: arrayCategoryName,
        color: colorInsider,
        size: sizeInsider,
        seller_name: sellerNameInsider
    }

    formData.append('data_insider', JSON.stringify(dataInsider));

    $.ajax({
        url: '/cart/add-to-cart',
        method: 'POST',
        data: formData,
        processData: false,
        contentType: false,
    }).done(function(result) {
        let locale = '';
        if (typeof localePrefix !== 'undefined' && localePrefix !== '') {
            locale = '/' + localePrefix;
        }
        if (result.status == "successful") {
            if (productInsider) {
                eventAddToCartInsider(productInsider);
            }
            $("#list-cart-items").html("");
            $(".mini-cart-list").show();
            $("#cart-error").hide();
            var html = "";
            var quantity = 0;
            var addItem = result.cartItems[0];
            result.cartItems.forEach((element) => {
                quantity += parseInt(element.quantity);
                html += `
                        <a class="mini-cart-item flex-box" href="${locale}${element.url}">
                            <img src="${getImageCdn(element.image_url, 540, 540)}" alt="" referrerpolicy="no-referrer">
                            <div class="mini-cart-content">
                                <div class="mini-cart-head">
                                    ${element.product_name}
                                </div>
                                <div class="mini-cart-info flex-box align-c ">
                                    <span class="new-price">${formatPrice(decorePrice(element.price), priceTemplateAddCart)}
                `;
                if (element.high_price && element.high_price > element.price) {
                    html += `<span class="discount-price" style="text-decoration: line-through;">${formatPrice(decorePrice(element.high_price), priceTemplateAddCart)}</span>`
                }
                html += `</span><span style"color: red;">&times;</span>
                                <span class="quantity-mini-cart"> ${element.quantity}</span>
                            </div>
                        </div>
                    </a>
                `;
            });
            $("#list-cart-items").append(html);
            $(".js-mini-cart-count").text(parseInt(quantity));
            if (parseInt(quantity) > 0) {
                $(".js-mini-cart-count").show();
            }
            $(".cart-icon").replaceWith($(".cart-icon").clone());
            $(".mini-cart-contain").html("");
            let showRelated = typeof isCustomDesign !== 'undefined' && !isCustomDesign ? true : false;
            const relatedProducts = result.relatedProducts;
            let listAdd = [];
            listAdd.push(addItem);
            addItem.quantity = quantityAddCart;
            let detail = {
                listAdd: listAdd,
                relatedProducts: relatedProducts,
                cartItems: result.cartItems
            }
            window.dispatchEvent(new CustomEvent('item-add-to-cart', {detail: detail}))
            window.dispatchEvent(new CustomEvent('change-cart', {detail: {showCart: true}}));
            localStorage.setItem("change-cart", Date.now());

            if (addItem && addItem.configurations) {
                try {
                    let configurations = JSON.parse(addItem.configurations);
                    if (configurations.edit_url) {
                        addItem.url = configurations.edit_url.url;
                    }
                } catch (error) {

                }
            }
            if (relatedProducts && relatedProducts.length > 0 && !useDefaultMiniCart && showRelated) {

                let addedToCartHtml = "";
                addedToCartHtml += `
                    <a class="add2basket-link" href="${locale}${addItem.url}">
                        <img class="md-add2basket-image image-add-to-cart" src="${getImageCdn(addItem.image_url, 540, 540)}" alt="" referrerpolicy="no-referrer">
                    </a>
                    <div class="add2basket-item-detail">
                        <a href="${locale}${addItem.url}">${addItem.product_name}</a>
                        <span class="add2basket-price">
                            ${formatPrice(decorePrice(addItem.price), priceTemplateAddCart)}
                            <span>&times;</span>
                            <span>${quantityAddCart}</span>
                        `;
                addedToCartHtml += `
                        </span>
                        <div class="add2basket-item-footer">
                            <a class="button checkout-button" href="${locale}/cart">${viewCartText}</a>
                            <a class="button buymore-button" id="add2basket-buymore" href="javascript:;">${buyMoreText}</a>
                        </div>
                    </div>
                `;

                self.toggleClass("is-loading");
                self.toggleClass("is-added");
                self.find(".loading-content").hide();

                setTimeout(() => {
                    self.toggleClass("is-added");
                    self.removeAttr("disabled");
                    self.find(".added-to-cart-content").hide();
                    self.find(".add-to-cart-content").show();
                }, 2000);

                let closePopup = document.querySelector('#add2basket-close')
                let buymorePopup = document.querySelector('#add2basket-buymore')
                let popupContent = document.querySelector('.add2basket-wrapper');

                $(document).click(function(e) {
                    var container = $(".add2basket-content");
                    // if the target of the click isn't the container nor a descendant of the container
                    if (!container.is(e.target) && container.has(e.target).length == 0) {
                        popupContent.classList.remove('active');
                    }
                });

                closePopup.addEventListener('click', function(event) {
                    popupContent.classList.remove('active');
                    event.stopPropagation();
                });
                buymorePopup.addEventListener('click', function(event) {
                    popupContent.classList.remove('active');
                    event.stopPropagation();
                });

            } else {
                let miniCartHtml = "";
                miniCartHtml += `
                    <div class="mini-shopping-cart-image-box">
                        <span class="mini-shopping-cart-check">
                            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-check" viewBox="0 0 16 16">
                                <path d="M10.97 4.97a.75.75 0 0 1 1.07 1.05l-3.99 4.99a.75.75 0 0 1-1.08.02L4.324 8.384a.75.75 0 1 1 1.06-1.06l2.094 2.093 3.473-4.425a.267.267 0 0 1 .02-.022z" />
                            </svg>
                        </span>
                        <img class="mini-shopping-cart-image" src="${getImageCdn(addItem.image_url, 540, 540)}" referrerpolicy="no-referrer"/>
                    </div>
                    <div class="mini-shopping-cart-title flex-b column">
                        <div>${addedToCartText}</div>
                        <span class="js-shopping-cart-title">${addItem.product_name}</span>
                    </div>
                    <a href="${locale}/cart" class="view-cart-button" type="button">${viewCartText}</a>
                `;
                setTimeout(() => {
                    self.toggleClass("is-loading");
                    self.toggleClass("is-added");
                    self.find(".loading-content").hide();
                    self.find(".added-to-cart-content").show();
                    setTimeout(() => {
                        self.toggleClass("is-added");
                        self.removeAttr("disabled");
                        self.find(".added-to-cart-content").hide();
                        self.find(".add-to-cart-content").show();
                    }, 2000);
                }, 1000);
            }
            
        } else {
            alert("Fail. Try again later");
        }
    });

    function eventAddToCartInsider(productInsider) {
        var localeInsider = 'us';
        if (typeof localePrefix !== 'undefined' && localePrefix !== '') {
            localeInsider = localePrefix;
        }
        if(typeof productInsider !== 'undefined') {
            let data = {
                type: 'add_to_cart',
                value: {
                    id: 'sku-' + productInsider.product_sku_id,
                    name: productInsider.name,
                    groupcode: localeInsider + '-' + productInsider.id,
                    taxonomy: productInsider.array_category_name,
                    unit_price: parseFloat(productInsider.high_price),
                    unit_sale_price: parseFloat(productInsider.price),
                    quantity: parseInt(quantityAddCart),
                    url: productInsider.url_product,
                    color: productInsider.color ?? "",
                    size: productInsider.size ?? "",
                    product_image_url: productInsider.image_url,
                    custom: {
                        merchandiser: productInsider.seller_name,
                    }
                }
            };
            pushEventToInsider(data);
        }
    }

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

function cartArrayToFormData(array) {
    const formData = new FormData();

    array.forEach((item, index) => {
        for (const key in item) {
            if (item.hasOwnProperty(key)) {
                const value = item[key];
                if (key === "file" && value instanceof File) {
                    // Đính kèm file với tên unique, ví dụ: files[0].file
                    formData.append(`items[${index}][${key}]`, value);
                } else {
                    // Đính kèm các thuộc tính khác
                    formData.append(`items[${index}][${key}]`, value);
                }
            }
        }
    });

    return formData;
}

async function cartHandleAddAllToCart(btnElement) {
    let isValid = true;
    if (typeof checkSizeBeforeAddToCart !== 'undefined' && typeof checkSizeBeforeAddToCart === 'function') {
        isValid = await checkSizeBeforeAddToCart();
    }

    if (!isValid) {
        return;
    }

    if (window.dataLayer) {
        window.dataLayer.push({'event': 'add_to_cart'});
        window.dataLayer.push({
            'dr_event_type': 'add_to_cart',
            'event':'dynamic_remarketing'
        });
    }

    let self = $(btnElement);
    self.attr("disabled", "disabled");
    self.addClass("is-loading");
    self.find(".add-to-cart-content").hide();
    self.find(".added-to-cart-content").show();
    self.find(".loading-content").show();

    let productId = $("#productId").val();
    let configurations = $("#configurations").val();
    let imageUrl = $("#imageUrl").val();
    let imageFile = document.getElementById('imageFile');

    let cartItems = [];
    for (let item of Object.values(window.multipleSizeItems)) {
        let itemConfigurations = item.configurations ? item.configurations : {};
        try {
            let parseConfigurations = JSON.parse(configurations);
            itemConfigurations = {...parseConfigurations, ...itemConfigurations};
        } catch (error) {
            
        }
        cartItems.push({
            productId: productId,
            productSkuId: item.sku_id,
            quantity: parseInt(item.quantity),
            productVariantOptions: '',
            configurations: JSON.stringify(itemConfigurations)
        })
    }

    const formData = cartArrayToFormData(cartItems);

    if (imageFile && imageFile.files && imageFile.files.length) {
        formData.append('imageFile', imageFile.files[0]);
    }
    $.ajax({
        url: '/cart/add-all-to-cart',
        method: 'POST',
        data: formData,
        processData: false,
        contentType: false,
    }).done(function(response) {
        if (response.status == 'successful') {
            var locale = '';
            if (typeof localePrefix !== 'undefined' && localePrefix !== '') {
                locale = '/' + localePrefix;
            }
            window.location.href = locale + '/cart';
        } else {
            toastr.error('Fail. Try again later');
        }

        self.toggleClass("is-loading");
        self.toggleClass("is-added");
        self.find(".loading-content").hide();

        setTimeout(() => {
            self.toggleClass("is-added");
            self.removeAttr("disabled");
            self.find(".added-to-cart-content").hide();
            self.find(".add-to-cart-content").show();
        }, 2000);

    })

}

window.addEventListener('sizeWasChose', function (event) {
    if (event.detail) {
        if (event.detail && event.detail.status.toLowerCase() == 'active') {
            if (cartCheckChoosingSize) {
                if ($("#product-page .product-addtocart").is(":visible")) {
                    $("#product-page .product-addtocart").first().click();
                }
                if (typeof showPopupcartCustomilyIframe !== 'undefined' && typeof showPopupcartCustomilyIframe === 'function') {
                    showPopupcartCustomilyIframe();
                }
                cartCheckChoosingSize = false;
            }
        } else {
            cartCheckChoosingSize = false;
        }
    } else if (cartCheckChoosingSize) {
        if ($("#product-page .product-addtocart").is(":visible")) {
            $("#product-page .product-addtocart").first().click();
        }
        if (typeof showPopupcartCustomilyIframe !== 'undefined' && typeof showPopupcartCustomilyIframe === 'function') {
            showPopupcartCustomilyIframe();
        }
        cartCheckChoosingSize = false;
    }
});

function decorePrice(price) {
    if (priceConfigAddCart) {
        price = (parseFloat(price) + parseFloat(priceConfigAddCart["adding_price"])) * parseFloat(priceConfigAddCart["ratio"]);
        price = decimalAdjust('ceil', price);
    }
    return price;
}

function decimalAdjust(type, value) {
    let matches = priceTemplateAddCart.match(/{money}{([^a-zA-z0-9]+)}{([0-9]+)}/);
    let exp = -2;
    if (matches.length == 3) {
        exp = parseInt(matches[2] * (matches[2] ? -1 : 1));
    }
    // If the exp is undefined or zero...
    if (typeof exp === 'undefined' || +exp === 0) {
    return Math[type](value);
    }
    value = +value;
    exp = +exp;
    // If the value is not a number or the exp is not an integer...
    if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
        return NaN;
    }
    // Shift
    value = value.toString().split('e');
    value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
    // Shift back
    value = value.toString().split('e');
    return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
}

async function showPopupcartCustomilyIframe() {
    if (!cartCustomizeIframeURL || cartCustomizeIframeURL == "") {
        return;
    }
    let isValid = canAddToCart;
    if (typeof checkSizeBeforeAddToCart !== 'undefined' && typeof checkSizeBeforeAddToCart === 'function') {
        isValid = await checkSizeBeforeAddToCart();
        if (!isValid) {
            cartCheckChoosingSize = true;
        }
    }
    window.dispatchEvent(new CustomEvent('check_size_add_to_cart', { detail: {isValid} }));
    // validate add to cart
    let validated = true;
    try {
        if (typeof window.validateAddToCart !== 'undefined' && window.validateAddToCart.length) {
            for (let i = 0; i < window.validateAddToCart.length; i++) {
                if (typeof window.validateAddToCart[i] === 'function') {
                    let result = await window.validateAddToCart[i]();
                    if (validated && !result) {
                        validated = false;
                    }
                }
            }
        }
    } catch (e) {
        console.warn(e);
    }

    window.dispatchEvent(new CustomEvent('validate_add_to_cart', { detail: {validated} }));
    if (!isValid || !validated) {
        event.preventDefault()
        return;
    }
    if (typeof beforeAddToCart !== 'undefined' && typeof beforeAddToCart === 'function') {
        await beforeAddToCart();
    }
    cartIframePopup = $('#customily-popup');
    $(cartIframePopup).css('display', 'block');
    $("body").addClass("open-popup-customily");
}

$(document).ready(async function() {
    
    var countryByIp = null;
    countryByIp = await getCountry();
    var nextEvent = await getEvent();
    var fastestShipping = 100;
    var canAddToCart = document.querySelector('#js-sku-chosen[default-sku-id=""]');
   
    let mode = getParameterByName("mode");
    if (mode && mode == "test") {
        countryByIp = "US";
    }
    var lastSkuShipping = null;
    var lastQuanityShipping = null;
    var lastCountryShipping = null;
    let selectCountryAddToCart = countryByIp;
    let selectProductSkuId = null;
    let productVariantOptions = $('#productVariantOptions').val();
    let selectPrice = null;
    let selectImage = null;
    let selectConfigurations = null;
    let quantityAddCart = $("#quantity").val();
    let quantityCheckout = $("#quantity").val();
    let priceRaw = $("#js-raw-price").val();
    let productTitle = $("#js-product-title").val();
    var isValidStripeExpressCheckout = false;
    var isValidPaypalExpressCheckout = typeof validPaypalExpressCheckout !== 'undefined' ? validPaypalExpressCheckout : false;
    var paypalAccount = null;
    var customerTokenCart = null;
    if (validCountry.includes(countryByIp) && useCheckoutInProductPage) {
        isValidStripeExpressCheckout = true;
    }
    if ($("#js-is-custom").val() == 1 || !priceRaw || currencyUnitAddToCart != defaultCurrencyUnitAddToCart) {
        isValidStripeExpressCheckout = false;
        isValidPaypalExpressCheckout = false;
    }
    let jsGgDiscount = $('#js-gg-discount').val();
    if (jsGgDiscount == 1 || getParameterByName("pv2")) {
        isValidStripeExpressCheckout = false;
        isValidPaypalExpressCheckout = false;
    }
    if (mode && mode == "test") {
        isValidStripeExpressCheckout = true;
        isValidPaypalExpressCheckout = true;
        countryByIp = "US";
        keyStripe = keyStripeTest;
    }
    const stripe = Stripe(keyStripe, {
        betas: ['ume_beta_1']
    });
    let shippingType = "standard";
    let selectedShipping = {};
    let shippingAddressInfo = {};
    var firstShippingInfo = null;
    let shippingInfoByPaymentRequestButton = {};
    var countries = [];
    var isValidSpecialShippingFee = false;
    var specialShippingFee = null;
    const elementsStripe = stripe.elements();
    var stripeElementStyle = {};

    if (isMobile) {
        stripeElementStyle = {
            paymentRequestButton: {
                type: 'default',
                theme: 'dark',
                height: '46px',
                borderRadius: '9px',
            },
        };
    } else {
        stripeElementStyle = {
            paymentRequestButton: {
                type: 'default',
                theme: 'dark',
                height: '54px',
                borderRadius: '9px',
            },
        };
    }
    var paymentRequest = null;
    if (isValidStripeExpressCheckout) {
        paymentRequest = stripe.paymentRequest({
            country: countryByIp,
            currency: currencyUnitAddToCart.toLowerCase(),
            total: {
                label: totalText,
                amount: formatPriceByCurrency(parseFloat(priceRaw) * quantityAddCart, "*"),
            },
            displayItems: [
                {
                    label: productTitle,
                    amount: formatPriceByCurrency(parseFloat(priceRaw) * quantityAddCart, "*"),
                },
                {
                    label: transactionFeeText,
                    amount: formatPriceByCurrency(parseFloat(priceRaw) * quantityAddCart, "*"),
                }
            ],
            requestPayerName: true,
            requestPayerEmail: true,
            requestPayerPhone: true,
            requestShipping: true,
        });
    }

    function getCountry() {
        return new Promise((resolve, reject) => {
            $.ajax({
                url: "/cart/get-country"
            }).then(function(response) {
                if (response && response.status == "successful") {
                    window.dispatchEvent(new CustomEvent('doneCountry', {detail: {"country": response.result}}));
                    resolve(response.result);
                }
                reject(null);
            }).catch(function() {
                reject(null);
            });
        });
    };
    
    function getEvent() {
        return new Promise((resolve, reject) => {
            let productId = $("#productId").val();
            $.ajax({
                url: "/cart/event?product_id=" + productId
            }).then(function(response) {
                if (response && response.status == "successful") {
                    resolve(response.result);
                }
                reject(null);
            }).catch(function() {
                reject(null);
            });
        });
    };

    function getCountries() {
        $.ajax({
            url: base_api_url_add_to_cart + "/countries?page_size=-1"
        }).done(function(response) {
            for (let index = 0; index < response.result.length; index++) {
                const element = response.result[index];
                countries[element.id] = element
            }
            window.dispatchEvent(new CustomEvent('doneCountries', {detail: {"countries": countries}}));
        });
    };

    getCountries();

    function formatPriceByCurrency(amount, $type = 'round') {
        let retval = amount;
        let acceptRound = ['JPY', "KRW", "VND"];
        if (acceptRound.includes(currencyUnitAddToCart) && $type == 'round') {
            retval = Math.round(amount);
        } else if (!keepOriginal.includes(currencyUnitAddToCart) && $type == '*') {
            retval = Math.round(((retval * 100) * 100) / 100);
        } else if (keepOriginal.includes(currencyUnitAddToCart) && $type == '*') {
            retval = Math.round(retval);
        }
        return retval;
    }

    setTimeout(function() {
        $(".button-add-to-cart").removeAttr('disabled');
    }, 1000);
    if (getShipping === 1) {
        getShippingInfo(selectCountryAddToCart, true);
    }
    window.addEventListener('variantChanged', function (event) {
        loaded();
        if (getShipping === 1) {
            getShippingInfo(selectCountryAddToCart);
        }
    });
    $("#quantity").change(function () {
        if (getShipping === 1) {
            getShippingInfo(selectCountryAddToCart);
        }
    });

    window.addEventListener('changePrintLocation', function (event, data) {
        if (getShipping === 1) {
            getShippingInfo(selectCountryAddToCart);
        }
    })

    function loaded() {
        $('.is-waiting').removeClass('is-waiting');
        $('.is-initing').removeClass('is-initing');
        canAddToCart = true;
    }

    if (canAddToCart) {
        loaded();
    }


    function renderRecommendProducts(relatedProducts) {
        let locale = '';
        if (typeof localePrefix !== 'undefined' && localePrefix !== '') {
            locale = '/' + localePrefix;
        }
        let relatedProductDom = [];

        relatedProducts.forEach(element => 
        {
            let url = element.url;
            if (locale != "" && !element.url.includes(locale)) {
                url = locale + element.url;
            }

            relatedProductDom.push(`
                <div class="md-add2basket-item">
                    <a class="md-add2basket-link" href="${url}?internal_source=cart-popup-suggestion" target="_blank">
                        <img class="md-add2basket-image" src="${getImageCdn(element.image_url, 540, 540)}" alt="${element.name}" referrerpolicy="no-referrer">
                    </a>
                    <div class="md-add2basket-title-box flex-b align-c">
                        <a class="md-product-title" href="${url}?internal_source=cart-popup-suggestion" target="_blank">
                            ${element.name}
                        </a>
                    </div>
                    <span class="md-add2basket-price">
                        ${formatPrice(decorePrice(element.price), priceTemplateAddCart)}
                        ${getHighPriceHtml(element)}
                    </span>
                </div>
            `);

        });

        $(".md-add2basket-list").html(relatedProductDom.join(''));
    }

    function getHighPriceHtml(item) {
        if (item.high_price && parseFloat(item.high_price) > parseFloat(item.price)) {
            return `<small style="text-decoration: line-through; color: #a1a1a1; padding-left: 5px;">${formatPrice(decorePrice(item.high_price), priceTemplateAddCart)}</small>`;
        }
        return '';
    }

    async function getShippingInfo(country = null, isGetCost = false) {
        let productId = $("#productId").val();
        let productSkuId = $("#productSkuId").val();
        let quantityAddCart = $("#quantity").val();
        if (!quantityAddCart) {
            quantityAddCart = 1;
        }
        var price = $("#js-raw-price").val();
        let url = '/shipping/info?id=' + productId + "&productSkuId=" + productSkuId + "&quantity=" + quantityAddCart;
        if (country) {
            url += "&country=" + country;
        }
        if (isGetCost) {
            url += "&getCost=1";
        }
        if (lastSkuShipping == productSkuId && lastQuanityShipping == quantityAddCart && lastCountryShipping == country) {
            return;
        }
        lastSkuShipping = productSkuId;
        lastQuanityShipping = quantityAddCart;
        lastCountryShipping = country;
        return new Promise((resolve, reject) => {     
            $.ajax({
                url: url,
            }).done(function(response) {
                if (response && response.status == 'successful') {
                    showShipping(response)
                    if (!firstShippingInfo && isValidStripeExpressCheckout) {
                        firstShippingInfo = response.result;
                        quantityCheckout = $("#quantity").val();
                        for (const [key, value] of Object.entries(firstShippingInfo)) {
                            if (key == "standard") {
                                selectedShipping = value;
                                let data = getDataUpdateEvent();
                                paymentRequest.update(data);
                            }
                        }
                        shippingInfoByPaymentRequestButton = response.result;
                    }
                    shippingInfoByPaymentRequestButton = response.result;
                    resolve(response.result);
                }
            })
        })
    }

    async function checkTax(country) {
        validTax = false;
        if (country == "US") {
            let productId = $("#productId").val();
            let productSkuId = $("#productSkuId").val();
            let url = "/cart/tax-us?product_id=" + productId + "&country=" + 226;
            if (productSkuId) {
                url += "&product_sku_id=" + productSkuId;
            }
            await $.ajax({
                url: url,
            }).done(function(response) {
                if (response && response.status == 'successful') {
                    validTax = response.result;
                }
            });
        }
    }

    function showShipping(response) {
        $(".product-delivery").show();

        const shippingInfo = response.result;
        const countryName = response.countryName;

        $(".delivery-country-name").text(countryName);

        let htmlShippingCalculate = '';
        let htmlCostToShip = '';
        let fee = 0;
        let index = 0;
        let isSame = true;

        for (const [key, value] of Object.entries(shippingInfo)) {
            if (fee === 0 && value.shipping_fee > 0) {
                fee = value.shipping_fee;
            } else {
                if (fee !== value.shipping_fee) {
                    isSame = false;
                }
            }
            index ++;
        }

        if (index === 1) {
            isSame = false;
        }
        let dayShip = 1;
        for (const [key, value] of Object.entries(shippingInfo)) {
            let minDate = new Date();
            let maxDate = new Date();
            minDate.setDate(minDate.getDate() + parseInt(value.default_min_time));
            maxDate.setDate(maxDate.getDate() + parseInt(value.default_max_time));

            let text = shippingInfoTemplate({
                minDate,
                maxDate,
                isSame,
                key,
                value,
                default_min_time: value.default_min_time,
                default_max_time: value.default_max_time,
            });

            let textFee = shippingInfoShippingFeeTemplate({
                key,
                value
            });
            if (typeof isAbTest !== "undefined" && isAbTest == 1) {
                if (key == "expresss") {
                    htmlShippingCalculate += text
                }
            } else {
                htmlShippingCalculate += text
            }
            htmlCostToShip += textFee;
            if (key == "standard" && value.handling_min_time) {
                dayShip = value.handling_min_time;
            }
            if (value.additional_info && value.additional_info.length > 0) {
                let additionalInfo = value.additional_info[0];
                if (parseFloat(additionalInfo.fee_limit) > 0 && additionalInfo.fee_if_limit == 0) {
                    let text = freeShippingOnOrderOverText;
                    $("#product-fee-if-limit").html(`<span style="font-weight: 500;">` + text.replace('#overAmount', formatPrice(decorePrice(parseFloat(additionalInfo.fee_limit)), priceTemplateAddCart)).replace('#cateName', additionalInfo.cate_name) + "</span>")
                }
                if (parseFloat(additionalInfo.adding_fee) == 0) {
                    let text = noExtraFeeText;
                    $("#product-free-second").html(`<span style="font-weight: 500;">` + text.replace('#cateName', additionalInfo.cate_name) + `</span>`)
                }
            }
        }
        let nextEventEnd = null;
        if (nextEvent && nextEvent.id) {
            nextEventEnd = new Date(nextEvent.end_at);
            if (fastestShipping != 100) {
                let fastestArrive = getNextBusinessDay(fastestShipping);
                if (nextEventEnd && nextEventEnd > fastestArrive) {
                    let text = arrivesBeforeText;
                    htmlShippingCalculate += 
                    `<p style="margin: 14px 0; font-size: 14px; font-weight: 400;">
                        <span style="text-transform: capitalize; font-weight: 500;">
                        ${text.replace("#event", nextEvent.name)}
                        </span>
                    </p>`;
                }
            }
        }
        if (response.warehouseCost) {
            if (["FR", "DE", "ES", "IT", "PL", "UK"].includes(selectCountryAddToCart) && ["Europe", "United Kingdom", "Germany"].includes(response.warehouseCost.location)) {
                htmlShippingCalculate += 
                `<p style="margin: 14px 0; font-size: 14px; font-weight: 400;">
                    <span style="text-transform: capitalize; font-weight: 500;">
                    ${locatedInText}
                    </span>
                    ${response.warehouseCost.location}
                </p>`;
            }
            if (selectCountryAddToCart == "US" && response.warehouseCost.location == "United States") {
                htmlShippingCalculate += 
                `<p style="margin: 14px 0; font-size: 14px; font-weight: 400;">
                    <span style="text-transform: capitalize; font-weight: 500;">
                    ${locatedInText}
                    </span>
                    ${response.warehouseCost.location}
                </p>`;
            }
        }
        let textReadyToShip = oneBusinessDayText;
        if (dayShip > 1) {
            textReadyToShip = oneBusinessDaysText;
        }
        htmlShippingCalculate += 
        `<p style="margin: 14px 0; font-size: 14px; font-weight: 400;">
            <span style="text-transform: capitalize; font-weight: 500;">
            ${readyToShipInText}
            </span>
            ${textReadyToShip.replace("#day", dayShip)}
        </p>`;
        $(".shipping-info-calculate").html(htmlShippingCalculate);
        $(".shipping-info-shipping-cost").html(htmlCostToShip);
    }

    function shippingInfoTemplate(data) {
        let shippingTemplate = 'ptv';

        if (typeof window.shippingTemplate !== 'undefined') {
            shippingTemplate = window.shippingTemplate;
        }
        buildShippingTimeline(data);

        switch (shippingTemplate) {
            case 'ptv':
                return ptvShippingTemplate(data);
            case 'et':
                return etShippingTemplate(data)
        }
    }

    function buildShippingTimeline(data) {
        if ($(".shipping-custom").length) {
            $(".shipping-custom").show();
            let textTitle = titleArrivesText;
            let textStartTemplate = fromToText;
            let textFinishTemplate = fromToText;
            let today = new Date();

            let minDateStartShip = null;
            let maxDateStartShip = null;
            let minDateFinishShip = null;
            let maxDateFinishShip = null;

            if (!useBusinessDay) {
                minDateStartShip = new Date();
                maxDateStartShip = new Date();
                minDateStartShip.setDate(minDateStartShip.getDate() + parseInt(data.value.handling_min_time));
                maxDateStartShip.setDate(maxDateStartShip.getDate() + parseInt(data.value.handling_max_time));

                minDateFinishShip = new Date();
                maxDateFinishShip = new Date();
                minDateFinishShip.setDate(minDateFinishShip.getDate() + parseInt(data.value.default_min_time));
                maxDateFinishShip.setDate(maxDateFinishShip.getDate() + parseInt(data.value.default_max_time));
            } else {
                minDateStartShip = getNextBusinessDay(data.value.handling_min_time);
                maxDateStartShip = getNextBusinessDay(data.value.handling_max_time);
                minDateFinishShip = getNextBusinessDay(data.default_min_time);
                maxDateFinishShip = getNextBusinessDay(data.default_max_time);
            }
            

            let fromFinishShip = monthNames[minDateFinishShip.getMonth()].replace("#date", minDateFinishShip.getDate());
            let toFinishShip = monthNames[maxDateFinishShip.getMonth()].replace("#date", maxDateFinishShip.getDate());
            textFinishTemplate = textFinishTemplate.replace('#from', `${fromFinishShip}`);
            textFinishTemplate = textFinishTemplate.replace('#to', `${toFinishShip}`);

            let fromStartShip = monthNames[minDateStartShip.getMonth()].replace("#date", minDateStartShip.getDate());
            let toStartShip = monthNames[maxDateStartShip.getMonth()].replace("#date", maxDateStartShip.getDate());
            textStartTemplate = textStartTemplate.replace('#from', `${fromStartShip}`);
            textStartTemplate = textStartTemplate.replace('#to', `${toStartShip}`);

            let textCurrent = monthNames[today.getMonth()].replace("#date", today.getDate());
            $(".timeline-current").text(textCurrent)
            $(".timeline-ship").text(textStartTemplate)
            $(".timeline-delivered").text(textFinishTemplate)
            let title = `<span>${textTitle.replace("#date", "<strong>" + textFinishTemplate + "</strong>")}</span>`;
            $(".shipping-custom .title-shipping-custom .text").html(title)
        }
    }

    function shippingInfoShippingFeeTemplate(data) {
        return `<span style="display: block">
                    ${ formatPrice(decorePrice(data.value.shipping_fee), priceTemplateAddCart) }
                </span>`;
    }

    function ptvShippingTemplate(data)
    {
        let from = null;
        let to = null;
        let textTemplate = betweenFromToText;
        textTemplate = textTemplate.replace('#key', data.key + '</span>');
        if (!useBusinessDay) {
            from = monthNames[data.minDate.getMonth()].replace("#date", data.minDate.getDate());
            to = monthNames[data.maxDate.getMonth()].replace("#date", data.maxDate.getDate());
            textTemplate = textTemplate.replace('#from', `${from}`);
            textTemplate = textTemplate.replace('#to', `${to}`);
        } else {
            let startTime = getNextBusinessDay(data.default_min_time);
            let endTime = getNextBusinessDay(data.default_max_time);
            from = monthNames[startTime.getMonth()].replace("#date", startTime.getDate());
            to = monthNames[endTime.getMonth()].replace("#date", endTime.getDate());
            textTemplate = textTemplate.replace('#from', `${from}`);
            textTemplate = textTemplate.replace('#to', `${to}`);
            if (fastestShipping > data.default_max_time) {
                fastestShipping = data.default_max_time;
            }
        }
        if ($(".order-delivery-box").length) {
            $(".order-delivery-box").show();
            $(".order-delivery-box .order-delivery-time").text(from + " - " + to);
        }
        let text = '';
        if (!data.isSame) {
            if (data.value.shipping_fee && data.value.shipping_fee > 0 && false) {
                text = formatPrice(decorePrice(data.value.shipping_fee), priceTemplateAddCart) + " ";
            }
            if (data.value.shipping_fee === 0) {
                text = freeText;
            }
        }
        textTemplate = text + textTemplate;

        return `<p style="margin: 14px 0; font-size: 14px; font-weight: 400;">
                    <span style="text-transform: capitalize; font-weight: 500;">
                    ${textTemplate}
                </p>`;
    }

    function etShippingTemplate(data) {
        let from = null;
        let to = null;
        let textTemplate = fromToText;
        if (!useBusinessDay) {
            from = monthNames[data.minDate.getMonth()].replace("#date", data.minDate.getDate());
            to = monthNames[data.maxDate.getMonth()].replace("#date", data.maxDate.getDate());
            textTemplate = textTemplate.replace('#from', `${from}`);
            textTemplate = textTemplate.replace('#to', `${to}`);
        } else {
            let startTime = getNextBusinessDay(data.default_min_time);
            let endTime = getNextBusinessDay(data.default_max_time);
            from = monthNames[startTime.getMonth()].replace("#date", startTime.getDate());
            to = monthNames[endTime.getMonth()].replace("#date", endTime.getDate());
            textTemplate = textTemplate.replace('#from', `${from}`);
            textTemplate = textTemplate.replace('#to', `${to}`);
        }
        if ($(".order-delivery-box").length) {
            $(".order-delivery-box").show();
            $(".order-delivery-box .order-delivery-time").text(from + " - " + to);
        }
        return `<span style="display: block">
                    ${textTemplate}
                </span>`;
    }

    function getNextBusinessDay(days) {
        const currentDate = new Date();
        let businessDayCount = 0;
      
        while (businessDayCount < days) {
            currentDate.setDate(currentDate.getDate() + 1); // Move to the next day
        
            // Check if it's a weekend (Saturday or Sunday)
            if (currentDate.getDay() !== 0 && currentDate.getDay() !== 6) {
                businessDayCount++; // If it's a business day, increment the count
            }
        }
      
        return currentDate;
    }

    function generateSlider() {
        a = document.querySelector('#add2basket-close')
        b = document.querySelector('.add2basket-wrapper');

        if (window.innerWidth > 1025) {
            function add2basketSlider (selector, config) {
                var
                _mainElement = document.querySelector(selector),
                _sliderWrapper = _mainElement.querySelector('.md-add2basket-list'),
                _sliderItems = _mainElement.querySelectorAll('.md-add2basket-item'),
                _sliderControls = _mainElement.querySelectorAll('.md-add2basket-slider-control'),
                _sliderControlLeft = _mainElement.querySelector('.md-add2basket-slider-control_left'),
                _sliderControlRight = _mainElement.querySelector('.md-add2basket-slider-control_right'),
                _wrapperWidth = parseFloat(getComputedStyle(_sliderWrapper).width),
                _itemWidth = parseFloat(getComputedStyle(_sliderItems[0]).width),
                _positionLeftItem = 0,
                _transform = 0,
                _step = _itemWidth / _wrapperWidth * 100,
                _items = [];


                _sliderItems.forEach(function (item, index) {
                    _items.push({ item: item, position: index, transform: 0 });
                });

                var position = {
                    getItemMin: function () {
                        var indexItem = 0;
                        _items.forEach(function (item, index) {
                            if (item.position < _items[indexItem].position) {
                                indexItem = index;
                            }
                        });
                        return indexItem;
                    },
                    getItemMax: function () {
                        var indexItem = 0;
                        _items.forEach(function (item, index) {
                            if (item.position > _items[indexItem].position) {
                                indexItem = index;
                            }
                        });
                        return indexItem;
                    },
                    getMin: function () {
                        return _items[position.getItemMin()].position;
                    },
                    getMax: function () {
                        return _items[position.getItemMax()].position;
                    }
                }

                var _transformItem = function (direction) {
                    var nextItem;
                    if (direction === 'right') {
                        if (_positionLeftItem + 1 > _items.length) {
                            return;
                        };
                        _positionLeftItem++;
                        if ((_positionLeftItem + _wrapperWidth / _itemWidth - 1) > position.getMax()) {
                            nextItem = position.getItemMin();
                            _items[nextItem].position = position.getMax() + 1;
                            _items[nextItem].transform += _items.length * 100;
                            // _items[nextItem].item.style.transform = 'translateX(' + _items[nextItem].transform + '%)';
                        }
                        _sliderControlLeft.style.display = 'flex'
                        if (_positionLeftItem > _items.length - 4) {
                            return;
                        };
                        if (_positionLeftItem == _items.length - 4) {
                            _sliderControlRight.style.display = 'none'
                        };
                        _transform -= _step;

                    }
                    if (direction === 'left') {

                        if (_positionLeftItem - 1 < 0) {
                            return;
                        };
                        _positionLeftItem--;
                        if (_positionLeftItem < position.getMin()) {
                            nextItem = position.getItemMax();
                            _items[nextItem].position = position.getMin() - 1;
                            _items[nextItem].transform -= _items.length * 100;
                            // _items[nextItem].item.style.transform = 'translateX(' + _items[nextItem].transform + '%)';
                        }
                        _sliderControlRight.style.display = 'flex'

                        if (_positionLeftItem < 0) {
                            return;
                        };
                        if (_positionLeftItem < 1) {
                            _sliderControlLeft.style.display = 'none'
                        };

                        _transform += _step;

                    }
                    _sliderWrapper.style.transform = 'translateX(' + _transform + '%)';
                }



                var _controlClick = function (e) {
                    var direction = this.classList.contains('md-add2basket-slider-control_right') ? 'right' : 'left';
                    e.preventDefault();
                    _transformItem(direction);
                };

                var _setUpListeners = function () {
                    _sliderControls.forEach(function (item) {
                        item.addEventListener('click', _controlClick);
                    });
                }

                _setUpListeners();
                return {
                    right: function () {
                        _transformItem('right');
                    },
                    left: function () {
                        _transformItem('left');
                    }
                }
            }
            var slider = add2basketSlider('.md-add2basket-slide')
        }
    }

    if (isValidStripeExpressCheckout) {
        paymentRequest.on('shippingaddresschange', async (event) => {
            // Perform server-side request to fetch shipping options
            var shippingInfo = await getShippingInfo(event.shippingAddress.country);
            await checkTax(event.shippingAddress.country)
            selectCountryAddToCart = event.shippingAddress.country;
            if (!shippingInfo) {
                if (shippingInfoByPaymentRequestButton) {
                    shippingInfo = shippingInfoByPaymentRequestButton;
                } else {
                    shippingInfo = firstShippingInfo;
                }
            }
            shippingAddressInfo = event.shippingAddress;
            storeDataCheckout()

            shippingInfoByPaymentRequestButton = shippingInfo;
            for (const [key, value] of Object.entries(shippingInfoByPaymentRequestButton)) {
                if (key == shippingType) {
                    selectedShipping = value;
                }
            }
            let shippingOptions = getShippingOption(shippingInfo, true)

            let dataUpdateEvent = getDataUpdateEvent(shippingOptions)
            dataUpdateEvent.status = 'success';
            event.updateWith(dataUpdateEvent);
        });

        paymentRequest.on('shippingoptionchange', async (event) => {
            storeDataCheckout()
            var shippingOption = event.shippingOption;
            shippingType = shippingOption.id;
            for (const [key, value] of Object.entries(shippingInfoByPaymentRequestButton)) {
                if (key == shippingType) {
                    selectedShipping = value;
                }
            }
            let dataUpdateEvent = getDataUpdateEvent();
            dataUpdateEvent.status = 'success';
            event.updateWith(dataUpdateEvent);
        });

        const prButton = elementsStripe.create('paymentRequestButton', {
            paymentRequest,
            style: stripeElementStyle,
        });

        (async () => {
            // Check the availability of the Payment Request API first.
            paymentRequest.canMakePayment().then(function(result) {
                if (result) {
                    prButton.mount('#payment-request-button');
                } else {
                    document.getElementById('payment-request-button').style.display = 'none';
                }
            });
        })();

        prButton.on('click', async function(event) {
            if (!selectConfigurations) {
                selectProductSkuId = $("#productSkuId").val();
                productVariantOptions = $('#productVariantOptions').val();
            }
            let result = false;
            if ($('#js-sku-chosen[has-size="true"]').length) {
                if ($('#js-sku-chosen[has-size="true"][selected-size]').length) {
                    result = true;
                }
            } else {
                result = true
            }
            let status = $("#js-sku-status").val();
            if (!result) {
                window.dispatchEvent(new CustomEvent('alertSizeNotChose'))
            }
            if (status != "ACTIVE" || !result) {
                event.preventDefault();
            }

            let shippingOptions = getShippingOption(shippingInfoByPaymentRequestButton, true)

            let dataUpdateEvent = getDataUpdateEvent(shippingOptions)

            paymentRequest.update(dataUpdateEvent);
        })
    
        paymentRequest.on('paymentmethod', async function(event) {
            let dataOrder = {
                payerName: event.payerName,
                payerEmail: event.payerEmail,
                payerPhone: event.payerPhone,
                shippingAddress: event.shippingAddress,
                paymentMethod: event.paymentMethod,
            }
            let orderData = await processOrder(dataOrder, 'product_express');

            //Create payment Intent
            var paymentIntentParams = {
                url: base_api_url_add_to_cart + '/stripe/payment-intent',
                method: 'POST',
                data: {
                    orderId: orderData.order.id,
                    currency: currencyUnitAddToCart,
                    token: token,
                    email: event.payerEmail.replace(/\s/gm,'')
                },
            };
            let paymentIntent = null;
            await $.ajax(paymentIntentParams).done(function(result) {
                paymentIntent = result;
            });

            //Confirm
            stripe.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.
                    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.
                        } else {
                            // The payment has succeeded.
                            window.location.replace(orderData.redirect);
                        }
                        });
                    } else {
                        // The payment has succeeded.
                        window.location.replace(orderData.redirect);
                    }
                }
            });
        });
    }

    if (isValidPaypalExpressCheckout) {
        function showPaypal() {
            paypal.Buttons({
                style: {
                    shape: 'rect',
                    height: isMobile ? 46 : 54,
                    layout: "horizontal",
                    tagline: false,
                    branding: false
                },
                onClick: function(data, actions) {
                    if (!selectConfigurations) {
                        selectProductSkuId = $("#productSkuId").val();
                        productVariantOptions = $('#productVariantOptions').val();
                    }
                    let result = false;
                    if ($('#js-sku-chosen[has-size="true"]').length) {
                        if ($('#js-sku-chosen[has-size="true"][selected-size]').length) {
                            result = true;
                        }
                    } else {
                        result = true
                    }
                    let status = $("#js-sku-status").val();
                    if (!result) {
                        window.dispatchEvent(new CustomEvent('alertSizeNotChose'))
                    }
                    if (status != "ACTIVE" || !result) {
                        event.preventDefault();
                        return actions.reject();
                    }
                },
                createOrder: async function(data, actions) {
                    storeDataCheckout()
                    shippingType = "standard";
                    let shippingOptions = getShippingOption(shippingInfoByPaymentRequestButton, true, 'paypal');
                    let amount = getAmount('paypal', shippingOptions);
                    let orderId = null;
                    let shippingFee = null;
                    if (isValidSpecialShippingFee && selectedShipping.type == 'standard') {
                        shippingFee = parseFloat(amount.shippingFee);
                    }
                    await $.ajax({
                        method: 'POST',
                        url: base_api_url_add_to_cart + '/paypal/express/create',
                        data: JSON.stringify({ 
                            amount: amount.totalWithoutShipping,
                            special_shipping_fee: shippingFee != null || shippingFee == 0 ? shippingFee : null,
                            shippingOptions,
                            service_token: "megaads@123",
                            mode: getParameterByName("mode")
                        }),
                        headers: {
                            'Content-Type': 'application/json',
                        }
                    }).done(function(response) {
                        orderId = response.order_id;
                        paypalAccount = response.account;
                    });
                    return orderId;
                },

                onShippingChange: async function(data, actions) {
                    storeDataCheckout()
                    let shippingOptions = [];
                    let isGetShippingInfo = false;
                    let countryId = null;
                    if (data.shipping_address && data.shipping_address.country_code != selectCountryAddToCart) {
                        selectCountryAddToCart = data.shipping_address.country_code;
                        for (const key in countries) {
                            if (Object.hasOwnProperty.call(countries, key)) {
                                const element = countries[key];
                                if (element.iso == data.shipping_address.country_code) {
                                    countryId = element.id;
                                    break;
                                }
                            }
                        }
                        isGetShippingInfo = true;
                        await getShippingInfo(countryId);
                        await checkTax(countryId == 226 ? "US" : "");
                        shippingOptions = getShippingOption(shippingInfoByPaymentRequestButton, true, 'paypal');
                    }
                    if (data.selected_shipping_option && data.selected_shipping_option.id && shippingType != data.selected_shipping_option.id) {
                        shippingType = data.selected_shipping_option.id;
                        selectedShipping = {
                            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,
                        };
                        isGetShippingInfo = true;
                        shippingOptions = getShippingOption(shippingInfoByPaymentRequestButton, false, 'paypal');
                    }
                    if (isGetShippingInfo) {
                        let amount = getAmount('paypal', shippingOptions);
                        let shippingFee = null;
                        if (isValidSpecialShippingFee && selectedShipping.type == 'standard') {
                            shippingFee = parseFloat(amount.shippingFee);
                        }
                        try {
                            const response = await $.ajax({
                                method: 'POST',
                                url: base_api_url_add_to_cart + '/paypal/express/update-shipping',
                                data: JSON.stringify({
                                    selected_shipping_option: selectedShipping,
                                    amount: amount.totalWithoutShipping,
                                    order_id: data.orderID, 
                                    shippingOptions, 
                                    account: paypalAccount,
                                    service_token: "megaads@123",
                                    mode: getParameterByName("mode"),
                                    country: countryId,
                                    special_shipping_fee: shippingFee != null || shippingFee == 0 ? shippingFee : null,
                                }),
                                headers: {
                                    'Content-Type': 'application/json',
                                }
                            });
                            if (response && 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,
                        }
                        let order = await processOrder(data, "paypal_express");
                        await updateInvoice(order.order.code, orderData.id);
                        let url = base_api_url_add_to_cart + '/paypal/v2/confirm?customerToken=' + customerTokenCart + '&order_code=' + order.order.code + '&token=' + orderData.id + '&ignore_localization=1&type_return=json';
                        if (getParameterByName("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-cart');
        }
        showPaypal();

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

    async function processOrder(data, paymentType = 'paypal_express') {
        //Create order
        let tokenUserQuery = localStorage.getItem("token_user_query");
        let token = makeid(50);
        customerTokenCart = token;
        var quantity = quantityCheckout;
        const currentUrl = window.location.href;
        let cartData = {
            productId: $("#productId").val(),
            productSkuId: selectProductSkuId,
            productVariantOptions: productVariantOptions,
            quantity: quantity,
            token: token,
            use_customer_id: 0,
            note: currentUrl
        }

        if (selectImage) {
            cartData['imageUrl'] = selectImage;
        }
        if (selectConfigurations) {
            cartData['configurations'] = selectConfigurations;
        }
        var addCartReqParams = {
            url: '/cart/add-to-cart',
            method: 'POST',
            data: cartData,
        };
        let shippingConfig = {};
        await $.ajax(addCartReqParams).done(function(result) {
            for (let index = 0; index < result.cartItems.length; index++) {
                const element = result.cartItems[index];
                if (paymentType == 'paypal_express') {
                    for (const [key, value] of Object.entries(shippingInfoByPaymentRequestButton)) {
                        if (key == shippingType) {
                            shippingConfig[element.id] = value.id;
                        }
                    }
                } else {
                    shippingConfig[element.id] = selectedShipping.id
                }
            }
        });

        //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 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 countries) {
            if (Object.hasOwnProperty.call(countries, key)) {
                const element = countries[key];
                
                if (element.iso == shippingAddress.country) {
                    countryId = element.id;
                }
                if (billingAddress && 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: shippingType,
            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
        };

        if (isValidSpecialShippingFee && shippingType == 'standard' && (specialShippingFee || specialShippingFee == 0)) {
            dataOrder.special_shipping_fee = parseFloat(specialShippingFee);
        }

        if (tokenUserQuery) {
            dataOrder.token_user_query = tokenUserQuery;
        }
        if (validTax) {
            dataOrder.other_tax_fee = calculateTrumpTax();
        }
        dataOrder.cjeventCookie = cjeventCookie;
        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_add_to_cart + "/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 makeid(length) {
        let result = '';
        const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        const charactersLength = characters.length;
        let counter = 0;
        while (counter < length) {
            result += characters.charAt(Math.floor(Math.random() * charactersLength));
            counter += 1;
        }
        return result;
    }

    function getShippingOption(shippingInfo, isUpdate = false, type = 'stripe') {
        var shippingOptions = [];
        var quantity = $("#quantity").val();
        var price = $("#js-raw-price").val();
        for (const [key, value] of Object.entries(shippingInfo)) {
            let minDate = new Date();
            let maxDate = new Date();
            minDate.setDate(minDate.getDate() + parseInt(value.default_min_time));
            maxDate.setDate(maxDate.getDate() + parseInt(value.default_max_time));
            let textTemplate = betweenFromToText;
            textTemplate = textTemplate.replace('#key', value.name_shipping);
            textTemplate = textTemplate.replace('#from', `${monthNames[minDate.getMonth()].replace("#date", minDate.getDate())}`);
            textTemplate = textTemplate.replace('#to', `${monthNames[maxDate.getMonth()].replace("#date", maxDate.getDate())}`);
            if (type == 'stripe') {
                shippingOptions.unshift({
                    id: key,
                    label: value.name_shipping,
                    detail: textTemplate,
                    amount: formatPriceByCurrency(value.shipping_fee, '*'),
                });
            } else {
                shippingOptions.unshift({
                    id: key,
                    label: value.name_shipping,
                    detail: textTemplate,
                    amount: parseFloat(value.shipping_fee),
                    selected: key == shippingType,
                });
            }
            if (isUpdate && key == 'standard') {
                if (type == 'stripe') {
                    selectedShipping = value;
                } else {
                    selectedShipping = {
                        id: key,
                        label: value.name_shipping,
                        detail: textTemplate,
                        amount: parseFloat(value.shipping_fee),
                        selected: key == shippingType,
                    };
                }
            }
        }
        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: productTitle,
                    amount: formatPriceByCurrency(amount.productPrice, "*"),
                },
                {
                    label: shippingFeeText,
                    amount: formatPriceByCurrency(amount.shippingFee, "*"),
                },
                {
                    label: `${transactionFeeText}`,
                    amount: formatPriceByCurrency(amount.transactionFee, "*"),
                },
            ],
        };
        if (shippingOptions) {
            data.shippingOptions = shippingOptions;
        }
        if (validTax) {
            data.displayItems.push({
                label: otherFeeText,
                amount: formatPriceByCurrency(amount.otherFee, "*"),
            });
        }
        return data;
    }

    function getAmount(type = 'stripe', shippingOptions = null) {
        let fee = type == 'stripe' ? stripeFee : paypalFee;
        let result = {
            total: 0,
            transactionFee: 0,
            otherFee: 0,
            productPrice: 0,
            shippingFee: 0,
        };
        var quantity = $("#quantity").val();
        var price = $("#js-raw-price").val();
        let shippingFee = selectedShipping.shipping_fee ? selectedShipping.shipping_fee : selectedShipping.amount;
        result.totalWithoutShipping = parseFloat(price) * parseFloat(quantity);
        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(price) * parseFloat(quantity);
        result.shippingFee = parseFloat(shippingFee);
        if (typeof useSpecialShippingFee !== "undefined" && useSpecialShippingFee && (selectCountryAddToCart == 'US' || selectCountryAddToCart == '226')) {
            if (shouldUseNewInterface == 'a') {
                if (result.productPrice >= 50) {
                    specialShippingFee = shippingFeeByLevel[0];
                }
                if (result.productPrice >= 100) {
                    specialShippingFee = shippingFeeByLevel[1];
                }
            }
            if (shouldUseNewInterface == 'b') {
                specialShippingFee = shippingFeeByLevel[0];
                if (result.productPrice >= 80) {
                    specialShippingFee = shippingFeeByLevel[1];
                }
            }
            let fee = type == 'stripe' ? stripeFee : paypalFee;
            if (specialShippingFee || specialShippingFee == 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(specialShippingFee, "*");
                            } else {
                                element.amount = parseFloat(specialShippingFee);
                            }
                            let shippingType = selectedShipping.type ? selectedShipping.type : selectedShipping.id;
                            if (shippingType == element.id) {
                                isValidSpecialShippingFee = true;
                                result.shippingFee = parseFloat(specialShippingFee);
                                result.transactionFee = decimalAdjust('ceil', fee * (result.productPrice + result.shippingFee) / 100);
                                result.totalWithoutShipping = result.productPrice + result.transactionFee + (result.otherFee ? result.otherFee : 0);
                            }
                        }
                    }
                } else {
                    let shippingType = selectedShipping.type ? selectedShipping.type : selectedShipping.id;
                    if (shippingType == 'standard') {
                        isValidSpecialShippingFee = true;
                        result.shippingFee = parseFloat(specialShippingFee);
                        result.transactionFee = decimalAdjust('ceil', fee * (result.productPrice + result.shippingFee) / 100);
                        result.totalWithoutShipping = result.productPrice + result.transactionFee + (result.otherFee ? result.otherFee : 0);
                    }
                }
            }
        }
        if (validTax) {
            result.otherFee = calculateTrumpTax();
            result.total += parseFloat(result.otherFee);
            result.totalWithoutShipping += parseFloat(result.otherFee);
        }
        return result;
    }

    function calculateTrumpTax() {
        var quantity = $("#quantity").val();
        var price = $("#js-raw-price").val();
        var total = parseFloat(price) * parseFloat(quantity);
        let tax = 0;
        let shippingFee = selectedShipping.shipping_fee ? selectedShipping.shipping_fee : selectedShipping.amount;
        if (isValidSpecialShippingFee && shippingType == 'standard' && (specialShippingFee || specialShippingFee == 0)) {
            shippingFee = parseFloat(specialShippingFee);
        }
        tax = decimalAdjust('ceil', (total + parseFloat(shippingFee)) * 0.2);
        return tax;
    }

    function storeDataCheckout() {
        quantityCheckout = $("#quantity").val();
        selectPrice = $("#js-raw-price").val();
        selectProductSkuId = $("#productSkuId").val();
        productVariantOptions = $('#productVariantOptions').val();
        let imageUrl = $("#imageUrl");
        let configurations = $("#configurations");
        if (imageUrl && imageUrl.length && $(imageUrl).val()) {
            selectImage = $(imageUrl).val();
        }
        if (configurations && configurations.length && $(configurations).val()) {
            selectConfigurations = $(configurations).val();
        }
    }

    window.addEventListener('variantChanged', function (event, data) {
        let detail = angular.copy(event.detail);
        $("#js-sku-status").val(detail.status)
    })


    $(document).ready(function() { 
        var customilyBtm = $('.customily-action-btn');
        var pid = $("#productId").val();
        if (pid) {
            $.ajax(`/get-product-personalize-url?id=${pid}`)
                .done(function(data) {
                    if (data && data.status === 'successful' && data.url != "") {
                        cartCustomilyIframe = $('#iframeHTML');
                        cartCustomizeIframeURL = data.url;
                        $(cartCustomilyIframe).attr('src', cartCustomizeIframeURL);
                        $(customilyBtm).css('display', 'block');
                        $("#product-page .product-addtocart").hide();
                    }
                });
        }
    });
    window.addEventListener("message", async function (event) {
        if (event.data.action === 'add-to-cart') {
            console.log(event)
            cartIframePopup = $('#customily-popup');
            $(cartCustomilyIframe).attr('src', cartCustomizeIframeURL);
            $(cartIframePopup).css('display', 'none');

            if (event.data.personalizationGUID) {
                let config = $("#configurations").val();
                if (config != '') {
                    config = JSON.parse(config);
                } else {
                    config = {};
                }
                config["Data customily"] = {};
                if (event.data.previewUrl) {
                    config["Data customily"]["previewUrl"] = event.data.previewUrl;
                    config["Preview url"] = {
                        "image_url": event.data.previewUrl
                    };
                }
                if (event.data.options) {
                    config["Data customily"]["options"] = event.data.options;
                }
                if (event.data.exportedFiles) {
                    config["Data customily"]["exportedFiles"] = event.data.exportedFiles;
                }
                config.disable_make_change = true;
                if (event.data.quantity && event.data.quantity > 0) {
                    $("#quantity").val(event.data.quantity);
                }
                $("#configurations").val(JSON.stringify(config));
                $("#product-page .product-addtocart").first().click();
                $("body").removeClass("open-popup-customily");
            }
        }
    }, false);
    var cartCustomilyCloseBtn = document.getElementById('customily-close-btn');

    if (cartCustomilyCloseBtn) {
        cartCustomilyCloseBtn.addEventListener("click", function() {
            cartIframePopup = $('#customily-popup');
            $(cartCustomilyIframe).attr('src', cartCustomizeIframeURL);
            $(cartIframePopup).css('display', 'none');
            $("body").removeClass("open-popup-customily");
        });
    }
    $(".customily-action-btn").on("click", function() {
        showPopupcartCustomilyIframe();
    });

});