(function ($) {

    "use strict";

    $(window).on('elementor/frontend/init', function () {
        setTimeout(function () {
           
            $('.pxl-grid').each(function (index, element) {
                var $grid_scope = $(this);
                var isoOptions = {};
                var dataLayout = $grid_scope.attr('data-layout');
                var layoutMode = dataLayout && dataLayout !== '' ? dataLayout : 'masonry';

                if ($grid_scope.hasClass('pxl-post-list')) {
                    var $grid_isotope = null;
                } else {
                    var $grid_masonry = $grid_scope.find('.pxl-grid-masonry');
                    isoOptions = {
                        itemSelector: '.pxl-grid-item',
                        layoutMode: layoutMode,
                        fitRows: {
                            gutter: 0
                        },
                        percentPosition: true,
                        masonry: {
                            columnWidth: '.grid-sizer',
                        },
                        containerStyle: null,
                        stagger: 30,
                        sortBy: 'name',
                    };
                    if ($grid_masonry.length && typeof $.fn.isotope !== 'undefined') {
                        var $grid_isotope = $grid_masonry.isotope(isoOptions);
                        $grid_isotope.imagesLoaded().progress(function () {
                            $grid_isotope.isotope('layout');
                        });

                    } else {
                        var $grid_isotope = null;
                    }
                }

                $grid_scope.on('click', '.pxl-grid-filter .filter-item', function (e) {
                    var $this = $(this);
                    var term_slug = $this.attr('data-filter');

                    $this.siblings('.filter-item.active').removeClass('active');
                    $this.addClass('active');
                    $grid_scope.find('.pxl-post--inner').removeClass('animated');

                    if ($this.closest('.pxl-grid-filter').hasClass('ajax')) {
                        var loadmore = $grid_scope.data('loadmore');
                        if (loadmore) {
                            loadmore.term_slug = term_slug;
                            clinara_grid_ajax_handler($this, $grid_scope, $grid_isotope,
                                { action: 'clinara_load_more_post_grid', loadmore: loadmore, iso_options: isoOptions, handler_click: 'filter', scrolltop: 0 }
                            );
                        } else {
                            console.warn('Loadmore data is undefined for filter click.');
                        }
                    } else {
                        if ($grid_isotope) {
                            $grid_isotope.isotope({ filter: term_slug });
                        }
                    }
                });

                $grid_scope.on('click', '.pxl-grid-pagination .ajax a.page-numbers', function (e) {
                    e.preventDefault();
                    e.stopPropagation();
                    var $this = $(this);
                    var loadmore = $grid_scope.data('loadmore');
                    var paged = $this.attr('href');
                    paged = paged.replace('#', '');
                    loadmore.paged = parseInt(paged);
                    clinara_grid_ajax_handler($this, $grid_scope, $grid_isotope,
                        { action: 'clinara_load_more_post_grid', loadmore: loadmore, iso_options: isoOptions, handler_click: 'pagination', scrolltop: 0, wpnonce: main_params.wpnonce }
                    );
                    $('html,body').animate({ scrollTop: $grid_scope.offset().top - 130 }, 500);
                });

                $grid_scope.on('click', '.btn-grid-loadmore', function (e) {
                    e.preventDefault();
                    var $this = $(this);
                    var loadmore = $grid_scope.data('loadmore');
                    if (loadmore) {
                        loadmore.paged = parseInt($grid_scope.data('start-page')) + 1;

                        clinara_grid_ajax_handler($this, $grid_scope, $grid_isotope,
                            { action: 'clinara_load_more_post_grid', loadmore: loadmore, iso_options: isoOptions, handler_click: 'loadmore', scrolltop: 0, wpnonce: main_params.wpnonce }
                        );
                    } else {
                        console.warn('Loadmore data is undefined for loadmore button click.');
                    }
                });

                $grid_scope.on('change', '.orderby', function (e) {
                    e.preventDefault();
                    var $this = $(this);
                    var loadmore = $grid_scope.data('loadmore');
                    if (loadmore) {
                        loadmore.orderby = $this.val();

                        clinara_grid_ajax_handler($this, $grid_scope, $grid_isotope,
                            { action: 'clinara_load_more_post_grid', loadmore: loadmore, iso_options: isoOptions, handler_click: 'select_orderby', scrolltop: 0 }
                        );
                    } else {
                        console.warn('Loadmore data is undefined for orderby change.');
                    }
                });
            });
            function clinara_grid_ajax_handler($this, $grid_scope, $grid_isotope, args = {}) {
                var settings = $.extend(true, {}, {
                    action: '',
                    loadmore: '',
                    iso_options: {},
                    handler_click: '',
                    scrolltop: 0
                }, args);

                var offset_top = $grid_scope.offset().top;

                if (settings.handler_click == 'loadmore') {
                    var loadmore_text = $this.closest('.pxl-load-more').data('loadmore-text');
                    var loading_text = $this.closest('.pxl-load-more').data('loading-text');

                }

                $.ajax({
                    url: main_params.ajax_url,
                    type: 'POST',
                    data: {
                        action: settings.action,
                        settings: settings.loadmore,
                        handler_click: settings.handler_click,
                        wpnonce: main_params.wpnonce
                    },
                    success: function (res) {
                        if (res.status == true) {
                            if (settings.handler_click == 'loadmore') {
                                if (settings.loadmore && settings.loadmore.wg_type == 'post-list') {
                                    $grid_scope.find('.pxl-list-inner').append(res.data.html);
                                } else {
                                    $grid_scope.find('.pxl-grid-inner').append(res.data.html);
                                }
                            } else {
                                if (settings.loadmore && settings.loadmore.wg_type == 'post-list') {
                                    $grid_scope.find('.pxl-list-inner .list-item').remove();
                                    $grid_scope.find('.pxl-list-inner').append(res.data.html);
                                } else {
                                    // Remove old items and insert new ones for filter/pagination
                                    if ($grid_isotope) {
                                        var $newItems = $(res.data.html);
                                        $grid_isotope.isotope('remove', $grid_isotope.isotope('getItemElements'))
                                            .isotope('insert', $newItems);

                                        $newItems.imagesLoaded().progress(function () {
                                            $grid_isotope.isotope('layout');
                                        });
                                    } else {
                                        $grid_scope.find('.pxl-grid-inner').html(res.data.html); // Fallback if Isotope not initialized
                                    }
                                }
                            }

                            if (settings.iso_options && $grid_isotope && settings.handler_click == 'loadmore') {
                                var $newItems = $(res.data.html);
                                $grid_scope.find('.pxl-grid-inner').append($newItems);
                                $grid_isotope.isotope('appended', $newItems);
                                $newItems.imagesLoaded().progress(function () {
                                    $grid_isotope.isotope('layout');
                                });
                            }


                            $grid_scope.data('start-page', res.data.paged);

                            if (settings.loadmore && settings.loadmore['pagination_type'] == 'loadmore') {
                                if (res.data.paged >= res.data.max) {
                                    $grid_scope.find('.pxl-load-more').hide();
                                } else {
                                    $grid_scope.find('.pxl-load-more').show();
                                }
                            }
                            if (settings.loadmore && settings.loadmore['pagination_type'] == 'pagination') {
                                $grid_scope.find(".pxl-grid-pagination").html(res.data.pagin_html);
                            }

                            if ($grid_scope.find('.result-count').length > 0) {
                                $grid_scope.find(".result-count").html(res.data.result_count);
                            }
                        }
                    },
                    beforeSend: function () {
                        $grid_scope.find('.pxl-grid-overlay-loading').removeClass('loaded').addClass('loader');
                        if (settings.handler_click == 'loadmore') {
                            $this.find('.pxl-loadmore-text').text(loading_text);
                            $this.parent().addClass('loading');
                        }
                    },
                    complete: function () {
                        $grid_scope.find('.pxl-grid-overlay-loading').removeClass('loader').addClass('loaded');
                        if (settings.handler_click == 'loadmore') {
                            $this.find('.pxl-loadmore-text').text(loadmore_text);
                            $this.parent().removeClass('loading');
                        }
                        if (settings.scrolltop) {
                            $('html, body').animate({ scrollTop: offset_top - 100 }, 0);
                        }
                        if (typeof elementorFrontend !== 'undefined') {
                            elementorFrontend.elements.$body.trigger('pxl/grid/ajax_loaded');
                            elementorFrontend.init();
                        }
                    }
                });
            }
        }, 150);
    });

})(jQuery);