interface AvatarProps {
  name?: string;
  src?: string;
  size?: "xs" | "sm" | "md" | "lg";
  color?: "rose" | "amber" | "blue" | "green" | "purple";
}

const sizes = {
  xs: "w-6 h-6 text-[10px]",
  sm: "w-8 h-8 text-xs",
  md: "w-10 h-10 text-sm",
  lg: "w-14 h-14 text-xl",
};

const colors = [
  "bg-rose-200 dark:bg-rose-800 text-rose-700 dark:text-rose-200",
  "bg-amber-200 dark:bg-amber-800 text-amber-700 dark:text-amber-200",
  "bg-blue-200 dark:bg-blue-800 text-blue-700 dark:text-blue-200",
  "bg-green-200 dark:bg-green-800 text-green-700 dark:text-green-200",
  "bg-purple-200 dark:bg-purple-800 text-purple-700 dark:text-purple-200",
];

function initials(name: string) {
  const parts = name.trim().split(" ");
  if (parts.length === 1) return parts[0].slice(0, 2).toUpperCase();
  return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();
}

function hashColor(name: string) {
  let h = 0;
  for (let i = 0; i < name.length; i++) h = (h * 31 + name.charCodeAt(i)) % colors.length;
  return colors[h];
}

export function Avatar({ name = "?", src, size = "md" }: AvatarProps) {
  if (src) {
    return (
      <img
        src={src}
        alt={name}
        className={`${sizes[size]} rounded-full object-cover flex-shrink-0`}
      />
    );
  }
  return (
    <div className={`${sizes[size]} ${hashColor(name)} rounded-full flex items-center justify-center font-semibold flex-shrink-0`}>
      {initials(name)}
    </div>
  );
}
