"use strict";

(function ($, w) {
  "use strict";

  var $window = $(w);
  function lerp(a, b, n) {
    return (1 - n) * a + n * b;
  }
  function getDistance(x1, y1, x2, y2) {
    return Math.hypot(x2 - x1, y2 - y1);
  }
  function getPointerPos(ev, container) {
    if (!ev) return {
      x: 0,
      y: 0
    };
    if (container) {
      var rect = container.getBoundingClientRect();
      return {
        x: ev.clientX - rect.left,
        y: ev.clientY - rect.top
      };
    }
    return {
      x: ev.clientX,
      y: ev.clientY
    };
  }
  function getTrailData($scope) {
    var data = $scope.data('ha-image-trails');
    if (data) return data;
    var $el = $scope.find('.ha-it-content[data-ha-image-trails]');
    if (!$el.length) $el = $scope.children('.ha-it-content[data-ha-image-trails]');
    if (!$el.length) $el = $scope.parent().find('.ha-it-content[data-ha-image-trails]');
    if ($el.length) {
      try {
        return JSON.parse($el.attr('data-ha-image-trails'));
      } catch (e) {}
    }
    return null;
  }
  function buildImagesHtml(images) {
    var html = '';
    for (var i = 0; i < images.length; i++) {
      html += '<div class="ha-it-content__img"><div class="ha-it-content__img-inner" style="background-image:url(' + images[i] + ')"></div></div>';
    }
    return html;
  }
  function ensureContent($scope, images) {
    var $content = $scope.find('.ha-it-content');
    if (!$content.length) {
      $content = $('<div class="ha-it-content">' + buildImagesHtml(images) + '</div>');
      $scope.prepend($content);
    } else if (!$content.find('.ha-it-content__img').length) {
      $content.html(buildImagesHtml(images));
    }
    return $content;
  }
  function playFallingAnimation(img, containerHeight, rotationDuration) {
    var fallDist = containerHeight + 200;
    gsap.timeline().from(img, {
      opacity: 0,
      scale: 0,
      ease: "elastic.out(1,0.3)"
    }).to(img, {
      rotation: "random([-360, 360])",
      duration: rotationDuration,
      ease: "power1"
    }, "<").to(img, {
      y: "+=" + fallDist,
      ease: "back.in(.4)",
      duration: 1
    }, 0);
  }
  $window.on("elementor/frontend/init", function () {
    var ImageTrailsHandler = function ImageTrailsHandler($scope) {
      if (!$scope.hasClass("ha-it-yes")) return;
      var trailData = getTrailData($scope);
      if (!trailData || !trailData.images || !trailData.images.length) return;
      var editMode = elementorFrontend.isEditMode();
      if (editMode && !trailData.showInEditor) return;
      var isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
      if (trailData.disableMobile && isMobile) return;
      if ($scope.data('ha-it-initialized')) {
        var oldTrail = $scope.data('ha-it-trail-instance');
        if (oldTrail && typeof oldTrail.destroy === 'function') oldTrail.destroy();
        var oldCursor = $scope.data('ha-it-cursor-instance');
        if (oldCursor && typeof oldCursor.destroy === 'function') oldCursor.destroy();
        $scope.removeData('ha-it-initialized');
        $scope.removeData('ha-it-trail-instance');
        $scope.removeData('ha-it-cursor-instance');
      }
      var containerEl = $scope[0];
      if (!containerEl) return;
      ensureContent($scope, trailData.images);
      var imageOpacity = trailData.imageOpacity !== undefined ? trailData.imageOpacity : 1;
      var threshold = trailData.threshold || 80;
      var duration = trailData.duration || 0.4;
      var trailStyle = trailData.trailStyle || 'normal';
      var rotationDuration = trailData.rotationDuration || 0.5;
      var mousePos = {
        x: 0,
        y: 0
      };
      var lastMousePos = {
        x: 0,
        y: 0
      };
      var cacheMousePos = {
        x: 0,
        y: 0
      };
      var images = [];
      var imgIndex = 0;
      var zIndexVal = 1;
      var animFrame = null;
      var initialized = false;
      $scope.find('.ha-it-content__img').each(function (i, el) {
        images.push({
          el: el,
          rect: el.getBoundingClientRect(),
          timeline: null
        });
      });
      if (!images.length) return;
      function onPointerMove(ev) {
        var e = ev.touches ? ev.touches[0] : ev;
        mousePos = getPointerPos(e, containerEl);
      }
      function onFirstMove() {
        cacheMousePos = {
          x: mousePos.x,
          y: mousePos.y
        };
        animFrame = requestAnimationFrame(render);
        containerEl.removeEventListener('mousemove', onFirstMove);
      }
      function render() {
        var dist = getDistance(mousePos.x, mousePos.y, lastMousePos.x, lastMousePos.y);
        cacheMousePos.x = lerp(cacheMousePos.x, mousePos.x, 0.1);
        cacheMousePos.y = lerp(cacheMousePos.y, mousePos.y, 0.1);
        if (dist > threshold) {
          showNextImage();
          lastMousePos = {
            x: mousePos.x,
            y: mousePos.y
          };
        }
        animFrame = requestAnimationFrame(render);
      }
      function showNextImage() {
        var img = images[imgIndex % images.length];
        imgIndex++;
        gsap.killTweensOf(img.el);
        gsap.set(img.el, {
          clearProps: "all"
        });
        if (trailStyle === 'falling') {
          var containerHeight = containerEl.offsetHeight;
          gsap.set(img.el, {
            opacity: 1,
            left: cacheMousePos.x,
            top: cacheMousePos.y,
            xPercent: -50,
            yPercent: -50,
            position: 'absolute'
          });
          playFallingAnimation(img.el, containerHeight, rotationDuration);
        } else {
          ++zIndexVal;
          gsap.set(img.el, {
            opacity: imageOpacity,
            scale: 1,
            zIndex: zIndexVal,
            x: cacheMousePos.x - img.rect.width / 2,
            y: cacheMousePos.y - img.rect.height / 2
          });
          img.timeline = gsap.timeline().to(img.el, {
            duration: duration,
            ease: 'power1',
            x: mousePos.x - img.rect.width / 2,
            y: mousePos.y - img.rect.height / 2
          }, 0).to(img.el, {
            duration: duration,
            ease: 'power3',
            opacity: 0,
            scale: 0.2
          }, duration);
        }
      }
      function initTrail() {
        if (initialized) return;
        containerEl.addEventListener('mousemove', onPointerMove);
        containerEl.addEventListener('touchmove', onPointerMove, {
          passive: false
        });
        containerEl.addEventListener('mousemove', onFirstMove);
        containerEl.addEventListener('mouseenter', function () {
          $scope.addClass('ha-it-active');
        });
        containerEl.addEventListener('mouseleave', function () {
          $scope.removeClass('ha-it-active');
        });
        initialized = true;
      }
      function destroyTrail() {
        if (animFrame) {
          cancelAnimationFrame(animFrame);
          animFrame = null;
        }
        if (containerEl) {
          containerEl.removeEventListener('mousemove', onPointerMove);
          containerEl.removeEventListener('touchmove', onPointerMove);
          containerEl.removeEventListener('mousemove', onFirstMove);
        }
        for (var i = 0; i < images.length; i++) {
          gsap.killTweensOf(images[i].el);
          gsap.set(images[i].el, {
            clearProps: 'all'
          });
        }
        initialized = false;
      }
      var allImgs = $scope.find('.ha-it-content__img-inner');
      if (allImgs.length && typeof imagesLoaded !== 'undefined') {
        imagesLoaded(allImgs.toArray(), {
          background: true
        }, initTrail);
      } else {
        initTrail();
      }
      $scope.data('ha-it-trail-instance', {
        destroy: destroyTrail
      });
      $scope.data('ha-it-initialized', true);
      if (trailData.cursor) initMagicCursor($scope, trailData);
    };
    function initMagicCursor($scope, trailData) {
      var isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
      if (isMobile) return;
      var cursorId = 'ha-it-cursor-' + $scope.data('id');
      if ($('#' + cursorId).length) return;
      var classAttr = 'ha-it-cursor';
      $scope.css('position', 'relative');
      $scope.addClass('ha-it-overflow-fix');
      $scope.append('<div class="' + classAttr + '" id="' + cursorId + '"><div class="ha-it-cursor__ball"></div></div>');
      var $ball = $('#' + cursorId).find('.ha-it-cursor__ball');
      var mouse = {
        x: 0,
        y: 0
      };
      var delayedMouse = {
        x: 0,
        y: 0
      };
      var ease = 0.15;
      var animFrame = null;
      var isInside = false;
      function onMouseMove(e) {
        var rect = $scope[0].getBoundingClientRect();
        mouse.x = e.clientX - rect.left;
        mouse.y = e.clientY - rect.top;
      }
      function updateCursor() {
        if (isInside) {
          delayedMouse.x += (mouse.x - delayedMouse.x) * ease;
          delayedMouse.y += (mouse.y - delayedMouse.y) * ease;
          $ball.css('transform', 'translate(-50%, -50%) translate(' + delayedMouse.x + 'px, ' + delayedMouse.y + 'px)');
        }
        animFrame = requestAnimationFrame(updateCursor);
      }
      $(document).on('mousemove.ha-it-cursor-' + $scope.data('id'), onMouseMove);
      $scope[0].addEventListener('mouseenter', function () {
        isInside = true;
        $ball.css('opacity', '');
      });
      $scope[0].addEventListener('mouseleave', function () {
        isInside = false;
        $ball.css('opacity', '0');
      });
      $ball.css('opacity', '0');
      animFrame = requestAnimationFrame(updateCursor);
      $scope.data('ha-it-cursor-instance', {
        destroy: function destroy() {
          if (animFrame) {
            cancelAnimationFrame(animFrame);
            animFrame = null;
          }
          $(document).off('mousemove.ha-it-cursor-' + $scope.data('id'));
          $('#' + cursorId).remove();
        }
      });
    }
    elementorFrontend.hooks.addAction("frontend/element_ready/section", ImageTrailsHandler);
    elementorFrontend.hooks.addAction("frontend/element_ready/column", ImageTrailsHandler);
    elementorFrontend.hooks.addAction("frontend/element_ready/container", ImageTrailsHandler);
  });
})(jQuery, window);