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

const DEFAULT_SCROLL_ANIMATION_DELAY = 200;

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


// 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);
  });
}

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);


// parallax init

$(window).on('load', function () {
  if (!$('.parallax-cols-section').length) return;

  const parallaxObserver = new IntersectionObserver((entries) => {
    if (entries[0].isIntersecting) {
      runParallaxAnimation($(entries[0].target));
      parallaxObserver.unobserve(entries[0].target);
    }
  }, {
    rootMargin: "100px",
    threshold: 0,
  });


  $('.parallax-cols-section').each(function () {
    parallaxObserver.observe(this);
  })

})

// parallax function

function runParallaxAnimation(container) {
  const parallaxEl = container.find('.parallax-col.-animation');

  let startpos = 'top bottom';
  if (container.attr('data-start-animation-based') == 'prevSection') {
    const prevSectionHeight = container.prev('section').innerHeight() + parseInt(container.css('margin-top'));
    startpos = `top ${prevSectionHeight}px`;
  }

  parallaxEl.each(function () {
    const column = this;

    let yValueByWindowSizeType1 = isPc ? '-30%' : '-20%';
    let yValueByWindowSizeType2 = isPc ? '-15%' : '-10%';
    let yValue = $(this).hasClass('-parallax-type-1') ? yValueByWindowSizeType1 : yValueByWindowSizeType2;

    gsap.to(column, {
      y: yValue,
      scrollTrigger: {
        invalidateOnRefresh: true,
        start: startpos,
        end: 'bottom top',
        trigger: container[0],
        // markers: true,
        scrub: 0.5,
      },
    });
  })
}


// Conveyor line functionality
const conveyor = $(".conveyor-belt__belt");

function conveyorReady(conveyor) {
  let thisConveyor = conveyor;
  const part = thisConveyor.find(".conveyor-belt__belt-part");
  if (part.length) {
    const partWidth = part.outerWidth();
    const containerWidth = part.closest('.conveyor-belt__belt').innerWidth();

    let partDublicateCount;
    let partHtml = part[0].outerHTML;
    let appendHtml = "";

    if (partWidth > containerWidth) {
      partDublicateCount = 1;
    } else {
      partDublicateCount = Math.ceil(containerWidth / partWidth);
    }

    for (var i = 0; i < partDublicateCount; i++) {
      appendHtml += partHtml;
    }

    thisConveyor.append(appendHtml);

    if (!thisConveyor.hasClass('-custom-trigger')) {
      startConveyorAnimation(thisConveyor, partWidth);
    }
  }
}

function startConveyorAnimation(conveyor, partWidth) {
  let index = 1.4;
  if (!isPc) {
    index = 1.5;
  }
  const speed = index * (partWidth / 100);

  let animationVal = `conveyor-part ${speed}s linear infinite`;
  if (conveyor.hasClass('-reverse')) {
    animationVal = `conveyor-part-reverse ${speed}s linear infinite`;
  }

  conveyor.find(".conveyor-belt__belt-part").css({
    animation: animationVal,
  });
}

// Conveyor start
$(window).on('load', function () {

  const conveyorObserver = new IntersectionObserver((entries) => {
    entries.forEach(function (item, index) {
      if (item.isIntersecting) {
        lazyload(item.target);
        const conveyor = $(item.target);
        conveyorReady(conveyor);
        conveyorObserver.unobserve(item.target);
      }
    })
  }, {
    rootMargin: '50px',
    threshold: 0
  });

  conveyor.each(function () {
    conveyorObserver.observe(this);
  });

})


// animate steps section

function animatePinnedCardsSection() {
  const pinnedSliderContainer = $('.pinned-tabs');
  const textCards = gsap.utils.toArray('.pinned-tab__item');
  const cardsWprappers = gsap.utils.toArray('.pinned-tab__card');

  let pinnedSlider, blockHeight, startPos, cardHeight, parentOffsetTop, cardOffsetTop, parentHeight;
  if (!pinnedSliderContainer.length || !textCards.length || !isPc) return;
  cardHeight = $(textCards[0]).innerHeight();
  blockHeight = (textCards.length * cardHeight) - cardHeight;
  parentOffsetTop = pinnedSliderContainer.offset().top;
  pinnedSlider = gsap.to('.pinned-tabs', {
    ease: "none",
    scrollTrigger: {
      invalidateOnRefresh: true,
      trigger: '.pinned-tabs',
      start: "center center",
      end: `+=${blockHeight}px`,
      pin: true,
      scrub: 0.5,
      // markers: true,
    }
  });

  textCards.forEach((card, index) => {
    const tl = gsap.timeline({
      scrollTrigger: {
        // markers: true,
        trigger: card,
        start: () => {
          cardOffsetTop = $(card).offset().top;
          startPos = parentOffsetTop - cardOffsetTop + (cardHeight / 2) + (cardHeight * index) - cardHeight;
          return `${startPos} center`;
        },
        end: `+=${cardHeight}`,
        onUpdate: (scroll) => {
          if (scroll.progress > 0.4 || index == 0) {
            $(card).closest('.pinned-tabs').find('.pinned-tabs__list').find('.tab.-active').removeClass('-active');
            $(card).closest('.pinned-tabs').find('.pinned-tabs__list').find('.tab').eq(index).addClass('-active');
            $(card).addClass('-active');
          } else {
            $(card).closest('.pinned-tabs').find('.pinned-tabs__list').find('.tab.-active').removeClass('-active');
            $(card).closest('.pinned-tabs').find('.pinned-tabs__list').find('.tab').eq(index - 1).addClass('-active');
            $(card).removeClass('-active');
          }
        },
        scrub: 1,
      }
    }).from(
      card, {
      y: "150vh",
    },
    )

    for (let i = 0; i < index; i++) {
      let scaling = 1 - ((index - i) * 0.1);
      tl.to(
        cardsWprappers[i], {
        scale: scaling,
      },
        '<'
      );
    }



  });

  setTimeout(() => {
    ScrollTrigger.refresh(true);
  }, 100)
}

