+(function($) {
    "use strict";

      // Set popup count.
    function finchcart_set_popup_count() {
        const prevPopupCountData = localStorage.getItem('wpbfc-popup-count');
        const hasPrevCount       = (prevPopupCountData && JSON.parse(prevPopupCountData).count && (JSON.parse(prevPopupCountData).time > Date.now() - 2 * 3600 * 1000));
        const popupCount         = hasPrevCount ? (JSON.parse(prevPopupCountData).count + 1) : 1;
        const popupCountData     = {count: popupCount, time: Date.now()}

        localStorage.setItem('wpbfc-popup-count', JSON.stringify(popupCountData));
    }

      // Get popup count.
    function finchcart_get_popup_count() {
        const popupData     = localStorage.getItem('wpbfc-popup-count');
        const hasPopupCount = (popupData && JSON.parse(popupData).count && (JSON.parse(popupData).time > Date.now() - 2 * 3600 * 1000));
        return hasPopupCount ? JSON.parse(popupData).count: 0;
    }

      // Get current product data.
    function get_current_product_data( data ){
        var $output = [];

        var [, , buttonHTML] = data,
        button               = buttonHTML[0],
        product_id           = $(button).data('product_id');

        if( button && product_id ){
            $output['button']     = button;
            $output['product_id'] = product_id;
        }

        return $output;
    }

      // Trigger the popup.
    function finchcart_added_to_cart_popup( data ) {

        const popupCount     = finchcart_get_popup_count();
        const popupShowTimes = FinchCartVars._finchcart_popup_show_type === 'everytime' ? Infinity : +FinchCartVars._finchcart_popup_show_times;

        if(popupShowTimes > popupCount){

            var product        = get_current_product_data(data),
                button         = product['button'],
                addedProductId = product['product_id'];

            var inside_popup_cart_button = 0;

            // For loop
            if( button.closest('.finchcart-modal-item-cart') == null ){
                var inside_popup_cart_button = 1;
            }
            
            // For single product
            if( button.closest('.finchcart-modal-item-cart') != null && button.closest('.finchcart-modal-item-cart').length == 0 ){
                var inside_popup_cart_button = 1;
            }

            if( inside_popup_cart_button ){
                
                wp.ajax.send( {
                    data: {
                        action    : 'finchcart_fire_added_to_cart_popup',
                        product_id: addedProductId,
                    },
                    beforeSend : function ( xhr ) {
                        $(button).addClass('finchcart_btn_loading');
                    },
                    success: function( response ) {
                        $(button).removeClass('finchcart_btn_loading');

                        var FinchCartModal = new jBox('Modal', {
                            content         : response,
                            closeButton     : FinchCartVars._finchcart_close_icon ? 'box'                                     : !1,
                            closeOnEsc      : FinchCartVars._finchcart_esc_close ? !0                                         : !1,
                            closeOnClick    : FinchCartVars._finchcart_overlay_close ? 'overlay'                              : !1,
                            addClass        : 'finch-cart-modal',
                            width           : FinchCartVars._finchcart_popup_width ? FinchCartVars._finchcart_popup_width + 'px': '1000px',
                            maxHeight       : '90%',
                            responsiveWidth : true,
                            responsiveHeight: true,
                            onOpen          : function () {
                                finchcart_set_popup_count();
                            }
                        });
                
                        FinchCartModal.open();

                        $('.finchcart-close-modal').on( 'click', function(){
                            FinchCartModal.close();
                        } );

                        finchcart_init_product_slider();
                    },
                    error: function(error) {
                        alert( error );
                    }
                });
            }else{
                wp.ajax.send( {
                    data: {
                        action    : 'finchcart_inside_popup_added_to_cart_notice',
                        product_id: addedProductId,
                    },
                    success: function( response ) {
                        const topPosition       = $(button).closest('.finch-cart-modal').find('.finchcart-modal-head').outerHeight();
                        const $notification_bar = $(button).closest('.finch-cart-modal').find('.finchcart-inside-popup-cart-notice');

                        $notification_bar.css('top', topPosition).fadeIn(300).append(response);

                        setTimeout(() => {
                            $notification_bar.fadeOut(600, function() {
                                $(this).empty();
                            });
                        }, 1500);
                    },
                    error: function(error) {
                        alert( error );
                    }
                });
            }
        }
    }

    // Init the popup for product loop and archive.
    
    $(document.body).on("added_to_cart", async function (e, ...data) {
        finchcart_added_to_cart_popup(data);
    });

    // Init the popup for the single product page cart.

    $('body').on('submit','form.cart', function (e) {
        const popupCount     = finchcart_get_popup_count();
        const popupShowTimes = FinchCartVars._finchcart_popup_show_type === 'everytime' ? Infinity : +FinchCartVars._finchcart_popup_show_times;

        if(popupShowTimes > popupCount){
            e.preventDefault();
            
            var $form         = $(this);
            var $submitButton = $form.find('button[type="submit"]');
            var data          = {};
            var productId     = '';

            $form.serializeArray().forEach(function(option) {
                if(option.name !== 'add-to-cart') {
                    data[option.name] = option.value;
                }else {
                    productId = option.value;
                }
            });

            data.product_id = $submitButton.val() ? $submitButton.val() : productId;

            if( !!parseInt(data.product_id) ) {
                // add product id to button to catch it by popup.
                $submitButton.attr('data-product_id', data.product_id);

                // Trigger event before add to cart.
                $( document.body ).trigger( 'adding_to_cart', [ $submitButton,  data]);

                $.ajax( {
                    type      : 'POST',
                    url       : wc_add_to_cart_params.wc_ajax_url.toString().replace( '%%endpoint%%', 'add_to_cart' ),
                    data      : data,
                    dataType  : 'json',
                    beforeSend: function( xhr ) {
                        $submitButton.addClass('loading').removeClass('added');
                    },
                    complete: function( res ) {
                        $submitButton.addClass('added').removeClass('loading');
                    },
                    success: function( res ) {
                        $( document.body ).trigger( 'added_to_cart', [ res.fragments, res.cart_hash, $submitButton ] );
                    },
                });
            }
        }
    });

    function finchcart_init_product_slider(){
        
        if(typeof Swiper !== "undefined"){

            var sliderOptions = $('.finchcart-modal-products-slider').data();

            var autoplay = {
                delay: sliderOptions.autoplayspeed,
            };

            if( sliderOptions.autoplay != true ){
                var autoplay = false;
            }

            var swiper = new Swiper(".finchcart-modal-products-slider", {
                loop      : sliderOptions.loop ? !0: !1,
                autoplay  : autoplay,
                pagination: {
                    el            : '.swiper-pagination',
                    clickable     : true,
                    dynamicBullets: true,
                },
                navigation: {
                    nextEl: '.swiper-button-next',
                    prevEl: '.swiper-button-prev',
                },
                breakpoints: {
                    400: {
                        slidesPerView: sliderOptions.columnsmobile ? parseInt(sliderOptions.columnsmobile): '',
                    },
                    500: {
                        slidesPerView: sliderOptions.columnslargemobile ? parseInt(sliderOptions.columnslargemobile): '',
                        spaceBetween : sliderOptions.columnsgap ? parseInt(sliderOptions.columnsgap)                : '',
                    },
                    768: {
                        slidesPerView: sliderOptions.columnstablet ? parseInt(sliderOptions.columnstablet): '',
                        spaceBetween : sliderOptions.columnsgap ? parseInt(sliderOptions.columnsgap)      : '',
                    },
                    900: {
                        slidesPerView: sliderOptions.columnssmalldesktop ? parseInt(sliderOptions.columnssmalldesktop): '',
                        spaceBetween : sliderOptions.columnsgap ? parseInt(sliderOptions.columnsgap)                  : '',
                    },
                    901: {
                        slidesPerView: sliderOptions.columnsdesktop ? parseInt(sliderOptions.columnsdesktop): '',
                        spaceBetween : sliderOptions.columnsgap ? parseInt(sliderOptions.columnsgap)        : '',
                    }
                }
            });
        }
    }

})(jQuery);