/* ItemIcon — looks up icon path from manifest, falls back to initials */

let ICON_MANIFEST = null;
const _manifestListeners = [];
fetch('data/icon-manifest.json')
  .then(r => r.json())
  .then(m => { ICON_MANIFEST = m; _manifestListeners.splice(0).forEach(fn => fn()); })
  .catch(() => { ICON_MANIFEST = {}; _manifestListeners.splice(0).forEach(fn => fn()); });

function useManifestReady() {
  const [, setN] = React.useState(0);
  React.useEffect(() => {
    if (ICON_MANIFEST) return;
    const fn = () => setN(n => n + 1);
    _manifestListeners.push(fn);
    return () => {
      const i = _manifestListeners.indexOf(fn);
      if (i >= 0) _manifestListeners.splice(i, 1);
    };
  }, []);
  return !!ICON_MANIFEST;
}

function ItemIcon({ itemType, name, size = 'md' }) {
  const ready = useManifestReady();
  const [failed, setFailed] = React.useState(false);
  const cls = 'item-icon ' + (size === 'lg' ? 'item-icon-lg' : size === 'sm' ? 'item-icon-sm' : '');
  if (!ready || failed || !ICON_MANIFEST || !ICON_MANIFEST[itemType]) {
    return <div className={cls + ' item-icon-fallback'}>{initialFor(name)}</div>;
  }
  return (
    <img
      className={cls}
      src={ICON_MANIFEST[itemType]}
      alt={name}
      onError={() => setFailed(true)}
      loading="lazy"
    />
  );
}

window.ItemIcon = ItemIcon;
