gsap.registerPlugin(ScrollTrigger, ScrollToPlugin);
ScrollTrigger.config({
  limitCallbacks: true,
  ignoreMobileResize: true,
});


const mm = gsap.matchMedia();

function intialSetup() {
  gsap.set(".main-logo-fade-in-up", {
    y: 100,
    opacity: 0,
  })
  gsap.set(".hero-content-fade-in", {
    opacity: 0,
  })
}

function setupHeroSectionAnimation() {

  gsap.to(".main-logo-fade-in-up", {
    y: 0,
    opacity: 1,
    duration: 1,
    delay: 0.6,
  })
  gsap.to(".hero-content-fade-in", {
    y: 0,
    opacity: 1,
    duration: 1,
    delay: 1,
  })
  gsap.to(".banner-square.square-big", {
    bottom: "350px",
    duration: 1.5,
    delay: 0.6,
    y: "100%",
    onStart: onStart,
    ease: "bounce.out",
    // paused: true
  }); // Adjust y value for desired position
  gsap.to(".banner-square.square-mid", {
    top: "-400px",
    duration: 1.5,
    y: "100%",
    delay: 1.1,
    onStart: onStart,
    ease: "bounce.out",
    // paused: true
  }); // Adjust y value for desired position
  gsap.to(".banner-square.square-small", {
    top: "-200px",
    duration: 1.5,
    y: "100%",
    delay: 1.6,
    onStart: onStart,
    onComplete: onComplete,
    onCompleteParams: [this],
    ease: "bounce.out",
    // paused: true
  });

  function onComplete(target) {
    setTimeout(() => {
      $("body").removeClass("no-scroll"); // Enable scrolling
      window.animationsInitialized = true;
    }, 50);
  }

  function onStart(target) { }

  if (ScrollTrigger.isInViewport(".hero-section")) {
    console.log("Hero section In viewport");
    // window.addEventListener("load", () => {
    //   document.body.classList.add("no-scroll");
    // });
  }
}

