import { mediaUrl } from "@/utils/mediaUrl";

interface Props {
  name?: string | null;
  src?: string | null;
  size?: number;
  className?: string;
}

function initialsOf(name?: string | null): string {
  if (!name) return "?";
  const parts = name.trim().split(/\s+/);
  if (parts.length === 1) return parts[0].slice(0, 2).toUpperCase();
  return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();
}

export default function Avatar({ name, src, size = 40, className = "" }: Props) {
  const dim = { width: size, height: size };
  const resolvedSrc = mediaUrl(src);
  if (resolvedSrc) {
    return (
      <img
        src={resolvedSrc}
        alt={name ?? ""}
        style={dim}
        className={`rounded-full object-cover border border-brand-lines/20 ${className}`}
      />
    );
  }
  return (
    <div
      style={dim}
      className={`rounded-full bg-brand-boxes/70 text-brand-text flex items-center justify-center font-semibold border border-brand-lines/20 ${className}`}
    >
      <span style={{ fontSize: Math.max(10, size * 0.4) }}>{initialsOf(name)}</span>
    </div>
  );
}
