"use client";

/**
 * Avatar primitives — circular profile images with letter fallback,
 * plus a stack-of-avatars helper for "X people / brands" displays
 * (think GitHub collaborator stack).
 */

interface AvatarProps {
  src?: string | null;
  /** Used for the letter fallback + the alt attribute. */
  name?: string | null;
  /** Pixel size — controls width/height/font. Defaults to 32. */
  size?: number;
  /** Optional ring color (e.g. for online indicators). */
  ringClass?: string;
}

export function Avatar({ src, name, size = 32, ringClass }: AvatarProps) {
  const initial = (name ?? "?")[0]?.toUpperCase() ?? "?";
  const sizeClass = `w-[${size}px] h-[${size}px]`;
  const fontClass = size <= 24 ? "text-[9px]" : size <= 32 ? "text-xs" : "text-sm";

  if (src) {
    return (
      // eslint-disable-next-line @next/next/no-img-element
      <img
        src={src}
        alt={name ?? ""}
        className={`${sizeClass} rounded-full object-cover ${ringClass ?? ""}`}
        style={{ width: size, height: size }}
      />
    );
  }

  return (
    <span
      className={`rounded-full bg-gradient-to-br from-slate-200 to-slate-300 text-slate-600 font-semibold flex items-center justify-center ${fontClass} ${ringClass ?? ""}`}
      style={{ width: size, height: size }}
      aria-label={name ?? "Anonymous"}
    >
      {initial}
    </span>
  );
}

/** Stack of overlapping avatars with a "+N" overflow chip. */
interface AvatarStackProps {
  items: Array<{ src?: string | null; name?: string | null; key: string }>;
  /** Max avatars rendered before the overflow chip. */
  max?: number;
  size?: number;
}

export function AvatarStack({ items, max = 3, size = 24 }: AvatarStackProps) {
  const visible = items.slice(0, max);
  const overflow = items.length - visible.length;
  return (
    <div className="flex items-center -space-x-1.5">
      {visible.map((it) => (
        <span
          key={it.key}
          className="ring-2 ring-white rounded-full inline-block"
          style={{ width: size, height: size }}
          title={it.name ?? ""}
        >
          <Avatar src={it.src} name={it.name} size={size} />
        </span>
      ))}
      {overflow > 0 && (
        <span
          className="ring-2 ring-white rounded-full bg-slate-100 text-slate-600 text-[9px] font-semibold flex items-center justify-center inline-block"
          style={{ width: size, height: size }}
        >
          +{overflow}
        </span>
      )}
    </div>
  );
}
