import { avatarColor } from "@/theme/accents";

interface AvatarProps {
  name: string;
  image?: string | null;
  size?: "sm" | "md" | "lg";
}

const SIZES = { sm: "w-6 h-6 text-[var(--z-font-xs)]", md: "w-8 h-8 text-[var(--z-font-md)]", lg: "w-12 h-12 text-lg" };

export function Avatar({ name, image, size = "md" }: AvatarProps) {
  const sizeClass = SIZES[size];

  if (image) {
    return (
      <img
        src={image}
        alt={name}
        class={`${sizeClass} rounded-lg object-cover border border-[var(--z-border)] shrink-0`}
        onError={(e) => { (e.target as HTMLImageElement).style.display = "none"; }}
      />
    );
  }

  const color = avatarColor(name || "?");
  const initial = (name || "?").charAt(0).toUpperCase();

  return (
    <div
      class={`${sizeClass} rounded-lg flex items-center justify-center font-semibold shrink-0`}
      style={{ background: `${color}20`, color }}
    >
      {initial}
    </div>
  );
}
