//IMPORTANT: This need a fix on the isotope file to work in the elementor preview. See https://github.com/elementor/elementor/issues/6756
/*You need to comment the following files on the isotope file:
// check that elem is an actual element
    /*if ( !( elem instanceof HTMLElement ) ) {
      return;
}*/
function startElemenfolio(){

    jQuery('#elementor-preview-iframe').contents().find('.elpt-portfolio-content-isotope').imagesLoaded( function() {
        // IMPORTANT: Use :not(.elpt-portfolio-content-isotope-pro) to prevent double Isotope
        // initialization. Elements with -pro class are handled by $container for pagination.

        //Masonry (without pagination)
        var $grid = jQuery('#elementor-preview-iframe').contents().find('.elpt-portfolio-content-isotope:not(.elpt-portfolio-content-isotope-pro)').isotope({
            itemSelector: '.portfolio-item-wrapper',
            layoutMode: 'masonry',
        });
        //Packery (without pagination)
        var $packery = jQuery('#elementor-preview-iframe').contents().find('.elpt-portfolio-content-packery:not(.elpt-portfolio-content-isotope-pro)').isotope({
            layoutMode: 'packery',
            itemSelector: '.portfolio-item-wrapper'
        });

        //fitRows (for Special Grid 7 - Alternate Rows 1, without pagination)
        var $fitrows = jQuery('#elementor-preview-iframe').contents().find('.elpt-portfolio-content-fitrows:not(.elpt-portfolio-content-isotope-pro)').isotope({
            layoutMode: 'fitRows',
            itemSelector: '.portfolio-item-wrapper'
        });

        $fitrows.imagesLoaded().progress( function() {
            $fitrows.isotope('layout');
        });

        /*
        * Paginated Isotope
        */
        var itemSelector = ".portfolio-item-wrapper";

        // Detect layout mode based on classes
        var $containerElement = jQuery('#elementor-preview-iframe').contents().find('.elpt-portfolio-content-isotope-pro');
        var layoutMode = 'masonry'; // default

        if ($containerElement.hasClass('elpt-portfolio-content-fitrows')) {
            layoutMode = 'fitRows';
        } else if ($containerElement.hasClass('elpt-portfolio-content-packery')) {
            layoutMode = 'packery';
        }

        var $container = $containerElement.isotope({
            layoutMode: layoutMode,
            itemSelector: itemSelector
        });

        $container.imagesLoaded().progress( function() {
            $container.isotope('layout');
        });

        // Pagination Variables
        var itemsPerPageDefault = jQuery('#elementor-preview-iframe').contents().find('#powerfolio_pagination_postsperpage').val();
        if (itemsPerPageDefault === undefined) {
            itemsPerPageDefault = 10;
        }

        var itemsPerPage = defineItemsPerPage();
        var currentNumberPages = 1;
        var currentPage = 1;
        var currentFilter = '*';
        var filterAtribute = 'data-filter';
        var pageAtribute = 'data-page';
        var pagerClass = 'isotope-pager';

        // Resize handler - simplified for editor preview
        // Note: In editor preview, filters are not interactive, so we just refresh layout
        jQuery(window).resize(function(){
            if ($container.length > 0) {
                goToPage(currentPage);
            } else {
                $grid.isotope('layout');
                $packery.isotope('layout');
                $fitrows.isotope('layout');
            }
        });

        // update items based on current filters
        function changeFilter(selector) {
            $container.isotope({ filter: selector }
        ); }


        function getFilterSelector() {
            var selector = itemSelector;
            if (currentFilter != '*') {
              selector += currentFilter;
            }
            return selector;
        }

        function goToPage(n) {
            currentPage = n;

            var selector = getFilterSelector();
            selector += `[${pageAtribute}="${currentPage}"]`;

            changeFilter(selector);
        }

        function defineItemsPerPage() {
            var pages = itemsPerPageDefault;

            return pages;
        }

        function setPagination() {
            var SettingsPagesOnItems = function() {
                var itemsLength = $container.children(itemSelector).length;
                var pages = Math.ceil(itemsLength / itemsPerPage);
                var item = 1;
                var page = 1;
                var selector = getFilterSelector();

                $container.children(selector).each(function(){
                    if (item > itemsPerPage) {
                        page++;
                        item = 1;
                    }
                    jQuery(this).attr(pageAtribute, page);
                    item++;
                });

                currentNumberPages = page;
            }();

            var CreatePagers = function() {
                var $isotopePager = jQuery('#elementor-preview-iframe').contents().find('.' + pagerClass);
                if ($isotopePager.length === 0) {
                    $isotopePager = jQuery('<div class="' + pagerClass + '"></div>');
                    $container.after($isotopePager);
                } else {
                    $isotopePager.html(''); // Clear existing pagination
                }

                for (var i = 0; i < currentNumberPages; i++) {
                    var $pager = jQuery('<a href="javascript:void(0);" class="pager" ' + pageAtribute + '="' + (i + 1) + '"></a>');
                    $pager.html(i + 1);

                    $pager.click(function() {
                        //var page = jQuery(this).eq(0).attr(pageAtribute);
                        //goToPage(page);
                    });

                    $pager.appendTo($isotopePager);
                }
            }();
        }


        setPagination();
        goToPage(1);
   });
}

jQuery(window).on('load', function(){
    elementorFrontend.hooks.addAction('frontend/element_ready/widget', function($scope){
        startElemenfolio();
    });

    setInterval(function() {
		startElemenfolio();
	}, 1000);
});
