/home/bdqbpbxa/demo-subdomains/adaptiq.goodface.com.ua/frontend/js/animations.js
// Animations module

// 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);
    let previousOffset = 0;
    let customDelay = 0;
    $(el).find('.animate-word').each(function () {
      let thisOffsetTop = $(this).offset().top;

      if (previousOffset != thisOffsetTop) {
        customDelay += 0.08;
      }
      $(this).find('.animate-word__inner').css('transition-delay', `${customDelay}s`);

      previousOffset = thisOffsetTop;
    })
  });
}

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








// Custom animations

// Button animations

function buttonHoversPrepare(el) {
  const nodesArr = getAllTextNodesFromElement(el[0]);
  let delay = 0.1;

  let originalText = el.text();
  let buttonNewHtml = `<span class="btn-innerText"><span class="btn-original-text">${originalText}</span>`;

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

    textArr.forEach(el => {
      buttonNewHtml += `<span class="btn-word" style="transition-delay: ${delay}s"> ${el} </span>`;
      delay += 0.05;
    });

    buttonNewHtml += '</span>';

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

    node.replaceWith(replaceNode);
  });
}

$(window).on('load', function () {
  $('.default-button').each(function () {
    buttonHoversPrepare($(this));
  })
})





// main screen animation

$(window).on('load', function () {
  if (('.main__wrapper').length) {
    let defaultContainer = $('.-default-text');
    let hiddenBlock = defaultContainer.closest('.main__wrapper');
    if (!isPc) {
      hiddenBlock = defaultContainer.closest('.main__slider-slide');
    }
    let yTranslate = hiddenBlock.innerHeight();
    let onBlackSectionContainer = $('.-on-black-section-text');
    let headerHeight = $('.header').innerHeight();

    // Main cube animate 

    const boxes = gsap.utils.toArray('.cube');
    boxes.forEach(box => {
      let elObj = $(box);
      let xFinal = elObj.attr('data-x-final');
      let yFinal = elObj.attr('data-y-final');
      let rotationFinal = elObj.attr('data-rotation-final');
      gsap.to(box, {
        x: xFinal,
        y: yFinal,
        rotation: rotationFinal,
        duration: 3,
        scale: 1,
        scrollTrigger: {
          // invalidateOnRefresh: true,
          start: function () {
            let el = $(box);
            let elTopOffset = el.offset().top;
            let container = el.closest('.main__wrapper');
            let containerHeight = container.innerHeight();
            let containerOffsetTop = container.offset().top;

            let scrolbarTriggerPos = '80%';
            let elementTriggerPos = 'center';
            if (!isPc) {
              scrolbarTriggerPos = yTranslate + headerHeight;
              elementTriggerPos = containerOffsetTop - elTopOffset;
            }

            return `${elementTriggerPos} ${scrolbarTriggerPos}`;
          },
          end: function () {
            let el = $(box);
            let elTopOffset = el.offset().top;
            let container = el.closest('.main__wrapper');
            let containerHeight = container.innerHeight();
            let containerOffsetTop = container.offset().top;

            let scrolbarTriggerPos = '71.6%';
            let elementTriggerPos = containerHeight + containerOffsetTop - elTopOffset - 5;
            if (!isPc) {
              scrolbarTriggerPos = yTranslate + headerHeight;
              elementTriggerPos = containerOffsetTop - elTopOffset + yTranslate;
            }

            return `${elementTriggerPos} ${scrolbarTriggerPos}`;
          },
          trigger: box,
          scrub: 1.5,
          once: true,
        }

      });
    });

    // main text animate
    // Black text animation
    gsap.to(defaultContainer[0], {
      x: '0',
      y: yTranslate,
      scale: 1,
      scrollTrigger: {
        invalidateOnRefresh: true,
        start: textStartPos(defaultContainer),
        end: textEndPos(defaultContainer),
        trigger: '.--black-section.main__wrapper',
        scrub: 1.5,
        once: true,
      },
    });

    // White text animation
    gsap.fromTo(onBlackSectionContainer[0], {
      y: -yTranslate,
    }, {
      x: '0',
      y: 0,
      scale: 1,
      scrollTrigger: {
        invalidateOnRefresh: true,
        start: textStartPos(defaultContainer),
        end: textEndPos(defaultContainer),
        trigger: '.--black-section.main__wrapper',
        scrub: 1.5,
        once: true,
        onUpdate: self => {
          if (self.progress == 1) {
            $('.main-section').removeClass('-is-animated');
            $('.-on-black-section-text').removeClass('-on-black-section-text');
            $('.-delete-after-animate').remove();
            ScrollTrigger.refresh(true);
          }
        },
      },
    });

    

    function textStartPos(el) {
      let container = el.closest('.main__wrapper').next('.main__wrapper');
      let thisOffsetTop = el.offset().top;
      let containerOffsetTop = container.offset().top;

      let elementTriggerPos = 'top';
      let scrolbarTriggerPos = '71.6%';
      if (!isPc) {
        elementTriggerPos = -yTranslate - headerHeight;
        scrolbarTriggerPos = 'top';
      }

      return `${elementTriggerPos} ${scrolbarTriggerPos}`;
    }

    function textEndPos(el) {
      let container = el.closest('.main__wrapper').next('.main__wrapper');
      let thisOffsetTop = el.offset().top;
      let containerOffsetTop = container.offset().top;
      let containerHeight = container.innerHeight();

      let elementTriggerPos = containerHeight - 5;
      let scrolbarTriggerPos = '71.5%';
      if (!isPc) {
        elementTriggerPos = -headerHeight;
        scrolbarTriggerPos = 'top';
      }

      return `${elementTriggerPos} ${scrolbarTriggerPos}`;
    }
  }
})


// Line animations

$(window).on('load', function () {
  // all horizontal lines
  if ($('.--horizontal-border').length) {
    const horizontalLines = gsap.utils.toArray('.--horizontal-border');
    horizontalLines.forEach(line => {
      gsap.to(line, {
        width: '100%',
        scrollTrigger: {
          start: 'top 70%',
          trigger: line,
        },
      });
    })
  }

  // all vertical lines
  if ($('.--vertical-border').length) {
    const verticallLines = gsap.utils.toArray('.--vertical-border');
    verticallLines.forEach(line => {
      gsap.to(line, {
        height: '100%',
        scrollTrigger: {
          start: 'top 70%',
          trigger: line,
        },
      });
    })
  }
})




// Open/close header menu

// $('.header__burger').click(function () {
//   let header = $(this).closest('.header');




//   if (!header.hasClass('-opened')) {
//     lockScroll();
//     fullTransitionendCallback($('.menu-bg'), function () {
//       let transitionDelay = 0.1;
//       $('.header__menu-menu a').each(function () {
//         TweenMax.to($(this)[0], {
//           css: {
//             y: 0,
//             opacity: 1,
//             duration: "+=0.5"
//           },
//           ease: 'linear',
//         });
//         transitionDelay = +0.1;
//       })
//     });

//   } else {
//     unlockScroll();
//   }
//   header.toggleClass('-opened');
// })

// inputs animation

$(document).on('focus', '.input-box input, .input-box textarea', function () {
  $(this).closest('.input-box').addClass('-filled');
})

$(document).on('blur', '.input-box input, .input-box textarea', function () {
  $(this).closest('.input-box').removeClass('-filled');
})