import { useRef, forwardRef, useLayoutEffect } from '@wordpress/element';
import { useBlockProps } from '@wordpress/block-editor';
import { useAnimateOnChange } from './useAnimateOnChange';
import DynamicTag from '../DynamicTag';
import { getBlockStyleClasses, getNativeWPClasses } from '../blockStyleUtils';

const AnimatedBlockWrapper = forwardRef(function AnimatedBlockWrapper(
	{ children, className = '', tagName = 'div', animationEntrance = '', animationDuration = 'normal', animationDelay = '', attributes },
	externalRef
) {
	const internalRef = useRef(null);

	const combinedClasses = [
		'lg-block',
		className,
		getBlockStyleClasses(attributes),
		getNativeWPClasses(attributes),
	].filter(Boolean).join(' ');
	
	const blockProps = useBlockProps({
		ref: internalRef,
		className: combinedClasses,
		tagName,
		'data-animation': [animationEntrance, animationDuration].filter(Boolean).join(' '),
	});

	// Ensure Gutenberg's ref gets the internal DOM node
	useLayoutEffect(() => {
		if (typeof externalRef === 'function') {
			externalRef(internalRef.current);
		} else if (externalRef) {
			externalRef.current = internalRef.current;
		}
	}, [externalRef]);

	// Use the internal ref for animation effects
	useAnimateOnChange({
		ref: internalRef,
		animationEntrance,
		animationDuration,
		animationDelay
	});

	return <DynamicTag tagName={tagName} {...blockProps}>{children}</DynamicTag>;
});

export default AnimatedBlockWrapper;