function setupCardAnimation() {
  // GSAP matchMedia to set different animations based on screen width
  const txtSlideUpArr = gsap.utils.toArray(`[txt-slide-up-invest-detail] > [text-split]`);

  for (let txt of txtSlideUpArr) {
    let typeSplit = new SplitType(txt, {
      types: "words, chars",
      tagName: "span",
    });

    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 80%",
      pinnedContainer: ".animation-container",
      markers: false,
      onLeaveBack: () => {
        tl.reverse();
      },
    });

    ScrollTrigger.create({
      trigger: txt,
      start: "top 80%",
      pinnedContainer: ".animation-container",
      onEnter: () => tl.play(),
    });
  }

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

  // mm.add("(min-width: 2160px) ", function () {
  //   const cardSlides = gsap.utils.toArray(".swiper-slide");
  //   gsap.set(cardSlides, { opacity: 0 }); // Initial state: invisible
  //   gsap.to(cardSlides, {
  //     scrollTrigger: {
  //       trigger: ".invest-detail-section", // Trigger element
  //       start: "top 50%", // Start pinning when the section reaches the top
  //       end: "top 20%", // Extend the pin duration for the animations
  //       scrub: true, // Smooth scrubbing effect
  //       markers: false
  //     },
  //     opacity: 1, // Initial state: invisible
  //     stagger: 0.2, // Delay between animations for each card
  //   })
  // });

  // mm.add("(min-width: 769px) and (max-width:2159px)", function () {

  mm.add("(min-width: 769px)", function () {
    const cardSlides = gsap.utils.toArray(".swiper-slide"); // Select all card slides except the first 
    const totalDuration = (0.5 * (cardSlides.length - 1)) + 1; // Stagger * (number of slides - 1) + duration

    // Create a timeline for animations
    gsap.timeline({
      scrollTrigger: {
        toggleActions: "play pause none none",
        trigger: ".invest-detail-section", // Trigger element
        start: "top top", // Start pinning when the section reaches the top
        end: `+=${totalDuration * 500}px`, // Extend the pin duration for the animations
        pin: ".animation-container", // Pin the animation container
        scrub: true, // Smooth scrubbing effect
        pinSpacing: true, // Disable automatic spacing for pinned elements
      },
      markers: false, // Add markers for debugging
    });

    gsap.set(cardSlides, { opacity: 0 }); // Initial state: invisible

    gsap.to(cardSlides[0], {
      scrollTrigger: {
        trigger: cardSlides[0], // Trigger element
        start: "top 90%", // Start pinning when the section reaches the top
        end: `+=${(2 + 1 * 1) * totalDuration * 500 / 3}px`, // Extend the pin duration for the animations
        scrub: true, // Smooth scrubbing effect
        // markers: true
      },
      opacity: 1, // Initial state: invisible
    })
    gsap.to(cardSlides[1], {
      scrollTrigger: {
        trigger: cardSlides[1], // Trigger element
        start: "top 65%", // Start pinning when the section reaches the top
        end: `+=${ ((2 + 2 * 1) * totalDuration * 500 / 3) * 0.8 }px`, // Extend the pin duration for the animations
        scrub: true, // Smooth scrubbing effect
        // markers: true
      },
      opacity: 1, // Initial state: invisible
    })
    gsap.to(cardSlides[2], {
      scrollTrigger: {
        trigger: cardSlides[2], // Trigger element
        start: "top 35%", // Start pinning when the section reaches the top
        end: `+=${ ((2 + 3 * 1) * totalDuration * 500 / 3) * 0.5 }px`, // Extend the pin duration for the animations
        scrub: true, // Smooth scrubbing effect
        // markers: true
      },
      opacity: 1, // Initial state: invisible
    })

  });

  mm.add("(max-width: 768px)", function () {
    const cardSlides = gsap.utils.toArray(".swiper-slide");
    gsap.set(cardSlides, { opacity: 0 }); // Initial state: invisible
    cardSlides.forEach((card, index) => {
      gsap.to(card, {
        scrollTrigger: {
          trigger: card, // Trigger element
          start: "top 70%", // Start pinning when the section reaches the top
          end: "top 20%", // Extend the pin duration for the animations
          scrub: true, // Smooth scrubbing effect
          // markers: true
        },
        opacity: 1, // Initial state: invisible
      })
    })
  });
}

function setupTextAnimation() {
  const txtSlideUpArr = gsap.utils.toArray(`[txt-slide-up] > [text-split]`);

  for (let txt of txtSlideUpArr) {
    let typeSplit = new SplitType(txt, {
      types: "words, chars",
      tagName: "span",
    });

    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 80%",
      pinnedContainer: ".animation-container",
      markers: false,
      onLeaveBack: () => {
        tl.reverse();
      },
    });

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

    // Check if the element is in the viewport
    if (ScrollTrigger.isInViewport(txt)) {
      tl.play();
    }
  }

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

function setupMiddleSectionAnimation() {
  const middleSectionContent = document.querySelector(".middle-section .container");
  const middleSectionContentScrollTop = middleSectionContent.getBoundingClientRect().top;
  console.log("🚀 ~ setupMiddleSectionAnimation ~ middleSectionContentScrollTop:", middleSectionContentScrollTop)
  const middleSectionContentScrollBottom = middleSectionContent.getBoundingClientRect().bottom;
  console.log("🚀 ~ setupMiddleSectionAnimation ~ middleSectionContentScrollBottom:", middleSectionContentScrollBottom)
  const windowScrollHeight = window.innerHeight;

  mm.add("(min-width: 1440px)", function () {
    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: ".invest-detail-section",
        trigger: ".middle-section .container",
        start: "top 80%",
        end: "bottom 10%",
        scrub: 0.5,
        snap: 1 / 2,
        // markers: true,
        pinnedContainer: ".animation-container",
        onToggle: (self) => {
          if (self.isActive) {
            circleTimeline.play();
          } else {
            circleTimeline.reverse();
          }
        },
        fastScrollEnd: true,
      });
  });

  mm.add("(max-width: 1439px)", function () {
    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: ".invest-detail-section",
        trigger: ".middle-section .container",
        start: `top 80%`,
        end: `bottom 10%`,
        scrub: 0.5,
        snap: 1 / 2,
        // markers: true,
        pinnedContainer: ".animation-container",
        onToggle: (self) => {
          if (self.isActive) {
            circleTimeline.play();
          } else {
            circleTimeline.reverse();
          }
        },
        fastScrollEnd: true,
      });
  });
}

