// elementor menu
let isMenuInitialized = false;
jQuery(function (){

    // init bs tooltip
    let tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
    let tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl)
    })

    // append backdrops to DOM
    jQuery('body').append('<div class="search-backdrop"></div>');

    // add mega menu class
    jQuery('.banta-mega-menu-parent > ul').addClass('banta-mega-menu');

    // change color of blockquote icon
    changeBlockquoteIconColor();


    if (jQuery(window).width() >= 992){
        // init mega menu
        let megaMenus = jQuery('.banta-mega-menu');
        // megaMenus.parent('li').addClass('position-static');
        let menuContainer = megaMenus.parents('.banta-elementor-menu-container');
        megaMenus.css({
            width: menuContainer.outerWidth() + 'px'
        });
    }


    initMobileMenu();


    jQuery( window ).resize(function() {
        initMobileMenu();
    });
})
function changeBlockquoteIconColor(){
    const root = document.documentElement; // This selects the <html> element
    const styles = getComputedStyle(root);
    const primaryColor = styles.getPropertyValue('--colorPrimary').trim();
    const svgString = `<svg width="800px" height="800px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
    <path d="M2 12.3501H7.79999C9.32999 12.3501 10.38 13.5101 10.38 14.9301V18.1501C10.38 19.5701 9.32999 20.7301 7.79999 20.7301H4.58002C3.16002 20.7301 2 19.5701 2 18.1501V12.3501" stroke="${primaryColor}" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
    <path d="M2 12.35C2 6.29998 3.13003 5.30003 6.53003 3.28003" stroke="${primaryColor}" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
    <path d="M13.6299 12.3501H19.4299C20.9599 12.3501 22.0099 13.5101 22.0099 14.9301V18.1501C22.0099 19.5701 20.9599 20.7301 19.4299 20.7301H16.2099C14.7899 20.7301 13.6299 19.5701 13.6299 18.1501V12.3501" stroke="${primaryColor}" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
    <path d="M13.6299 12.35C13.6299 6.29998 14.7599 5.30003 18.1599 3.28003" stroke="${primaryColor}" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
    </svg>`;
    const encodedSVG = encodeURIComponent(svgString);
    jQuery('blockquote').css('background-image',`url('data:image/svg+xml;utf8,${encodedSVG}')`);
}


function initMobileMenu(){
    let width = jQuery(window).width();
    let menuItem = jQuery(document).find('.banta-elementor-menu li.menu-item-has-children');
    let mobileLogoSrc = jQuery('#mobileMenuLogoSrc').val();
    let mobileProfileLink = jQuery('#mobileMenuProfileBtnLink').val();
    let showMobileMenuProfileBtn = jQuery('#showMobileMenuProfileBtn').val();
    if (width <= 992){
        if (!isMenuInitialized){
            isMenuInitialized = true;
            menuItem.append('<span class="banta-el-menu-item-toggle" onclick="openSubMenu(this)"><i class="iconly-Arrow-Left-2 icli"></i></span>');
            menuItem.find('ul').append('<div class="banta-menu-heading">' +
                '<span class="banta-menu-heading-back" onclick="menuBack(this)"><i class="iconly-Arrow-Right-2 icli"></i></span>' +
                '<span class="banta-menu-heading-name">'+jQuery(this).parent().html()+'</span>' +
                '</div>');


            // append heading
            jQuery('.banta-elementor-menu ul.menu-items').append('<div class="banta-menu-heading">' +
                '<img src="'+mobileLogoSrc+'" alt="logo"></div>');

            // append profile button to heading
            if(showMobileMenuProfileBtn !== 'false' && showMobileMenuProfileBtn !== 'no' && showMobileMenuProfileBtn !== ''){
                jQuery('.banta-elementor-menu ul.menu-items .banta-menu-heading')
                    .append('<a href="'+mobileProfileLink+'" class="btn btn-primary shadow-lg"><span class="iconlyBulk-Add-User"><span class="path2"></span><span class="path3"></span></span></a>');
            }


            // mega menu fix
            let megaMenus = jQuery('.banta-mega-menu');
            megaMenus.parent('li').removeClass('position-static');
            megaMenus.removeClass('banta-mega-menu');
            megaMenus.css({
                width: 250 + 'px'
            });


        }
    }else{
        jQuery('.banta-el-menu-item-toggle,.banta-menu-heading').remove();
        isMenuInitialized = false;
    }
}
function menuBack(btn){
    jQuery(btn).parent().parent('.sub-menu').removeClass('open');
}
function openSubMenu(arrow){
    let submenu = jQuery(arrow).prev('ul.sub-menu');
    submenu.addClass('open');

    // set title
    let title = jQuery(arrow).parent('.menu-item').find('a:first').html();
    submenu.find('.banta-menu-heading-name').html(title);
}
function menuToggleElementor() {
    jQuery('.banta-menu-backdrop').fadeIn();
    jQuery(".banta-elementor-menu").addClass('open');
}
jQuery(document).on('click','.banta-menu-backdrop',function (){
    jQuery(this).fadeOut();
    jQuery('.banta-elementor-menu').removeClass('open');
    jQuery('.sub-menu').removeClass('open');
});
jQuery(document).on('click','.menu-backdrop',function (){
    jQuery(this).fadeOut();
    jQuery('.menu-items').removeClass('open');
    jQuery('.menu-items ul').removeClass('open');
});



