import { tns } from 'tiny-slider';

window.sliders = [];
const initSliders = () => {
    // Sliders initialization
    /* Generic item slider */
    const itemSliders = document.querySelectorAll('.item-slider');
    if (itemSliders.length) {
        initItemSliders(itemSliders);
    }
};

function initItemSliders (sliderElements) {
    const sliders = window.sliders;

    /* Generic item slider */
    for (const [i, sliderElement] of sliderElements.entries()) {
        createSlider(sliderElement, i);
    }

    window.addEventListener('resize', () => {
        for (const sliderId in sliders) {
            if (!sliders[sliderId]) continue;

            const range = getRange();

            if (!sliders[sliderId]['enabled-' + range]) {
                sliders[sliderId].controls.hide();
            } else {
                if (sliders[sliderId].slider) {
                    sliders[sliderId].controls.show();
                }
            }

            window.dispatchEvent(new Event('contentResize'));
        }
    });
    window.dispatchEvent(new Event('resize'));
}

const createSlider = (el, index) => {
    const sliders = window.sliders;

    const currentRange = getRange();

    // get controls
    const sliderId = 'itemSlider' + index;
    const controlsSelector = el.getAttribute('data-controls');
    const controls = document.querySelector(controlsSelector);

    // get slides
    const slides = el.querySelectorAll('.slider__panel');

    // slider data
    sliders[sliderId] = [];
    sliders[sliderId].element = el;
    sliders[sliderId].controls = controls;
    sliders[sliderId]['initial-slide'] = el.getAttribute('data-initial-slide');
    sliders[sliderId].autoWidth = el.getAttribute('data-autowidth');

    const attributes = ['items', 'move', 'enabled'];
    const attrDefaultValues = ['1', '1', true];

    const ranges = { xl: 1370, lg: 1200, md: 992, sm: 768, xs: 576, xxs: 0 };

    for (const [i, attribute] of attributes.entries()) {
        let currentValue = attrDefaultValues[i];

        for (const rangeKey in ranges) {
            const defaultValue = currentValue;

            // e.g. sliders[sliderId]['items-lg'] = el.data('items-lg') ? el.data('items-lg') : sliders[sliderId]['items-xl'];
            const value = el.getAttribute('data-' + attribute + '-' + rangeKey);
            sliders[sliderId][attribute + '-' + rangeKey] = value || defaultValue;

            currentValue = sliders[sliderId][attribute + '-' + rangeKey];
        }
    }

    const responsiveConfig = {};
    let defaultSlidesCount = 1;
    let defaultMoveCount = 1;
    let defaultEnabled = true;
    for (const rangeKey in ranges) {
        const breakpoint = ranges[rangeKey];
        const slidesCount = el.getAttribute('data-items-' + rangeKey)
            ? el.getAttribute('data-items-' + rangeKey)
            : defaultSlidesCount;
        const moveCount = el.getAttribute('data-move-' + rangeKey)
            ? el.getAttribute('data-move-' + rangeKey)
            : defaultMoveCount;
        const enabled = el.getAttribute('data-enabled-' + rangeKey)
            ? el.getAttribute('data-enabled-' + rangeKey)
            : defaultEnabled;
        responsiveConfig[breakpoint] = {
            items: slidesCount,
            slideBy: moveCount,
            disable: !enabled
        };

        defaultSlidesCount = slidesCount;
        defaultMoveCount = moveCount;
        defaultEnabled = enabled;
    }

    sliders[sliderId].slides = slides;
    sliders[sliderId].responsiveConfig = responsiveConfig;

    if (sliders[sliderId]['enabled-' + currentRange]) {
        initSlider(sliderId);
    } else {
        enableLoadMore(sliderId);
    }
}

function enableLoadMore (sliderId) {
    const sliders = window.sliders;

    sliders[sliderId].controls.hide();

    const loadMore = sliders[sliderId]['load-more'];
    const range = getRange();
    const slideCount = sliders[sliderId]['items-' + range];
    if (loadMore) {
        loadMore.show();
        sliders[sliderId].slides.slice(slideCount).hide();
    }
}

function initSlider (sliderId) {
    const sliders = window.sliders;

    const range = getRange();
    const slideRange = 'items-' + range;
    const moveRange = 'move-' + range;
    const itemsCount = sliders[sliderId][slideRange];
    const moveCount = sliders[sliderId][moveRange];
    const controls = sliders[sliderId].controls;
    const el = sliders[sliderId].element;
    const initialSlide = sliders[sliderId]['initial-slide'];
    const sliderEl = el.querySelector('.slider__container');
    const prevBtn = controls.querySelector('.slider-controls__prev');
    const nextBtn = controls.querySelector('.slider-controls__next');
    const currentCount = controls.querySelector('.slider-controls__count-current');
    const totalCount = controls.querySelector('.slider-controls__count-total');

    if (sliderEl) {
        controls.show();
        el.classList.add('item-slider--active');

        // const popupSelector = '.modal-trigger, .glightbox';
        // const popups = document.querySelectorAll(popupSelector);
        const slider = tns({
            container: sliderEl,
            autoWidth: sliders[sliderId].autoWidth,
            loop: true,
            prevButton: prevBtn || null,
            nextButton: nextBtn || null,
            nav: false,
            items: itemsCount,
            slideBy: moveCount,
            startIndex: initialSlide,
            responsive: sliders[sliderId].responsiveConfig
            /* onInit: function () {
                if (popups.length) {
                    import('./popups').then(({ initPopups }) => {
                        initPopups();
                    });
                }
            } */
        });
        sliders[sliderId].slider = slider;

        if (currentCount && totalCount) {
            totalCount.innerHTML = slider.getInfo().slideCount;
            slider.events.on('transitionStart', (slider) => {
                currentCount.innerHTML = slider.displayIndex;
            });
        }
    } else {
        controls.hide();
        el.classList.remove('item-slider--active');
    }

    window.dispatchEvent(new Event('resize'));
}

function getRange () {
    const width = window.innerWidth;

    if (width >= 1200) {
        return 'xl';
    } else if (width > 992) {
        return 'lg';
    } else if (width > 768) {
        return 'md';
    } else if (width > 576) {
        return 'sm';
    } else {
        return 'xs';
    }
}

HTMLElement.prototype.hide = function () {
    this.style.display = 'none';
}

HTMLElement.prototype.show = function () {
    this.style.display = '';
}

export { initSliders };
