(function ($) {
    'use strict';

    function initComparisonTableScroll() {
        const wrappers = document.querySelectorAll('.oea-comparison-table-wrapper');

        wrappers.forEach(function (wrapper) {

            const hasHorizontalScroll = wrapper.scrollWidth > wrapper.clientWidth;

            if (!hasHorizontalScroll) {
                return;
            }

            let isScrolling = false;

            wrapper.addEventListener('wheel', function (e) {
                const hasHorizontalScroll = wrapper.scrollWidth > wrapper.clientWidth;
                if (!hasHorizontalScroll) return;

                const canScrollVertically = wrapper.scrollHeight > wrapper.clientHeight;

                if (e.shiftKey || (!canScrollVertically && Math.abs(e.deltaY) > Math.abs(e.deltaX))) {
                    e.preventDefault();

                    wrapper.scrollLeft += e.deltaY;
                    isScrolling = true;

                    setTimeout(function () {
                        isScrolling = false;
                    }, 150);
                }
            }, { passive: false });

            let isDown = false;
            let startX;
            let scrollLeft;

            wrapper.addEventListener('mousedown', function (e) {
                if (e.target.tagName === 'A' || e.target.closest('a')) {
                    return;
                }
                isDown = true;
                wrapper.classList.add('is-dragging');
                startX = e.pageX - wrapper.offsetLeft;
                scrollLeft = wrapper.scrollLeft;
            });

            wrapper.addEventListener('mouseleave', function () {
                isDown = false;
                wrapper.classList.remove('is-dragging');
            });

            wrapper.addEventListener('mouseup', function () {
                isDown = false;
                wrapper.classList.remove('is-dragging');
            });

            wrapper.addEventListener('mousemove', function (e) {
                if (!isDown) return;
                e.preventDefault();
                const x = e.pageX - wrapper.offsetLeft;
                const walk = (x - startX) * 2;
                wrapper.scrollLeft = scrollLeft - walk;
            });
        });
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initComparisonTableScroll);
    } else {
        initComparisonTableScroll();
    }

    if (typeof elementorFrontend !== 'undefined') {
        elementorFrontend.hooks.addAction('frontend/element_ready/oradel_comparison_table.default', function ($scope) {
            setTimeout(initComparisonTableScroll, 100);
        });
    }

})(jQuery);

