"use client";
import { useState } from "react";
import { initials } from "@/lib/format";

/** Photo with a graceful fallback to initials if the image is missing or blocked. */
export function Avatar({ person, size = 56, className = "" }: { person: { firstName: string; lastName: string; photoUrl?: string | null }; size?: number; className?: string }) {
  const [broken, setBroken] = useState(false);
  const style = { width: size, height: size, fontSize: Math.max(11, size / 2.6) };
  if (person.photoUrl && !broken) {
    // eslint-disable-next-line @next/next/no-img-element
    return <img src={person.photoUrl} alt={`${person.firstName} ${person.lastName}`} style={style} className={`rounded-full object-cover bg-cream shrink-0 ${className}`} onError={() => setBroken(true)} />;
  }
  return <span style={style} className={`grid place-items-center rounded-full bg-ink text-white font-medium shrink-0 ${className}`}>{initials(person)}</span>;
}
