//markers: {startColor:"white", endColor:"white"}
//--------- Gsap Text Split Animation Start---------//
gsap.registerPlugin(ScrollTrigger);

function debounce(func){
  var timer;
  return function(event){
    if(timer) clearTimeout(timer);
    timer = setTimeout(func,300,event);
  };
}


//--------- Gsap txt Slide up Animation timeline---------//
function textSlideUpAnimation(element) {
  let tl = gsap.timeline();
  tl.from($(element).find('.char'), {
    yPercent: 110,
    duration: 0.5,
    ease: 'back.out(2)',
    stagger: {
      amount: 0.6, // Reducing stagger to fit within main animation timing
      ease: 'power2.inout',
    },
  });
  return tl;
}
//--------- Gsap txt Slide up Animation timeline End---------//

var mediaMatch = gsap.matchMedia();

//-------------------------------------------------------------------------------------------------------------------------------------//
function initEntryAni(){
    //--------- Gsap Text Fade Animation---------//


    $('.fadeInUp').each(function (index) {
      let tll = new gsap.timeline({ paused: true });
      tll.from($(this), {
        opacity: 0,
        yPercent: 20,
        duration: 1.5,
        ease: 'sine.inOut',
        stagger: 2,
      });
  
      tll.to($(this), {
        opacity: 1,
        yPercent: 0,
        duration: 1.5,
        ease: 'sine.inOut',
        stagger: 2,
      });
      ScrollTrigger.create({
        trigger: $(this),
        start: "top bottom",
        onLeaveBack: () => {
          tll.pause(0);
        },
      });
      ScrollTrigger.create({
        trigger: $(this),
        start: "top 80%",
        onEnter: () => tll.play(),
      });
    });
  

  $('.fadeIn').each(function (index) {
    let tlx = new gsap.timeline({ paused: true });
    tlx.from($(this), {
      opacity: 0,
      duration: 1,
      // delay: 0.5,
      ease: 'sine.inOut',
      stagger: 2,
    });
    tlx.to($(this), {
      opacity: 1,
      duration: 1,
      // delay: 0.5,
      ease: 'sine.inOut',
      stagger: 2,
    });

    ScrollTrigger.create({
      trigger: $(this),
      start: 'top bottom',
      onLeaveBack: () => {
        tlx.pause(0);
      },
    });

    ScrollTrigger.create({
      trigger: $(this),
      start: 'top 100%',
      onEnter: () => tlx.play(),
    });
  });
  //--------- Gsap Text Fade Animation---------//
// Animate squares on page load with delays, fade-in, and bounce effect
gsap.to(".banner-square.square-big", {
  bottom: '350px',
  duration: 1.5,
  y: "100%",
  ease: "bounce.out"
}); // Adjust y value for desired position
gsap.to(".banner-square.square-mid", {
  top: '-400px',
  duration: 1.5,
  y: "100%",
  delay: 0.5,
  ease: "bounce.out"
}); // Adjust y value for desired position
gsap.to(".banner-square.square-small", {
  top: '-200px',
  duration: 1.5,
  y: "100%",
  delay: 1,
  onComplete: onComplete,
  onCompleteParams: [this],
  ease: "bounce.out"
})

// function onComplete() {
//   console.log(this.targets()[0]);
// }
const cardSlides = gsap.utils.toArray(".swiper-slide");
  

  cardSlides.forEach((leftSlide, index)=>{
    gsap.set(leftSlide, {zIndex:index, backgroundColor: "white", opacity: index > 0 ? 0 : 1})
  })


function onComplete(target) {
  // console.log(target);
  // this.init();
  setTimeout(()=>{
    init();
    ScrollTrigger.sort();
  }, 200);
}

}
//--------- Gsap Card Bounce Drop Animation---------//
function init() {
  // gsap.registerPlugin(ScrollTrigger);


  gsap.utils.toArray('[txt-slide-up] > [text-split]').forEach(function (txt) {

      // console.log(txt.innerHTML)
      let typeSplit = new SplitType(txt, {
        types: 'words, chars',
        tagName: 'span',
      });

      // let els = txt.getElementsByClassName('char');
    let tl = new gsap.timeline({ paused: true });
    tl.from(typeSplit.chars, {
      yPercent: 110,
      duration: 1,
      ease: 'back.out(2)',
      stagger: {
        amount: 0.8,
        ease: 'power2.inout',
      },
    });

    ScrollTrigger.create({
      trigger: txt,
      // toggleActions: "play none none reset",
      start: "top bottom",
      pinnedContainer: '.animation-container',
      // markers:false,
      onLeaveBack: () => {
        tl.pause(0);
      },
    });

    ScrollTrigger.create({
      trigger: txt,
      // toggleActions: "play none none reset",
      start: "top 80%",
      pinnedContainer: '.animation-container',
      // markers:{startColor:"purple", endColor:"pink"},
      // markers:true,
      onEnter: () => tl.play(),
    });
  })

  gsap.set('[txt-slide-up]', { opacity: 1 });
//--------- Gsap Text Split Animation End---------//
let windowWidth = window.innerWidth;
  
  // gsap.set(".invest-detail-section", { opacity: 1});

  let investTimeline = gsap.timeline({
    scrollTrigger: {
      trigger: ".invest-detail-section",
      start: "center center",
      end: "150% top",  // Increase the end distance to accommodate multiple cards
      scrub: 1,
      pin: true,
      pin: '.animation-container',
      pinnedContainer: '.animation-container',
      // markers: true,
      // toggleActions: "play none none reset",
      // snap: {
      //   snapTo: 'labels', // snap to the closest label in the timeline
      //   duration: { min: 0.2, max: 3 }, // the snap animation should be at least 0.2 seconds, but no more than 3 seconds (determined by velocity)
      //   delay: 0.5, // wait 0.2 seconds from the last scroll event before doing the snapping
      //   ease: 'none' // the ease of the snap animation ("power3" by default)
      // }
      invalidateOnRefresh: true,
      preventOverlaps:true,
    fastScrollEnd: true, // (default 2500px/s)
    },
    autoAlpha:0
  });

  if(windowWidth <= 1439){
    investTimeline
    //       // .from(".swiper-slide:nth-child(1)", {x:width+50, rotate: 65, opacity: 1, duration: 1,ease: "none"})
    .set(".swiper-slide:not(:first-child)", { opacity: 0 })
    .addLabel("investment")
      .addLabel("first")
      .fromTo(".swiper-slide:nth-child(1)", {opacity: 1}, {opacity: 0, duration: 0.1, ease: "none"})
      .fromTo(".swiper-slide:nth-child(2)", {opacity: 0}, {opacity: 1, duration: 0.5, ease: "none"})
      .addLabel("second")
      .fromTo(".swiper-slide:nth-child(2)", {opacity: 1}, {opacity: 0, duration: 0.1, ease: "none"})
      .fromTo(".swiper-slide:nth-child(3)",  {opacity: 0}, {opacity: 1, duration: 0.5, ease: "none"})
      // .to(".swiper-slide:nth-child(3)", {x: -1 * (width+50),  rotate: -75, duration: 1, ease: "none"})
    // .set(".swiper-slide:not(:first-child)", { opacity: 0 })
    // .addLabel("investment")
    // .to(".swiper-slide:not(:first-child)", { opacity: 1, stagger: 1, duration: 0.1 })
  }else{
    investTimeline
    .set(".swiper-slide:not(:first-child)", { opacity: 0 })
    .addLabel("investment")
    .to(".swiper-slide:not(:first-child)", { opacity: 1, stagger: 1, duration: 0.5 , ease: "none"})
  }
  

      // ScrollTrigger.refresh();
      // ScrollTrigger.sort();

      let circleTimeline = new gsap.timeline({ paused: true });
      circleTimeline.fromTo(".animated-circle", {width: "0vmax", height: "0vmax", ease: "none"}, {width: "142vmax", height: "142vmax", ease: "none"}),

  ScrollTrigger.create({
		trigger:".middle-section",
		start: "top center",
    end: "bottom center",
    // scrub: 0.5,
    // pin: true,
    // pin: '.animation-container',
    // markers: true,
    pinnedContainer: '.animation-container',
		onToggle: (self) => {
      if (self.isActive) {
        circleTimeline.play();
      } else {
        circleTimeline.reverse();
      }
// console.log("toogle",slide )
      // self.isActive ? leftSlideAni.play() : leftSlideAni.pause(0);
    },
    // onEnter, onLeave, onEnterBack, and onLeaveBack
    // action: "play", "pause", "resume", "reset", "restart", "complete", "reverse", and "none".
		// toggleActions:"play reverse restart reverse",
    // invalidateOnRefresh: true,
		// preventOverlaps:true,
    fastScrollEnd: true, // (default 2500px/s)

	})


const sliderRight = document.querySelector(".gsap-slider .gsap-slide-right");
// console.log(sliderRight.offsetWidth);
// console.log(sliderRight.scrollWidth);
function getScrollAmount() {
  let slideImagesWidth = sliderRight.scrollWidth;
  const slideImgs = document.querySelectorAll(".gsap-slider .slide-second-col img");
  let lastItemWidth = document.querySelector(".gsap-slider .slide-second-col img:last-of-type").offsetWidth;
  

  const totalImgsCount = slideImgs.length;
  const imgRightPadding = (slideImagesWidth - (lastItemWidth * totalImgsCount) ) / totalImgsCount;
  
  console.log(
    "windowWidth: ",
    windowWidth,
    "// lastItemWidth: ",
    lastItemWidth
  );

  // ((( windows width / 2 ) - lastItemWidth) /2 )
  
  let padding = ((windowWidth - lastItemWidth) /2 ) - (imgRightPadding)
//   // return -(slideImagesWidth) - padding;
//  console.log(padding)

let xScroll = -(lastItemWidth+imgRightPadding) * 3
if(windowWidth <= 767){
  return xScroll + padding
}
else{
  return xScroll
}
// console.log((-slideImagesWidth+lastItemWidth) )
  
}

// getScrollAmount();
const tween = gsap.timeline()
.to(
  sliderRight,
  {
    x: getScrollAmount,
    duration: 3,
    //The fake-scrolling animation (just the part that's moving the container horizontally)
    //must have no easing (ease: "none").
    ease: "none",
  }
)
.set(
  ".gsap-slider .slide-second-col:nth-child(1)",
  {
    opacity: 0,
    //The fake-scrolling animation (just the part that's moving the container horizontally)
    //must have no easing (ease: "none").
    ease: "none",
  },
  1
)
.set(
  ".gsap-slider .slide-second-col:nth-child(2)",
  {
    opacity: 0,
    //The fake-scrolling animation (just the part that's moving the container horizontally)
    //must have no easing (ease: "none").
    ease: "none",
  },
  2
)

ScrollTrigger.create({
  trigger: ".gsap-wrapper",
  start: "center center",
  end: () => `+=${getScrollAmount() * -1}`,
  pinnedContainer: '.animation-container',
  pin: true,
  pin: ".animation-container",
  animation: tween,
  scrub: 1,
  invalidateOnRefresh: true,
  // markers: true,
});

// const leftSlides = gsap.utils.toArray(".gsap-slider .gsap-slide-left .gsap-fade:not(:first-child)");
const leftSlides = gsap.utils.toArray(".gsap-slider .gsap-slide-left .gsap-fade");
// console.log(leftSlides)
// const rightSlides = gsap.utils.toArray(".gsap-slider .gsap-slide-right .slide-second-col:not(:first-child)");
const rightSlides = gsap.utils.toArray(".gsap-slider .gsap-slide-right .slide-second-col");
// console.log(rightSlides)
leftSlides.forEach((leftSlide, index)=>{
  gsap.set(leftSlide, {zIndex:index, backgroundColor: "white", opacity: index > 0 ? 0 : 1})
  })

rightSlides.forEach((slide, index) => {
  // console.log(slide , leftSlides[index])
  const leftSlide = leftSlides[index];

  let tl = new gsap.timeline({ paused: true });
  let tll = new gsap.timeline({ paused: true });
  if(index > 0){

    const headline = leftSlide.querySelector("h1")
    // console.log(headline)
    const tagline = leftSlide.querySelector("p")
    // console.log(tagline)
  
    let typeSplit = new SplitType(headline, {
      types: 'words, chars',
      tagName: 'span',
    });
  
    // let els = txt.getElementsByClassName('char');
    
    tl.from(typeSplit.chars, {
      yPercent: 110,
      duration: 1,
      ease: 'back.out(2)',
      stagger: {
        amount: 0.8,
        ease: 'power2.inout',
      },
    });
  
    
        tll.from(tagline, {
          opacity: 0,
          yPercent: 20,
          duration: 0.5,
          ease: 'sine.inOut',
          stagger: 2,
        });
    
        tll.to(tagline, {
          opacity: 1,
          yPercent: 0,
          duration: 1,
          ease: 'sine.inOut',
          stagger: 2,
        });
  }

  const leftSlideAni = gsap
    .timeline({ paused: true })
    .to(leftSlide, { opacity: 1, duration: 0.01 })

  // const headline = section.querySelector("h2");
  //Pinning and snapping won't work on ScrollTriggers with a containerAnimation.
  ScrollTrigger.create({
    trigger: slide,
    start: "left 65%",
    end: "right 65%",
    // onEnter: () => mapAni.play(),
    // onLeave: () => mapAni.pause(0),
    // onEnterBack: () => mapAni.play(),
    // onLeaveBack: () => mapAni.pause(0),
    onToggle: (self) => {
      if (self.isActive) {
        leftSlideAni.play();
        tl.play()
        tll.play()
      } else {
        leftSlideAni.pause(0);
        tl.pause(0)
        tll.pause(0)
      }
// console.log("toogle",slide )
      // self.isActive ? leftSlideAni.play() : leftSlideAni.pause(0);
    },
    // animation: gsap.to(headline, { scale: 0.6 }),
    scrub: true,
    // markers: true,
    containerAnimation: tween,
    fastScrollEnd: true,
  });

})

// ScrollTrigger.sort();


}
//--------- Gsap Card Bounce Drop Animation End---------//

