jQuery(document).ready(function($) {
    // var ajaxUrl = blogmaticObject.ajaxUrl, wpnonce = blogmaticObject._wpnonce
    const { ajaxUrl, themeColor, _wpnonce: wpnonce, headerSticky } = blogmaticObject

    $(window).on("resize", function() {
        let selector = $('body')
        if( $(window).width() <= 426 ) {
            selector.removeClass( 'is-desktop is-tablet' ).addClass( 'is-smartphone' )
        } else if( $(window).width() <= 769 ) {
            selector.removeClass( 'is-desktop is-smartphone' ).addClass( 'is-tablet' )
        } else {
            selector.removeClass( 'is-smartphone is-tablet' ).addClass( 'is-desktop' )
        }
    })

    // top date time
    var timeElement = $( ".top-date-time .time" )
    if( timeElement.length > 0 ) {
        setInterval(function() {
            timeElement.html(new Date().toLocaleTimeString())
        },1000);
    }
    
    // handle preloader
    function blogmaticPreloader( timeOut = 3000 ) {
        setTimeout(function() {
            $('body .blogmatic_loading_box').hide();
        }, timeOut);
    }
    blogmaticPreloader()

    // header - normal search
    var searchSectionContainer = $('.search-wrap')
    if( searchSectionContainer.length > 0 ) {
        searchSectionContainer.on( 'click', '.search-trigger', function(){
            var _this = $(this)
            _this.siblings().show()
            _this.parent().addClass('toggled')
            _this.siblings().find('.search-field').focus()
            onElementOutsideClick( _this.parent(), function(){
                _this.parent().removeClass( 'toggled' )
                _this.siblings().find( '.search-form-close' ).click()
            })
        })

        // close search popup
        var closeButton = searchSectionContainer.find('.search-form-wrap')
        if( closeButton.length > 0 ) {
            closeButton.on('click', '.search-form-close', function(){
                var _thisButton = $(this), parentElement = _thisButton.parents('.search-wrap')
                parentElement.removeClass('toggled')
                _thisButton.parent().hide()
            })
        }

        // on ESC button click
        $(document).on('keydown', function( event ){
            if( event.keyCode == 27 ) {
                closeButton.hide()
                closeButton.parent().removeClass('toggled')
            }
        })
    }

    // check for dark mode drafts
    if( localStorage.getItem( "themeMode" ) != null ) {
        if( localStorage.getItem("themeMode") == "dark" ) {
            $('body').addClass( 'blogmatic-dark-mode' ).removeClass('blogmatic-light-mode')
        } else {
            $('body').addClass( 'blogmatic-light-mode' ).removeClass('blogmatic-dark-mode')
        }
    }

    // header - theme mode
    var themeModeContainer = $('.mode-toggle-wrap')
    if( themeModeContainer.length > 0 ) {
        themeModeContainer.on( 'click', '.mode-toggle', function(){
            var _this = $(this), bodyElement = _this.parents('body')
            if( bodyElement.hasClass('blogmatic-dark-mode') ) {
                localStorage.setItem( 'themeMode', 'light' )
                bodyElement.removeClass('blogmatic-dark-mode').addClass('blogmatic-light-mode')
            } else {
                localStorage.setItem( 'themeMode', 'dark' )
                bodyElement.removeClass('blogmatic-light-mode').addClass('blogmatic-dark-mode')
            }
        })
    }

    // header - canvas menu
    var canvasMenuContainer = $('.blogmatic-canvas-menu')
    if( canvasMenuContainer.length > 0 ) {
        canvasMenuContainer.on( 'click', '.canvas-menu-icon', function() {
            var _this = $(this), bodyElement = _this.parents('body')
            bodyElement.toggleClass('blogmatic-model-open');
            onElementOutsideClick( _this.siblings(), function(){
                bodyElement.removeClass( 'blogmatic-model-open' )
            })
        })
    }

    // on element outside click function
    function onElementOutsideClick( currentElement, callback ) {
        $(document).mouseup(function( e ) {
            var container = $(currentElement);
            if ( !container.is(e.target) && container.has(e.target).length === 0) callback();
        })
    }

    // back to top script
    if( $( "#blogmatic-scroll-to-top" ).length ) {
        var scrollContainer = $( "#blogmatic-scroll-to-top" );
        $(window).scroll(function() {
            if ( $(this).scrollTop() > 500 ) {
                scrollContainer.addClass('show');
            } else {
                scrollContainer.removeClass('show');
            }
        });
        scrollContainer.on( 'click', '.scroll-to-top-wrapper, .icon-text', function(event) {
            event.preventDefault();
            // Animate the scrolling motion.
            $("html, body").animate({scrollTop:0},"slow");
        });
    }

    // post format - gallery
    // var gallery = $('.wp-block-gallery')
    // if( gallery.length > 0 ) {
    //     if( blogmaticObject.singleGalleryLightbox != 1 ) return
    //     gallery.each(function(){
    //         var _this = $(this)
    //         var findImageSrc = _this.find('.wp-block-image img')
    //         var srcArgs = []
    //         findImageSrc.each(function(){
    //             srcArgs.push({
    //                 src: $(this).attr('src'),
    //                 type: 'image'
    //             })
    //         })
    //         _this.magnificPopup({
    //             items: srcArgs,
    //             gallery: {
    //                 enabled: true
    //             },
    //             type: 'image'
    //         })
    //     })
    // }

    // main header sticky
    if( headerSticky ) {
        $(window).on('scroll', function(){
            var scroll = $(window).scrollTop()
            var mainHeaderContainer = $('header.site-header')
            if( scroll >= 200 ) {
                mainHeaderContainer.addClass('header-sticky--enabled').removeClass('header-sticky--disabled')
            } else {
                mainHeaderContainer.addClass('header-sticky--disabled').removeClass('header-sticky--enabled')
            }
        })
    }

    // cursor animation
    var cursorContainer = $('.blogmatic-cursor')
    if( cursorContainer.length > 0 ) {
        $(document).on( 'mousemove', function( event ){
            cursorContainer[0].style.top = 'calc('+ event.pageY +'px - 15px)'
            cursorContainer[0].style.left = 'calc('+ event.pageX +'px - 15px)'
        })
        var selector = 'a, button, input[type="submit"], #blogmatic-scroll-to-top .icon-text, #blogmatic-scroll-to-top .icon-holder, .pagination.pagination-type--ajax-load-more, .blogmatic-widget-loader .load-more, .mode-toggle-wrap .mode-toggle, .blogmatic-canvas-menu .canvas-menu-icon, .blogmatic-table-of-content .toc-fixed-icon, .blogmatic-social-share.show-on-click'
        $( selector ).on( 'mouseover', function(){
            $( cursorContainer ).addClass( 'isActive' )
        })
        $( selector ).on( 'mouseout', function(){
            $( cursorContainer ).removeClass( 'isActive' )
        })
    }

    // social share
    var socialShareContainer = $( '.blogmatic-social-share' )
    if( socialShareContainer.length > 0 ) {
        // for print
        var printButton = socialShareContainer.find( '.print' )
        printButton.each(function(){
            $(this).on( 'click', function(){ 
                $(this).find( 'a' ).removeAttr( 'href' )
                window.print()
            })
        })
        // for copy link
        var copyLinkButton = socialShareContainer.find( '.copy_link' )
        copyLinkButton.each(function(){
            $(this).on( 'click', function( event ) { 
                event.preventDefault()
                var copyLinkButtonAnchor = $(this).find( 'a' )
                var linkToCopy = copyLinkButtonAnchor.attr( 'href' )
                navigator.clipboard.writeText( linkToCopy )
            })
        })

        // share icon
        if( socialShareContainer.hasClass( 'show-on-click' ) ) {
            socialShareContainer.on('click', '.share-icon', function(){
                $(this).toggleClass('active')
            })
        }
    }

    /**
     * convert string true or false to bool true or false
     * 
     * @since 1.0.0
     */
    const blogmaticConverToBoolean = ( value ) => {
        return ( value === 'true' ) ? true : false
    }

    /**
     * Initialize swiper js
     * 
     * @since 1.0.0
     */
    const blogmaticInitializeSwiper = ( props ) => {
        const { arrows, fade, loop, speed, autoplay, autoplaySpeed, slidesPerView, slidesPerGroup, breakpoints, swiperClass, autoHeight, direction, spaceBetween, navigation } = props
        let swiperObject = {
            arrows: blogmaticConverToBoolean( arrows ) || true,
            loop: blogmaticConverToBoolean( loop ),
            speed: parseInt( speed ) || 500,
            pagination: {
                el: '.swiper-pagination',
                clickable: true
            },
        }
        if( navigation ) swiperObject = { ...swiperObject, navigation: navigation }
        if( autoHeight !== undefined ) swiperObject = { ...swiperObject, autoHeight: autoHeight }
        if( spaceBetween !== undefined ) swiperObject = { ...swiperObject, spaceBetween: spaceBetween }
        if( direction !== undefined ) swiperObject = { ...swiperObject, direction: direction }
        if( slidesPerView !== undefined ) swiperObject = { ...swiperObject, slidesPerView: parseInt( slidesPerView ) }
        if( slidesPerGroup !== undefined ) swiperObject = { ...swiperObject, slidesPerGroup: parseInt( slidesPerGroup ) }
        if( breakpoints !== undefined ) swiperObject = { ...swiperObject, breakpoints: { ...breakpoints } }
        if( ( fade !== undefined ) || true ) swiperObject = { 
            ...swiperObject,
            effect: blogmaticConverToBoolean( fade ) ? 'fade' : 'slide',
            fadeEffect: {
                crossFade: true
            }
        }
        if( blogmaticConverToBoolean( autoplay ) || false ) swiperObject = { 
            ...swiperObject,
            autoplay: { 
                delay: parseInt( autoplaySpeed ) || 3000,
                stopOnLastSlide: true
            }
        }
        return new Swiper( swiperClass, swiperObject );
    }

    /**
     * Main Banner JS
     * 
     * @since 1.0.0
     */
    var fullWidthBannerContainer = $('#blogmatic-main-banner-section')
    if( fullWidthBannerContainer.length > 0 ) {
        const { arrows, fade, infiniteLoop, speed, autoplay, autoplaySpeed } = blogmaticObject
        var mainBannerTopObject = {
            arrows: arrows,
            fade: fade,
            loop: infiniteLoop,
            speed: speed,
            autoplay: autoplay,
            autoplaySpeed: autoplaySpeed,
            navigation: false,
            swiperClass: '.main-banner-wrap.swiper'
        }

        let thumbsObject = {
            spaceBetween: 15,
            slidesPerView: 4,
            loop: true,
            freeMode: true,
            watchSlidesProgress: true,
        }
        thumbsObject = { 
            ...thumbsObject,
            navigation: {
                nextEl: '.custom-button-next',
                prevEl: '.custom-button-prev'
            },
            breakpoints : {
                50: { slidesPerView: 2 },
                500: { slidesPerView: 4 }
            }
        }
        let mainBannerThumbs = new Swiper( '.swiper.main-banner-swiper-thumbs', thumbsObject );
        let mainBannerTop = new Swiper('.swiper.main-banner-wrap', { 
            ...mainBannerTopObject,
            effect: blogmaticConverToBoolean( fade ) ? 'fade' : 'slide',
            fadeEffect: {
                crossFade: true
            },
            thumbs: { 
                swiper: mainBannerThumbs 
            } 
        })

        mainBannerThumbs.on("navigationNext navigationPrev", function(){
            const activeIndex = mainBannerThumbs.realIndex;  // Get the real index of the current slide
            mainBannerTop.slideToLoop( activeIndex );
        })
        
    }

    /**
     * Carousel JS
     * 
     * @since 1.0.0
     */
    var carouselContainer = $('.blogmatic-carousel-section')
    if( carouselContainer.length > 0 ) {
        let _this = carouselContainer
        const { carouselArrows, carouselInfiniteLoop, carouselSpeed, carouselAutoplay, carouselAutoplaySpeed, carouselSlideToShow, slidesToScroll } = blogmaticObject
        blogmaticInitializeSwiper({
            arrows: carouselArrows,
            loop: carouselInfiniteLoop,
            speed: carouselSpeed,
            autoplay: carouselAutoplay,
            autoplaySpeed: carouselAutoplaySpeed,
            slidesPerView: carouselSlideToShow,
            slidesPerGroup: slidesToScroll,
            spaceBetween: _this.hasClass( 'carousel-layout--two' ) ? 15 : 24,
            navigation: { nextEl: '.custom-button-next', prevEl: '.custom-button-prev' },
            breakpoints: {
                50: { slidesPerView: 1 },
                610: { slidesPerView: 2 },
                769: { slidesPerView: carouselSlideToShow },
            },
            swiperClass: '#blogmatic-carousel-section .swiper'
        })
    }

    /**
     * Carousel Posts JS
     * 
     * @since 1.0.0
     */
    var cpWidgets = $( ".blogmatic-widget-carousel-posts" )
    cpWidgets.each(function() {
        var _this = $(this), parentWidgetContainerId = _this.parents( ".widget.widget_blogmatic_carousel_widget" ).attr( "id" ), parentWidgetContainer
        if( typeof parentWidgetContainerId != 'undefined' ) {
            parentWidgetContainer = $( "#" + parentWidgetContainerId )
            var ppWidget = parentWidgetContainer.find( ".carousel-posts-wrap" );
        } else {
            var ppWidget = _this;
        }
        if( ppWidget.length > 0 ) {
            let swiperObject = {
                arrows: true,
                loop: true,
                autoplay: true,
                effect: 'fade',
                fadeEffect: {
                    crossFade: true
                },
                autoHeight: true,
                direction: 'horizontal',
                navigation: { nextEl: _this.find( '.custom-button-next' )[0], prevEl: _this.find( '.custom-button-prev' )[0] },
            }
            new Swiper( _this.find( '.swiper' )[0], swiperObject )
        }
    })

    /**
     * Gallery Post Format JS
     * 
     * @since 1.0.0
     */
    // archive masonry layout 
    var masonryContainer = $("body.archive--masonry-layout #primary .blogmatic-inner-content-wrap")
    masonryContainer.masonry({
        // options
        // itemSelector: 'article, div.blogmatic-advertisement-block',
        gutter: 30,
    })

    // handle the post gallery post format
    var postGalleryElems = $("body #primary article.format-gallery .post-thumbnail-wrapper")
    if( postGalleryElems.length > 0 ) {
        postGalleryElems.each(function() {
            let swiperObject = {
                navigation: {
                    nextEl: $(this).find( '.custom-button-next' )[0],
                    prevEl: $(this).find( '.custom-button-prev' )[0]
                }
            }
            new Swiper( $(this).find('.swiper')[0], swiperObject )
        })
    }

    /**
     * Responsive header builder toggle button
     * 
     * @since 1.0.0
     */
    var responsiveHeaderBuilderWrapper = $('.bb-bldr--responsive')
    if( responsiveHeaderBuilderWrapper.length > 0 ) {
        let toggleButton = responsiveHeaderBuilderWrapper.find( '.toggle-button-wrapper' )
        toggleButton.on("click", function() {
            let _this = $(this)
            _this.parents( '.bb-bldr-row' ).siblings( '.bb-bldr-row.mobile-canvas' ).toggleClass( 'open' )
        })
    }

    const progressBar = {
        init: function() {
            this.scrollEvent()
        },
        selectors: {
            'scroll-to-top': {
                'selector': '#blogmatic-scroll-to-top.display--fixed .scroll-to-top-wrapper',
                'property': 'background',
                'usesBackground': true
            },
            'single-progress': {
                'selector': 'body.page .single-progress, body.single .single-progress, body.archive .single-progress, body.search .single-progress',
                'property': 'width',
                'usesBackground': false
            }
        },
        totalScrollableArea: $('body')[0].clientHeight,
        sizeOfScrollBar: window.innerHeight,
        scrollEvent: function() {
            let self = this
            $(window).on("scroll", function(){
                let scrollBarPosition = window.scrollY
                if( scrollBarPosition < 1 ) {   /* Hide when Top is reached */
                    $( self.selectors['single-progress'].selector ).hide()
                } else {
                    $( self.selectors['single-progress'].selector ).show()
                }
                let width = self.getWidth( scrollBarPosition )
                if( self.isBottom() ) width = 100   /* Run when bottom is reached */
                let background = 'conic-gradient('+ themeColor +' '+ width +'%, transparent '+ width +'%)'
                Object.entries( self.selectors ).forEach(( current ) => {
                    const [ ID, selectorValues ] = current
                    const { selector, property, usesBackground } = selectorValues
                    if( usesBackground ) {
                        $( selector ).attr( 'style', property + ': ' + background )
                    } else {
                        $( selector ).css( property, width + '%' )
                    }
                })
            })
        },
        getWidth: function( scrollBarPosition ) {
            let width = ( ( ( scrollBarPosition + this.sizeOfScrollBar ) / this.totalScrollableArea ) * 100 )
            return Math.round( width );
        },
        isBottom: function() {
            if ( $(window).scrollTop() + $(window).height() >= $(document).height()) return true
        }
    }
    progressBar.init()

    /* Header Sticky */
    if( headerSticky ) {
        let lastScroll = 0
        $( window ).on('scroll',function() {
            var scroll = $( this ).scrollTop();
            let selector = $('body header.site-header')
            if( scroll > 50 ) {
                if ( scroll > lastScroll ) {
                    /* Scrolling Down */
                    selector.addClass( 'fixed--on' ).removeClass( 'fixed--off' )
                } else {
                    /* Scrolling UP */
                    selector.removeClass( 'fixed--on' ).addClass( 'fixed--off' )
                }
                lastScroll = scroll
            } else {
                $( selector ).addClass("header-sticky--disabled fixed--off").removeClass( 'fixed--on' );
            }
        });
    }
})