/**
 * External dependencies.
 */
import { createHigherOrderComponent } from '@wordpress/compose';

/**
 * Internal dependencies.
 */
import DynamicImageEnhancer from '@spectra-pro-extensions/dynamic-content/enhancers/DynamicImageEnhancer';
import { isAllowedBlockForImage } from '@spectra-pro-extensions/dynamic-content/utils/helpers';
import { IMAGE_BLOCK_CONTENT_CONFIG } from '@spectra-pro-extensions/dynamic-content/utils/constants';

/**
 * Higher-order component to enhance blocks with dynamic image content capability.
 *
 * Wraps the original BlockEdit component to add support for dynamic images in
 * supported blocks, based on the provided configuration and block attributes.
 *
 * @since x.x.x
 *
 * @param {Function} BlockEdit - The original BlockEdit component to enhance.
 * @return {Function} The enhanced component with dynamic image support.
 */
const withDynamicImage = createHigherOrderComponent( ( BlockEdit ) => {
	return ( props ) => {
		// Skip enhancement if the block is not supported for dynamic images.
		if ( ! isAllowedBlockForImage( props ) ) return <BlockEdit { ...props } />;

		const { clientId, name: blockName, attributes } = props;

		const { spectraProEnableDynamicImage, spectraProDynamicImage } = attributes;

		// Retrieve the block's configuration for dynamic image content.
		const config = IMAGE_BLOCK_CONTENT_CONFIG?.[ blockName ];

		// Skip enhancement if no configuration exists for the block.
		if ( ! config ) return <BlockEdit { ...props } />;

		const contentAttr = config.contentAttr;

		// Skip enhancement if dynamic image is not enabled or no dynamic image data is set.
		if ( ! spectraProEnableDynamicImage || ! spectraProDynamicImage ) return <BlockEdit { ...props } />;

		return (
			<DynamicImageEnhancer
				clientId={ clientId }
				blockName={ blockName }
				attributes={ attributes }
				contentAttr={ contentAttr }
				props={ props }
				BlockEdit={ BlockEdit }
			/>
		);
	};
}, 'withDynamicImage' );

export default withDynamicImage;
