const TEAM_AVATAR_COLORS = [
  "#adf661",
  "#2ce1c1",
  "#8b5cf6",
  "#f59e0b",
  "#ef4444",
  "#3b82f6",
];

function hashTeamId(id: string): number {
  let hash = 0;
  for (let i = 0; i < id.length; i++) {
    hash = (hash * 31 + id.charCodeAt(i)) & 0xffff;
  }
  return hash;
}

interface TeamAvatarProps {
  teamId: string;
  teamName: string;
  logoUrl?: string | null;
  size?: "sm" | "md" | "lg";
}

const sizeClasses = {
  sm: "h-6 w-6 text-[10px]",
  md: "h-9 w-9 text-sm",
  lg: "h-12 w-12 text-base",
};

export function TeamAvatar({ teamId, teamName, logoUrl, size = "md" }: TeamAvatarProps) {
  if (logoUrl) {
    return (
      <img
        src={logoUrl}
        alt={teamName}
        className={`${sizeClasses[size]} object-cover shrink-0`}
      />
    );
  }

  const color = TEAM_AVATAR_COLORS[hashTeamId(teamId) % TEAM_AVATAR_COLORS.length];
  const initials =
    teamName
      .split(/\s+/)
      .filter(Boolean)
      .slice(0, 2)
      .map((w) => w[0].toUpperCase())
      .join("") || "?";

  return (
    <div
      role="img"
      aria-label={teamName}
      className={`${sizeClasses[size]} flex shrink-0 items-center justify-center font-bold`}
      style={{ backgroundColor: "#000", color }}
    >
      {initials}
    </div>
  );
}
