function normalizeName(value) {
  return String(value || '').trim().toLowerCase();
}

export function resolveProfileAvatar({
  avatarUrl = '',
  profile = null,
  profileId = '',
  name = '',
  profilesById = null,
  profilesByName = null,
}) {
  if (avatarUrl) return avatarUrl;
  if (profile?.avatar_url) return profile.avatar_url;
  if (profileId && profilesById?.get(profileId)?.avatar_url) return profilesById.get(profileId).avatar_url;
  const normalized = normalizeName(name || profile?.name);
  if (normalized && profilesByName?.get(normalized)?.avatar_url) return profilesByName.get(normalized).avatar_url;
  return '';
}

export default function ProfileAvatar({
  profile = null,
  profileId = '',
  name = '',
  avatarUrl = '',
  profilesById = null,
  profilesByName = null,
  size = 32,
  fontSize = 12,
  fallbackBg = 'var(--accent)',
  fallbackColor = '#000',
  alt = '',
  style = {},
}) {
  const resolvedUrl = resolveProfileAvatar({ avatarUrl, profile, profileId, name, profilesById, profilesByName });
  const initials = String(name || profile?.name || '?')
    .split(' ')
    .map((part) => part[0])
    .slice(0, 2)
    .join('')
    .toUpperCase();

  if (resolvedUrl) {
    return (
      <div style={{ width: size, height: size, borderRadius: '50%', overflow: 'hidden', flexShrink: 0, ...style }}>
        <img src={resolvedUrl} alt={alt || name || profile?.name || ''} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
      </div>
    );
  }

  return (
    <div
      style={{
        width: size,
        height: size,
        borderRadius: '50%',
        background: fallbackBg,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        flexShrink: 0,
        ...style,
      }}
    >
      <span style={{ fontSize, fontWeight: 600, color: fallbackColor, lineHeight: 1 }}>{initials || '?'}</span>
    </div>
  );
}
