/**
 * PersonalizeWP Product Collection Block - Save Component
 *
 * @package PersonalizeWP
 */

import { __ } from '@wordpress/i18n';
import { useBlockProps } from '@wordpress/block-editor';

/**
 * The save function defines the way in which the different attributes should
 * be combined into the final markup, which is then serialized by the block
 * editor into `post_content`.
 *
 * @see https://developer.wordpress.org/block-editor/reference-guides/block-api/block-edit-save/#save
 *
 * @return {WPElement} Element to render.
 */
export default function save(props) {
	const { attributes } = props;
	const {
		queryId,
		pwpRecipe,
		pwpMaxProducts = 8,
		pwpFallbackBehavior = 'show_all',
		pwpFallbackMessage = 'Discover our featured products',
		pwpCollectionTitle,
		layoutType = 'grid',
		gridColumns = 3
	} = attributes;

	if (!pwpRecipe) {
		return null;
	}

	const maxProducts = Math.max(1, Math.min(20, parseInt(pwpMaxProducts, 10) || 8));
	const blockId = queryId;
	const fallbackMessage = pwpFallbackMessage || __('Discover our featured products', 'personalizewp');

	const blockProps = useBlockProps.save({
		className: 'pwp-product-collection-block',
		'data-recipe': pwpRecipe,
		'data-max-products': maxProducts,
		'data-fallback-behavior': pwpFallbackBehavior,
		'data-fallback-message': fallbackMessage,
		'data-block-id': blockId,
	});

	return (
		<div {...blockProps}>
			<pwp-product-collection
				recipe={pwpRecipe}
				max-products={maxProducts}
				fallback-behavior={pwpFallbackBehavior}
				fallback-message={fallbackMessage}
				layout-type={layoutType}
				grid-columns={gridColumns}
				block-id={blockId}
				collection-title={pwpCollectionTitle || ''}
			>
				<div className="woocommerce">
					<div className="woocommerce-info">
						<span className="pwp-loading-spinner"></span>
						{__('Loading personalized products...', 'personalizewp')}
					</div>
				</div>
			</pwp-product-collection>
		</div>
	);
}
