/home/bdqbpbxa/demo-subdomains/paytech.goodface.com.ua/frontend/js/animations.js
// Scroll animations - params

const DEFAULT_SCROLL_ANIMATION_DELAY = 200;

const DEFAULT_SCROLL_ANIMATION_OFFSET = {
  'word': 0.7,
  'fade': 0.25,
  'scale': 0.25,
  'swim-top': 0.25,
  'swim-left': 0.25,
  'swim-right': 0.25,
  'animate-group': 0.1
};


// Scroll animations - main functionality

function scrollAnimations() {
  const scrollBottom = window.scrollY + window.innerHeight;

  const groupElements = $('[data-animate-group]').not('.-animated');
  const singleElements = $('[data-animate]').not('.-animated, [data-animate-group] [data-animate]');

  singleElements.each(function() {
    const offsetTop = $(this).offset().top;

    if (scrollBottom > offsetTop) {
      const startOffset = offsetTop + getScrollAnimationElementOffset(this);

      if (scrollBottom > startOffset) {
        const dataType = $(this).data('animate');

        if (dataType === 'word') scrollAnimateTextPrepare(this);

        $(this).outerWidth(); // Lifehack for text animation
        $(this).addClass('-animated');

        scrollAnimateClearTransition(this);
      }
    }
  });

  groupElements.each(function() {
    const offsetTop = $(this).offset().top;

    if (scrollBottom > offsetTop) {
      const startOffset = offsetTop + getScrollAnimationElementOffset(this);

      if (scrollBottom > startOffset) {
        $(this).find('[data-animate="word"]').each(function() {
          scrollAnimateTextPrepare(this);
        });

        $(this).outerWidth(); // Lifehack for text animation

        $(this).addClass('-animated');
        $(this).find('[data-animate]').addClass('-animated');

        scrollAnimateClearTransition(this);
      }
    }
  });
}


// Scroll animations - helpers

function scrollAnimateTextPrepare(el) {
  const nodesArr = getAllTextNodesFromElement(el);
  const delay = $(el).css('transition-delay');

  nodesArr.forEach(node => {
    const textContent = node.textContent.trim();
    const textArr = textContent.split(' ');

    let textNodeNewHtml = '';

    textArr.forEach(el => {
      textNodeNewHtml += ` <span class="animate-word" style="transition-delay: ${delay}"><span class="animate-word__inner" style="transition-delay: ${delay}">${el}</span></span> `;
    });

    const replaceNode = document.createRange().createContextualFragment(textNodeNewHtml);

    node.replaceWith(replaceNode);
  });

  $(el).find('i').each(function() {
    let prevHtml = $(this).html();
    $(this).html(prevHtml.trim());
    $(' <span> </span> ').insertAfter(this);
  })
}

function getScrollAnimationElementOffset(el) {
  let offset = 0;
  let dataOffset = Number($(el).data('offset'));

  if (dataOffset === 0) return 0;

  if (!dataOffset) {
    const isGroup = $(el).is('[data-animate-group]');
    const animationType = $(el).data('animate');
    const type = isGroup ? 'animate-group' : animationType;

    dataOffset = DEFAULT_SCROLL_ANIMATION_OFFSET[type];
  }

  if (dataOffset && dataOffset <= 1) {
    offset = $(el).outerHeight() * dataOffset;
  }

  if (dataOffset && dataOffset > 1) {
    offset = dataOffset;
  }

  return offset;
}

function getAllTextNodesFromElement(el) {
  const nodes = el.childNodes;
  const nodesArr = [];

  nodes.forEach(node => {
    const isTextNode = node.nodeType === 3 && node.textContent.trim().length;

    if (isTextNode) {
      nodesArr.push(node);
    }
  });

  el.querySelectorAll('*').forEach(childEl => {
    const nodes = childEl.childNodes;

    nodes.forEach(node => {
      const isTextNode = node.nodeType === 3 && node.textContent.trim().length;

      if (isTextNode) {
        nodesArr.push(node);
      }
    });
  });

  return nodesArr;
}

