"use client";

const AVATAR_TONES = [
  "from-teal-500 to-cyan-600",
  "from-sky-500 to-blue-600",
  "from-emerald-500 to-teal-600",
  "from-indigo-500 to-violet-600",
  "from-amber-500 to-orange-600",
  "from-rose-500 to-pink-600",
];

function toneIndex(seed: string) {
  let hash = 0;
  for (let i = 0; i < seed.length; i += 1) hash = (hash + seed.charCodeAt(i) * (i + 1)) % 997;
  return hash % AVATAR_TONES.length;
}

export function StudentAvatar({
  firstName,
  lastName,
  size = "md",
}: {
  firstName?: string | null;
  lastName?: string | null;
  size?: "sm" | "md" | "lg";
}) {
  const initials = [firstName?.[0], lastName?.[0]].filter(Boolean).join("") || "؟";
  const sizeClass =
    size === "sm" ? "h-9 w-9 text-xs" : size === "lg" ? "h-14 w-14 text-lg" : "h-11 w-11 text-sm";
  const tone = AVATAR_TONES[toneIndex(`${firstName ?? ""}${lastName ?? ""}`)];

  return (
    <div
      className={`flex shrink-0 items-center justify-center rounded-full bg-gradient-to-br font-bold text-white shadow-sm ${tone} ${sizeClass}`}
    >
      {initials}
    </div>
  );
}
