function createEvent(eventName, payload, eventDetail) {
    return new CustomEvent(eventName, {
        detail: {
            payload,
            resolve: eventDetail.resolve,
            reject: eventDetail.reject,
        },
    });
}

/* eslint-disable no-unused-vars -- used globally */
function createPopupSlider({ type, sliderSelector, onAppendEvent, onAppend, onClose }) {
    const events = {
        CLOSE_JUST_ADDED: 'CLOSE_JUST_ADDED',
        CLOSE_MINI_BASKET: 'CLOSE_MINI_BASKET',
    };

    const el = {
        $body: $('body'),
        slider: sliderSelector,
        sliderWrap: `${sliderSelector} .custom-slider__wrap`,
        sliderWrapScroll: 'custom-slider__wrap--scroll',
        footer: '.custom-slider__footer',
        closePopup: `${sliderSelector} .close-popup`,
        $stickyWrapper: $('.sticky-wrapper'),
        $headerWrapper: $('.header-wrapper'),
        scrollDisable: 'slider-scroll-disable',
        footerFixed: 'footer-fixed',
        btnMiniBasket: '.header-minicart__btn',
    };

    function isSmallBreakpoint() {
        return Wick.Responsive.getCurrentBreakpoint() === 'down-sm';
    }

    function getAnimationClass() {
        return isSmallBreakpoint() ? 'bottom-to-top' : 'right-to-left';
    }

    function adjustHeight() {
        const stickyWrapperHeight = el.$stickyWrapper.outerHeight() || 0;
        const headerWrapperHeight = el.$headerWrapper.outerHeight() || 0;

        const totalHeight = stickyWrapperHeight + headerWrapperHeight;
        $(el.slider).css('height', `calc(100% - ${totalHeight}px)`);
    }

    function hideSlider() {
        $(el.slider).removeClass('show');

        setTimeout(() => {
            el.$body.removeClass(el.scrollDisable);

            if (!isSmallBreakpoint()) {
                el.$body.css('padding-right', '');
            }

            if (type === 'cart') {
                $(el.slider).removeAttr('style').empty();
            }

            $(el.slider).addClass('d-none');
        }, 400);
    }

    function handleScroll(sliderWrap) {
        const scrollHeight = $(sliderWrap)[0].scrollHeight;
        const scrollTop = $(sliderWrap).scrollTop();
        const clientHeight = $(sliderWrap)[0].clientHeight;
        const scrollBottom = scrollHeight - scrollTop - clientHeight;

        if (scrollBottom > 75) {
            $(el.footer).addClass(el.footerFixed);
            $(sliderWrap).addClass(el.sliderWrapScroll);
        } else {
            $(el.footer).removeClass(el.footerFixed);
            $(sliderWrap).removeClass(el.sliderWrapScroll);
        }
    }

    function showSlider() {
        if (isSmallBreakpoint()) {
            adjustHeight();
        }

        const animationClass = getAnimationClass();
        const scrollBarWidth = window.innerWidth - document.documentElement.clientWidth;
        $(el.slider).removeClass('bottom-to-top right-to-left').addClass(animationClass);

        $('html, body').animate({ scrollTop: 0 }, 300, () => {
            Wick.Backdrop.show();
            $(el.slider).removeClass('d-none');

            setTimeout(() => {
                $(el.slider).addClass('show');
                handleScroll(el.sliderWrap);
                el.$body.addClass(el.scrollDisable);

                if (!isSmallBreakpoint()) {
                    el.$body.css('padding-right', `${scrollBarWidth}px`);
                }
            }, 100);
        });
    }

    function handleSliderClose(eventName) {
        return new Promise((resolve, reject) => {
            const eventDetail = { resolve, reject };
            const event = createEvent(eventName, {}, eventDetail);
            window.dispatchEvent(event);
        })
            .then(() => {})
            .catch((error) => {
                console.error(error);
            })
            .finally(() => {
                hideSlider();
                Wick.Backdrop.hide();
                if (typeof onClose === 'function') {
                    onClose();
                }
            });
    }

    function bindClosePopup() {
        $(document).on('click', el.closePopup, async () => {
            if (type === 'cart') {
                await handleSliderClose(events.CLOSE_JUST_ADDED);
            }

            if (type === 'miniBasket') {
                await handleSliderClose(events.CLOSE_MINI_BASKET);
            }

            hideSlider();
            Wick.Backdrop.hide();
        });
    }

    function handleResize() {
        const animationClass = getAnimationClass();

        if ($(el.slider).hasClass('show')) {
            $(el.slider).removeClass('bottom-to-top right-to-left').addClass(animationClass);

            if (isSmallBreakpoint()) {
                adjustHeight();
            } else {
                $(el.slider).css('height', '');
                Wick.Backdrop.show();
            }
        }
    }

    function shouldClosePopup(event) {
        const $target = $(event.target);
        return (
            !$target.closest(el.slider).length &&
            !$target.closest(el.closePopup).length &&
            $(el.slider).hasClass('show')
        );
    }

    function init() {
        bindClosePopup();

        if (onAppendEvent && onAppend) {
            window.addEventListener(onAppendEvent, (event) => {
                onAppend(event, { showSlider, handleScroll, el });
            });
        }

        $(window).on('resize', _.debounce(handleResize, 100));

        $('body').on('click', async (event) => {
            if (shouldClosePopup(event)) {
                if (type === 'cart') {
                    await handleSliderClose(events.CLOSE_JUST_ADDED);
                }

                if (type === 'miniBasket') {
                    await handleSliderClose(events.CLOSE_MINI_BASKET);
                }
            }
        });
    }

    init();

    return {
        showSlider,
        handleScroll,
    };
}
