document.addEventListener("DOMContentLoaded", function () {
	const timeline = document.querySelector(
		".wp-block-carhop-blocks-story-timeline",
	);
	if (!timeline) return;

	function initBlock() {
		const years = timeline.querySelectorAll(".story-timeline__year");
		years.forEach((year, index) => {
			year.setAttribute("data-active", index === 0 ? "true" : "false");
		});
	}

	function removePreviousActiveLinkInSidebar() {
		const activeSidebarLinks = document.querySelectorAll(
			`.story-timeline__years .story-timeline__year[data-active="true"]`,
		);

		activeSidebarLinks.forEach((sidebarLink) => {
			sidebarLink.setAttribute("data-active", "false");
		});
	}

	const timelineStepsProgressionObserver = new IntersectionObserver(
		(entries) => {
			// Ne pas traiter les entrées si l'observer est en pause (pendant un clic)
			// const isIntersetionObserverPaused = getChapterObserverPausedState();
			// if (isIntersetionObserverPaused) return;

			entries.forEach((entry) => {
				const blockId = entry.target.getAttribute("id");
				const relatedStepLink = document.querySelector(`a[href="#${blockId}"]`);

				if (entry.isIntersecting) {
					removePreviousActiveLinkInSidebar();
					// setActiveLinkInSidebar();

					entry.target.setAttribute("active", "true");
					relatedStepLink?.parentElement?.setAttribute("data-active", "true");
				}
			});
		},
		{
			rootMargin: "-10% 0px -50% 0px",
		},
	);

	const timelineSteps = document.querySelectorAll(
		".story-timeline__innerblocks .wp-block-carhop-blocks-story-timeline-step",
	);

	timelineSteps.forEach((step) => {
		timelineStepsProgressionObserver.observe(step);
	});

	initBlock();
});

// Initialiser les écouteurs de liens
// observeChapterLinks();

// // Observer tous les titres h2 de l'article
// const titlesBlocks = document.querySelectorAll('.article-content h2');
// titlesBlocks.forEach((block) => {
//   chapterProgressionObserver.observe(block);
// });
