import {athenaConfig, athenaConfigDemo} from '../global/athena-config.js';
import {setProductPrice} from '../global/helpers/athena-price-helper.js';

export function athenaStory(){

    document.addEventListener('click', function(event){
        if(event.target.closest('.athena-story-item')){
            let recommenderId = event.target.closest('.athena-story-item').getAttribute('data-recommender-id');
            let productSkus = event.target.closest('.athena-story-item').getAttribute('data-recommender-sku');
            
            fetch(`${athenaConfigDemo.storyUrl}/api/v1/product-widgets/get-response?token=${athenaConfig.websiteToken}&product_widget_id=${recommenderId}&product_skus[]=${productSkus}`)
                .then(response => {
                    if(response.ok){
                        return response.json();
                    }else{
                        throw new Error('Network response was not ok');
                    }
                })
                .then((data) => {
                    let products = data.data.products;
                    if(products.length){

                        const swiper = new Swiper('.swiper', {
                            loop: false,
                            direction: 'vertical',
                            autoHeight: true,
                            observer: true,
                            observeParents: true,
                            slidesPerView: 1,
                            mousewheel: {
                                releaseOnEdges: true,
                            },
                            navigation: {
                                nextEl: '.swiper-button-next-modified',
                                prevEl: '.swiper-button-prev-modified'
                            },
                            virtual: {
                                slides: (function () {
                                    const slides = [];
                                    for (let i = 0; i < products.length; i += 1) {
                                        const priceElement = setProductPrice('product', products[i]);
                                        slides.push(`
                                                <div class="swiper-slide item product product-item athena-recommendation__product-item">
                                                    <div class="swiper-slide-inner" data-element-id-product-recommendation="${products[i].id}"
                                                    data-element-sku-product-recommendation="${products[i].original_sku}">
                                                        <a class="athena-product-item-link">
                                                            <span class="athena-product-item-photo">
                                                                <img class="athena-product-image-photo" src="${products[i].image}" alt="${products[i].name}">
                                                            </span>
                                                        </a>
                                                        <span class="athena-product-item-details">
                                                            <a href="" class="athena-page-product-link">
                                                                <span class="athena-product-name" title="${products[i].name}">${products[i].name}</span>
                                                            </a>
                                                            ${priceElement ? priceElement : ''}
                                                        </span>
                                                    </div>
                                                    <div class="athena-story-social-container">
                                                        <span class="athena-story-add-to-cart"></span>
                                                        <span class="athena-story-like"></span>
                                                        <span class="athena-story-wishlist"></span>
                                                    </div>
                                                </div>
                                            `);
                                    }
                                    return slides;
                                }()),
                            },
                        });

                    }
                })
                .catch(error => console.error('Error:', error));


            document.body.classList.add('active-athena-stories-recommender');
            document.querySelector('.athena-stories-recommender-content')?.classList.add('active');

        }

        if(event.target.classList.contains('athena-story-add-to-cart') || event.target.classList.contains('athena-story-like') || event.target.classList.contains('athena-story-wishlist')){
            event.target.classList.add('pulse-btn');
            window.setTimeout(function(){
                event.target.classList.remove('pulse-btn');
            }, 200)
        }

        if(event.target.closest('.close-story')){

            if(document.body.classList.contains('active-athena-stories-recommender')){
                if(document.querySelector('.athena-stories-recommender-content-inner .swiper-wrapper')){

                    const swiperMain = document.querySelector('.swiper');
                    if(swiperMain){
                        swiperMain.swiper?.destroy()
                    }

                    document.querySelector('.athena-stories-recommender-content-inner .swiper-wrapper').innerHTML = '';

                    document.querySelector('.athena-stories-recommender-content')?.classList.remove('active');
                    document.body.classList.remove('active-athena-stories-recommender');

                }
            }

        }

    });

    document.addEventListener('keydown', function(e){
        if(document.body.classList.contains('active-athena-stories-recommender')){
            e.preventDefault();
            if(e.keyCode == 27){
                document.querySelector('.close-story').click();
            }
            if(e.keyCode == 38) {
                document.querySelector('.swiper-button-prev-modified').click();
            }
            else if(e.keyCode == 40) {
                document.querySelector('.swiper-button-next-modified').click();
            }
        }

    });
}