(function ($) {
    function detectHoverAndTouch() {
        let hasHover = false;
        let lastTouchTime = 0;

        function enableHover() {
            if (new Date() - lastTouchTime < 500) return;
            $('.oea-post-grid').removeClass('touch-device');
            hasHover = true;
        }

        function disableHover() {
            $('.oea-post-grid').addClass('touch-device');
            hasHover = false;
        }

        function updateLastTouchTime() {
            lastTouchTime = new Date();
        }

        $(document).on('touchstart', updateLastTouchTime);
        $(document).on('touchstart', disableHover);
        $(document).on('mousemove', enableHover);

        enableHover();
    }

    function initPostsGridWidget(container, widgetId) {
        const elements = {
            container: container,
            loadMoreButton: $('#oea-load-more-' + widgetId),
            
            taxonomyMenuItems: $('[data-widget-id="' + widgetId + '"] .links li'),
            loadingIcon: $('[data-widget-id="' + widgetId + '"] .loading-icon'),
            widgetWrapper: $('[data-widget-id="' + widgetId + '"]'),
            taxonomyLinks: $('[data-widget-id="' + widgetId + '"] .links')
        };

        const state = {
            page: 2,
            isLoading: false,
            isLastPage: container.data('is_last_page'),
            termId: 'all',
            isTaxonomyChange: false
        };

        const config = {
            postsPerPage: elements.loadMoreButton.data('posts-per-page') || (elements.infiniteScrollTrigger && elements.infiniteScrollTrigger.data('posts-per-page')),
            orderBy: container.data('order_by'),
            order: container.data('order'),
            taxonomyType: elements.taxonomyLinks.data('taxonomy'),
            paginationType: container.data('pagination_type')
        };

        const UIManager = {
            showLoading() {
                if (!state.isTaxonomyChange) {
                    elements.loadingIcon.show();
                }
                elements.loadMoreButton.hide();
            },

            hideLoading() {
                elements.loadingIcon.hide();
                elements.loadMoreButton.show();
            },

            setLoadingOverlay(show) {
                elements.container[show ? 'addClass' : 'removeClass']('loading-overlay');
            },

            updatePaginationVisibility() {
                if (state.isLastPage) {
                    elements.loadMoreButton.hide();
                    
                    elements.loadingIcon.hide();
                } else {
                    if (config.paginationType === 'infinite_scroll') {
                        this.initInfiniteScroll();
                    }
                }
            },

            initInfiniteScroll() {
                $(window).off('scroll.widget-' + widgetId);
                if (elements.infiniteScrollTrigger && elements.infiniteScrollTrigger.length && !state.isLastPage) {
                    const scrollHandler = debounce(() => {
                        const scrollPosition = $(window).scrollTop() + $(window).height();
                        const triggerPosition = elements.infiniteScrollTrigger.offset().top;
                        if (scrollPosition >= triggerPosition) {
                            loadPosts();
                        }
                    }, 200);

                    $(window).on('scroll.widget-' + widgetId, scrollHandler);
                }
            }
        };

        const PaginationManager = {
            updateButtons(currentPage = 1) {
                const prevButton = elements.widgetWrapper.find('.prev-page-button');
                const nextButton = elements.widgetWrapper.find('.next-page-button');

                prevButton.data('page', currentPage - 1).toggle(currentPage > 1);
                nextButton.data('page', currentPage + 1).toggle(!state.isLastPage);
            },

            updateNumbered(currentPage, totalPages) {
                const paginationWrapper = $(`.oea-pagination-numbers[data-widget-id="${widgetId}"]`);
                if (!paginationWrapper.length) return;

                paginationWrapper.empty();

                const fragment = document.createDocumentFragment();
                for (let i = 1; i <= totalPages; i++) {
                    const pageLink = $('<a>', {
                        href: '#',
                        class: `oea-page-number${i === currentPage ? ' active' : ''}`,
                        'data-page': i,
                        'data-widget-id': widgetId,
                        text: i
                    })[0];
                    fragment.appendChild(pageLink);
                }
                paginationWrapper[0].appendChild(fragment);
            }
        };

        function loadPosts(customPage) {
            if (state.isLoading) return;

            state.isLoading = true;
            UIManager.showLoading();

            const pageToLoad = customPage || state.page;

            const ajaxData = {
                action: 'oradel_load_more_posts',
                security: oradel_ajax_object.security,
                page: pageToLoad,
                posts_per_page: container.data('posts_per_page'),
                order_by: config.orderBy,
                order: config.order,
                category_position: container.data('category_position'),
                categories_count: container.data('categories_count'),
                post_skin: container.data('post_skin'),
                show_image: container.data('show_image'),
                image_size: container.data('image_size'),
                tax_query: JSON.stringify(container.data('tax_query') || []),
                exclude_posts: container.data('exclude_posts') || [],
                exclude_no_image: container.data('exclude_no_image'),
                ignore_sticky_posts: container.data('ignore-sticky-posts'),
                post_elements_order: JSON.stringify(container.data('post_elements_order') || []),
                open_in_new_tab: container.data('open_in_new_tab'),
                lazy_loading: container.data('lazy_loading'),
                no_posts_text: container.data('no_posts_text'),
                taxonomy_type: config.taxonomyType,
                term_id: state.termId
            };

            $.ajax({
                url: oradel_ajax_object.ajax_url,
                type: 'POST',
                data: ajaxData,
                success: handleAjaxSuccess,
                error: handleAjaxError
            });

            function handleAjaxSuccess(response) {
                if (!response.success) {
                    elements.container.html('<div class="oea-no-posts-found">No posts found</div>');
                    UIManager.hideLoading();
                    return;
                }

                if (state.page === 1 || customPage) {
                    elements.container.html(response.data.html);
                } else {
                    elements.container.append(response.data.html);
                }

                state.page = customPage ? customPage + 1 : state.page + 1;
                state.isLastPage = response.data.is_last_page;
                state.isLoading = false;
                UIManager.hideLoading();
                UIManager.updatePaginationVisibility();
                PaginationManager.updateButtons(customPage || state.page - 1);
                PaginationManager.updateNumbered(pageToLoad, response.data.total_pages);

                if (typeof window.initMobileCardsScrollAnimation === 'function') {
                    setTimeout(window.initMobileCardsScrollAnimation, 100);
                }

                finishLoading();
            }

            function handleAjaxError() {
                state.isLoading = false;
                UIManager.hideLoading();
                finishLoading();
            }

            function finishLoading() {
                UIManager.setLoadingOverlay(false);
                state.isTaxonomyChange = false;
            }
        }

        function handleTaxonomyClick(e) {
            e.preventDefault();

            elements.taxonomyMenuItems.removeClass('active');
            $(this).addClass('active');

            state.termId = $(this).data('term-id');
            state.page = 1;
            state.isTaxonomyChange = true;

            elements.loadingIcon.hide();
            UIManager.setLoadingOverlay(true);
            elements.loadMoreButton.show();

            loadPosts();
        }

        function handlePageNumberClick(e) {
            e.preventDefault();
            const targetPage = $(this).data('page');
            UIManager.setLoadingOverlay(true);
            loadPosts(targetPage);
        }

        function handlePaginationButtonClick(e) {
            e.preventDefault();
            const targetPage = $(this).data('page');
            UIManager.setLoadingOverlay(true);
            loadPosts(targetPage);
        }

        function handleLoadMoreClick(e) {
            e.preventDefault();
            loadPosts();
        }

        function initEvents() {
            elements.taxonomyMenuItems.on('click', handleTaxonomyClick);
            elements.widgetWrapper.on('click', '.oea-page-number', handlePageNumberClick);
            elements.widgetWrapper.on('click', '.prev-page-button, .next-page-button', handlePaginationButtonClick);
            elements.loadMoreButton.on('click', handleLoadMoreClick);
        }

        function init() {
            if (config.paginationType === 'infinite_scroll') {
                UIManager.initInfiniteScroll();
            }
            initEvents();
        }

        init();
    }

    function initializePostGrids() {
        $('[id^="oea-posts-"]').each(function () {
            const container = $(this);
            const widgetId = container.attr('id').replace('oea-posts-', '');
            initPostsGridWidget(container, widgetId);
        });
    }

    $(document).ready(initializePostGrids);
    $(document).ready(detectHoverAndTouch);

    if (window.elementorFrontend && elementorFrontend.hooks && typeof elementorFrontend.hooks.addAction === 'function') {
        elementorFrontend.hooks.addAction('frontend/element_ready/global', function ($scope) {
            $scope.find('[id^="oea-posts-"]').each(function () {
                const container = $(this);
                const widgetId = container.attr('id').replace('oea-posts-', '');
                initPostsGridWidget(container, widgetId);
            });
        });
    }

})(jQuery);