// search modal
jQuery(document).on('click','.header-search-btn',function (){
    jQuery('.search-backdrop').fadeIn();
    jQuery('.search-modal').addClass('show');
    setTimeout(function (){
        jQuery('#searchInput').focus();
    },100);

});
jQuery(document).on('click','.search-backdrop',function (){
    jQuery(this).fadeOut();
    jQuery('.search-modal').removeClass('show');
});
jQuery(document).on('click','.btn-close-search-modal',function (){
    jQuery('.search-backdrop').fadeOut();
    jQuery('.search-modal').removeClass('show');
});

// cart dropdown
jQuery(document).on('click','.cart-button-container',function (event){
    if (!jQuery(event.target).hasClass('cart-dropdown-close') && !jQuery(event.target).hasClass('icon-x1')) {
        if (jQuery(window).width() <= 992){
            jQuery(this).addClass('open');
        }
    }
});
jQuery(document).on('click','.cart-dropdown-close',function (){
    jQuery(this).parents('.cart-button-container').removeClass('open');
    console.log('close clicked')
});


function isJsonString(str) {
    try {
        JSON.parse(str);
    } catch (e) {
        return false;
    }
    return true;
}


/////////////////////////////////////
/////////////// Story ///////////////
/////////////////////////////////////
const defaultStoryDuration = 7000;
jQuery(document).ready(function (){
    setVolumeSetting();
});

// Global Swiper options
const globalSwiperOptions = {
    changeDirection: 'rtl',
    spaceBetween: 16,
    speed: 200,
    freeMode:true,
    on: {
        slideChange: addClassToSwiperStartEnd,
        init: addClassToSwiperStartEnd,
        autoplayTimeLeft(s, time, progress) {
            jQuery(this.el).find(".autoplay-progress svg").css("--progress", 1 - progress);
            jQuery(this.el).find(".autoplay-progress span").html(Math.ceil(time / 1000));
        }
    },
};

function addClassToSwiperStartEnd() {
    const swiperContainer = this.el;
    let centered = jQuery(swiperContainer).attr('swiper-center');
    let loop = jQuery(swiperContainer).attr('swiper-loop');

    // remove init class
    jQuery(swiperContainer).removeClass('swiper-before-init');
    // remove spinner
    jQuery(swiperContainer).find('.swiper-spinner').remove();

    if (this.isBeginning) {
        if (centered !== 'yes' && loop !== 'yes'){
            swiperContainer.classList.add('at-start');
        }
        swiperContainer.classList.remove('at-end');
    } else if (this.isEnd) {
        swiperContainer.classList.remove('at-start');
        swiperContainer.classList.add('at-end');
    } else {
        swiperContainer.classList.remove('at-start', 'at-end');
    }
}

// init stories swiper
// new Swiper('#storiesSwiperSm', {
//     ...globalSwiperOptions,
//     loop:false,
//     speed: 200,
//     freeMode:true,
//     slidesPerView: 3.6,
//     navigation: {
//         nextEl: '.custom-swiper-button-next',
//         prevEl: '.custom-swiper-button-prev',
//         enabled:false
//     },
//     breakpoints: {
//         // when window width is >= 992px
//         1350: {
//             slidesPerView: 13.3,
//             navigation: {
//                 nextEl: '.custom-swiper-button-next',
//                 prevEl: '.custom-swiper-button-prev',
//                 enabled:true
//             },
//         },
//         1200: {
//             slidesPerView: 11.3,
//             navigation: {
//                 nextEl: '.custom-swiper-button-next',
//                 prevEl: '.custom-swiper-button-prev',
//                 enabled:true
//             },
//         },
//         992: {
//             slidesPerView: 8.3,
//             navigation: {
//                 nextEl: '.custom-swiper-button-next',
//                 prevEl: '.custom-swiper-button-prev',
//                 enabled:true
//             },
//         },
//         768: {
//             slidesPerView: 6.3,
//             navigation: {
//                 nextEl: '.custom-swiper-button-next',
//                 prevEl: '.custom-swiper-button-prev',
//                 enabled:true
//             },
//         },
//         576: {
//             slidesPerView: 5.3,
//             navigation: {
//                 nextEl: '.custom-swiper-button-next',
//                 prevEl: '.custom-swiper-button-prev',
//                 enabled:false
//             },
//         },
//         380: {
//             slidesPerView: 4.3,
//             navigation: {
//                 nextEl: '.custom-swiper-button-next',
//                 prevEl: '.custom-swiper-button-prev',
//                 enabled:false
//             },
//         }
//     }
// });

