import { getChainIconUrl } from '../../config/chainIcons';

interface ChainIconProps {
  chainId: number
  name?: string
  size?: number
  className?: string
}

export default function ChainIcon({ chainId, name, size = 24, className = '' }: ChainIconProps) {
  const src = getChainIconUrl(chainId);

  if (src) {
    const fallbackChar = name ? name.charAt(0).toUpperCase() : chainId.toString().slice(0, 1);
    return (
      <span className={`relative inline-flex flex-shrink-0 ${className}`} style={{ width: size, height: size }}>
        <img
          src={src}
          alt={name ? `${name} chain` : `Chain ${chainId}`}
          width={size}
          height={size}
          className="rounded-full absolute inset-0 w-full h-full object-cover"
          onError={(e) => {
            e.currentTarget.style.display = 'none';
            const fb = e.currentTarget.nextElementSibling as HTMLElement;
            if (fb) fb.style.display = 'flex';
          }}
        />
        <span
          className="rounded-full bg-[#252830] flex items-center justify-center text-xs font-medium text-[#A0A0A0] hidden"
          style={{ width: size, height: size }}
          aria-hidden
        >
          {fallbackChar}
        </span>
      </span>
    );
  }

  return (
    <span
      className={`rounded-full bg-[#252830] flex items-center justify-center text-xs font-medium text-[#A0A0A0] flex-shrink-0 ${className}`}
      style={{ width: size, height: size }}
      title={name ?? `Chain ${chainId}`}
    >
      {name ? name.charAt(0).toUpperCase() : chainId.toString().slice(0, 1)}
    </span>
  );
}
