document.addEventListener("DOMContentLoaded", function () {
	const tablist = document.querySelector(
		".statistiques-collections__toolbar .tablist",
	);
	if (!tablist) return;

	const tabsButtons = tablist.querySelectorAll("button");

	function setActiveTab(currentTab) {
		tabsButtons.forEach((tab) => {
			tab.setAttribute("aria-selected", "false");
		});
		currentTab.setAttribute("aria-selected", "true");
	}

	function setActiveTabPanel(currentTabButton) {
		const currentTabPanelId = currentTabButton.getAttribute("aria-controls");
		const currentTabPanel = document.querySelector(
			`.statistiques-collections__stats-items #${currentTabPanelId}`,
		);
		currentTabPanel.setAttribute("data-active", "true");
		animateBar(currentTabPanel);
	}

	function animateBar(currentTabPanel) {
		const bar = currentTabPanel.querySelector(".percentage-bar");
		const percentage = bar.getAttribute("data-percentage");
		bar.style.width = "0%";
		requestAnimationFrame(() => {
			bar.style.width = `${percentage}%`;
		});
	}

	function hideAllTabPanels() {
		const tabPanels = document.querySelectorAll(
			".statistiques-collections__stats-items .statistiques-collections__stat-item",
		);
		tabPanels.forEach((tabPanel) => {
			tabPanel.setAttribute("data-active", "false");
		});
	}

	tabsButtons.forEach((tab) => {
		tab.addEventListener("click", () => {
			setActiveTab(tab);
			hideAllTabPanels();
			setActiveTabPanel(tab);
		});
	});
});
