import { useState } from 'react';
import { emojiToCodepoint, getTwemojiUrl } from '../../utils/twemoji';

interface TwemojiImgProps {
	emoji: string;
	size?: number;
	className?: string;
}

/**
 * Render a unicode emoji via the Twemoji 14 CDN. Falls back to the
 * system emoji if the CDN image 404s (Unicode 15+ characters that
 * Twemoji 14 never shipped).
 */
export function TwemojiImg({ emoji, size = 22, className }: TwemojiImgProps) {
	const [broken, setBroken] = useState(false);
	if (broken) {
		return (
			<span
				className={className}
				style={{ fontSize: size, lineHeight: 1, display: 'inline-block' }}
			>
				{emoji}
			</span>
		);
	}
	return (
		<img
			src={getTwemojiUrl(emoji)}
			alt={emoji}
			width={size}
			height={size}
			loading="lazy"
			draggable={false}
			className={className}
			style={{ display: 'inline-block', verticalAlign: 'middle' }}
			onError={() => setBroken(true)}
			data-emoji-codepoint={emojiToCodepoint(emoji)}
		/>
	);
}
