

// quick look modal
function initQuickLook(){
    let quickLookButtons = jQuery('.show-bcp-modal');
    let modal = jQuery('.bcp-modal');
    let imageContainer = jQuery('.bcp-modal-image');
    let bcpBackdrop = jQuery('.bcp-backdrop');
    let swiperConfig = {
        ...globalSwiperOptions,
        slidesPerView: 1,
        spaceBetween: 0,
        loop:false,
        freeMode:false,
        speed: 300,
        navigation: {
            nextEl: '.custom-swiper-button-next',
            prevEl: '.custom-swiper-button-prev',
        },
        pagination: {
            el: '.custom-swiper-pagination',
            type: 'bullets',
            clickable: true,
            dynamicBullets: true,
        },
    };

    quickLookButtons.each(function (i, button){
        let swiper = null;

        jQuery(button).click(function (){
            let id = jQuery(button).attr('data-bcp-id');

            // set modal data if not already done
            if (modal.attr('data-bcp-id') !== id){

                modal.attr('data-bcp-id',id);
                let title = jQuery(button).attr('data-bcp-title');
                let rating = jQuery(button).attr('data-bcp-rating');
                let description = jQuery(button).attr('data-bcp-description');
                let link = jQuery(button).attr('data-bcp-link');
                let images = jQuery(button).attr('data-bcp-images');
                let price = jQuery(button).attr('data-bcp-price');
                let attributes = jQuery(button).attr('data-bcp-attributes');
                let stock = jQuery(button).attr('data-bcp-stock');
                let stockContainer = modal.find('.bcp-modal-stock:not(.unavailable)');
                let stockContainerUnavailable = modal.find('.bcp-modal-stock.unavailable');

                if (stock === 'instock'){
                    stockContainerUnavailable.addClass('d-none');
                    stockContainer.removeClass('d-none');
                }else{
                    stockContainerUnavailable.removeClass('d-none');
                    stockContainer.addClass('d-none');
                }

                modal.find('.bcp-modal-title').html(title);
                modal.find('.bcp-modal-rating').html(rating);
                modal.find('.bcp-modal-description').html(description);

                if (attributes !== '' && isJsonString(attributes)){
                    modal.find('.bcp-modal-description').append(JSON.parse(attributes));
                }
                modal.find('.bcp-modal-more').attr('href',link);
                if(price !== ''){
                    modal.find('.bcp-modal-price').html(JSON.parse(price));
                }

                // image
                images = JSON.parse(images);
                imageContainer.find('.swiper-slide').remove();
                jQuery(images).each(function (i,link){
                    let el = "<div class='swiper-slide'><img src='"+link+"' alt='gallery image'></div>";
                    imageContainer.find('.swiper-wrapper').append(el);
                });
            }


            swiper = new Swiper('.bcp-modal-image',swiperConfig);

            modal.addClass('show');
            bcpBackdrop.fadeIn('fast');
        });

        // modal close (x) button click
        let close = modal.find('.bcp-modal-close');
        close.click(function (){
            if (swiper != null) swiper.destroy();
            modal.removeClass('show');
            bcpBackdrop.fadeOut('fast');
        });

        bcpBackdrop.click(function (){
            if (swiper != null) swiper.destroy();
            jQuery(this).fadeOut('fast');
            modal.removeClass('show');
        });
    });
}

jQuery(function (){
    initQuickLook();

    // product favorite button / wishlist handler
    jQuery('.custom-wishlist-button').on('click', function(e) {
        e.preventDefault();
        let button = jQuery(this);
        let product_id = button.attr('data-product-id');
        button.find('i').addClass('circle-loader');
        jQuery.ajax({
            url:  site_url_object.ajax_url,
            type: 'POST',
            data: {
                action: 'toggle_wishlist',
                product_id: product_id
            },
            error: function(e) {
                button.find('i').removeClass('circle-loader');
            },
            success: function(response) {
                button.find('i').removeClass('circle-loader');

                if (response.success) {
                    // Update icon based on the wishlist status
                    let newIcon = response.data.is_in_wishlist ? 'iconly-Heart icbo text-danger' : 'iconly-Heart';
                    button.find('i').attr('class', newIcon); // Change icon

                    if(response.data.is_in_wishlist){
                        showToast('به لیست علاقه مندی شما اضافه شد.');
                    }else {
                        showToast('از لیست علاقه مندی حذف شد.');
                    }
                }
            }
        });
    });

})