function scrollAnimateClearTransition(el) {
  const isGroup = $(el).is('[data-animate-group]');
  const doNotClearAnimations = $(el).is('[data-do-not-clear-animate]');

  if (isGroup) {
    $(el).find('[data-animate]').each(function() {
      const animateEl = this;
      const doNotClearAnimations = $(this).is('[data-do-not-clear-animate]');

      const callbackEl = $(this).is('[data-animate="word"]') ? $(this).find('.animate-word__inner')[0] : this;

      if (!doNotClearAnimations) {
        fullTransitionendCallback(callbackEl, function(e) {
          $(animateEl).off('transitionend');
          $(animateEl).removeAttr('data-animate data-index').css('transition-delay', '');
        });
      }
    });
  } else if (!isGroup && !doNotClearAnimations) {
    fullTransitionendCallback(el, function(e) {
      $(e.target).off('transitionend');
      $(e.target).removeAttr('data-animate data-index').css('transition-delay', '');
    });
  }
}

// Scroll animations - initialization

function scrollAnimationsInit() {
  $('[data-animate-group]').each(function() {
    const groupDataType = $(this).data('animate-group');
    const groupDataDelay = $(this).data('delay');

    const groupType = groupDataType !== 'list' && groupDataType !== 'index-list' ? 'default' : groupDataType;
    const groupDelay = groupDataDelay ? groupDataDelay : DEFAULT_SCROLL_ANIMATION_DELAY;


    $(this).find('[data-animate]').each(function(index) {
      let delay = 0;

      const itemDataIndex = $(this).data('index');
      const itemDataDelay = $(this).data('delay');

      if (groupType === 'default') {
        delay = itemDataDelay ? itemDataDelay : 0;
      }

      if (groupType === 'list') {
        delay = itemDataIndex ? groupDelay * itemDataIndex : groupDelay * index;
      }

      $(this).css('transition-delay', `${delay}ms`);
    });
  });

  scrollAnimations();

  $(window).on("scroll", scrollAnimations);
}

$(window).on("load", scrollAnimationsInit);


/* Animate main screen */
function initMainScreenAnimation() {
  let animatedCard = $('.animated-hero-card');
  if (!animatedCard.length) return;


  animatedCard.append(`<span class="preparedBlock"></span>`);
  let cardPositionChecker = animatedCard.find('.preparedBlock');


  let cardoffset = cardPositionChecker.offset();
  let cardHeight = cardPositionChecker.innerHeight();

  let finalPositionPlace = $('.hero-card__item:nth-child(3)');
  let finalWidth = finalPositionPlace.innerWidth();
  cardPositionChecker.css('width', finalWidth);

  let finalPositionX = finalPositionPlace.offset().left - cardoffset.left;
  let finalPositionY = finalPositionPlace.offset().top - cardoffset.top;




  let endPosition = finalPositionY + (cardHeight / 2);

  cardPositionChecker.remove();

  gsap.to(animatedCard[0], {
    x: finalPositionX,
    y: finalPositionY,
    width: finalWidth,
    scrollTrigger: {
      invalidateOnRefresh: true,
      start: 'center center',
      end: `${endPosition}px center`,
      trigger: animatedCard[0],
      scrub: 1,
    },
  });
}

$(window).on('load resize', initMainScreenAnimation);


/* Prepare main screen background to animations */

// function prepareMainScreenBackground() {
//   let container = $('.hero__right-bg');
//   if (!container.length) return;
//   let buble = container.find('span');

//   let containerWidth = container.innerWidth();
//   let containerHeiht = container.innerHeight();

//   let gapValue = container.css('gap');
//   let preparedGapValue = Number(gapValue.substring(0, gapValue.length - 2));
//   let bubleWidth = buble.innerWidth() + preparedGapValue;
//   let bubleHeight = buble.innerHeight() + preparedGapValue;

//   let countPerRow = Math.ceil(containerWidth / bubleWidth) + 2;
//   let countPerColumn = Math.ceil(containerHeiht / bubleHeight) + 1;

//   let totalCount = (countPerRow * countPerColumn) - 3;
//   container.html('');
//   for (let i = 1; i <= totalCount; i++) {
//     container.append('<span></span>');
//   }
// }

// $(window).on('load', prepareMainScreenBackground);

/* make dots active/inactive */

// let intervalIsrunning = false;

// function animateMainScreenDots() {
//   let container = $('.hero__right-bg');
//   if (!container.length) return;
//   let buble = container.find('circle');

//   buble.each(function() {
//     let intervalTime = randomRange(0, 10);
//     setInterval(() => {
//       $(this).toggleClass('-active');
//     }, intervalTime * 1000);
//   })
// }

// $(window).on('load', animateMainScreenDots);

// function randomRange(min, max) {
//   let cal = (Math.random() * (max - min) + min);
//   return parseFloat(cal);
// }