/**Ajax Paggination*/
var productData = document.querySelectorAll('.tp-ajax-paginate-wrapper');

if( productData.length > 0 ){
    productData.forEach(function(self, index){
        Ajaxpagination(self, index)
    })

    function Ajaxpagination(item, index){
        let getPostWidget = item.dataset.widgetid,
            scope = document.querySelectorAll(`.elementor-element-${getPostWidget}`),
            producAttr = (productData && productData[index].dataset.searchattr) ? JSON.parse(productData[index].dataset.searchattr) : [],
            Pagin = scope[0].querySelectorAll('.theplus-pagination'),
            oldOffset = producAttr.offset_posts ? producAttr.offset_posts : 0,
            visiblePages = (producAttr.visible_pages && Number(producAttr.visible_pages) > 0) ? Number(producAttr.visible_pages) : 3;

        if( producAttr.listing_type != 'wishlist' && producAttr.listing_type != 'recently_viewed' ) {
            /** Pagination Click*/
            if(Pagin.length > 0){
                let pagBtn = Pagin[0].querySelectorAll('.tp-ajax-paginate'),
                    totalResult = (item.dataset) ? Number(item.dataset.totalCount) : 0,
                    displayPost = producAttr.display_post ? Number(producAttr.display_post) : 0,
                    tpPagNum = Math.ceil(totalResult/displayPost);

                onpagBtnClick( pagBtn, item, Pagin, producAttr, oldOffset, tpPagNum, index, visiblePages );
            }
        }
    }

    function onpagBtnClick( pagBtn, item, Pagin, producAttr, oldOffset, tpPagNum, index, visiblePages ) {
        visiblePages = (visiblePages && Number(visiblePages) > 0) ? Number(visiblePages) : 3;
        pagBtn.forEach(function (self) {
            self.addEventListener('click', function (e) {
                e.preventDefault();
                tpgbSkeleton_filter("visible", item);

                var PageNumber = crntPage = '';
                if (!this.classList.contains('paginate-prev') && !this.classList.contains('paginate-next')) {
                    PageNumber = Number(this.dataset.page);

                    let offset = (Number(PageNumber) - Number(1)) * Number(producAttr.display_post);
                    producAttr['new_offset'] = offset + Number(oldOffset);

                    if (PageNumber > 0) {
                        crntPage = Pagin[0].querySelector('.current');
                        if (crntPage && crntPage.classList.contains('current')) {
                            crntPage.classList.remove('current');
                        }
                        this.classList.add('current');

                        setVisibleWindow(Pagin, PageNumber, tpPagNum, visiblePages);
                        addRemoveClass(PageNumber, Pagin, tpPagNum);
                    }
                }

                if (this.classList.contains('paginate-prev')) {
                    crntPage = Pagin[0].querySelector('.tp-ajax-paginate.current');
                    let prevSibling = crntPage ? crntPage.previousElementSibling : null;

                    if (prevSibling && prevSibling.classList.contains('tp-number')) {
                        PageNumber = Number(prevSibling.dataset.page);

                        let offset = PageNumber ? (Number(PageNumber) - Number(1)) * Number(producAttr.display_post) : '';
                        producAttr['new_offset'] = offset + Number(oldOffset);

                        prevSibling.classList.add('current');
                        crntPage.classList.remove('current');

                        setVisibleWindow(Pagin, PageNumber, tpPagNum, visiblePages);
                        addRemoveClass(PageNumber, Pagin, tpPagNum);
                    }
                }

                if (this.classList.contains('paginate-next')) {
                    crntPage = Pagin[0].querySelector('.current');
                    let nextSibling = crntPage ? crntPage.nextElementSibling : null;

                    if (nextSibling && nextSibling.classList.contains('tp-number')) {
                        PageNumber = Number(nextSibling.dataset.page);

                        let offset = PageNumber ? (Number(PageNumber) - Number(1)) * Number(producAttr.display_post) : '';
                        producAttr['new_offset'] = offset + Number(oldOffset);

                        crntPage.classList.remove('current');
                        nextSibling.classList.add('current');

                        setVisibleWindow(Pagin, PageNumber, tpPagNum, visiblePages);
                        addRemoveClass(PageNumber, Pagin, tpPagNum);
                    }
                }

                paginateAjax(producAttr, item, index, this);
            })
        });
    }

    function setVisibleWindow(Pagin, currentPage, totalPages, visiblePages) {
        if (!Pagin || !Pagin[0]) return;
        let numbers = Pagin[0].querySelectorAll('.tp-ajax-paginate.tp-number');
        if (numbers.length === 0) return;

        let windowSize = Math.max(1, Math.min(visiblePages, totalPages)),
            half = Math.floor((windowSize - 1) / 2),
            start = currentPage - half,
            end = start + windowSize - 1;

        if (start < 1) {
            start = 1;
            end = start + windowSize - 1;
        }
        if (end > totalPages) {
            end = totalPages;
            start = end - windowSize + 1;
            if (start < 1) {
                start = 1;
            }
        }

        numbers.forEach(function (btn) {
            let page = Number(btn.dataset.page);
            if (page >= start && page <= end) {
                btn.classList.remove('tp-page-hide');
            } else {
                btn.classList.add('tp-page-hide');
            }
        });
    }

    function addRemoveClass(PageNumber, Pagin, tpPagNum){
        let GetPrev = Pagin[0].querySelectorAll('.paginate-prev'),
            GetNext = Pagin[0].querySelectorAll('.paginate-next')

        if( PageNumber > 1 ){
            addPageHide('remove', GetPrev)
        }else{
            addPageHide('add', GetPrev)
        }

        if( PageNumber == tpPagNum ){
            addPageHide('add', GetNext)
        }else{
            addPageHide('remove', GetNext)
        }
    }

    function addPageHide(type, GetPrev){
        if( GetPrev.length > 0 ){
            if( 'add' === type && !GetPrev[0].classList.contains('tp-page-hide') ){
                GetPrev[0].classList.add('tp-page-hide')
            }
            if( 'remove' === type && GetPrev[0].classList.contains('tp-page-hide') ){
                GetPrev[0].classList.remove('tp-page-hide')
            }
        }
    }

    function paginateAjax(producAttr, item, index, $this) {

        var security = (producAttr.theplus_nonce) ? producAttr.theplus_nonce : '';

        var ajaxData = {
            action : 'theplus_ajax_based_pagination',
            option : producAttr,
            nonce : security,
        };

        if( producAttr.listing_type == 'wishlist' ) {
            var login = jQuery('body').hasClass('logged-in') ? 'true' : 'false';
            var shopList = '';
            if( login == 'false') {
                var getlsvaluewlnl = JSON.parse( localStorage.getItem( producAttr.shopname ) );
                shopList = getlsvaluewlnl ? getlsvaluewlnl : '';
            }
            var wlData = {
                'login': login,
                'shopname': producAttr.shopname,
                'notloginwl': shopList,
            };
            Object.assign( ajaxData, wlData );
        } else if ( producAttr.listing_type == 'recently_viewed' ) {
            var login = jQuery('body').hasClass('logged-in') ? 'true' : 'false';
            var shopList = '';
            if( login == 'false') {
                if ( 'recently_viewed' == producAttr.listing_type ) {
                    let nonlogincookies = Cookies.get('tpwoorplnonlogin');
                    if ( !nonlogincookies ) {
                        console.log('');
                    } else if ( nonlogincookies.length != 0 ) {
                        if ( nonlogincookies.includes("|")) {
                            getlsvaluewlnl = nonlogincookies.split("|");
                        } else {
                            getlsvaluewlnl = nonlogincookies.split(" ");
                        }
                        shopList = getlsvaluewlnl;
                    }
                }
            }
            var wlData = {
                'login': login,
                'shopname': producAttr.shopname,
                'notloginwl': shopList,
            };
            Object.assign( ajaxData, wlData );
        }

        jQuery.ajax({
            url : theplus_ajax_url,
            method : "POST",
            async: true,
            cache: false,
            data : ajaxData,
            success: function(data){
                if( productData.length > 0 ){

                    if( producAttr.listing_type == 'wishlist' || producAttr.listing_type == 'recently_viewed' ) {
                        let getid = '';
                        getid = $this.parentElement.previousElementSibling.id;

                        document.querySelector(`#${getid}.post-inner-loop`).innerHTML = '';
                        document.querySelector(`#${getid}.post-inner-loop`).innerHTML = data.HtmlData;
                    }else{
                        productData[index].innerHTML = '';
                        productData[index].innerHTML = data.HtmlData;
                    }
                }
            },
            complete: function() {
                Resizelayout(index, producAttr);
                if( producAttr.loading_optn == 'skeleton' ){
                    tpgbSkeleton_filter("hidden",item);
                }
            }
        });
    }

    var tpgbSkeleton_filter = function(type, item) {
        let skeleton = item.querySelectorAll('.tp-skeleton');
        if( skeleton.length > 0 ){
            skeleton.forEach(function(self) {
                if( self.style.visibility == 'visible' && self.style.opacity == 1 ){
                    if( "hidden" === type ){
                        self.style.cssText = "visibility: hidden; opacity: 0;";
                    }
                }else{
                    if( "visible" === type ){
                        self.style.cssText = "visibility: visible; opacity: 1;";
                    }
                }
            });
        }
    }

    var Resizelayout = function(index, producAttr) {
        if( 'grid' === producAttr.layout || 'masonry' === producAttr.layout ){
            setTimeout(function(){
                jQuery(productData[index]).isotope('reloadItems').isotope();
            }, 1000);
        }else if( 'metro' === producAttr.layout ){
            setTimeout(function(){
                theplus_setup_packery_portfolio();	
            }, 1000);
        }
    }
}