//-------------------------------------------------------------------------------------------------------------------------------------//



// //--------- Gsap Swiper First Slider With Rolling Animation---------//
// mediaMatch.add("(max-width: 767px)", () => {
//   console.log("small screen");

//   // const slides = document.querySelectorAll(".swiper-slide");
//   // let slidesWidth = slides[0].offsetWidth * 3;
//   let width = window.innerWidth

//   let timeline = gsap.timeline({
//     scrollTrigger: {
//       trigger: ".invest-detail-section",
//       start: "center center",
//       end: "500% center",  // Increase the end distance to accommodate multiple cards
//       scrub: 1,
//       pin: true,
//       pin: '.animation-container',
//       pinnedContainer: '.animation-container',
//       // markers: true,
//       toggleActions: "play none none reset",
//       // snap: {
//       //   snapTo: 'labels', // snap to the closest label in the timeline
//       //   duration: { min: 0.2, max: 3 }, // the snap animation should be at least 0.2 seconds, but no more than 3 seconds (determined by velocity)
//       //   delay: 0.5, // wait 0.2 seconds from the last scroll event before doing the snapping
//       //   ease: 'none' // the ease of the snap animation ("power3" by default)
//       // }
//       preventOverlaps:true,
//     fastScrollEnd: true, // (default 2500px/s)
//     },
//     autoAlpha:0,
//   });

  
//   timeline
//       // .from(".swiper-slide:nth-child(1)", {x:width+50, rotate: 65, opacity: 1, duration: 1,ease: "none"})
//       .set(".swiper-slide:not(:first-child)", {x:width+50})
//       .addLabel("first")
//       .to(".swiper-slide:nth-child(1)", {x: -1 * (width+50),  rotate: -75, duration: 0.5, ease: "none"})
//       .from(".swiper-slide:nth-child(2)", {x:width+50, rotate: 65, opacity: 1, duration: 0.5, ease: "none"} , "+=0.1")
//       .addLabel("second")
//       .to(".swiper-slide:nth-child(2)", {x: -1 * (width+50),  rotate: -75, duration: 0.5, ease: "none"})
//       .from(".swiper-slide:nth-child(3)", {x:width+50, rotate: 65, opacity: 1, duration: 0.5, ease: "none"}, "+=0.1")
//       // .to(".swiper-slide:nth-child(3)", {x: -1 * (width+50),  rotate: -75, duration: 1, ease: "none"})

