document.addEventListener("DOMContentLoaded", function () {
	const animatedBlocks = document.querySelectorAll(
		".orphic-ui-block-animated-image-layers",
	);

	const observer = new IntersectionObserver(
		(entries) => {
			entries.forEach((entry) => {
				if (entry.isIntersecting) {
					const layers = entry.target.querySelectorAll(".animated-layer");
					if (entry.target.dataset.loop == 1) {
						layers.forEach((layer, index) => {
							// Initial delay based on layer index
							setTimeout(
								() => {
									// Start the first appearance
									layer.classList.add("visible");

									// Set up toggle interval
									let isVisible = true;
									setInterval(() => {
										isVisible = !isVisible;
										if (isVisible) {
											layer.classList.add("visible");
										} else {
											layer.classList.remove("visible");
										}
									}, 4000);
								},
								500 + index * 500,
							);
						});
					} else {
						layers.forEach((layer, index) => {
							setTimeout(
								() => {
									layer.classList.add("visible");
								},
								500 + index * 500,
							); // 500ms delay between each layer
						});
					}
					observer.unobserve(entry.target); // Stop observing once animation starts
				}
			});
		},
		{
			threshold: 0.2, // Trigger when 20% of the element is visible
		},
	);

	animatedBlocks.forEach((block) => {
		observer.observe(block);
	});
});
