"use client";

import { useState } from "react";

export function PlayerAvatar({
  name,
  size = 24,
  className = "",
}: {
  name: string;
  size?: number;
  className?: string;
}) {
  const [failed, setFailed] = useState(false);
  const dim = `${size}px`;
  const initial = name.slice(0, 1).toUpperCase();

  if (failed || !name) {
    return (
      <div
        className={`rounded bg-muted text-muted-foreground shrink-0 flex items-center justify-center font-bold ${className}`}
        style={{ width: dim, height: dim, fontSize: size * 0.5 }}
        aria-label={name}
      >
        {initial}
      </div>
    );
  }

  return (
    <img
      src={`https://mc-heads.net/avatar/${encodeURIComponent(name)}/${size}`}
      alt=""
      width={size}
      height={size}
      loading="lazy"
      decoding="async"
      onError={() => setFailed(true)}
      className={`rounded shrink-0 bg-muted ${className}`}
    />
  );
}
