// Reusable avatar that prefers an uploaded image and falls back to a coloured
// letter circle. Use this everywhere the app needs to render a profile.

import { useCachedAvatarUrl } from '../lib/avatarCache';

interface Props {
  url?: string | null | undefined;
  displayName?: string | null | undefined;
  className?: string;
  // Background gradient classes used when no image is set. Defaults to a
  // brand-tinted fallback; callers can override (e.g. to colour-by-id).
  fallbackClass?: string;
  alt?: string;
}

export function Avatar({
  url,
  displayName,
  className = 'h-10 w-10',
  fallbackClass = 'bg-accent/20 text-accent',
  alt,
}: Props) {
  const effectiveUrl = useCachedAvatarUrl(url);
  if (effectiveUrl) {
    return (
      <img
        src={effectiveUrl}
        alt={alt ?? displayName ?? ''}
        className={'shrink-0 rounded-full object-cover ' + className}
        draggable={false}
      />
    );
  }
  const letter = (displayName ?? '?').trim().charAt(0).toUpperCase() || '?';
  return (
    <div
      aria-hidden={alt ? undefined : 'true'}
      className={
        'flex shrink-0 items-center justify-center rounded-full font-semibold ' +
        fallbackClass +
        ' ' +
        className
      }
    >
      {letter}
    </div>
  );
}
