const COLORS = ["#22c55e", "#06b6d4", "#f59e0b", "#f97316", "#84cc16", "#14b8a6", "#64748b"];

export function Avatar({ name, size = 32, src }: { name: string; size?: number; src?: string | null }) {
  const normalized = name.trim() || "?";
  const color = COLORS[hashString(normalized) % COLORS.length];
  const initials = normalized
    .split(/[\s_-]+/)
    .slice(0, 2)
    .map((part) => part[0]?.toUpperCase())
    .join("");

  return (
    <span
      className="avatar"
      style={{ "--avatar-color": color, width: size, height: size, fontSize: Math.max(11, size * 0.36) } as React.CSSProperties}
      aria-hidden="true"
    >
      {src ? <img src={src} alt="" /> : initials || "?"}
    </span>
  );
}

function hashString(value: string) {
  let hash = 0;
  for (let index = 0; index < value.length; index += 1) {
    hash = (hash << 5) - hash + value.charCodeAt(index);
    hash |= 0;
  }
  return Math.abs(hash);
}
