import {updateEeaProducts, updateEeaCheckoutProducts, syncEeaProducts} from './basket/gtm';
import {toggleWisdom, checkDeliveryStock, addDeliveryStock, createWisdom} from './basket/wisdom';
import {updateOrderSummary} from './components/order-summary';
import {checkVoucherCode, voucherRemove} from './components/voucher/voucher';

var Wick = window.Wick || {};
Wick.BasketPage = {
    el: {
        $voucherFormBtn: $('#form-checkout-voucher .voucher__btn'),
        value: '.checkout-widget__item-value',
        discountValue: '.checkout-widget__detail-value',
        $orderTotal: $('.checkout-widget__total'),
        orderTotalValue: '.checkout-widget__total-value',
        $orderItem: $('.order-item'),
        content: '.content',
        orderItem: '.order-item',
        total: '.order-item__total',
        promo: '.p-promotion',
        promoClose: '.p-promotion__close',
        quantityButton: '.order-item__quantity-btn',
        removeButton: '.order-item__action-btn-remove',
        quantityValue: '.order-item__quantity-value',
        ccSection: '.cc-order',
        ccOrderInfo: '.cc-order__info',
        ccOrderInfoHide: 'cc-order__info-hide',
        storeUnselected: '.cc-order__store-unselected',
        ccCloseLink: '.cc-order__close-link',
        ccButtonInDelivery: '.order-item__action-btn[data-type="Click & Collect"]',
        deliveryButtonInCC: '.order-item__action-btn[data-type="Delivery"]',
        deliveryStockButton: '.order-item__action-btn[data-type="Delivery Stock"]',
        totalHide: 'order-item__total-hide',
        btnPrimary: 'order-item__action-btn-primary',
        btnPrimaryDefault: 'btn-primary',
        btnSecondary: 'btn-secondary',
        basketMainSection: '.basket__section',
        actionButton: '.order-item__action-btn',
        deliveryMessage: '.order-item__delivery',
        basketDeliveySection: '.basket__section[data-type="Delivery"]',
        basketCCSection: '.basket__section[data-type="Click & Collect"]',
        updateStoreButton: 'button[id^="update_store"]',
        orderSectionCta: '.cc-order__section-cta',
        itemTotal: '.order-item__total-value .order-item__value',
        orderItemValue: '.order-item__value',
        orderItemValueSm: 'order-item__value-sm',
        orderItemValueXs: 'order-item__value-xs',
        discountItem: '.checkout-widget__details-discount',
        orderItemInfo: '.order-item__info',
        orderItemInfoTile: 'order-item__info-tile',
        orderItemOffers: '.order-item__offers',
        orderItemInfoOffers: 'order-item__info-offers',
        checkoutAction: '.checkout-action',
        checkoutActionLarge: 'checkout-action__large',
        checkoutPayPalWrapper: '.checkout-widget__basket-block',
        charityInput: '#donation',
        charityItem: '.charity-new',
        checkoutWidgetDetails: '.checkout-widget__details',
        subtotal: '.checkout-widget__item-bold',
        vat: '.checkout-widget__item-vat',
        delivery: '.checkout-widget__item-delivery',
        charity: '.checkout-widget__item-charity',
        cc: '.checkout-widget__item-cc',
        orderTotal: '.checkout-widget__total',
        orderSummary: '.checkout-widget_order-summary',
        voucherRemove: '.checkout-widget__voucher-remove',
        promoWrapper: '.checkout-header__promo',
        wisdomClose: '.order-item__wisdom-link',
        wisdomCheck: '.wisdom__btn-check',
        wisdomAdd: '.wisdom__btn-add',
        changeLink: '.wisdom__link',
        checkoutHeader: '.checkout-header',
    },
    getEqualMapForUpdateCart: function (data) {
        return [
            {
                item: Wick.BasketPage.el.subtotal,
                itemValue: Wick.BasketPage.el.value,
                dataValue: data.subtotalWithoutCharity.formattedValue,
                value: data.subTotal.value,
                title: 'Items Subtotal:'
            },
            {
                item: Wick.BasketPage.el.vat,
                itemValue: Wick.BasketPage.el.value,
                dataValue: data.totalTax.formattedValue,
                value: data.totalTax.value,
                title: 'Includes VAT:'
            },
            {
                item: Wick.BasketPage.el.cc,
                itemValue: Wick.BasketPage.el.value,
                dataValue: 'FREE',
                title: 'Click & Collect:'
            },
            {
                item: Wick.BasketPage.el.delivery,
                itemValue: Wick.BasketPage.el.value,
                dataValue: data.deliveryCost.formattedValue,
                value: data.deliveryCost.value,
                title: 'Delivery:'
            },
            {
                item: Wick.BasketPage.el.charity,
                itemValue: Wick.BasketPage.el.value,
                dataValue: data.charityPrice.formattedValue,
                value: data.charityPrice.value,
                title: 'Young Minds donation:'
            },
            {
                item: Wick.BasketPage.el.discountItem,
                itemValue: Wick.BasketPage.el.discountValue,
                dataValue: data.totalDiscounts.formattedValue,
                value: data.totalDiscounts.value,
            },
            {
                item: Wick.BasketPage.el.orderTotal,
                itemValue: Wick.BasketPage.el.orderTotalValue,
                dataValue: data.totalPrice.formattedValue,
                value: data.totalPrice.value,
            },
        ];
    },
    updateItemQuantity: function () {
        let context,
            charity;

        if ($(this).closest(Wick.BasketPage.el.orderItem).length) {
            context = $(this).closest(Wick.BasketPage.el.orderItem);
        } else if ($(this).closest(Wick.BasketPage.el.charityItem).length) {
            charity = true;
            context = $(this).closest(Wick.BasketPage.el.charityItem);
        }

        let quantityInput = context.find(Wick.BasketPage.el.quantityValue),
            value = quantityInput.val(),
            maxValue = quantityInput.attr('max') ? +quantityInput.attr('max') : 99999,
            minValue = +quantityInput.attr('min'),
            action = $(this).attr('data-action'),
            entryNumber = charity
                ? context.find('input[name="entryNumber"]').val()
                : +context.attr('data-id');

        //for local update quantity value before API Call
        switch (action) {
            case 'plus':
                value = Number.parseInt(value, 10) + 1;
                if (maxValue >= value) {
                    Wick.BasketPage.updateQuantity(quantityInput, value);
                    Wick.BasketPage.debounceQuantityChange(entryNumber, value, quantityInput, context);
                }
                break;
            case 'minus':
                value = Number.parseInt(value, 10) - 1;
                if (minValue < value) {
                    Wick.BasketPage.updateQuantity(quantityInput, value);
                    Wick.BasketPage.debounceQuantityChange(entryNumber, value, quantityInput, context);
                }
                break;
            case 'remove':
                value = 0;
                charity || Wick.BasketPage.updateQuantity(quantityInput, value);
                Wick.BasketPage.debounceQuantityChange(entryNumber, value, quantityInput, context);
                break;
            default:
                value === ' '
                    ? Wick.BasketPage.updateQuantity(quantityInput, value)
                    : (value = +value , Wick.BasketPage.updateQuantity(quantityInput, value));
                Wick.BasketPage.debounceQuantityChange(entryNumber, value, quantityInput, context);
                break;
        }

        Wick.BasketPage.toggleItemTotal(context, +quantityInput.val())
    },
    debounceQuantityChange: _.debounce(function (entryNumber, value, quantityInput, context) {
        Wick.BasketPage.updateQuantityAction(entryNumber, value, quantityInput, context)
    }, 200),
    updateQuantityAction: function (entryNumber, quantityToUpdate, quantityInput, context) {
        console.log('case(api) to update quantity', entryNumber, quantityToUpdate);
        //checkEnv
        if (!Wick.chechLocalEnv) {
            // api
            const callOption = {
                link: `${window.location.origin}/cart/entry/${entryNumber}?quantity=${quantityToUpdate}`,
                type: 'PUT',
                local: false,
            }
            Wick.BasketPage.updateAction(
                callOption,
                quantityToUpdate,
                quantityInput,
                context,
                (data) => {
                    syncEeaProducts();
                    if (data.statusMessage !== 'accErrorMsgs') {
                        const basketSection = Wick.BasketPage.el.basketMainSection;
                        $(document).trigger("EEUpdateCart", {
                            cartEntryNumber: entryNumber,
                            initialCartQuantity: data.quantity - data.quantityAdded,
                            newCartQuantity: data.quantity,
                            fulfillment: context.closest(basketSection).attr('data-type'),
                        });
                    }
                },
            );
        } else {
            Wick.BasketPage.updateQuantityOperation(
                quantityToUpdate,
                quantityInput,
                context,
                Wick.BasketData.updateQuantity
            );
        }
    },
    updateQuantityOperation: function (quantityToUpdate, quantityInput, context, data) {
        let maxValue = +quantityInput.attr('max'),
            minValue = +quantityInput.attr('min'),
            charity = context.hasClass('charity-new') ? true : false,
            errorStatus = data.statusMessage === 'accErrorMsgs'

        console.log('errorStatus', errorStatus);

        minValue === 0 ? minValue = 1 : minValue = minValue;

        if (errorStatus) {
            Wick.BasketPage.updateCart(true)
            Wick.BasketPage.updateQuantity(quantityInput, data.quantity);
            Wick.BasketPage.showNotification(data);
        } else {
            if (charity) {
                Wick.BasketPage.updateCart();
                Wick.BasketPage.toggleCharityElements();
            } else {
                if (maxValue > 1 || minValue > 1) {
                    if (quantityToUpdate > maxValue || quantityToUpdate < minValue) {
                        Wick.BasketPage.showNotification(data);
                    }
                } else if (quantityToUpdate === 0) {
                    Wick.BasketPage.showNotification(data);
                }

                if (quantityToUpdate === 0) {
                    Wick.BasketPage.updateCart(data.message || true)
                } else {
                    Wick.BasketPage.updateItemTotal(data, context)
                    Wick.BasketPage.updateCart(null, context)
                }
            }
        }
    },
    loadIndexing: function () {
        Wick.BasketPage.el.$orderItem.each(function (index) {
            $(this).attr('data-id', index);
        })
    },
    updateQuantity: function (quantityInput, accum) {
        quantityInput.val(accum);
        quantityInput.attr('value', accum);
    },
    updateItemTotal: function (data, context) {
        let totalValue = context.find(Wick.BasketPage.el.itemTotal);
        let totalPrice = data.entry.itemTotalWithoutDiscount.formattedValue;
        totalValue.text(totalPrice);
        Wick.BasketPage.changeFontSizeForOrderValue(context);
    },
    toggleItemTotal: function (context, quantity) {
        quantity <= 1
            ? $(context).find(Wick.BasketPage.el.total).addClass(Wick.BasketPage.el.totalHide)
            : $(context).find(Wick.BasketPage.el.total).removeClass(Wick.BasketPage.el.totalHide);
    },
    updateAction: function (options, quantityToUpdate, quantityInput, context, successCallback) {
        $.ajax({
            url: options.link,
            method: options.type,
            success: function (data) {
                Wick.BasketPage.updateQuantityOperation(
                    quantityToUpdate,
                    quantityInput,
                    context,
                    data
                );
                successCallback(data);
            },
        });
    },
    updateCart: function (repaintData, context, charity) {
        console.log('case(api) to update cart');
        if (!Wick.chechLocalEnv) {
            //api
            const callOption = {
                link: `${window.location.origin}/cart/current`,
                type: 'GET',
                local: false,
            }
            Wick.BasketPage.updateCartAction(callOption, repaintData, context, charity);
        } else {
            updateOrderSummary(
                Wick.BasketData.updateCart,
                Wick.BasketPage.getEqualMapForUpdateCart(Wick.BasketData.updateCart)
            );

            !repaintData || Wick.BasketPage.repaintOrderItems(Wick.BasketData.updateCart, repaintData);
            !charity || Wick.BasketPage.addCharityEntryNumber(Wick.BasketData.updateCart);

            //update promotion when update quantity
            if (context && context.length) {
                Wick.BasketPage.updatePromotion(Wick.BasketData.updateCart, context);
            }

            Wick.BasketPage.addPotentialPromo(Wick.BasketData.updateCart);
        }
    },
    updateCartAction: function (options, repaintData, context, charity) {
        $.ajax({
            url: options.link,
            method: options.type,
            success: function (data) {
                updateOrderSummary(data, Wick.BasketPage.getEqualMapForUpdateCart(data));

                if (repaintData) {
                    if (typeof repaintData === 'object' &&
                        !Array.isArray(repaintData) &&
                        repaintData !== null) {
                        repaintData.basket.products = data.entries;
                        $(document).trigger("EEUpdateDeliveryMode", repaintData);
                    }

                    Wick.BasketPage.repaintOrderItems(data, repaintData);
                }

                !charity || Wick.BasketPage.addCharityEntryNumber(data);

                //update promotion when update quantity
                if (context && context.length) {
                    Wick.BasketPage.updatePromotion(data, context);
                }

                Wick.BasketPage.addPotentialPromo(data);
                updateEeaProducts(data.deliveryOrderGroups, data.pickupOrderGroups);
                updateEeaCheckoutProducts(data.deliveryOrderGroups, data.pickupOrderGroups);
                $(document).trigger("cartUpdate");
            },
        });
    },
    addCharityEntryNumber: function (data) {
        let entryNumber;
        data.deliveryOrderGroups.forEach(order => {
            order.entries.forEach(item => {
                item.charity ? entryNumber = item.entryNumber : null
            })
        })
        if ($(Wick.BasketPage.el.charityItem).find('input[name="entryNumber"]').length) {
            $(Wick.BasketPage.el.charityItem).find('input[name="entryNumber"]').val(entryNumber)
        } else {
            $(Wick.BasketPage.el.charityItem).prepend(
                `<input type="hidden" name="entryNumber" value="${entryNumber}">`
            )
        }
    },
    updatePromotion: function (data, context) {
        $(Wick.BasketPage.el.orderItem).each(function () {
            let itemNumber = {entryNumber: +$(this).attr('data-id')}

            $(this).find(Wick.BasketPage.el.orderItemInfo).removeClass(Wick.BasketPage.el.orderItemInfoOffers);
            $(this).find(Wick.BasketPage.el.orderItemInfo).addClass(Wick.BasketPage.addPromotions(itemNumber, data, true));
            $(this).find(Wick.BasketPage.el.orderItemOffers).remove()

            if ($(this).find(Wick.BasketPage.el.orderItemInfo).hasClass(Wick.BasketPage.el.orderItemInfoOffers)) {
                $(this).find(Wick.BasketPage.el.orderItemInfo).prepend(Wick.BasketPage.addPromotions(itemNumber, data));
            }
        })
    },
    showNotification: function (data) {
        let notificationType;
        switch (data.statusMessage) {
            case 'accConfirmedMsgs':
                notificationType = 'success'
                break;
            case 'accWarnMsgs':
                notificationType = 'warning'
                break;
            case 'accErrorMsgs':
                notificationType = 'error'
                break;
        }

        Wick.Notification.show({
            text: data.message,
            container: '.notification-area',
            type: notificationType,
            closeBtn: true
        });

    },
    hideUnusedDeliveryTypeCost: function (data, isVoucher) {
        $(Wick.BasketPage.el.delivery).show()
        $(Wick.BasketPage.el.cc).show()
        if (isVoucher) {
            if (!data.deliveryOrder) {
                $(Wick.BasketPage.el.delivery).hide()
            } else if (!data.clickAndCollectOrder) {
                $(Wick.BasketPage.el.cc).hide()
            }
        } else {
            if (data.clickAndCollectOnly) {
                $(Wick.BasketPage.el.delivery).hide()
            } else if (data.deliveryItemsQuantity > 0 && data.pickupItemsQuantity === 0) {
                $(Wick.BasketPage.el.cc).hide()
            }
        }
    },
    paintActionButton: function () {
        $(Wick.BasketPage.el.basketMainSection).each(function () {
            if ($(this).attr('data-type') === "Delivery") {
                $(this).find(Wick.BasketPage.el.actionButton).each(function () {
                    $(this).removeClass(Wick.BasketPage.el.btnPrimaryDefault);
                    $(this).attr('data-type') === "Delivery" || $(this).attr('data-type') === "Delivery Stock"
                        ? $(this).addClass(Wick.BasketPage.el.btnPrimary)
                        : $(this).addClass(Wick.BasketPage.el.btnSecondary);
                })
            } else if ($(this).attr('data-type') === "Click & Collect") {
                $(this).find(Wick.BasketPage.el.actionButton).each(function () {
                    $(this).removeClass(Wick.BasketPage.el.btnPrimaryDefault);
                    $(this).attr('data-type') === "Delivery" || $(this).attr('data-type') === "Delivery Stock"
                        ? $(this).addClass(Wick.BasketPage.el.btnSecondary)
                        : $(this).addClass(Wick.BasketPage.el.btnPrimary);
                })
            }
        })
    },
    hideCCSectionInDelivery: function (context) {
        let delivery = context.find(Wick.BasketPage.el.deliveryMessage),
            cc = context.find(Wick.BasketPage.el.ccSection);

        delivery.show();
        cc.hide();
    },
    showCCSectionInDelivery: function () {
        if ($(this).closest(Wick.BasketPage.el.basketDeliveySection).length) {
            let context = $(this).closest(Wick.BasketPage.el.orderItem),
                delivery = context.find(Wick.BasketPage.el.deliveryMessage),
                cc = context.find(Wick.BasketPage.el.ccSection),
                ccOrderInfo = context.find(Wick.BasketPage.el.ccOrderInfo);

            delivery.hide();
            cc.show();
            ccOrderInfo.removeClass(Wick.BasketPage.el.ccOrderInfoHide);

            context.find(Wick.BasketPage.el.storeUnselected).unbind();
            context.find(Wick.BasketPage.el.ccCloseLink).unbind();

            context.find(Wick.BasketPage.el.storeUnselected).on('click', (e) => e.preventDefault());
            context.find(Wick.BasketPage.el.ccCloseLink).on('click', function (e) {
                e.preventDefault();
                Wick.BasketPage.hideCCSectionInDelivery(context);
            })
        }
    },
    changeMethodToDelivery: function () {
        if ($(this).closest(Wick.BasketPage.el.basketCCSection).length) {
            let context = $(this).closest(Wick.BasketPage.el.orderItem),
                entryNumber = +context.attr('data-id');
            console.log('case(api) change to delivery method, entry -', entryNumber);

            const payload = {
                cartEntryNumber: entryNumber,
                basket: {},
                fulfilmentData: {
                    fulfillmentType: 'Delivery'
                }
            }

            //checkEnv
            if (!Wick.chechLocalEnv) {
                // api
                const callOption = {
                    link: `${window.location.origin}/cart/entry/${entryNumber}/delivery`,
                    type: 'PUT',
                    local: false,
                }
                Wick.BasketPage.updateDeliveryMethod(callOption, payload)
            } else {
                Wick.BasketPage.showNotification(Wick.BasketData.changeMethod)
                Wick.BasketPage.updateCart(payload);
            }
        }
    },
    changeMethodToCC: function () {
        let context = $(this).closest(Wick.BasketPage.el.orderItem),
            storeId = $(this).closest(Wick.BasketPage.el.orderSectionCta).find('.storeNamePost').val(),
            entryNumber = +context.attr('data-id'),
            quantity = context.find(Wick.BasketPage.el.quantityValue).val();

        console.log('case(api) change to C&C method, entry -', entryNumber, 'storeId', storeId, 'qty-', quantity);

        const payload = {
            cartEntryNumber: entryNumber,
            basket: {},
            fulfilmentData: {
                fulfillmentType: 'C&C',
                storeId: storeId,
            }
        }

        //checkEnv
        if (!Wick.chechLocalEnv) {
            // api
            const callOption = {
                link: `${window.location.origin}/cart/entry/${entryNumber}/collection?storeId=${storeId}&quantity=${quantity}`,
                type: 'PUT',
                local: false,
            }
            Wick.BasketPage.updateDeliveryMethod(callOption, payload);
        } else {
            Wick.BasketPage.showNotification(Wick.BasketData.changeMethod)
            Wick.BasketPage.updateCart(payload);
        }
    },
    updateDeliveryMethod: function (options, payload) {
        $.ajax({
            url: options.link,
            method: options.type,
            success: function (data) {
                Wick.BasketPage.showNotification(data)
                Wick.BasketPage.updateCart(payload);
            },
        });
    },
    removeOrderItem: function (message) {
        let currentLink = window.location.href,
            msg = encodeURIComponent(message),
            link;

        if (currentLink.includes('?')) {
            link = `${currentLink}&notificationMessage=${msg}`
        } else {
            link = `${currentLink}?notificationMessage=${msg}`
        }

        window.location.replace(link);
    },
    repaintOrderItems: function (data, message) {
        let ccGroup = data.pickupOrderGroups && data.pickupOrderGroups.length ? data.pickupOrderGroups : [];
        let deliveryGroup = data.deliveryOrderGroups && data.deliveryOrderGroups.length ? data.deliveryOrderGroups : [],
            type;

        $(Wick.BasketPage.el.orderItem).remove();


        if (!ccGroup.length && !deliveryGroup.length) {
            if (message && (typeof message === 'string' || message instanceof String)) {
                Wick.BasketPage.removeOrderItem(message);
            }
        }


        if (ccGroup.length) {
            type = 'cc';
            if ($(Wick.BasketPage.el.basketCCSection).length) {
                ccGroup.forEach((obj) => {
                    obj.entries.forEach(item => {
                        $(Wick.BasketPage.el.basketCCSection).append(Wick.BasketPage.createOrderItem(item, type, data));
                    })
                })
            } else {
                $(Wick.BasketPage.el.content).prepend(Wick.BasketPage.createBasketSection(type, ccGroup, data));
            }
        } else {
            $(Wick.BasketPage.el.basketCCSection).remove();
        }

        if (deliveryGroup.length) {
            if (deliveryGroup.length === 1 && deliveryGroup[0].entries.length === 1 && deliveryGroup[0].entries[0].charity) {
                $(Wick.BasketPage.el.basketDeliveySection).remove();
            } else {
                type = 'delivery';

                if ($(Wick.BasketPage.el.basketDeliveySection).length) {
                    deliveryGroup.forEach((obj) => {
                        obj.entries.forEach(item => {
                            $(Wick.BasketPage.el.basketDeliveySection).append(Wick.BasketPage.createOrderItem(item, type, data));
                        })

                    })
                } else {
                    $(Wick.BasketPage.el.content).prepend(Wick.BasketPage.createBasketSection(type, deliveryGroup, data));
                }
            }
            Wick.BasketPage.addCharityEntryNumber(data);
        } else {
            $(Wick.BasketPage.el.basketDeliveySection).remove();
        }

        $('.order-item').each(function () {
            let quantity = +$(this).find('.order-item__quantity-value').val();
            Wick.BasketPage.toggleItemTotal(this, quantity)
        })

        Wick.BasketPage.paintActionButton();
        Wick.BasketPage.changeFontSizeForOrderValue();
        Wick.BasketPage.checkPayPalAvailability(data);
        $(document).trigger("cartRerender");
    },
    createBasketSection: function (type, group, data) {
        type === 'cc' ? type = 'Click & Collect' : type = 'Delivery';
        let orderItems = [];

        group.forEach(obj => {
            obj.entries.forEach(item => {
                orderItems.push(Wick.BasketPage.createOrderItem(item, type, data));
            })
        });

        return `
            <section class="basket__section" data-type="${type}">
                <div class="checkout-title">
                    <h3 class="checkout-title__title">
                        ${type}
                    </h3>
                </div>
                ${orderItems.join('')}
            </section>
        `
    },
    createOrderItem: function (item, type, data) {

        if (!item.charity) {
            return `
            <div class="order-item" data-id="${item.entryNumber}">
                <div class="order-item__main">
                    <div class="order-item__image">
                        <a href="${item.product.url}" class="oder-item__image-link">
                            <img 
                                src="${item.product.images ? item.product.images[1].url : '/'}" 
                                alt="${item.product.images ? item.product.images[1].altText : item.product.name}"
                            >
                        </a>
                    </div>
                    <div class="order-item__content">
                        <div class="order-item__info  ${!item.product.installationProduct || 'order-item__info-tile'} ${!item.updateable || Wick.BasketPage.addPromotions(item, data, true)}">
                                ${!item.updateable || Wick.BasketPage.addPromotions(item, data)}
                                <div class="order-item__title">
                                    <a href="${item.product.url}" class="oder-item__title-link">
                                        ${item.product.name}
                                    </a>
                              </div>
                                <div class="order-item__quantity">
                                    <button class="btn order-item__quantity-btn" data-action="plus" ${item.updateable || 'disabled'}>
                                        <span class="btn__text">
                                            <i class="fal fa-plus"></i>
                                        </span>
                                    </button>
                                    <label class="order-item__quantity-label">
                                        <input type="number" 
                                               class="order-item__quantity-value tbx" 
                                               min="${item.minOrderQuantity ? item.minOrderQuantity : '0'}" 
                                               max="${item.maxOrderQuantity ? item.maxOrderQuantity : '99999'}" 
                                               value="${item.quantity}"
                                               ${item.updateable || 'disabled'}
                                        >
                                    </label>
                                    <button class="btn order-item__quantity-btn" data-action="minus" ${item.updateable || 'disabled'}>
                                        <span class="btn__text">
                                            <i class="fal fa-minus"></i>
                                        </span>
                                    </button>
                                </div>
                                <div class="order-item__cost">
                                    <div class="order-item__price">
                                        <div class="order-item__price-title">Item</div>
                                        <div class="order-item__price-value">
                                            <span class="order-item__value">
                                                ${item.basePrice.value === 0 ? 'FREE' : item.basePrice.formattedValue}
                                            </span>
                                        </div>
                                    </div>
                                    ${Wick.BasketPage.createPerMeterPrice(item)}
                                    <div class="order-item__total order-item__total-hide">
                                        <div class="order-item__price-title">Total</div>
                                        <div class="order-item__total-value">
                                            <span class="order-item__value">
                                               ${item.itemTotalWithoutDiscount.value === 0 ? 'FREE' : item.itemTotalWithoutDiscount.formattedValue}
                                            </span>
                                        </div>
                                    </div>
                                </div>
                        </div>
                    </div>
                    <div class="order-item__action">
                        <div class="order-item__action-ctas">
                            ${Wick.BasketPage.createActionButton(item, 'cc')}
                            ${Wick.BasketPage.createActionButton(item, 'delivery')}
                        </div>
                        <div class="order-item__action-remove" ${item.updateable || 'style="display: none"'}>
                            <button class="btn order-item__action-btn-remove" data-action="remove">
                                <span class="btn__text">
                                  <i class="fas fa-trash"></i>
                                </span>
                            </button>
                        </div>
                    </div>
                </div>
                ${createWisdom(item)}
                ${Wick.BasketPage.createDeliveryMessage(item, type)}
                ${Wick.BasketPage.createCCFinder(item)}
            </div>
        `
        }
    },
    createActionButton: function (item, type) {
        let available,
            title,
            dataType;
        if (type === 'cc') {
            title = 'Click & Collect';
            dataType = 'Click & Collect';
            available = item.cartPageControls.availableForCollection;
        } else if (type === 'delivery') {
            if (item.cartPageControls.availableForDelivery) {
                title = 'For Delivery';
                dataType = 'Delivery';
                available = item.cartPageControls.availableForDelivery;
            } else if (item.cartPageControls.availableForWickesFulfilment) {
                title = 'Check Delivery Stock';
                dataType = 'Delivery Stock';
                available = item.cartPageControls.availableForWickesFulfilment;
            }
        }

        if (available) {
            return `
            <button class="btn order-item__action-btn" data-type="${dataType}" ${item.updateable || 'disabled'}>
                <span class="btn__text">
                   ${title}
                </span>
            </button>
        `
        } else {
            return ''
        }

    },
    addPromotions: function (item, data, forClass) {
        let arr = [];

        data.potentialProductPromotions.forEach((entry) => {
            entry.consumedEntries.forEach((promo) => {
                if (promo.orderEntryNumber === item.entryNumber) {
                    if (arr.length) {
                        let duplicate = arr.every((el) => {
                            return el !== `<div class="order-line__promo">${entry.description}</div>`
                        })

                        !duplicate || arr.push(`<div class="order-line__promo">${entry.description}</div>`);

                    } else {
                        arr.push(`<div class="order-line__promo">${entry.description}</div>`);
                    }
                }
            })

        });

        data.appliedProductPromotions.forEach((entry) => {
            entry.consumedEntries.forEach((promo) => {
                if (promo.orderEntryNumber === item.entryNumber) {
                    if (arr.length) {
                        let duplicate = arr.every((el) => {
                            return el !== `<div class="order-line__promo">${entry.description}</div>`
                        })

                        !duplicate || arr.push(`<div class="order-line__promo">${entry.description}</div>`);

                    } else {
                        arr.push(`<div class="order-line__promo">${entry.description}</div>`);
                    }
                }
            })
        });

        if (forClass) {
            return arr.length ? 'order-item__info-offers' : '';
        } else {
            return arr.length ? `<div class="order-item__offers">${arr.join('')}</div>` : ''
        }
    },
    createPerMeterPrice: function (item) {
        if (item.product.installationProduct) {
            return `
                <div class="order-item__price-m">
                    <div class="order-item__price-m-title">Per m<sup>2</sup></div>
                    <div class="order-item__price-m-value">
                        <span class="order-item__value">£${item.product.installationDetails.pricePerSQM}</span>
                    </div>
                </div>
            `
        } else {
            return ''
        }
    },
    createDeliveryMessage: function (item, type) {
        if (type === 'delivery') {
            let currentFulfillment = item.product.fulfillmentAttributes.type,
                coincidenceFulfillmentValue = $(Wick.BasketPage.el.content).find(`#${currentFulfillment}`).val()

            if (coincidenceFulfillmentValue) {
                return `
            <div class="order-item__delivery">
                <i class="order-item__delivery-icon fas fa-exclamation-circle"></i>
                <div class="order-item__delivery-message">
                    ${coincidenceFulfillmentValue}
                </div>
            </div>
            `
            } else {
                return ''
            }
        } else {
            return ''
        }
    },
    createCCFinder: function (item) {
        return `
            <div class="cc-order">
                <div class="cc-order__head">
                    ${Wick.BasketPage.checkStoreAvailability(item.deliveryPointOfService, item)}
                </div>
                ${Wick.BasketPage.createCCOrderInfo(item)}
            </div>
        `
    },
    createCCOrderInfo: function (item) {
        if (item.updateable) {
            return `
                <div class="cc-order__info ${item.deliveryPointOfService ? 'cc-order__info-hide' : ''} bw" data-product="${item.product.code}">
                        <div class="cc-order__close">
                            <a href="#" class="cc-order__close-link">
                                Close
                            </a>
                        </div>
                        <div class="cc-order__section cc-order__section-find">
                            <div class="cc-order__section-info">
                                <div class="stock__postcode">
                                    <label class="stock__postcode_label">
                                        <input type="text" class="stock__input tbx" name="bw-postcode" id="bw-postcode_${item.entryNumber}">
                                        <button class="btn btn-secondary stock__target" id="geoLocationIcon_${item.entryNumber}">
                                            <span class="btn__text">
                                                <i class="far fa-crosshairs"></i>
                                            </span>
                                        </button>
                                    </label>
                                    <span class="stock__postcode_invalid-msg">
                                        Check that you entered a valid postcode or place name.
                                    </span>
                                </div>
                                <div class="stock__quest">
                                    <label class="chb" for="stock-only_${item.entryNumber}">
                                        <input 
                                            type="checkbox" 
                                            value="" 
                                            id="stock-only_${item.entryNumber}" 
                                            name="stock-only_${item.entryNumber}" 
                                            checked="checked"
                                        >
                                        <ins><i class="fas fa-check"></i></ins>
                                        <span>Only show stores with stock.</span>
                                    </label>
                                    <label class="chb" for="cc-only_${item.entryNumber}">
                                        <input 
                                            type="checkbox"
                                            value=""
                                            id="cc-only_${item.entryNumber}"
                                            name="cc-only_${item.entryNumber}"
                                            name="cc-only" 
                                            checked="checked"
                                        >
                                        <ins><i class="fas fa-check"></i></ins>
                                        <span>Only show stores with Click & Collect.</span>
                                    </label>
                                </div>
                            </div>
                            <div class="cc-order__section-cta">
                                <button class="btn btn_full btn-primary" id="bw_pickupstore_search_button_${item.entryNumber}">
                                    <span class="btn__text">
                                        Find Stores
                                    </span>
                                </button>
                            </div>
                            <input type="hidden" name="findStores" value="/store-pickup/${item.product.code}/pointOfServices" class="findStores" />
                        </div>
                    </div>
                </div>
            `
        } else {
            return ''
        }
    },
    checkStoreAvailability: function (store, item) {
        if (store) {
            return `
                <div class="cc-order__store">
                    <i class="cc-order-icon fas fa-store"></i>
                    ${store.description}
                </div>
                <a href="#" class="cc-order__change" ${item.updateable || 'style="display: none"'}>
                    Change Store location
                </a>
            `
        } else {
            return `
                <div class="cc-order__store-select">
                    <div class="cc-order__store cc-order__store-unselected">
                        <i class="cc-order-icon fas fa-exclamation-circle"></i>
                        <a href="#">
                            Select store location
                        </a>
                    </div>
                </div>
            `
        }
    },
    checkPayPalAvailability: function (data) {
        let payPalEnabled = data.payPalEnabled,
            clickAndCollectOnly = data.clickAndCollectOnly,
            canDisplayPayPal = $('#canDisplayPayPalOnBasketPage').val()

        $(Wick.BasketPage.el.checkoutAction).find(Wick.BasketPage.el.checkoutPayPalWrapper).remove();

        if (payPalEnabled && clickAndCollectOnly && canDisplayPayPal) {
            $(Wick.BasketPage.el.checkoutAction).each(function () {
                if ($(this).hasClass(Wick.BasketPage.el.checkoutActionLarge)) {
                    let idForBtn = "paypal-button-container-content";
                    $(this).append(Wick.BasketPage.paintPayPal(idForBtn));
                    if (!Wick.chechLocalEnv) {
                        prepareButtons('#' + idForBtn);
                    }
                } else {
                    let idForBtn = "paypal-button-container-content-small";
                    $(this).append(Wick.BasketPage.paintPayPal(idForBtn));
                    if (!Wick.chechLocalEnv) {
                        prepareButtons('#' + idForBtn);
                    }
                }
            })
        }
    },
    paintPayPal: function (idForBtn) {
        return `
            <div class="checkout-action__section checkout-widget__basket-block">
                <div class="form-row__col-btn pay-pal_container" data-paypal>
                    <a class="pay-pal_wrap">
                        <div class="buttons-container">
                            <div class="paypal-button-container">
                                <div class="paypal-button" id=${idForBtn}></div>
                            </div>
                        </div>
                    </a>
                </div>
            </div>
        `
    },
    updateCharity: function () {
        if ($('#donation').attr('disabled') === 'disabled') {
            $('#donation').removeAttr('disabled')
        } else {
            if ($(this).attr('type') === 'checkbox') {
                $('#donation').attr('disabled', 'disabled')
            }
        }

        let context = $(this).closest(Wick.BasketPage.el.charityItem),
            productCode = context.find('input[name="productCode"]').val();
        if (context.hasClass('charity-new-added')) {
            $(this).removeAttr('checked')
        } else {
            $(this).attr('checked', 'checked');
            Wick.BasketPage.charityActionForAdd(productCode);
        }

    },
    charityActionForAdd: function (value) {
        if (!Wick.chechLocalEnv) {
            // api
            const callOption = {
                link: `${window.location.origin}/cart/add?productCodePost=${value}&qty=1`,
                type: 'POST',
            }
            Wick.BasketPage.charityActionCall(callOption)
        } else {
            Wick.BasketPage.updateCart(...Array(2), true);
            Wick.BasketPage.toggleCharityElements();
        }
    },
    charityActionCall: function (options) {
        $.ajax({
            url: options.link,
            method: options.type,
            success: function (data) {
                Wick.BasketPage.updateCart(...Array(2), true);
                Wick.BasketPage.toggleCharityElements();
            },
        });
    },
    toggleCharityElements: function () {
        if ($(Wick.BasketPage.el.charityItem).hasClass('charity-new-added')) {
            $(Wick.BasketPage.el.charityItem).removeClass('charity-new-added');
            $(Wick.BasketPage.el.charityInput).prop('checked', false);
        } else {
            $(Wick.BasketPage.el.charityItem).addClass('charity-new-added');
        }
    },
    removePromotion: function () {
        $(this).closest(Wick.BasketPage.el.promo).remove()
    },
    addPotentialPromo: function (data) {
        $(Wick.BasketPage.el.promo).remove();

        if ((data.potentialOrderPromotions && data.potentialOrderPromotions.length)
            || (data.appliedOrderPromotions && data.appliedOrderPromotions.length)) {
            $(Wick.BasketPage.el.promoWrapper).append(Wick.BasketPage.createPotentialPromo(data));
        }
    },
    createPotentialPromo: function (data) {
        const arr = [];
        if (data.potentialOrderPromotions && data.potentialOrderPromotions.length) {
            data.potentialOrderPromotions.forEach((promo) => {
                !promo.description || arr.push(`
                    <div class="p-promotion">
                        <div class="p-promotion__icon">
                            <i class="icon fas fa-gift"></i>
                        </div>
                        <div class="p-promotion__description">
                            ${promo.description}
                        </div>
                        <div class="p-promotion__close">
                            <i class="icon fas fa-times"></i>
                        </div>
                    </div>
                `
                )
            })
        }

        if (data.appliedOrderPromotions && data.appliedOrderPromotions.length) {
            data.appliedOrderPromotions.forEach((promo) => {
                !promo.description || arr.push(`
                    <div class="p-promotion">
                        <div class="p-promotion__icon">
                            <i class="icon fas fa-gift"></i>
                        </div>
                        <div class="p-promotion__description">
                            ${promo.description}
                        </div>
                        <div class="p-promotion__close">
                            <i class="icon fas fa-times"></i>
                        </div>
                    </div>
                `
                )
            })
        }
        if ($(Wick.BasketPage.el.promoWrapper).length) {
            return arr.join('');
        } else {
            $(Wick.BasketPage.el.checkoutHeader).before(`<div class="checkout-header__promo">${arr.join('')}</div>`)
        }
    },
    changeFontSizeForOrderValue: function (context) {
        if (!context) {
            let self;
            $(Wick.BasketPage.el.orderItem).each(function () {
                self = this;
                Wick.BasketPage.calculateFontSizeForOrderValue(self);
            })
        } else {
            Wick.BasketPage.calculateFontSizeForOrderValue(context);
        }
    },
    calculateFontSizeForOrderValue: function (context) {
        if (!$(context).find(Wick.BasketPage.el.orderItemInfo).hasClass(Wick.BasketPage.el.orderItemInfoTile)) {
            let length = 0;
            $(context).find(Wick.BasketPage.el.orderItemValue).each(function () {
                $(this).removeClass(Wick.BasketPage.el.orderItemValueSm)
                $(this).removeClass(Wick.BasketPage.el.orderItemValueXs)
                length = length + $(this).text().length
            });
            if (length >= 16) {
                $(context).find(Wick.BasketPage.el.orderItemValue).addClass(Wick.BasketPage.el.orderItemValueXs)
            } else if (length >= 14) {
                $(context).find(Wick.BasketPage.el.orderItemValue).addClass(Wick.BasketPage.el.orderItemValueSm)
            }
        }
    },
    limitingQuantityValue: function () {
        const charactersLimit = 5;

        if (this.value.length > charactersLimit) {
            this.value = this.value.slice(0, charactersLimit);
        }
    }
};
$(document).ready(function () {
    function init() {
        if (!$('.page_basket.basket').length) {
            return;
        }

        Wick.BasketPage.el.$voucherFormBtn.on('click', checkVoucherCode);
        $(Wick.BasketPage.el.content).on('click', Wick.BasketPage.el.quantityButton, Wick.BasketPage.updateItemQuantity);
        $(Wick.BasketPage.el.content).on('click', Wick.BasketPage.el.removeButton, Wick.BasketPage.updateItemQuantity);
        $(Wick.BasketPage.el.content).on('change', Wick.BasketPage.el.quantityValue, Wick.BasketPage.updateItemQuantity);
        $(Wick.BasketPage.el.content).on('input', Wick.BasketPage.el.quantityValue, Wick.BasketPage.limitingQuantityValue);
        $(Wick.BasketPage.el.content).on('click', Wick.BasketPage.el.ccButtonInDelivery, Wick.BasketPage.showCCSectionInDelivery);
        $(Wick.BasketPage.el.content).on('click', Wick.BasketPage.el.deliveryButtonInCC, Wick.BasketPage.changeMethodToDelivery);
        $(Wick.BasketPage.el.content).on('click', Wick.BasketPage.el.updateStoreButton, Wick.BasketPage.changeMethodToCC);
        $(Wick.BasketPage.el.charityInput).on('click', Wick.BasketPage.updateCharity);
        $(Wick.BasketPage.el.charityItem).on('click', Wick.BasketPage.el.removeButton, Wick.BasketPage.updateCharity);
        $(Wick.BasketPage.el.orderSummary).on('click', Wick.BasketPage.el.voucherRemove, voucherRemove);
        $(Wick.BasketPage.el.promoWrapper).on('click', Wick.BasketPage.el.promoClose, Wick.BasketPage.removePromotion);
        $(Wick.BasketPage.el.content).on('click', Wick.BasketPage.el.deliveryStockButton, toggleWisdom);
        $(Wick.BasketPage.el.content).on('click', Wick.BasketPage.el.wisdomClose, toggleWisdom);
        $(Wick.BasketPage.el.content).on('click', Wick.BasketPage.el.wisdomCheck, checkDeliveryStock);
        $(Wick.BasketPage.el.content).on('click', Wick.BasketPage.el.wisdomAdd, addDeliveryStock);
        $(Wick.BasketPage.el.content).on('click', Wick.BasketPage.el.changeLink, Wick.Wisdom.showDefaultStage);
        $('main').on('click', Wick.BasketPage.el.promoClose, Wick.BasketPage.removePromotion);

        $(Wick.BasketPage.el.voucherRemove).unbind('click');
        Wick.BasketPage.paintActionButton();
        Wick.BasketPage.changeFontSizeForOrderValue();

        if (Wick.chechLocalEnv) {
            Wick.BasketPage.loadIndexing();
        }
    }

    init();
});