jQuery(document).ready(function($) {
    // custom add to cart ajax
    jQuery('.ajax-add-to-cart').click(function(e) {
        e.preventDefault();
        let button = jQuery(this);
        let cartButton = jQuery('.btn-open-wc-cart');
        let cartButtonContainer = jQuery('.cart-button-container');

        let product_id = button.attr('data-product-id');
        button.find('i').addClass('circle-loader');

        jQuery.ajax({
            type: 'POST',
            url: site_url_object.ajax_url,
            data: {
                action: 'custom_add_to_cart',
                product_id: product_id
            },
            success: function(response) {

                button.find('i').removeClass('circle-loader');
                if (response.success) {

                    showToast(response.data.message,'iconly-Tick-Square icli','toast-success');

                    // Update cart fragments if they exist
                    if (response.data.fragments) {
                        jQuery.each(response.data.fragments, function(key, value) {
                            jQuery(key).replaceWith(value);
                        });
                    }

                    // Trigger WooCommerce events
                    jQuery(document.body).trigger('added_to_cart', [response.data.fragments, response.data.cart_hash]);
                    jQuery(document.body).trigger('wc_fragment_refresh');
                    jQuery(document.body).trigger('wc_fragments_loaded');
                    jQuery(document.body).trigger('wc_fragments_refreshed');

                    // Force refresh cart widget content as backup
                    jQuery.ajax({
                        type: 'POST',
                        url: site_url_object.ajax_url,
                        data: {
                            action: 'refresh_cart_widget'
                        },
                        success: function(refreshResponse) {
                            if (refreshResponse.success) {
                                jQuery('.woocommerce-cart-form').html(refreshResponse.data.cart_content);
                                jQuery('.cart-badge').text(refreshResponse.data.cart_count);
                            }
                        }
                    });

                    // Add the class
                    cartButton.addClass('cart-button-animated');
                    cartButtonContainer.addClass('open');

                    // Remove the class after 4 seconds
                    setTimeout(function() {
                        cartButton.removeClass('cart-button-animated');
                    }, 4000);

                    setTimeout(function() {
                        cartButtonContainer.removeClass('open');
                    }, 1500);

                } else {
                    console.error('Error adding product.');
                }
            },
            error: function() {
                button.find('i').removeClass('circle-loader');
                console.error('Ajax Request Failed.');
            }
        });
    });
});
function showToast(message = '', icon = 'icon-heart', type = 'toast-primary') {
    let toastEl = jQuery('.banta-toast');

    // set data
    toastEl.removeClass().addClass('banta-toast ' + type);
    toastEl.find('.toast-msg').html(message);
    toastEl.find('.toast-icon i').removeClass().addClass(icon);

    // show toast
    toastEl.addClass('show');
    setTimeout(() => {
        toastEl.removeClass('show');
    }, 3000);
}




let GeneralBantaWidgetsHandler = function () {
    initBannersMobile();
    initQuickLook();
    initSwipers();
};


