//--------- Gsap Text Split Animation Start---------//
gsap.registerPlugin(ScrollTrigger);


var mediaMatch = gsap.matchMedia();

let typeSplit = new SplitType('[text-split]', {
  types: 'words, chars',
  tagName: 'span',
});

$('[txt-slide-up]').each(function (index) {
  let tl = new gsap.timeline({ paused: true });
  tl.from($(this).find('.text-split .char'), {
    yPercent: 110,
    duration: 1,
    ease: 'back.out(2)',
    stagger: {
      amount: 0.8,
      ease: 'power2.inout',
    },
  });

  ScrollTrigger.create({
    trigger: $(this),
    toggleActions: "play none none reset",
    start: "top bottom",
    onLeaveBack: () => {
      tl.pause(0);
    },
  });

  ScrollTrigger.create({
    trigger: $(this),
    toggleActions: "play none none reset",
    start: "top 80%",
    onEnter: () => tl.play(),
  });
}); 

gsap.set('[txt-slide-up]', { opacity: 1 });




// delay text animation
// Initialize SplitType for elements with the attribute [text-split-slow]
let typeSplitNew = new SplitType('[text-split-slow]', {
  types: 'words, chars',
  tagName: 'span',
});

// Ensure elements are properly selected for GSAP
// let tl2 = new gsap.timeline({ paused: true });

// tl2.from('.split-text-slow .char', {
//   yPercent: 110,
//   duration: 1,
//   ease: 'back.out(2)',
//   stagger: {
//     amount: 0.8,
//     ease: 'power2.inout',
//   },
// });

// // Create ScrollTrigger for each element with [text-split-slow]
// mediaMatch.add("(min-width: 768px)", () => {
//   document.querySelectorAll('[text-split-slow]').forEach((element) => {
//     ScrollTrigger.create({
//       trigger: element,
//       start: "center center",
//       // markers: true,
//       onLeaveBack: () => {
//         tl2.pause(0);
//       },
//     });

//     ScrollTrigger.create({
//       trigger: element,
//       start: '800%',
//       onEnter: () => tl2.play(),
//     });
//   });
//   // Set initial state for elements with the attribute [txt-slide-up-slow]
//   gsap.set('[txt-slide-up-slow]', { opacity: 1 });
// });

// mediaMatch.add("(max-width: 767px)", () => {
//   document.querySelectorAll('[text-split-slow]').forEach((element) => {
//     ScrollTrigger.create({
//       trigger: element,
//       start: "center center",
//       // markers: true,
//       onLeaveBack: () => {
//         tl2.pause(0);
//       },
//     });

//     ScrollTrigger.create({
//       trigger: element,
//       start: '500%',
//       onEnter: () => tl2.play(),
//     });
//   });
//   // Set initial state for elements with the attribute [txt-slide-up-slow]
//   gsap.set('[txt-slide-up-slow]', { opacity: 1 });
// });

function initSplitTextSlow() {
  console.log("initSplitTextSlow")
  gsap.from('.split-text-slow .char', {
    yPercent: 110,
    duration: 1,
    ease: 'back.out(2)',
    stagger: {
      amount: 0.8,
      ease: 'power2.inout',
    },
  });
  // Set initial state for elements with the attribute [txt-slide-up-slow]
  gsap.set('[txt-slide-up-slow]', { opacity: 1 });
}



// Initialize SplitType for elements with the attribute [text-split-slow]
let typeSplitNew2 = new SplitType('[text-split-middle]', {
  types: 'words, chars',
  tagName: 'span',
});

// // Ensure elements are properly selected for GSAP
// let tl3 = new gsap.timeline({ paused: true });

// tl3.from('.text-split-middle .char', {
//   yPercent: 110,
//   duration: 1,
//   ease: 'back.out(2)',
//   stagger: {
//     amount: 0.8,
//     ease: 'power2.inout',
//   },
// });

// // Create ScrollTrigger for each element with [text-split-slow]
// document.querySelectorAll('[text-split-middle]').forEach((element) => {
//   ScrollTrigger.create({
//     trigger: element,
//     start: "top 100%",
//     onLeaveBack: () => {
//       tl3.pause(0);
//     },
//   });

//   ScrollTrigger.create({
//     trigger: element,
//     // markers: true,
//     start: 'top top',
//     onEnter: () => tl3.play(),
//   });
// });

// // Set initial state for elements with the attribute [txt-slide-up-slow]
// gsap.set('[txt-slide-up-middle]', { opacity: 1 });





// Ensure elements are properly selected for GSAP
function middleTextAnimation() {
  gsap.from('.text-split-middle .char', {
    yPercent: 110,
    duration: 1,
    ease: 'back.out(2)',
    stagger: {
      amount: 0.8,
      ease: 'power2.inout',
    },
  });
  // Set initial state for elements with the attribute [txt-slide-up-slow]
  gsap.set('[txt-slide-up-middle]', { opacity: 1 });

}

//--------- Gsap Text Split Animation End---------//

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

