import { useLayoutEffect } from '@wordpress/element';

// Utility to map duration class to ms
const getDurationInMs = (duration = 'normal') => {
	switch (duration) {
		case 'animate__slower': return 3000;
		case 'animate__slow': return 2000;
		case 'animate__fast': return 700;
		case 'animate__faster': return 500;
		default: return 1000; // 'normal' or empty
	}
};

export const useAnimateOnChange = ({ ref, animationEntrance = '', animationDuration = 'normal', animationDelay = '' }) => {
	useLayoutEffect(() => {
		const el = ref?.current;
		if (!el) return;

		const animationClasses = [
			'animate__animated',
			animationEntrance,
			animationDuration
			// animationDelay is purposely excluded
		].filter((cls) => typeof cls === 'string' && cls.trim().length > 0);

		// Remove current classes
		el.classList.remove(...animationClasses);

		// Force reflow to restart animation
		void el.offsetWidth;

		// Apply animation classes
		el.classList.add(...animationClasses);
		el.style.visibility = 'visible';

		// Cleanup after animation ends
		const cleanupDelay = getDurationInMs(animationDuration) + 100; // slight buffer
		const cleanup = setTimeout(() => {
			el.classList.remove(...animationClasses);
			el.style.visibility = 'visible';
		}, cleanupDelay);

		return () => clearTimeout(cleanup);
	}, [animationEntrance, animationDuration, animationDelay]);
};
