jQuery(document).ready(function ($) {
    const $masonryContainer = $('.masonry-container');
    
    if ($masonryContainer.length === 0) {
        return;
    }

    function applyRandomHeights($items) {
        const heights = [240, 280, 320, 360, 400, 450, 500];
        
        const $images = $items ? $items.find('.masonry-item-image') : $('.masonry-item-image');
        
        $images.each(function() {
            const randomHeight = heights[Math.floor(Math.random() * heights.length)];
            $(this).css('height', randomHeight + 'px');
        });
    }

    function initMasonry() {
        applyRandomHeights();
        
        $masonryContainer.imagesLoaded(function () {
            $masonryContainer.masonry({
                itemSelector: '.masonry-item',
                columnWidth: '.masonry-item',
                percentPosition: true,
                gutter: 21
            });
        });
    }

    initMasonry();

    $(window).on('resize', function() {
        $masonryContainer.masonry('layout');
    });

    $(document).on('aurora:postsAppended', function (e, $newItems) {
        
        applyRandomHeights($newItems);
        $newItems.imagesLoaded(function () {
            $masonryContainer.append($newItems).masonry('appended', $newItems);
            $masonryContainer.masonry('layout');
        });
    });
});