function buildDownloadIcons() {
	let brochureLinks = document.querySelectorAll(".brochure-link-format");

	const iconSrc = img_path_datas.downloadIconPath;
	brochureLinks.forEach((brochureLink) => {
		const brochureLinkIcon = document.createElement("img");
		brochureLinkIcon.src = iconSrc;
		brochureLinkIcon.classList.add("brochure-download-icon");
		brochureLinkIcon.alt = textTranslationsBrochureLink.download;

		brochureLink.appendChild(brochureLinkIcon);
	});
}

async function fetchBrochureSourcePost(brochurePostId) {
	const response = await fetch(`/wp-json/wp/v2/brochures/${brochurePostId.toString()}`);
	return await response.json();
}

async function fetchRelatedPdfUrl(brochureId) {
	const response = await fetch(`/wp-json/wp/v2/media/${brochureId.toString()}`);
	return await response.json();
}

async function hydrateBrochuresLinks() {
	const brochureLinks = Array.from(document.querySelectorAll(".brochure-link-format"));
	if (!brochureLinks.length) return;

	for (const brochureLink of brochureLinks) {
		const brochurePostId = brochureLink.getAttribute("brochure-post-id");
		const brochureOrigHref = brochureLink.getAttribute("href");

		brochurePostSource = await fetchBrochureSourcePost(brochurePostId);
		if (!brochurePostSource.acf || !brochurePostSource.acf.brochure_pdf) continue;

		brochureAttachedMedia = await fetchRelatedPdfUrl(brochurePostSource.acf.brochure_pdf);
		if (brochureAttachedMedia.source_url) {
			brochureLink.setAttribute("href", brochureAttachedMedia.source_url);
		}
	}
}

window.addEventListener("DOMContentLoaded", (event) => {
	buildDownloadIcons();
	// hydrateBrochuresLinks(); // Plus besoin depuis le que single-post-type Brochure redirige automatiquement vers le PDF correspondant
});
