/**
 * Render a Gutenberg / My Blocks identity icon in admin lists.
 */
import { useEffect, useState } from '@wordpress/element';
import {
	cachedLucideIdentitySvg,
	fetchLucideIdentitySvg,
	normalizeBlockIdentityIcon,
	parseBlockIdentityIcon,
} from '../../shared/blockIdentityIcon';
import { normalizeInlineSvg } from '../../shared/iconRegistry';

/**
 * @param {object} props
 * @param {string} props.icon
 * @param {string} [props.className]
 */
export default function BlockIdentityIcon( { icon, className = '' } ) {
	const ref = normalizeBlockIdentityIcon( icon || 'screenoptions' );
	const parsed = parseBlockIdentityIcon( ref );
	const [ svg, setSvg ] = useState( () =>
		parsed?.kind === 'lucide'
			? cachedLucideIdentitySvg( parsed.value )
			: ''
	);

	useEffect( () => {
		if ( parsed?.kind !== 'lucide' ) {
			return undefined;
		}
		let cancelled = false;
		const cached = cachedLucideIdentitySvg( parsed.value );
		if ( cached ) {
			setSvg( cached );
			return undefined;
		}
		fetchLucideIdentitySvg( parsed.value ).then( ( next ) => {
			if ( ! cancelled ) {
				setSvg( next || '' );
			}
		} );
		return () => {
			cancelled = true;
		};
	}, [ parsed?.kind, parsed?.value ] );

	const wrapClass = [ 'bm-block-identity-glyph', className ]
		.filter( Boolean )
		.join( ' ' );

	if ( parsed?.kind === 'emoji' ) {
		return (
			<span className={ wrapClass + ' is-emoji' } aria-hidden="true">
				{ parsed.value }
			</span>
		);
	}

	if ( parsed?.kind === 'lucide' ) {
		const html =
			normalizeInlineSvg( svg ) ||
			'<svg viewBox="0 0 24 24" width="1em" height="1em" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><circle cx="12" cy="12" r="3" opacity="0.25"/></svg>';
		return (
			<span
				className={ wrapClass + ' is-svg' }
				aria-hidden="true"
				dangerouslySetInnerHTML={ { __html: html } }
			/>
		);
	}

	const slug = parsed?.value || 'screenoptions';
	return (
		<span
			className={ `${ wrapClass } dashicons dashicons-${ slug } bm-dashicon` }
			aria-hidden="true"
		/>
	);
}