function scrollToPinnedTab(index, container) {
  let cardHeight = container.find('.pinned-tab__item').innerHeight();
  let margin = container.closest('.pin-spacer').offset().top - (window.innerHeight / 2) - (cardHeight / 2);

  let cardPosition = margin + (cardHeight * (index + 1));
  $("html, body").animate({
    scrollTop: cardPosition
  }, 700);
}

$(document).on('click', '.pinned-tabs .tab', function () {
  let index = $(this).index();
  let container = $(this).closest('.pinned-tabs');
  scrollToPinnedTab(index, container);
})
$(window).on('load', function () {
  if (!$('.pinned-tabs').length) return;
  const stepsSectionObserver = new IntersectionObserver((entries) => {
    if (entries[0].isIntersecting) {
      animatePinnedCardsSection();
      stepsSectionObserver.unobserve(entries[0].target);
    }
  }, {
    rootMargin: "100px",
    threshold: 0,
  });


  $('.pinned-tabs').each(function () {
    stepsSectionObserver.observe(this);
  })

});


// animate scrolled-slider__container

function animateScrollingSlider() {
  const pinnedSliderContainer = $('.scrolled-slider__container');
  const textCards = gsap.utils.toArray('.scrolled-slider__item');
  const imgCards = gsap.utils.toArray('.scrolled-slider__img img');

  let blockHeight, startPos, cardHeight, parentOffsetTop, cardOffsetTop, parentHeight;

  if (!pinnedSliderContainer.length || !textCards.length || !isPc) return;

  cardHeight = 300;
  blockHeight = (textCards.length * cardHeight);
  parentOffsetTop = pinnedSliderContainer.offset().top;

  const pinnedSlider = gsap.to('.scrolled-slider__container', {
    ease: "none",
    scrollTrigger: {
      invalidateOnRefresh: true,
      trigger: '.scrolled-slider__container',
      start: "center center",
      end: `+=${blockHeight}px`,
      pin: true,
      scrub: 0.5,
      // markers: true,
    }
  });


  textCards.forEach((card, index) => {

    const tl = gsap.timeline({
      scrollTrigger: {
        // markers: true,
        trigger: card,
        start: () => {
          cardOffsetTop = $(card).offset().top;
          startPos = parentOffsetTop - cardOffsetTop + (cardHeight / 2) + (cardHeight * index);
          return `${startPos} center`;
        },
        end: `+=${cardHeight}`,
        onUpdate: (scroll) => {
          if (scroll.progress > 0 || index == 0) {
            $(card).closest('.scrolled-slider__container').find('.scrolled-slider__item.-active').removeClass('-active');
            $(card).closest('.scrolled-slider__container').find('.scrolled-slider__img img.-active').removeClass('-active');
            $(imgCards[index]).addClass('-active');
            $(card).addClass('-active');

            let height = $(card).find('.text-overflow .text').innerHeight();
            $(card).find('.text-overflow').css('height', height);
            $(card).prev().find('.text-overflow').css('height', 0);
            activeCardIndex = index;
          } else {
            $(card).closest('.scrolled-slider__container').find('.scrolled-slider__item.-active').removeClass('-active');
            $(card).closest('.scrolled-slider__container').find('.scrolled-slider__img img.-active').removeClass('-active');
            $(imgCards[index - 1]).addClass('-active');
            $(card).removeClass('-active');
            $(textCards).eq(index - 1).addClass('-active');

            let height = $(card).find('.text-overflow .text').innerHeight();
            $(textCards).eq(index - 1).find('.text-overflow').css('height', height);
            $(card).find('.text-overflow').css('height', 0);
            activeCardIndex = index - 1;
          }

          for (let i = 0; i < textCards.length; i++) {
            let opacityIndex = Math.abs(i - activeCardIndex);
            let opacity = 1;

            if (opacityIndex == 0) {
              opacity = 1;
            } else if (opacityIndex == 1) {
              opacity = 0.7
            } else {
              opacity = 0.7 - (opacityIndex * 0.1) + 0.1;
            }

            opacity = Math.max(0.3, opacity);

            $(textCards[i]).find('.title .text').css('opacity', opacity);
          }

        },
        scrub: 1,
      }
    })


  });
}