function setupFinancialSectionAnimation() {
  let windowWidth = window.innerWidth;
  const sliderRight = document.querySelector(".gsap-slider .gsap-slide-right");

  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: ".animated-financial-container",
    start: "center center",
    end: () => `+=${getScrollAmount() * -1}`,
    pin: true,
    pin: ".animation-container",
    pinnedContainer: ".animation-container",
    // pin: ".gsap-slider",
    animation: tween,
    scrub: true,
    // invalidateOnRefresh: true,
    // markers:{startColor:"purple", endColor:"pink"},
    // 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 });

    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.
    if (index > 0) {
      ScrollTrigger.create({
        trigger: slide,
        start: "left 65%",
        end: "right 65%",
        pinnedContainer: ".animation-container",
        // 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,
        // invalidateOnRefresh: true,
        containerAnimation: tween,
        horizontal: true,
        fastScrollEnd: true,
      });
    } else {
      ScrollTrigger.create({
        trigger: ".animated-financial-container",
        start: "top 80%",
        end: "bottom center",
        pinnedContainer: ".animation-container",
        // 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,
        // invalidateOnRefresh: true,
        // markers: true,
        // containerAnimation: tween,
        fastScrollEnd: true,
      });
    }
  });

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

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

function faqSectionHeadingAnimation() {
  const txtSlideUpArr = gsap.utils.toArray(`.faq-section [txt-slide-up] > [text-split]`);

  for (let txt of txtSlideUpArr) {
    let typeSplit = new SplitType(txt, {
      types: "words, chars",
      tagName: "span",
    });

    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 80%",
      pinnedContainer: ".animation-container",
      markers: false,
      onLeaveBack: () => {
        tl.reverse();
      },
    });

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

    // Check if the element is in the viewport
    if (ScrollTrigger.isInViewport(txt)) {
      tl.play();
    }
  }

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

document.addEventListener("DOMContentLoaded", function () {

  intialSetup();
  setTimeout(() => {
    $("#loader").fadeOut(500, function () {
      $(this).remove();
    });
  }, 1);

  setupHeroSectionAnimation();
  setupCardAnimation();
  setupTextAnimation();
  setupMiddleSectionAnimation();
  setupFinancialSectionAnimation();
  faqSectionHeadingAnimation();
  // ================== Resize Event ==================

  // Flag to prevent multiple reloads
  let resizeTimeout;

  // Store the window width
  let windowWidth = $(window).width();
  let windowHeight = $(window).height();
  console.log("🚀 ~ windowWidth:", windowWidth);

  window.addEventListener("resize", function () {
    // Check if the window width has actually changed
    if ($(window).width() != windowWidth || $(window).height() != windowHeight) {
      // Update windowWidth
      windowWidth = $(window).width();

      // Debounce logic: Clear the previous timeout and set a new one
      clearTimeout(resizeTimeout);
      resizeTimeout = setTimeout(() => {
        window.location.reload(); // Reload the page on resize for non-mobile devices
      }, 300); // Adjust delay as necessary for your use case
    }
  });

  window.onbeforeunload = function () {
    window.scrollTo(0, 0);
  };
});

// ================== Helper Functions ==================

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

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