const MOBILE_BREAKPOINT = 768;

let scrollTriggers = [];
let stickDistance = 0;

function getBlocks() {
	return gsap.utils.toArray(".scroll-story-block");
}

function getBlockCards(block) {
	return gsap.utils.toArray(block.querySelectorAll(".narrative-card"));
}

function applyEvenOddClasses() {
	getBlocks().forEach((block) => {
		getBlockCards(block).forEach((card, index) => {
			card.classList.remove("narrative-card--even", "narrative-card--odd");
			if (index % 2 === 0) {
				card.classList.add("narrative-card--even");
			} else {
				card.classList.add("narrative-card--odd");
			}
		});
	});
}

function initScrollTriggersForBlock(block) {
	const cards = getBlockCards(block);
	if (cards.length === 0) return;

	let firstCardST = ScrollTrigger.create({
		trigger: cards[0],
		start: "top 10%",
	});
	scrollTriggers.push(firstCardST);

	let lastCardST = ScrollTrigger.create({
		trigger: cards[cards.length - 1],
		start: "top 10%",
	});
	scrollTriggers.push(lastCardST);

	cards.forEach((card, index) => {
		var scale = 1 - (cards.length - index) * 0.025;
		let scaleDown = gsap.to(card, {
			scale: scale,
			// transformOrigin: "50% " + (lastCardST.start + stickDistance),
			// transformOrigin: "center top",
		});

		let cardST = ScrollTrigger.create({
			trigger: card,
			start: "top 10%",
			end: () => lastCardST.start + stickDistance,
			pin: true,
			// markers: true,
			pinSpacing: false,
			// pinSpacing: true,
			ease: "none",
			animation: scaleDown,
			toggleActions: "restart none none reverse",
		});

		scrollTriggers.push(cardST);
	});
}

function initScrollTriggers() {
	killScrollTriggers();

	getBlocks().forEach((block) => {
		initScrollTriggersForBlock(block);
	});

	ScrollTrigger.refresh();
}

function killScrollTriggers() {
	scrollTriggers.forEach((st) => st.kill());
	scrollTriggers = [];

	gsap.utils.toArray(".scroll-story-block .narrative-card").forEach((card) => {
		gsap.set(card, { clearProps: "all" });
	});
}

function handleResize() {
	const isMobile = window.innerWidth < MOBILE_BREAKPOINT;

	if (isMobile) {
		killScrollTriggers();
	} else {
		if (scrollTriggers.length === 0) {
			initScrollTriggers();
		} else {
			ScrollTrigger.refresh();
		}
	}
}

applyEvenOddClasses();
handleResize();

window.addEventListener("load", () => {
	if (window.innerWidth >= MOBILE_BREAKPOINT && scrollTriggers.length > 0) {
		ScrollTrigger.refresh();
	}
});

let resizeTimer;
window.addEventListener("resize", () => {
	clearTimeout(resizeTimer);
	resizeTimer = setTimeout(() => {
		handleResize();
	}, 250);
});
