!(function ($, elementor) {
  "use strict";

  var widgetPostMasonryGrid = function ($scope, $) {
    var $grid = $scope.find(".tx-post-masonry-grid-wrap");

    if (!$grid.length) return;

    // Read data attributes from wrapper
    var layoutMode = $grid.data("layout") || "fitRows";
    var paginationType = $grid.data("pagination") || "none";
    var noPostText = $grid.data("no-post-text") || "NO MORE POSTS";
    var loadingGif = $grid.data("loading-gif") || "";

    // ----- Init Isotope -----
    $grid.imagesLoaded(function () {
      $grid.isotope({
        itemSelector: ".tx-post-masonry-grid-item",
        percentPosition: true,
        layoutMode: layoutMode,
      });

      $grid.find(".tx-post-masonry-grid-item").addClass("tx-isotope-animation-start");

      // ✅ Force re-layout after all images are loaded
      setTimeout(function () {
        $grid.isotope("layout");
      }, 300);
    });

    // ----- Infinite Scroll / Load More -----
    if (paginationType === "infinite" || paginationType === "load-more") {
      $grid.infinitescroll(
        {
          errorCallback: function () {
            $scope.find(".tx-post-infinite").delay(500).fadeOut(500, function () {
              $(this).remove();
            });
          },
          navSelector: ".tx-post-infinite",
          nextSelector: ".tx-post-infinite .tx-post-nav-previous a",
          itemSelector: ".tx-post-masonry-grid-item",
          loading: {
            img: loadingGif,
            msgText: "",
            finishedMsg: "<div id='tx-no-more-posts'>" + noPostText + "</div>",
            speed: 0,
          },
        },
        function (newElements) {
          var $newElems = $(newElements);
          $newElems.imagesLoaded(function () {
            $grid.isotope("appended", $newElems);
            $newElems.addClass("tx-isotope-animation-start");

            // ✅ Force re-layout after new elements
            $grid.isotope("layout");
          });

          // ✅ Keep button visible in load-more mode
          if (paginationType === "load-more") {
            $scope.find(".tx-post-infinite").show();
          }
        }
      );

      // For Load More (pause auto)
      if (paginationType === "load-more") {
        $(window).off(".infscr"); // prevent auto-trigger
        $scope.find(".tx-post-infinite .tx-post-nav-previous a").on("click", function (e) {
          e.preventDefault();
          $grid.infinitescroll("retrieve");
          $scope.find(".tx-post-infinite").show();

          // ✅ Ensure layout refresh after button click
          setTimeout(function () {
            $grid.isotope("layout");
          }, 300);
        });
      }
    }
  };

  $(window).on("elementor/frontend/init", function () {
    elementorFrontend.hooks.addAction(
      "frontend/element_ready/avas-post-masonry-grid.default",
      widgetPostMasonryGrid
    );
  });
})(jQuery, window.elementorFrontend);