// init large stories
let largeStoriesSwiper = new Swiper('#storiesSwiperLg', {
    changeDirection: 'rtl',
    effect: 'cube',
    autoplay: {
        delay: defaultStoryDuration,
        disableOnInteraction:false,
    },
    on: {
        afterInit: function () {
            this.autoplay.stop();
        },
        autoplayTimeLeft: function (swiper, timeLeft, percentage) {
            let p = percentage * 100;
            let width = 100 - p;
            if (width > 0 && width < 100 && (this.autoplay.running && !this.autoplay.paused)) {
                jQuery('.large-stories-swiper .swiper-pagination-bullet-active > span').css('width',width + '%');
            }
        },
        autoplayPause:function (){
            console.log('autoplayPause');
            let activeSlide = this.slides[this.activeIndex];
            let btn = jQuery(activeSlide).find('.story-play-pause-btn');
            let storyItem = jQuery(activeSlide).find('.story-item-lg');
            let videoTag = storyItem.find('video').get(0);
            btn.removeClass('playing');
            if (videoTag){
                videoTag.pause();
            }
        },
        autoplayResume: function (){
            console.log('autoplayResume');
            let activeSlide = this.slides[this.activeIndex];
            let btn = jQuery(activeSlide).find('.story-play-pause-btn');
            let storyItem = jQuery(activeSlide).find('.story-item-lg');
            let videoTag = storyItem.find('video').get(0);
            btn.addClass('playing');
            if (videoTag){
                videoTag.play();
            }
        },
        autoplayStart: function (){
            console.log('autoplayStart');
            let activeSlide = this.slides[this.activeIndex];
            let storyItem = jQuery(activeSlide).find('.story-item-lg');
            let videoTag = storyItem.find('video').get(0);
            if(storyItem.hasClass('video') && videoTag && document.readyState === 'complete'){
                videoTag.play();
            }
        },
        autoplayStop: function (){
            console.log('autoplayStop');

        },
        slideChange:function (){
            console.log('slideChange');

            let activeSlide = this.slides[this.activeIndex];
            let storyItem = jQuery(activeSlide).find('.story-item-lg');
            let videoTag = storyItem.find('video').get(0);
            let playBtn = jQuery(activeSlide).find('.story-play-pause-btn');
            let timeout = 0;
            if (!jQuery('.stories-wrapper').hasClass('show')) timeout = 1000;

            // pause all videos
            stopAllVideos();
            // reset autoplay width
            jQuery('.large-stories-swiper .swiper-pagination-bullet > span').css('width',0 + '%');


            if (storyItem.hasClass('video') && videoTag){
                let swiper = this;
                videoTag.addEventListener('loadeddata', function() {
                    swiper.params.autoplay.delay = videoTag.duration * 1000;
                    setTimeout(function (){
                        videoTag.play();
                        playBtn.addClass('playing');

                    },timeout);
                    console.log('delay set to video: ' + swiper.params.autoplay.delay);
                });


            }else{
                this.params.autoplay.delay = defaultStoryDuration;
            }


        }
    },
    cubeEffect: {
        slideShadows: true,
    },
    pagination: {
        el: '.swiper-pagination',
        type: 'bullets',
        clickable:true,
        renderBullet: function (index, className) {
            return '<span class="' + className + '"><span></span></span>';
        }
    },
    navigation: {
        nextEl: '.custom-swiper-button-next',
        prevEl: '.custom-swiper-button-prev',
        enabled:false
    },
    breakpoints:{
        568:{
            navigation: {
                nextEl: '.custom-swiper-button-next',
                prevEl: '.custom-swiper-button-prev',
                enabled:true
            }
        }
    }
})