function scrollToSlideInScrollingSlider(index, container) {
  let cardHeight = 300;
  let margin = container.closest('.pin-spacer').offset().top - (window.innerHeight / 2) - (cardHeight / 2);
  let cardPosition = margin + (cardHeight * (index + 2));
  let speedCalc = Math.max(Math.abs(cardPosition - $('html, body').scrollTop()) / 10, 400);
  $("html, body").animate({
    scrollTop: cardPosition
  }, speedCalc);
}

$(document).on('click', '.scrolled-slider__item', function () {
  let index = $(this).index();
  let container = $(this).closest('.scrolled-slider__container');
  scrollToSlideInScrollingSlider(index, container);
})
$(window).on('load', function () {
  if (!$('.scrolled-slider__container').length) return;

  const scrollingSliderObserver = new IntersectionObserver((entries) => {
    if (entries[0].isIntersecting) {
      animateScrollingSlider();
      scrollingSliderObserver.unobserve(entries[0].target);
    }
  }, {
    rootMargin: "100px",
    threshold: 0,
  });


  $('.scrolled-slider__container').each(function () {
    scrollingSliderObserver.observe(this);
  })

});




// animate how-it-work__container

function animateHowItWorkScrollingSlider() {
  const pinnedHowItWorkSliderContainer = $('.how-it-work-slider');
  const textHowItWorkCards = gsap.utils.toArray('.how-it-work-slider__container.-pc .how-it-work-slider__item');
  let blockHeight, startPos, cardHeight, parentOffsetTop, cardOffsetTop, parentHeight;
  if (!pinnedHowItWorkSliderContainer.length || !textHowItWorkCards.length || !isPc) return;


  textHowItWorkCards.forEach(card => {
    cardHeight = $(card).outerHeight();
  });

  blockHeight = textHowItWorkCards.length * cardHeight;
  parentOffsetTop = pinnedHowItWorkSliderContainer.offset().top;

  const pinnedSlider = gsap.to(pinnedHowItWorkSliderContainer[0], {
    ease: "none",
    scrollTrigger: {
      invalidateOnRefresh: true,
      trigger: pinnedHowItWorkSliderContainer[0],
      start: "center center",
      end: `+=${blockHeight}px`,
      pin: true,
      scrub: 0.5,
      // markers: true,
    }
  });


  textHowItWorkCards.forEach((card, index) => {

    const tl = gsap.timeline({
      scrollTrigger: {
        // markers: true,
        trigger: card,
        start: () => {
          cardOffsetTop = $(card).offset().top;
          startPos = parentOffsetTop - cardOffsetTop + (cardHeight / 2) + (cardHeight * index);
          return `${startPos} center`;
        },
        end: `+=${cardHeight}`,
        onUpdate: (scroll) => {
          if (scroll.progress > 0 || index == 0) {
            $(card).addClass('-active');
            let transform = 0;
            let opacity = 1;
            if (index == 0) {
              transform = 0;
            } else {
              transform = 72 * index;

            }
            $(card).css({ 'transform': `translateY(${transform}px)`, 'opacity': opacity, });
            for (let i = index - 1; i >= 0; i--) {
              opacity = (10 - i - 4) / 10;
              $(textHowItWorkCards[i]).find('.how-it-work-slider__item-overlay').css('opacity', opacity);
            }
          } else {
            $(card).removeClass('-active');
            $(card).css({ 'transform': `translateY(150%)`, 'opacity': 0, });
            for (let i = 0; i < index; i++) {
              opacity = 0;
              $(textHowItWorkCards[i]).find('.how-it-work-slider__item-overlay').css('opacity', opacity);
            }
          }
        },
        scrub: 1,
      }
    })
  });
}



$(window).on('load', function () {
  if (!$('.how-it-work-slider').length) return;

  const scrollingHowItWorkSliderObserver = new IntersectionObserver((entries) => {
    if (entries[0].isIntersecting) {
      animateHowItWorkScrollingSlider();
      scrollingHowItWorkSliderObserver.unobserve(entries[0].target);
    }
  }, {
    rootMargin: "100px",
    threshold: 0,
  });


  $('.how-it-work').each(function () {
    scrollingHowItWorkSliderObserver.observe(this);
  })

});