/**
 * Use this file for JavaScript code that you want to run in the front-end
 * on posts/pages that contain this block.
 *
 * When this file is defined as the value of the `viewScript` property
 * in `block.json` it will be enqueued on the front end of the site.
 *
 * Example:
 *
 * ```js
 * {
 *   "viewScript": "file:./view.js"
 * }
 * ```
 *
 * If you're not making any changes to this file because your project doesn't need any
 * JavaScript running in the front-end, then you should delete this file and remove
 * the `viewScript` property from `block.json`.
 *
 * @see https://developer.wordpress.org/block-editor/reference-guides/block-api/block-metadata/#view-script
 */
const OrphicHoverHighlight = {
	blocks: null,
	intervals: new Map(),

	init() {
		// Nettoyer tous les intervalles existants
		this.intervals.forEach((interval) => {
			clearInterval(interval);
		});
		this.intervals.clear();

		this.blocks = document.querySelectorAll(".hover-highlight-block");
		if (this.blocks.length) {
			this.blocks.forEach(async (block, index) => {
				// Attendre que toutes les images soient chargées avant de configurer le bloc
				await this.waitForImages(block);
				this.setupBlock(block, index);
			});
		}

		// Gestion responsive
		window.addEventListener('resize', this.handleResize.bind(this));
		this.handleResize();

		// Gestion de la structure mobile avec images
		this.setupMobileLayout();
	},

	waitForImages(block) {
		return new Promise((resolve) => {
			const images = block.querySelectorAll('.hover-highlight-image img');
			if (!images.length) {
				resolve();
				return;
			}

			let loadedImages = 0;
			const totalImages = images.length;

			function imageLoaded() {
				loadedImages++;
				if (loadedImages === totalImages) {
					resolve();
				}
			}

			images.forEach((img) => {
				if (img.complete) {
					imageLoaded();
				} else {
					img.addEventListener('load', imageLoaded);
					img.addEventListener('error', imageLoaded); // En cas d'erreur, on continue quand même
				}
			});
		});
	},

	setupMobileLayout() {
		if (window.innerWidth <= 950) {
			const mobileWrapper = document.querySelectorAll('.js-mobile-wrapper');

			mobileWrapper.forEach(wrapper => {
				// Vérifier si le wrapper a déjà été traité
				if (wrapper.dataset.processed === 'true') return;

				const mobileItems = wrapper.querySelector('.js-mobile-items');
				const items = mobileItems.querySelectorAll('.hover-highlight-mobile-item');
				const contentHolder = wrapper.querySelector('.js-mobile-content-holder');

				if (contentHolder && items.length > 0) {
					const images = contentHolder.querySelectorAll('.hover-highlight-image');
					const fragment = document.createDocumentFragment();

					// Créer les nouveaux éléments
					items.forEach((item, index) => {
						if (images[index]) {
							const wrapper = document.createElement('div');
							wrapper.className = 'hover-highlight-mobile-item-wrapper';

							// Clone les éléments
							const itemClone = item.cloneNode(true);
							const imageClone = images[index].cloneNode(true);

							wrapper.appendChild(itemClone);

							const contentDiv = document.createElement('div');
							contentDiv.className = 'hover-highlight-mobile-item-content';
							contentDiv.appendChild(imageClone);
							wrapper.appendChild(contentDiv);

							fragment.appendChild(wrapper);
						}
					});

					// Remplacer le contenu original par la nouvelle structure
					const parentElement = wrapper.parentNode;
					parentElement.insertBefore(fragment, wrapper);

					// Marquer le wrapper comme traité avant de le supprimer
					wrapper.dataset.processed = 'true';
					// Supprimer les éléments originaux
					wrapper.remove();
				}
			});
		}
	},

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

		this.blocks.forEach((block) => {
			const desktopContainer = block.querySelector('.hover-highlight-container.desktop');
			const mobileContainer = block.querySelector('.hover-highlight-container.mobile');

			if (desktopContainer && mobileContainer) {
				if (isMobile) {
					desktopContainer.style.display = 'none';
					mobileContainer.style.display = 'flex';
					// Reset la hauteur en mode mobile
					desktopContainer.style.height = '';
					this.setupMobileLayout();
				} else {
					desktopContainer.style.display = 'flex';
					mobileContainer.style.display = 'none';
					// Recalculer la hauteur en mode desktop
					this.waitForImages(block).then(() => {
						this.calculateBlockHeight(block);
					});
				}
			}
		});
	},

	setupBlock(block, blockIndex) {
		const textItems = block.querySelectorAll(".hover-highlight-container.desktop .hover-highlight-text-item");
		const images = block.querySelectorAll(".hover-highlight-image");
		let currentIndex = 0;
		let isHovered = false;

		// Initialiser le premier élément comme actif
		if (textItems.length > 0) {
			textItems[0].classList.add("active");
		}

		// Initialiser les images
		if (images.length > 0) {
			images[0].classList.add("active");
			images[0].style.opacity = "1";
			images[0].style.visibility = "visible";
		}

		this.calculateBlockHeight(block);

		// Fonction pour passer à l'élément suivant
		const goToNextItem = () => {
			if (isHovered) return; // Ne pas continuer si en hover

			const nextIndex = (currentIndex + 1) % textItems.length;
			changeActiveItem(nextIndex, "down");
		};

		// Fonction pour changer l'élément actif
		const changeActiveItem = (newIndex, direction) => {
			// Mise à jour des classes textes
			textItems.forEach((item, idx) => {
				if (idx === newIndex) {
					item.classList.add("active");
				} else {
					item.classList.remove("active");
				}
			});

			// Animation des images
			const currentImage = images[currentIndex];
			const nextImage = images[newIndex];

			if (currentImage && nextImage) {
				// Nettoyer les classes précédentes
				images.forEach((img) => {
					img.classList.remove(
						"active",
						"exit-up",
						"exit-down",
						"enter-up",
						"enter-down",
					);
				});

				// Appliquer les classes d'animation
				currentImage.classList.add(`exit-${direction}`);
				nextImage.classList.add(`enter-${direction}`);

				setTimeout(() => {
					nextImage.classList.add("active");
					nextImage.classList.remove(`enter-${direction}`);
				}, 50);

				currentImage.style.opacity = "0";
				currentImage.style.visibility = "hidden";
				nextImage.style.opacity = "1";
				nextImage.style.visibility = "visible";

				// Nettoyer après l'animation
				setTimeout(() => {
					nextImage.classList.remove(`enter-${direction}`);
					currentImage.classList.remove(`exit-${direction}`);
				}, 500);
			}

			// Mettre à jour l'index courant
			currentIndex = newIndex;
		};

		// Démarrer l'intervalle seulement pour la version desktop
		if (window.innerWidth > 950) {
			let intervalId = setInterval(goToNextItem, 4000);
			this.intervals.set(blockIndex, intervalId);
		}

		// Gestion des hover sur les textes (version desktop)
		textItems.forEach((item, index) => {
			item.addEventListener("mouseenter", () => {
				isHovered = true;
				clearInterval(this.intervals.get(blockIndex));

				if (currentIndex === index) return;
				const direction = index < currentIndex ? "up" : "down";
				changeActiveItem(index, direction);
			});

			item.addEventListener("mouseleave", () => {
				isHovered = false;
				clearInterval(this.intervals.get(blockIndex));
				const intervalId = setInterval(goToNextItem, 4000);
				this.intervals.set(blockIndex, intervalId);
			});
		});
	},

	calculateBlockHeight(block) {
		if (window.innerWidth > 950) {
			const images = block.querySelectorAll(".hover-highlight-image");
			let maxHeight = 0;
			images.forEach((image) => {
				if (image.offsetHeight > maxHeight) maxHeight = image.offsetHeight;
			});
			if (maxHeight) {
				const desktopContainer = block.querySelector('.hover-highlight-container.desktop');
				if (desktopContainer) {
					desktopContainer.style.height = maxHeight + "px";
				}
			}
		}
	},
};

// Initialize when DOM is ready
if (document.readyState === "loading") {
	document.addEventListener("DOMContentLoaded", () => {
		OrphicHoverHighlight.init();
	});
} else {
	OrphicHoverHighlight.init();
}
