/**
 * External dependencies.
 */
import { useBlockProps, InnerBlocks } from '@wordpress/block-editor';
import { memo, useEffect, useState } from '@wordpress/element';

/**
 * Internal dependencies.
 */
import { RenderFullWidthAppenderWhenEmpty } from '@spectra-components/block-appender';
import { spectraClassNames } from '@spectra-helpers';
import { useSpectraStyles } from '@spectra-hooks';

/**
 * The Editor Block render.
 *
 * @since x.x.x
 * @param {Object} props The element props.
 * @return {Element} The rendered block.
 */
const Render = ( props ) => {
	// Destructure the required props.
	const { attributes, context, clientId } = props;
	const { editorInnerBlocksPreview = false } = context?.countdown || {}; // Get preview mode from countdown context.

	// Track visibility state - hidden by default unless in preview mode.
	const [ editorStyle, setEditorStyle ] = useState( editorInnerBlocksPreview ? {} : { display: 'none' } );

	// Update visibility when preview mode changes (Live vs Expired toggle).
	useEffect( () => {
		setEditorStyle( editorInnerBlocksPreview ? {} : { display: 'none' } );
	}, [ editorInnerBlocksPreview ] );

	// Define style properties to extract from attributes.
	const config = [
		{ key: 'textColor' },
		{ key: 'textColorHover' },
		{ key: 'backgroundColor' },
		{ key: 'backgroundColorHover' },
		{ key: 'backgroundGradient' },
		{ key: 'backgroundGradientHover' },
	];

	// Generate CSS variables and classes.
	const { style, classNames } = useSpectraStyles( attributes, config );

	const blockProps = useBlockProps( {
		style: { ...style, ...editorStyle }, // Merge generated styles with visibility state.
		className: spectraClassNames( classNames ),
	} );

	return (
		<div { ...blockProps }>
			<InnerBlocks renderAppender={ RenderFullWidthAppenderWhenEmpty( clientId ) } />
		</div>
	);
};

// Memoize component to prevent re-renders when countdown timer updates.
export default memo( Render, ( prevProps, nextProps ) => {
	// Extract only the preview mode value, ignoring timer updates.
	const prevPreview = prevProps.context?.countdown?.editorInnerBlocksPreview;
	const nextPreview = nextProps.context?.countdown?.editorInnerBlocksPreview;

	// Re-render only if these specific props change, not on every timer tick.
	return (
		prevProps.attributes === nextProps.attributes &&
		prevProps.clientId === nextProps.clientId &&
		prevProps.isSelected === nextProps.isSelected &&
		prevPreview === nextPreview
	);
} );