function initSwipers(){
    // init carousel
    let myCustomSlider = document.querySelectorAll(".elementor-swiper[swiper-items]");
    for(let jSwiperIndex=0; jSwiperIndex < myCustomSlider.length; jSwiperIndex++ ) {
        myCustomSlider[jSwiperIndex].classList.add('swiper-container-' + jSwiperIndex);


        let swiper = jQuery(myCustomSlider[jSwiperIndex]);
        let isBannerSwiper = false;
        let isInstantOfferSwiper = false;

        if(swiper.hasClass('banner-swiper')){isBannerSwiper = true}
        if(swiper.hasClass('products-instant-offer')){isInstantOfferSwiper = true}

        if (!swiper.hasClass('swiper-initialized')){
            let margin = parseInt(swiper.attr('swiper-margin'));
            let loop = swiper.attr('swiper-loop');
            loop = loop === 'yes';

            let autoplay = swiper.attr('swiper-autoplay');
            autoplay = autoplay === 'yes';

            // items
            let items = swiper.attr('swiper-items');
            if (isNaN(items)) items = 1;
            let itemsTablet = swiper.attr('swiper-items-tablet');
            if (isNaN(itemsTablet)) itemsTablet = 1;
            let itemsMobile = swiper.attr('swiper-items-mobile');
            if (isNaN(itemsMobile)) itemsMobile = 1;

            // items
            let itemsPerGroup = swiper.attr('swiper-items-per-group');
            if (isNaN(itemsPerGroup)) itemsPerGroup = 1;

            // autoplay delay
            let autoplayDelay = parseInt(swiper.attr('swiper-autoplay-delay'));
            if (isNaN(autoplayDelay)) autoplayDelay = 4000;

            // animation speed
            let speed = parseInt(swiper.attr('swiper-speed'));
            if (isNaN(speed)) speed = 800;

            // center
            let center = swiper.attr('swiper-center');
            center = center === 'yes';

            // animate effect
            let effect = swiper.attr('swiper-effect');
            if (effect === undefined) effect = 'slide';
            if (effect === 'none') speed = 1;
            if (effect === 'cards') {
                items = 1;
                itemsTablet = 1;
                itemsTablet = 1;
                itemsPerGroup = 1;
            }


            let swiperOptions = {
                ...globalSwiperOptions,
                ...(!loop && { slidesPerGroup: itemsPerGroup }),
                ...(!isBannerSwiper && { centeredSlides: center }),
                ...(!isBannerSwiper && { centeredSlidesBounds: center }),
                ...(isInstantOfferSwiper && { freeMode: false }),
                loop: loop,
                speed: speed,
                slidesPerView: itemsMobile,
                spaceBetween: margin,
                effect: effect,
                roundLengths:true,
                autoplay: {
                    enabled: autoplay,
                    delay: autoplayDelay,
                    stopOnLastSlide:false,
                    // disableOnInteraction:false
                },
                navigation: {
                    enabled: false,
                    nextEl: '.custom-swiper-button-next',
                    prevEl: '.custom-swiper-button-prev',
                },
                breakpoints: {
                    // when window width is >= 576
                    576: {
                        slidesPerView: itemsMobile,
                        navigation: {
                            enabled: true,
                            nextEl: '.custom-swiper-button-next',
                            prevEl: '.custom-swiper-button-prev',
                        },
                    },
                    // when window width is >= 768
                    768: {
                        slidesPerView: itemsTablet,
                        navigation: {
                            enabled: true,
                            nextEl: '.custom-swiper-button-next',
                            prevEl: '.custom-swiper-button-prev',
                        },
                    },
                    // when window width is >= 992
                    992: {
                        slidesPerView: items,
                        navigation: {
                            enabled: true,
                            nextEl: '.custom-swiper-button-next',
                            prevEl: '.custom-swiper-button-prev',
                        },
                    }
                }
            };

            if (jQuery('.swiper-container-' + jSwiperIndex).hasClass('banner-swiper')){
                swiperOptions['pagination']= {
                    el: '.custom-swiper-pagination',
                    type: 'bullets',
                    clickable: true,
                    dynamicBullets: true,
                };
                swiperOptions['freeMode'] = false;
            }

            let swiperObj = new Swiper('.swiper-container-' + jSwiperIndex, swiperOptions);
            // fix loop issue
            if (loop){
                swiperObj.slideToLoop(1, 0);
            }
        }
    }
}

function initBannersMobile(){
    // change main slide images on mobile
    let bannerImages = jQuery('img.banner-image');
    bannerImages.each(function (){
        let mainImage = jQuery(this);
        let img = document.createElement('img');
        let originalSrc = mainImage.attr('data-original-image');
        let src = mainImage.attr('data-mobile-image');

        if (window.innerWidth <= 992) {
            mainImage.attr('src',src).removeClass('d-none');

            // if(src !== '') {
            //     // mainImage.addClass('d-none');
            //     img.src = src;
            //     // img.onload = function (){
            //     //     mainImage.attr('src',src).removeClass('d-none');
            //     // }
            //     mainImage.attr('src',src).removeClass('d-none');
            //
            // }
        }else{
            // img.src = originalSrc;
            // img.onload = function (){
            //     mainImage.attr('src',originalSrc).removeClass('d-none');
            // }
            mainImage.attr('src',originalSrc).removeClass('d-none');

        }
    });
}


