(function ($) {
  function isSlideTextElement(el) {
    return el.className && el.className.indexOf("bb-animate--slide_text") !== -1;
  }

  $(document).ready(() => {
    $(".bb-animate").each((_, el) => {
      function loadedAnimation() {
        $(el).addClass("bb-animated");
        $(el).removeClass("bb-animating");
      }

      function getAnimationEndTarget() {
        if (isSlideTextElement(el)) {
          var words = el.querySelectorAll(".bb-word");
          return words.length > 0 ? words[words.length - 1] : el;
        }
        return el;
      }

      var observer = new IntersectionObserver((entries) => {
        entries.forEach((entry) => {
          if (!entry.target) return;
          var isOnce = entry.target.classList.contains("bb-animate-once");

          if (entry.isIntersecting) {
            // Element entered viewport — trigger animation
            var endTarget = getAnimationEndTarget();
            endTarget.removeEventListener("animationend", loadedAnimation);
            endTarget.addEventListener("animationend", loadedAnimation);
            // Force-restart CSS animation: pause → reflow → play
            entry.target.classList.add("bb-animated");
            void entry.target.offsetWidth;
            entry.target.classList.remove("bb-animated");
            entry.target.classList.add("bb-animating");
            if (isOnce) {
              observer.unobserve(entry.target);
            }
          } else {
            // Element left viewport — reset for replay (non-once only)
            if (!isOnce) {
              entry.target.classList.remove("bb-animating");
              entry.target.classList.remove("bb-animated");
            }
          }
        });
      });
      observer.observe(el);
    });
  });

  function updateScale(el, { initialScale, finalScale, type }) {
    const rect = el.getBoundingClientRect();

    if (rect.top > window.innerHeight || rect.bottom < 0) return;

    const triggerPoint = window.innerHeight - 50;

    if (rect.top < triggerPoint) {
      const progress =
        type === "down"
          ? Math.min((triggerPoint - rect.top) / rect.height, 1)
          : Math.max((triggerPoint - rect.top) / rect.height, 0);
      const currentScale =
        initialScale - (initialScale - finalScale) * progress;
      el.style.transform = `scale(${currentScale})`;
    } else {
      el.style.transform = `scale(${initialScale})`;
    }
  }

  $(document).on("scroll", (e) => {
    $(".bb-animate--scale_up").each((_, el) => {
      updateScale(el, {
        initialScale: 1,
        finalScale: $(el).data("animation-scale") ?? 1,
        type: "up",
      });
    });
    $(".bb-animate--scale_down").each((_, el) => {
      updateScale(el, {
        initialScale: $(el).data("animation-scale") ?? 1,
        finalScale: 1,
        type: "down",
      });
    });
  });
})(window.jQuery);
