import React, { useState } from 'react';
import { getItemEmoji } from '../utils/itemUtils';
import './ItemIcon.css';

/**
 * Renders a Minecraft item icon.
 * First tries to load the actual item sprite from mc-heads.net.
 * Falls back to an emoji representation if the image fails.
 */
function ItemIcon({ itemName, size = 32 }) {
  const [imgError, setImgError] = useState(false);

  if (!itemName) {
    return <span className="item-icon-emoji" style={{ fontSize: size * 0.7 }}>📦</span>;
  }

  // Strip namespace for the icon URL
  const shortName = itemName.replace(/^[a-z0-9_]+:/, '');

  if (imgError) {
    return (
      <span className="item-icon-emoji" style={{ fontSize: size * 0.7 }}>
        {getItemEmoji(itemName)}
      </span>
    );
  }

  return (
    <img
      className="item-icon-img"
      src={`https://mc-heads.net/item/${shortName}/${size}`}
      alt={shortName}
      width={size}
      height={size}
      loading="lazy"
      onError={() => setImgError(true)}
      style={{ imageRendering: 'pixelated' }}
    />
  );
}

export default ItemIcon;
