// Function to convert hex to RGBA
export function hexToRgba( hex, opacity = 1 ) {
	let isValidHex = /^#([0-9A-F]{3}){1,2}$/i.test( hex );

	if ( !isValidHex ) {
		return 'rgba(0, 0, 0, 1)'; // Fallback to default color
	}

	let fullHex = hex.length === 4 ?
		'#' + hex[ 1 ] + hex[ 1 ] + hex[ 2 ] + hex[ 2 ] + hex[ 3 ] + hex[ 3 ] :
		hex;

	let r = parseInt( fullHex.slice( 1, 3 ), 16 );
	let g = parseInt( fullHex.slice( 3, 5 ), 16 );
	let b = parseInt( fullHex.slice( 5, 7 ), 16 );

	return `rgba(${ r }, ${ g }, ${ b }, ${ opacity })`;
}

// Function to convert hex to RGB
export function hexToRgb( hex ) {
	if ( !hex || typeof hex !== 'string' ) {
		// Return a fallback value (e.g., black) if hex is undefined or not a string
		return '0, 0, 0';
	}

	var bigint = parseInt( hex.replace( '#', '' ), 16 );
	var r = ( bigint >> 16 ) & 255;
	var g = ( bigint >> 8 ) & 255;
	var b = ( bigint >> 0 ) & 255;

	return `${ r }, ${ g }, ${ b }`;
}

// Utils for checking if a URL is valid
export function isValidUrl( url ) {
	if ( !url || url.startsWith( '#' ) ) {return true;} // Allow empty or anchor links
	try {
		new URL( url );
		return true;
	} catch {
		return false;
	}
}

// Utils for Hover State
export function useHoverState( initialAttributes ) {
	const [ attributes, setAttributes ] = useState( initialAttributes );

	const toggleHoverState = ( isHovered ) => {
		setAttributes( ( prev ) => ( {
			...prev,
			isHovered,
		} ) );
	};

	return { attributes, setAttributes, toggleHoverState };
}
