import { useState } from "react";
import { API_URL } from "../config/api.ts";

interface AvatarProps {
  userId: string;
  username: string;
  hasAvatar: boolean;
  size?: number;
  version?: number;
}

export function Avatar(
  { userId, username, hasAvatar, size = 36, version }: AvatarProps,
) {
  const [imgFailed, setImgFailed] = useState(false);
  const sizeStyle = { width: size, height: size };

  if (hasAvatar && !imgFailed) {
    const src = version
      ? `${API_URL}/api/avatars/${userId}?v=${version}`
      : `${API_URL}/api/avatars/${userId}`;
    return (
      <img
        src={src}
        alt={username}
        title={username}
        style={sizeStyle}
        className="avatar-img"
        onError={() => setImgFailed(true)}
      />
    );
  }

  return (
    <div
      className="avatar-initials"
      title={username}
      style={{ ...sizeStyle, fontSize: size * 0.45 }}
    >
      {username.charAt(0).toUpperCase()}
    </div>
  );
}