//       // ScrollTrigger.refresh();
//       // ScrollTrigger.sort();
// });

// mediaMatch.add("(min-width: 768px) and (max-width: 1439px)", () => {
//   console.log("medium screen");
    
//   // const slides = document.querySelectorAll(".swiper-slide");
//   // let slidesWidth = slides[0].offsetWidth * 3;
//   let width = window.innerWidth

//   let timeline = gsap.timeline({
//     scrollTrigger: {
//       trigger: ".invest-detail-section",
//       start: "center center",
//       end: "500% center",  // Increase the end distance to accommodate multiple cards
//       scrub: 1,
//       pin: true,
//       pin: '.animation-container',
//       pinnedContainer: '.animation-container',
//       // markers: true,
//       toggleActions: "play none none reset",
//       // snap: {
//       //   snapTo: 'labels', // snap to the closest label in the timeline
//       //   duration: { min: 0.2, max: 3 }, // the snap animation should be at least 0.2 seconds, but no more than 3 seconds (determined by velocity)
//       //   delay: 0.5, // wait 0.2 seconds from the last scroll event before doing the snapping
//       //   ease: 'none' // the ease of the snap animation ("power3" by default)
//       // }
//       preventOverlaps:true,
//     fastScrollEnd: true, // (default 2500px/s)
//     },
//     autoAlpha:0,
//   });

  
//   timeline
//       .set(".swiper-slide:not(:first-child)", {x:width})
//       // .from(".swiper-slide:nth-child(1)", {x:width, scale: 0.6, rotate: 65, opacity: 1, duration: 1,ease: "none"}, 0)
//       .addLabel("first")
//       .to(".swiper-slide:nth-child(1)", {x: -1 * (width),  scale: 0.6, rotate: -75, duration: 0.5, ease: "none"})
//       .from(".swiper-slide:nth-child(2)", {x:width, scale: 0.6,rotate: 65, opacity: 1, duration: 0.5, ease: "none"} , "<")
//       .addLabel("second")
//       .to(".swiper-slide:nth-child(2)", {x: -1 * (width),  scale: 0.6,rotate: -75, duration: 0.5, ease: "none"}, 0.6)
//       .from(".swiper-slide:nth-child(3)", {x:width, scale: 0.6,rotate: 65, opacity: 1, duration: 0.5, ease: "none"}, "<")
//       // .to(".swiper-slide:nth-child(3)", {x: -1 * (width),  scale: 0.6,rotate: -75, duration: 1, ease: "none"},2.3)