// bcp tabs
jQuery(document).on('click','.bcp-tabs-nav-item',function (){
    let tabButton = jQuery(this);
    if (!tabButton.hasClass('active')){
        // find tabs container
        let tabs = tabButton.parents('.bcp-tabs');

        // inactivate all tabs
        tabs.find('.bcp-tabs-nav-item').removeClass('active');
        tabs.find('.bcp-tab-content').removeClass('active').hide(0)
            .promise().done(function() {
            // activate current tab
            tabButton.addClass('active');
            let tabId = tabButton.attr('bcp-data-tab-id');
            tabs.find('.bcp-tab-content#' + tabId).fadeIn(200).addClass('active');
        });
    }
});

// detect window resize event
window.onresize = GeneralBantaWidgetsHandler;
window.onload = GeneralBantaWidgetsHandler;


// initial bcp widgets
jQuery( window ).on( 'elementor/frontend/init', function() {

    // swipers
    elementorFrontend.hooks.addAction( 'frontend/element_ready/banta_products_swiper_1.default', GeneralBantaWidgetsHandler);
    elementorFrontend.hooks.addAction( 'frontend/element_ready/banta_products_swiper_2.default', GeneralBantaWidgetsHandler);
    elementorFrontend.hooks.addAction( 'frontend/element_ready/banta_products_swiper_3.default', GeneralBantaWidgetsHandler);
    elementorFrontend.hooks.addAction( 'frontend/element_ready/banta_products_swiper_4.default', GeneralBantaWidgetsHandler);
    elementorFrontend.hooks.addAction( 'frontend/element_ready/banta_posts_swiper_1.default', GeneralBantaWidgetsHandler);
    elementorFrontend.hooks.addAction( 'frontend/element_ready/banta_posts_swiper_2.default', GeneralBantaWidgetsHandler);
    elementorFrontend.hooks.addAction( 'frontend/element_ready/banta_posts_slider.default', GeneralBantaWidgetsHandler);
    elementorFrontend.hooks.addAction( 'frontend/element_ready/banta_portfolios_swiper.default', GeneralBantaWidgetsHandler);
    elementorFrontend.hooks.addAction( 'frontend/element_ready/banta_feedbacks_swiper.default', GeneralBantaWidgetsHandler);
    elementorFrontend.hooks.addAction( 'frontend/element_ready/banta_team_swiper.default', GeneralBantaWidgetsHandler);
    elementorFrontend.hooks.addAction( 'frontend/element_ready/banta_product_categories_swiper.default', GeneralBantaWidgetsHandler);
    elementorFrontend.hooks.addAction( 'frontend/element_ready/banta_stories_swiper.default', GeneralBantaWidgetsHandler);
    elementorFrontend.hooks.addAction( 'frontend/element_ready/banta_image_slider.default', GeneralBantaWidgetsHandler);

    elementorFrontend.hooks.addAction( 'frontend/element_ready/banta_product_tabs_1.default', GeneralBantaWidgetsHandler);
    elementorFrontend.hooks.addAction( 'frontend/element_ready/banta_product_tabs_2.default', GeneralBantaWidgetsHandler);
    elementorFrontend.hooks.addAction( 'frontend/element_ready/banta_product_tabs_3.default', GeneralBantaWidgetsHandler);
    elementorFrontend.hooks.addAction( 'frontend/element_ready/banta_product_tabs_4.default', GeneralBantaWidgetsHandler);

    elementorFrontend.hooks.addAction( 'frontend/element_ready/banta_products_instant_offer_1.default', GeneralBantaWidgetsHandler);
    elementorFrontend.hooks.addAction( 'frontend/element_ready/banta_products_instant_offer_2.default', GeneralBantaWidgetsHandler);
    elementorFrontend.hooks.addAction( 'frontend/element_ready/banta_products_instant_offer_3.default', GeneralBantaWidgetsHandler);
} );