/**
 * Avatar — renders the user's uploaded image (avatar_url) or, as a fallback, their
 * initials in a coloured circle. Works in both server and client components (no
 * hooks). Theme the initials fallback via `fallbackClassName`.
 */
export function getInitials(name?: string | null, email?: string | null): string {
  if (name?.trim()) {
    return name
      .trim()
      .split(/\s+/)
      .slice(0, 2)
      .map((p) => p[0]?.toUpperCase() ?? "")
      .join("");
  }
  if (email) return email.slice(0, 2).toUpperCase();
  return "•";
}

interface AvatarProps {
  src?: string | null;
  name?: string | null;
  email?: string | null;
  size?: number;
  className?: string;
  /** Tailwind classes for the initials fallback circle (bg + text colour). */
  fallbackClassName?: string;
}

export function Avatar({
  src,
  name,
  email,
  size = 40,
  className = "",
  fallbackClassName = "bg-primary-100 text-primary-700",
}: AvatarProps) {
  if (src) {
    return (
      // eslint-disable-next-line @next/next/no-img-element
      <img
        src={src}
        alt={name ?? email ?? "avatar"}
        width={size}
        height={size}
        style={{ width: size, height: size }}
        className={`shrink-0 rounded-full object-cover ${className}`}
      />
    );
  }
  return (
    <div
      aria-hidden
      style={{ width: size, height: size, fontSize: Math.round(size * 0.4) }}
      className={`flex shrink-0 items-center justify-center rounded-full font-heading font-semibold ${fallbackClassName} ${className}`}
    >
      {getInitials(name, email)}
    </div>
  );
}