jQuery(document).on('click','.story-item',function (e){
    e.preventDefault();
    let index = jQuery(this).attr('data-story-index');

    // animate
    let circle = jQuery(this).find('.story-item-circle');
    circle.addClass('animated');

    // check clicked story type
    let clickedStory = jQuery(largeStoriesSwiper.slides[index]).find('.story-item-lg');
    let video = undefined;
    // load video if exist
    if (clickedStory.hasClass('video')){
        // set autoplay delay to video duration
        let videoTag = clickedStory.find('video').first();
        if (videoTag){
            video = videoTag.get(0);
            video.load();
        }
    }else{
        largeStoriesSwiper.params.autoplay.delay = defaultStoryDuration;
    }

    // show story
    setTimeout(function(){
        // slide to clicked story
        if(largeStoriesSwiper.realIndex !== index){
            largeStoriesSwiper.slideTo(index,0,false);
        }
        if (clickedStory.hasClass('video') && video !== undefined){
            // set autoplay delay to video duration
            console.log("!!!!!! video.duration: " + video.duration);
            largeStoriesSwiper.params.autoplay.delay = video.duration * 1000;
        }else{
            largeStoriesSwiper.params.autoplay.delay = defaultStoryDuration;
            console.log('story delay has been set to default: ' + largeStoriesSwiper.params.autoplay.delay);
        }

        jQuery('.stories-wrapper').addClass('show');
        circle.removeClass('animated');
        largeStoriesSwiper.autoplay.start();
    },1000);
});

// video end event
jQuery('video.story-video-tag').on('ended',function(){
    largeStoriesSwiper.slideNext();
});

function setVolumeSetting(){
    let allVideos = jQuery(largeStoriesSwiper.slides).find('video');
    let buttons = jQuery(".story-volume-btn");
    let volume = localStorage.getItem("volume");
    if (volume === "0"){
        buttons.addClass('muted');
        jQuery(allVideos).each(function() {
            let video = jQuery(this).get(0);
            video.volume = 0;
        });
    }
}

// story volume button
jQuery(document).on('click','.story-volume-btn',function (){
    let btn = jQuery(this);
    let storyItem = btn.parents('.story-item-lg');
    let videoTag = storyItem.find('video').get(0);
    let allVideos = jQuery(largeStoriesSwiper.slides).find('video');
    if(btn.hasClass('muted')){
        videoTag.volume = 1;
        jQuery('.story-volume-btn').removeClass('muted');
        localStorage.setItem("volume","1");
        jQuery(allVideos).each(function() {
            let video = jQuery(this).get(0);
            video.volume = 1;
        });
    }else{
        videoTag.volume = 0;
        jQuery('.story-volume-btn').addClass('muted');
        localStorage.setItem("volume","0");
        jQuery(allVideos).each(function() {
            let video = jQuery(this).get(0);
            video.volume = 0;
        });
    }
});

// story play/pause button
jQuery(document).on('click','.story-play-pause-btn',function (){
    if(largeStoriesSwiper.autoplay.paused){
        largeStoriesSwiper.autoplay.resume();
    }else{
        largeStoriesSwiper.autoplay.pause();
    }
});

// story back button
jQuery(document).on('click','.story-item-lg-back',function (){
    closeStories();
});

document.addEventListener('DOMContentLoaded', function() {
    const storiesWrapper = document.querySelector('.stories-wrapper');
    if (storiesWrapper){
        storiesWrapper.addEventListener('click', function(event) {
            // Check if the event target is the wrapper itself
            if (event.target === storiesWrapper) {
                closeStories();
            }
        });
    }
});

function closeStories(){
    // pause all videos
    stopAllVideos();
    // hide stories
    jQuery('.stories-wrapper').removeClass('show');

    // stop swiper autoplay
    largeStoriesSwiper.autoplay.stop();
}

function stopAllVideos(){
    let videos = jQuery(largeStoriesSwiper.slides).find('video');
    jQuery(videos).each(function() {
        let video = jQuery(this).get(0);
        video.pause();
        video.currentTime = 0;
    });
}


// woocommerce custom quantity buttons
jQuery('.td-quantity-button').on('click', function () {
    var $this = jQuery(this);
    var $input = $this.parent().find('input');
    var $quantity = $input.val();
    var $new_quantity = 0;
    if ($this.hasClass('plus')) {
        var $new_quantity = parseFloat($quantity) + 1;
    } else {
        if ($quantity > 0) {
            var $new_quantity = parseFloat($quantity) - 1;
        }
    }
    $input.val($new_quantity);
});



// move woocommerce notices
var $noticesWrapper = jQuery('.woocommerce-notices-wrapper');
if ($noticesWrapper.length) {
    var $customContainer = jQuery('<div class="custom-container mt-3"></div>');
    $noticesWrapper.wrap($customContainer);
}