//--------- Gsap Card Bounce Drop Animation---------//
$(document).ready(function () {
  gsap.registerPlugin(ScrollTrigger);
  // 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,
    ease: "bounce.out"
  }); // Adjust y value for desired position
  // end vector animation

  // Create the animated circle
  gsap.to(".animated-circle", {
    scrollTrigger: {
      trigger: ".middle-section",
      start: "top top+=20%", // Start animation when top of section hits center of viewport
      end: "100% center",  // End animation when bottom of section hits center of viewport
      scrub: 3, // Delay the scrub effect to make it slower (try values like 1, 2, or 3 for slower effects)
      markers: false, // Optional: Show markers for debugging
    },
    keyframes: [
      {
        width: "500vw",
        height: "500vw",
        // ease: "sine.inOut", // Slow start with a slight acceleration
        duration: 1, ease: "none"
      },
      {
        width: "0vw",
        height: "0vw",
        // ease: "sine.inOut", // Faster contraction
        duration: 1, ease: "none"
      }
    ],
    onStart: middleTextAnimation,
    onComplete: middleTextAnimation
  });

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

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

//--------- Gsap Swiper Last Slider With Split Text Animation---------//
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;
}

document.addEventListener("DOMContentLoaded", function () {
  const slidesLeft = gsap.utils.toArray(".gsap-fade:not(:last-child)");
  const slidesLastLeft = gsap.utils.toArray(".gsap-fade:last-child");
  const slidesRight = gsap.utils.toArray(".gsap-slide:not(:last-child)");
  const slidesLastRight = gsap.utils.toArray(".gsap-slide:last-child");

  const splitSlideWidth = slidesLastRight[0].offsetWidth * 4;
  console.log(splitSlideWidth)
  
  const timeline = gsap.timeline({
    scrollTrigger: {
      trigger: ".gsap-slider",
      start: "center center",
      // end: "+=" + splitSlideWidth - window.innerHeight, // Extending the scroll effect length
      end: "500% top", // Extending the scroll effect length
      scrub: 1.5,    // Slowing down scrub speed for smoother pin scroll
      pin: true,
      toggleActions: "play none none reset",
      onUpdate: (self) => {
        console.log("progress:", self.progress)
        if(self.progress === 1) {
          initSplitTextSlow()
        }        
      }
    },
  });

  slidesLeft.forEach((slideLeft, index) => {
    const slideRight = slidesRight[index];

    // Animate the left slide with synchronized text animation
    // timeline
    //   .fromTo(
    //     slideLeft,
    //     { display: 'none' },
    //     { display: 'block', y: 0, duration: 0.8 },
    //     index * 1
    //   )
    //   .to(
    //     slideLeft,
    //     { display: 'none', opacity: 0, duration: 0.8 },
    //     (index + 0.5) * 1
    //   ).add(() => textSlideUpAnimation(slideLeft), index * 1); // Trigger text animation
    timeline
    .fromTo(
      slideLeft,
      { display: 'none' },
      { display: 'block', y: 0 },
      index * 1
    )
    .to(
      slideLeft,
      { display: 'none' },
      (index + 0.5) * 1
    ).add(() => textSlideUpAnimation(slideLeft), index * 1); // Trigger text animation

    // Animate the right slide with synchronized text animation
    timeline
      .fromTo(
        slideRight,
        { x: 500, opacity: 0 },
        { x: 0, opacity: 1, duration: 0.5 },
        index * 1
      )
      .to(
        slideRight,
        { x: -500, opacity: 0, duration: 0.5 },
        (index + 0.9) * 1
      )
  });  
  timeline.from(slidesLastLeft, {opacity:0,  duration: 0.8 }, 3)
  timeline.to(slidesLastLeft, {opacity:1,  duration: 0.8 }, 3).add(() => textSlideUpAnimation(slidesLastLeft), 3 * 1);

  timeline.from(slidesLastRight, {x:500, duration: 0.8, opacity:0 }, 3)
  timeline.to(slidesLastRight, {x:0, duration: 0.8, opacity:1 }, 3)
}); 

//--------- Gsap Swiper Last Slider With Split Text Animation End---------//

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

//--------- Gsap Text Fade Animation---------//
$('.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(),
  });
});

$('.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(),
  });
});



