gsap.registerPlugin(ScrollTrigger);

const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;

const stacks = document.querySelectorAll("[data-media-stack]");

function initMediaStack(stack) {
  const track = stack.querySelector("[data-media-stack-pin]");
  const cards = gsap.utils.toArray(
    stack.querySelectorAll("[data-media-stack-item]")
  );
  if (!track || !cards.length) return;

  const gap = Number(stack.dataset.mediaStackGap) || 30;
  const total = cards.length;

  if (reducedMotion) {
    cards.forEach((card, i) => {
      gsap.set(card, {
        autoAlpha: i === 0 ? 1 : 0,
        zIndex: i === 0 ? 1 : 0,
      });
    });

    let active = 0;
    ScrollTrigger.create({
      trigger: track,
      start: "top top",
      end: "bottom bottom",
      invalidateOnRefresh: true,
      onUpdate: (self) => {
        const next = Math.min(
          total - 1,
          Math.floor(self.progress * total)
        );
        if (next === active) return;
        active = next;
        cards.forEach((card, i) => {
          gsap.set(card, {
            autoAlpha: i === active ? 1 : 0,
            zIndex: i === active ? 1 : 0,
          });
        });
      },
    });
    return;
  }

  const depth = gap * (total - 1);
  gsap.set(cards, { y: depth, z: -depth });

  cards.forEach((card, index) => {
    const isFirst = index === 0;
    const tl = gsap.timeline({
      scrollTrigger: {
        trigger: track,
        start: () =>
          `top top+=${
            ((track.clientHeight - window.innerHeight) / total) * index
          }`,
        end: () =>
          `bottom bottom+=${
            ((track.clientHeight - window.innerHeight) / total) * index
          }`,
        scrub: 0.5,
        invalidateOnRefresh: true,
      },
    });

    for (let step = 0; step < total - 1; step++) {
      tl.to(card, {
        y: `-=${gap}`,
        z: `+=${gap}`,
        ease: "back.inOut(3)",
      });
    }

    if (!isFirst) {
      tl.to(card, {
        yPercent: -80,
        y: "-50vh",
        scale: 1.2,
        rotation: (Math.random() - 0.5) * 50,
        ease: "power4.in",
      });
    }
  });
}

if (!reducedMotion) {
  const lenis = new Lenis({
    lerp: 0.1,
    smoothWheel: true,
  });

  lenis.on("scroll", ScrollTrigger.update);
  gsap.ticker.add((time) => {
    lenis.raf(time * 1000);
  });
  gsap.ticker.lagSmoothing(0);
}

stacks.forEach(initMediaStack);
