"use client";

import clsx from "clsx";
import { useEffect, useState } from "react";

export function ContactAvatar({
  value,
  photoUrl = "",
  size = "sm",
}: {
  value: string;
  photoUrl?: string;
  size?: "sm" | "md" | "lg";
}) {
  const [imageFailed, setImageFailed] = useState(false);
  const safeValue = value.trim();
  const initials = safeValue.split(/\s|@/).filter(Boolean).slice(0, 2).map((part) => part[0]?.toUpperCase()).join("") || "?";

  useEffect(() => {
    setImageFailed(false);
  }, [photoUrl]);

  return (
    <span className={clsx(
      "grid shrink-0 place-items-center overflow-hidden rounded-full bg-[color-mix(in_srgb,var(--accent)_14%,white)] font-black text-[var(--accent)]",
      size === "lg" ? "h-14 w-14 text-sm" : size === "md" ? "h-11 w-11 text-xs" : "h-9 w-9 text-xs",
    )}>
      {photoUrl && !imageFailed ? (
        <img src={photoUrl} alt="" className="h-full w-full object-cover" loading="lazy" onError={() => setImageFailed(true)} />
      ) : initials}
    </span>
  );
}
