import { useBlockProps, InnerBlocks } from '@wordpress/block-editor';
import { generateBlockClasses } from './utilities/generate-block-classes';
import { generateBlockStyles } from './utilities/generate-block-styles';

// Helper function to generate CSS style string
const generateBlockStyleString = ( stylesObject ) => {
	let styles = '';
	for ( const [key, value] of Object.entries( stylesObject ) ) {
		styles += `${key}: ${value};`;
	}

	return styles;
};

export default function save( { attributes } ) {
	// Access uniqueClass from attributes
	const { uniqueClass } = attributes;

	// Generate the required block classes and styles
	const { blockWrapperClasses, buttonGroupWrapperClasses, innerBlockEditorClasses } = generateBlockClasses( {
		...attributes,
	} );

	const { blockWrapperStyles, buttonGroupWrapperStyles, innerBlocksStyles, overlayStyles } = generateBlockStyles( {
		...attributes,
	} );

	// Generate the CSS strings for both the block wrapper and button group wrapper
	const blockWrapperStyleString = generateBlockStyleString( blockWrapperStyles );
	const buttonGroupWrapperStyleString = generateBlockStyleString( buttonGroupWrapperStyles );
	const overlayStyleString = generateBlockStyleString( overlayStyles );
	const innerBlocksStyleString = generateBlockStyleString( innerBlocksStyles );

	const blockProps = useBlockProps.save( { className: `${blockWrapperClasses}` } );

	return (
		<div {...blockProps}>
			{/* Inject the generated style string */}
			<style>{`.ssmb-block-wrapper.${uniqueClass} { ${blockWrapperStyleString} }`}</style>
			<style>{`.ssmb-button-group-wrapper.${uniqueClass}-button-group { ${buttonGroupWrapperStyleString} }`}</style>
			<style>{`.ssmb-block-editor-inner-blocks.${uniqueClass}-button-list { ${innerBlocksStyleString} }`}</style>
			<style>{`.ssmb-overlay-background.${uniqueClass}-overlay-background { ${overlayStyleString} }`}</style>

			<div className={ blockWrapperClasses }>

				{/* Button Group Wrapper */}
				<div className={ buttonGroupWrapperClasses }>

					{/* Background overlay (when an image exists) */}
					{ ( attributes.backgroundImageDesktop || attributes.backgroundImageTablet || attributes.backgroundImageMobile
                        || attributes.backgroundImageURLDesktop || attributes.backgroundImageURLTablet || attributes.backgroundImageURLMobile
					) && ( <div className={`ssmb-overlay-background ${attributes.uniqueClass}-overlay-background`}></div> ) }

					{/* Block Editor Inner Blocks */}
					<div className={ innerBlockEditorClasses }>

						{/* Inner Blocks Container */}
						<div className="ssmb-button-list">
							<InnerBlocks.Content />
						</div>
					</div>
				</div>
			</div>
		</div>
	);
}
