import { useBlockProps } from '@wordpress/block-editor';
import { generateButtonClasses } from '../utilities/generate-button-classes';
import { generateButtonStyles } from '../utilities/generate-button-styles';
import CustomButton from '../components/CustomButton';

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

	return styles;
};

const isValidUrl = ( url ) => {
	if ( !url || url.startsWith( '#' ) ) {return true;}
	try {
		new URL( url );
		return true;
	} catch {
		return false;
	}
};

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

	// Generate button classes and styles
	const { blockButtonClasses, buttonIconClasses, buttonClasses } = generateButtonClasses( attributes );
	const { blockButtonStyles, buttonOverlayStyles, buttonStyles } = generateButtonStyles( attributes );
	const { buttonIcon, isFontAwesome, buttonIconLink, openInNewTab, linkRel, linkTitle } = attributes;

	// Generate the style string
	const blockButtonStyleString = generateStyleString( blockButtonStyles );
	const buttonOverlayStyleString = generateStyleString( buttonOverlayStyles );
	const buttonStyleString = generateStyleString( buttonStyles );


	// Block properties for the main button container (ssmb-icon-button)
	const blockProps = useBlockProps.save( { className: blockButtonClasses, } );

	// Determine if the icon is FontAwesome or a custom SVG
	const icon = isFontAwesome
		? { iconName: buttonIcon.iconName, prefix: buttonIcon.prefix }
		: buttonIcon; // Use the SVG string directly

	// Validate URL, fallback to '#' if not valid
	const validLink = buttonIconLink && isValidUrl( buttonIconLink ) ? buttonIconLink : '#';

	// Security: rel should include noopener if open in new tab
	const relAttr = linkRel ? `${linkRel} noopener` : 'noopener';

	// Define target attribute based on new tab
	const targetAttr = openInNewTab ? '_blank' : '_self';

	return (
		<div {...blockProps}>
			{/* Inject the generated style string */}
			<style>{`.ssmb-block-button.${uniqueBlockButtonClass} { ${blockButtonStyleString} }`}</style>
			<style>{`.ssmb-button-overlay-background.${uniqueBlockButtonClass}-button-overlay-background { ${buttonOverlayStyleString} }`}</style>
			<style>{`.ssmb-icon-button.${uniqueBlockButtonClass} { ${buttonStyleString} }`}</style>

			{/* Background overlay (when an image exists) */}
			{ ( attributes.blockButtonBackgroundImageDesktop || attributes.blockButtonBackgroundImageTablet || attributes.blockButtonBackgroundImageMobile
                || attributes.blockButtonBackgroundImageURLDesktop || attributes.blockButtonBackgroundImageURLTablet || attributes.blockButtonBackgroundImageURLMobile
			) && ( <div className={`ssmb-button-overlay-background ${attributes.uniqueBlockButtonClass}-button-overlay-background`}></div> ) }

			{/* Button Wrapper */}
			<div className={ buttonIconClasses }>

				{/* Button Inner styles */}
				<div className={ buttonClasses }>

					{/* Render Custom Button */}
					{buttonIconLink ? (
						<a
							href = { validLink }
							target = { targetAttr }
							rel = { relAttr || undefined }
							title = { linkTitle || undefined }
						>
							<CustomButton
								icon = { buttonIcon }
								buttonIconColor = { attributes.buttonIconColor }
								hoverButtonIconColor = { attributes.hoverButtonIconColor }
								defaultColor = "#ffffff" // Set this to the default color
							/>
						</a>
					) : (
						<CustomButton
							icon = { buttonIcon }
							buttonIconColor = { attributes.buttonIconColor }
							hoverButtonIconColor = { attributes.hoverButtonIconColor }
							defaultColor = "#ffffff" // Set this to the default color
						/>
					)}
				</div>
			</div>
		</div>
	);
}
