jQuery(document).ready(function ($) {
    $('.oea-icon-menu-wrapper').each(function () {
        const $wrapper = $(this);
        const $container = $wrapper.find('.menu-container');
        if ($container.length) {
            initIconMenu($container, $wrapper);
        }
    });

    $('.menu-container').each(function () {
        const $container = $(this);
        if (!$container.closest('.oea-icon-menu-wrapper').length) {
            initIconMenu($container, null);
        }
    });

    function initIconMenu($container, $wrapper) {
        const $slides = $container.find('.slides');
        let $dots = $container.find('.dot');
        const $navigationArrows = $wrapper ? $wrapper.find('.navigation-arrows') : null;

        const itemsDesktop = parseInt($container.data('items-desktop')) || 10;
        const itemsTablet = parseInt($container.data('items-tablet')) || 8;
        const itemsMobile = parseInt($container.data('items-mobile')) || 9;
        const totalItems = parseInt($container.data('total-items')) || 0;
        const menuVersion = $container.data('menu-version') || 'v1';

        let currentSlide = 0;
        let totalSlides = 1;
        let itemsPerSlide = itemsDesktop;

        function getCurrentDevice() {
            const width = $(window).width();
            if (width <= 767) return 'mobile';
            if (width <= 1024) return 'tablet';
            return 'desktop';
        }

        function setSlidesHeight(h) {
            if (h && h > 0) {
                $slides.css({
                    'height': h + 'px'
                });
                if ($navigationArrows && $navigationArrows.length) {
                    const paddingTop = parseInt($container.css('padding-top'), 10) || 0;
                    $navigationArrows.css('top', (h / 2) + paddingTop + 'px');
                }
            }
        }

        function updateSlidesHeight() {
            let $current;

            if (menuVersion === 'v2') {
                const device = getCurrentDevice();
                $current = $slides.find(`.slide-${device}[data-slide="${currentSlide}"]`);
            } else {
                $current = $slides.find('.slide').eq(currentSlide);
            }

            if ($current.length) {
                const h = $current.outerHeight(true);
                setSlidesHeight(h);
            }
        }

        function precalculateSlideHeights() {
            if (menuVersion !== 'v2') return;

            const device = getCurrentDevice();
            const heights = {};

            $slides.find(`.slide-${device}`).each(function () {
                const slideIndex = $(this).data('slide');
                const height = $(this).outerHeight(true);
                if (height > 0) {
                    heights[slideIndex] = height;
                }
            });

            return heights;
        }

        function calculateSlides() {
            const device = getCurrentDevice();

            switch (device) {
                case 'mobile':
                    itemsPerSlide = itemsMobile;
                    break;
                case 'tablet':
                    itemsPerSlide = itemsTablet;
                    break;
                default:
                    itemsPerSlide = itemsDesktop;
            }

            totalSlides = Math.ceil(totalItems / itemsPerSlide);
            return totalSlides;
        }

        function initV2Navigation() {
            const device = getCurrentDevice();
            const $deviceSlides = $slides.find(`.slide-${device}`);
            totalSlides = $deviceSlides.length;

            const $dotsContainer = $container.find('.dots');
            if ($dotsContainer.length) {
                if (totalSlides > 1) {
                    $dotsContainer.show();
                } else {
                    $dotsContainer.hide();
                }
            }

            const slideHeights = precalculateSlideHeights();

            if (currentSlide >= totalSlides) {
                currentSlide = Math.max(0, totalSlides - 1);
            }

            goToSlide(currentSlide);

            setTimeout(() => {
                updateSlidesHeight();
                updateArrowStates();
            }, 50);
        }

        function reorganizeSlides() {
            

            const wasAnimated = $container.hasClass('oea-is-animated');
            const previousSlide = currentSlide;
            calculateSlides();

            const $allItems = $container.find('.menu-item').detach();
            $slides.empty();

            for (let i = 0; i < totalSlides; i++) {
                const $slide = $('<div class="slide" data-slide="' + i + '"></div>');
                const startIndex = i * itemsPerSlide;
                const endIndex = Math.min(startIndex + itemsPerSlide, totalItems);

                for (let j = startIndex; j < endIndex; j++) {
                    if ($allItems[j]) {
                        $slide.append($allItems[j]);
                    }
                }
                $slides.append($slide);
            }

            if (wasAnimated) {
                $slides.find('.menu-item').css({
                    'opacity': '1',
                    'transform': 'none',
                    'visibility': 'visible',
                    'animation': 'none'
                });
            }

            const $dotsContainer = $container.find('.dots');
            if ($dotsContainer.length) {
                $dotsContainer.empty();
                if (totalSlides > 1) {
                    currentSlide = Math.min(previousSlide, totalSlides - 1);
                    for (let i = 0; i < totalSlides; i++) {
                        const activeClass = i === currentSlide ? ' active' : '';
                        $dotsContainer.append('<span class="dot' + activeClass + '" data-slide="' + i + '"></span>');
                    }
                    $dots = $dotsContainer.find('.dot');
                    $dotsContainer.show();
                } else {
                    $dotsContainer.hide();
                }
            } else {
                currentSlide = Math.min(previousSlide, totalSlides - 1);
            }

            goToSlide(currentSlide);
            updateSlidesHeight();
            updateArrowStates();
        }

        const isElementorEditor = $('body').hasClass('elementor-editor-active');

        reorganizeSlides();

        if (isElementorEditor) {
            $container.addClass('js-loaded');
            updateSlidesHeight();
            updateArrowStates();
        } else {
            setTimeout(() => {
                $container.addClass('js-loaded');
                updateSlidesHeight();
                updateArrowStates();
            }, 100);
        }

        $container.on('click', '.dot', function () {
            const slideIndex = parseInt($(this).data('slide'));
            goToSlide(slideIndex);
        });

        if ($wrapper && $wrapper.length) {
            $wrapper.on('click', '.nav-arrow-prev', function () {
                if (currentSlide > 0) {
                    goToSlide(currentSlide - 1);
                }
            });

            $wrapper.on('click', '.nav-arrow-next', function () {
                if (currentSlide < totalSlides - 1) {
                    goToSlide(currentSlide + 1);
                }
            });
        }

        function goToSlide(slideIndex) {
            if (slideIndex < 0 || slideIndex >= totalSlides) {
                return;
            }

            currentSlide = slideIndex;

            const translateX = -slideIndex * 100;

            

            requestAnimationFrame(() => {
                $slides.css('transform', `translateX(${translateX}%)`);
            });

            $container.find('.dot').removeClass('active');
            $container.find('.dot').eq(slideIndex).addClass('active');

            updateArrowStates();

            if (menuVersion !== 'v2') {
                updateSlidesHeight();
            }
        }

        function updateArrowStates() {
            if (!$wrapper || !$wrapper.length) return;

            const $prevArrow = $wrapper.find('.nav-arrow-prev');
            const $nextArrow = $wrapper.find('.nav-arrow-next');

            if ($prevArrow.length && $nextArrow.length) {
                if (currentSlide <= 0) {
                    $prevArrow.prop('disabled', true).attr('aria-disabled', 'true');
                } else {
                    $prevArrow.prop('disabled', false).attr('aria-disabled', 'false');
                }

                if (currentSlide >= totalSlides - 1) {
                    $nextArrow.prop('disabled', true).attr('aria-disabled', 'true');
                } else {
                    $nextArrow.prop('disabled', false).attr('aria-disabled', 'false');
                }
            }
        }

        let startX = 0;
        let startY = 0;
        let isDragging = false;
        let isHorizontalSwipe = false;

        $container.on('touchstart', function (e) {
            if (totalSlides <= 1) return;
            startX = e.touches[0].clientX;
            startY = e.touches[0].clientY;
            isDragging = true;
            isHorizontalSwipe = false;
        });

        $container.on('touchmove', function (e) {
            if (!isDragging) return;

            const currentX = e.touches[0].clientX;
            const currentY = e.touches[0].clientY;
            const diffX = Math.abs(currentX - startX);
            const diffY = Math.abs(currentY - startY);

            if (!isHorizontalSwipe && diffX < 10 && diffY < 10) {
                return;
            }

            if (!isHorizontalSwipe) {
                isHorizontalSwipe = diffX > diffY;
            }

            if (isHorizontalSwipe) {
                e.preventDefault();
            }
        });

        $container.on('touchend touchcancel', function (e) {
            if (!isDragging || totalSlides <= 1) {
                isDragging = false;
                isHorizontalSwipe = false;
                return;
            }

            if (e.type === 'touchend' && e.changedTouches && e.changedTouches.length > 0) {
                const endX = e.changedTouches[0].clientX;
                const diffX = startX - endX;

                if (isHorizontalSwipe && Math.abs(diffX) > 50) {
                    if (diffX > 0 && currentSlide < totalSlides - 1) {
                        goToSlide(currentSlide + 1);
                    } else if (diffX < 0 && currentSlide > 0) {
                        goToSlide(currentSlide - 1);
                    }
                }
            }

            isDragging = false;
            isHorizontalSwipe = false;
        });

        let isMouseDown = false;
        let mouseStartX = 0;

        $container.on('mousedown', function (e) {
            if (totalSlides <= 1) return;
            mouseStartX = e.clientX;
            isMouseDown = true;
            $container.css('cursor', 'grabbing');
        });

        $(document).on('mousemove', function (e) {
            if (!isMouseDown) return;
            e.preventDefault();
        });

        $(document).on('mouseup', function (e) {
            if (!isMouseDown || totalSlides <= 1) return;

            const mouseEndX = e.clientX;
            const diffX = mouseStartX - mouseEndX;

            if (Math.abs(diffX) > 50) {
                if (diffX > 0 && currentSlide < totalSlides - 1) {
                    goToSlide(currentSlide + 1);
                } else if (diffX < 0 && currentSlide > 0) {
                    goToSlide(currentSlide - 1);
                }
            }

            isMouseDown = false;
            $container.css('cursor', 'grab');
        });

        $container.on('keydown', function (e) {
            if (totalSlides <= 1) return;
            if (e.key === 'ArrowLeft' && currentSlide > 0) {
                goToSlide(currentSlide - 1);
            } else if (e.key === 'ArrowRight' && currentSlide < totalSlides - 1) {
                goToSlide(currentSlide + 1);
            }
        });

        let resizeTimeout;
        $(window).on('resize', function () {
            clearTimeout(resizeTimeout);
            resizeTimeout = setTimeout(function () {
                reorganizeSlides();
                updateSlidesHeight();
            }, 250);
        });
    }
});