mediaMatch.add("(max-width: 767px)", () => {
  const slides = document.querySelectorAll(".swiper-slide");
  let slidesWidth = slides[0].offsetWidth * 3;
  slides[0].classList.add("swiper-slide-active");
  slides.forEach((slide, index) => {
    if (index !== 0) {
      gsap.set(slide, { scale: 0.6, rotation: -165, duration: 1, ease: "none", stagger: 2 });
    }
  });
  console.log("small screen");
  ScrollTrigger.create({
    trigger: '.invest-detail-section', // The element to pin
    start: '50% center', // Pin when the top of the section hits the center of the viewport
    // end: () => "+=" + slidesWidth - window.innerHeight, // End after 3 viewport heights
    end: "500% top",
    pin: true, // Pin the element
    scrub: 2, // Smooth scrolling,
    toggleActions: "play none none reset",
    onEnter: function () {
      document.querySelector('.invest-detail-section').classList.add('pinned'); // Add class
    },
    onLeaveBack: function () {
      document.querySelector('.invest-detail-section').classList.remove('pinned'); // Remove class
    },
    onUpdate: (self) => {
      const progress = self.progress; // Get the progress of the scroll
      const currentIndex = Math.floor(progress * (slides.length - 1)); // Calculate the current slide based on scroll progress
      // const scrollingUp = self.direction < 0; // Check 
      // Loop through each slide and update the active class
      slides.forEach((slide, index) => {
        slide.classList.toggle("swiper-slide-active", index === currentIndex);

        const isCenterSlide = index === currentIndex;
        if (currentIndex == 0) {
          gsap.to(".rollingSwiper", {
            xPercent: 0, duration: 1, ease: "none"
          })
        }
        if (currentIndex == 1) {
          gsap.to(".rollingSwiper", {
            xPercent: -100, duration: 1, ease: "none"
          })
        }
        if (currentIndex == 2) {
          gsap.to(".rollingSwiper", {
            xPercent: -200, duration: 1, ease: "none"
          })
        }
        if (currentIndex == 3) {
          gsap.to(".rollingSwiper", {
            xPercent: -300, duration: 1, ease: "none"
          })
        }

        // Apply animation to the current slide
        if (isCenterSlide) {
          gsap.to(slide, { scale: 1, rotation: 0, duration: 1, ease: "none", stagger: 2 });
        } else {
          const spinDirection = index < currentIndex ? -165 : 165; // Adjust rotation direction based on active index
          gsap.to(slide, { scale: 0.6, rotation: spinDirection, duration: 1, ease: "none", stagger: 2 });
        }
      });
    }
  });
});

mediaMatch.add("(min-width: 768px) and (max-width: 1439px)", () => {
  const slides = document.querySelectorAll(".swiper-slide");
  let slidesWidth = slides[0].offsetWidth * 3;
  console.log(slidesWidth, "medium screen");
  gsap.set(".rollingSwiper", {xPercent: 90})
  gsap.set(".swiper-slide:first-child", {rotate: 165})
  // ScrollTrigger for pinning and scrolling animation
  ScrollTrigger.create({
    trigger: '.invest-detail-section', // The element to pin
    start: 'center center', // Pin when the top of the section hits the center of the viewport
    end: () => "+=" + slidesWidth - window.innerHeight, // End after 3 viewport heights
    pin: true, // Pin the element
    scrub: true, // Smooth scrolling
    toggleActions: "play none none reset",
    onEnter: function () {
      document.querySelector('.invest-detail-section').classList.add('pinned'); // Add class
    },
    onLeaveBack: function () {
      document.querySelector('.invest-detail-section').classList.remove('pinned'); // Remove class
    },
    onUpdate: (self) => {
      const progress = self.progress; // Get the progress of the scroll
      const currentIndex = Math.floor(progress * (slides.length - 1)); // Calculate the current slide based on scroll progress
      const scrollingUp = self.direction < 0; // Check 
      // Loop through each slide and update the active class
      slides.forEach((slide, index) => {
        slide.classList.toggle("swiper-slide-active", index === currentIndex);

        const isCenterSlide = index === currentIndex;
        if (currentIndex == 0) {
          gsap.to(".rollingSwiper", {xPercent: 35, duration: 1, ease: "none"})
        }
        if (currentIndex == 1) {
          gsap.to(".rollingSwiper", {xPercent: 0, duration: 1, ease: "none"})
        }
        if (currentIndex == 2) {
          gsap.to(".rollingSwiper", {xPercent: -35, duration: 1, ease: "none"})
        }
        if (currentIndex == 3) {
          gsap.to(".rollingSwiper", {xPercent: -100, duration: 1, ease: "none"})
        }
        // this i want to only when scroll up
        if (scrollingUp && currentIndex == 0) {
          gsap.to(".rollingSwiper", {xPercent: 35, duration: 1, ease: "none"})
          // slide.classList.remove("swiper-slide-active");
        }
        // Apply animation to the current slide
        if (isCenterSlide) {
          gsap.to(slide, { scale: 1, rotation: 0, duration: 1, ease: "none", stagger: 2 });
        } else {
          const spinDirection = index < currentIndex ? -165 : 165; // Adjust rotation direction based on active index
          gsap.to(slide, { scale: 0.6, rotation: spinDirection, duration: 1, ease: "none", stagger: 2 });
        }
      });
    },
  });
});

mediaMatch.add("(min-width: 1440px)", ()=> {
  console.log("bigger screen");
  let cards = gsap.timeline({
    scrollTrigger: {
      trigger: ".invest-detail-section",
      start: "center center",
      // end: document.querySelector(".invest-detail-section").innerHeight,  // Increase the end distance to accommodate multiple cards
      end: "500% top",  // Increase the end distance to accommodate multiple cards
      scrub: 2,
      pin: true,
      toggleActions: "play none none reset",
    }
  });
  cards.from(".swiper-slide", { opacity: 0, stagger: 0.5 })
    .to(".swiper-slide", { opacity: 1, stagger: 0.5 });
});