//       // ScrollTrigger.refresh();
//       // ScrollTrigger.sort();
// });

// mediaMatch.add("(min-width: 1440px)", () => {
//   console.log("bigger screen");
  
//   let investTimeline = gsap.timeline({
//     scrollTrigger: {
//       trigger: ".invest-detail-section",
//       start: "center center",
//       end: "end center",  // Increase the end distance to accommodate multiple cards
//       scrub: true,
//       pin: true,
//       pin: '.animation-container',
//       pinnedContainer: '.animation-container',
//       // markers: true,
//       // toggleActions: "play none none reset",
//       // snap: {
//       //   snapTo: 'labels', // snap to the closest label in the timeline
//       //   duration: { min: 0.2, max: 3 }, // the snap animation should be at least 0.2 seconds, but no more than 3 seconds (determined by velocity)
//       //   delay: 0.5, // wait 0.2 seconds from the last scroll event before doing the snapping
//       //   ease: 'none' // the ease of the snap animation ("power3" by default)
//       // }
//       preventOverlaps:true,
//     fastScrollEnd: true, // (default 2500px/s)
//     },
//     autoAlpha:0
//   });

//   investTimeline
//       .set(".swiper-slide:not(:first-child)", { opacity: 0 })
//       .addLabel("investment")
//       .to(".swiper-slide:not(:first-child)", { opacity: 1, stagger: 0.5, duration: 0.5 })

//       // ScrollTrigger.refresh();
//       // ScrollTrigger.sort();
// });

//--------- Gsap Swiper First Slider With Rolling Animation End---------//
// function killAll() {
//   ScrollTrigger.getAll().forEach((trigger) => trigger.kill())
//   init()
// }

window.addEventListener("resize", debounce(function(e){
  console.log("end of resizing")
    ScrollTrigger.sort();
 }));
 
 $(document).ready(function () {
  initEntryAni();
  
  // init();
  // 
 })
 

//-------------------------------------------------------------------------------------------------------------------------------------//


