import { cn } from "@/lib/utils";

/** Initials-based avatar. Falls back to a deterministic brand tint per name. */
export function Avatar({
  name,
  src,
  size = "md",
  className,
}: {
  name: string;
  src?: string | null;
  size?: "xs" | "sm" | "md" | "lg" | "xl";
  className?: string;
}) {
  const sizeClass = {
    xs: "h-6 w-6 text-[10px]",
    sm: "h-8 w-8 text-xs",
    md: "h-10 w-10 text-sm",
    lg: "h-14 w-14 text-lg",
    xl: "h-20 w-20 text-2xl",
  }[size];

  const initials = name
    .split(/\s+/)
    .filter(Boolean)
    .slice(0, 2)
    .map((part) => part[0]?.toUpperCase() ?? "")
    .join("");

  if (src) {
    return (
      // eslint-disable-next-line @next/next/no-img-element
      <img
        src={src}
        alt={name}
        className={cn("shrink-0 rounded-full object-cover", sizeClass, className)}
      />
    );
  }

  // Deterministic hue so the same person always gets the same swatch. The band
  // is deliberately narrow and desaturated so avatars read as printed ink
  // swatches rather than competing with the single accent colour.
  let hash = 0;
  for (let index = 0; index < name.length; index += 1) {
    hash = (hash * 31 + name.charCodeAt(index)) % 360;
  }
  const hue = 18 + (hash % 5) * 14;

  return (
    <span
      className={cn(
        "inline-flex shrink-0 items-center justify-center rounded-full font-semibold text-doc-paper",
        sizeClass,
        className
      )}
      style={{ backgroundColor: `hsl(${hue} 28% 32%)` }}
      aria-hidden="true"
    >
      {initials || "?"}
    </span>
  );
}
