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

const palette = [
  "from-gold-300 to-gold-500 text-[#1f1604]",
  "from-indigo-200 to-indigo-400 text-indigo-900",
  "from-emerald-200 to-emerald-400 text-emerald-900",
  "from-rose-200 to-rose-400 text-rose-900",
  "from-sky-200 to-sky-400 text-sky-900",
  "from-amber-200 to-amber-400 text-amber-900",
  "from-violet-200 to-violet-400 text-violet-900",
]

const variantMap: Record<string, string> = {
  gold: "from-gold-300 to-gold-500 text-[#1f1604]",
  muted: "from-neutral-200 to-neutral-300 text-neutral-800",
  indigo: "from-indigo-200 to-indigo-400 text-indigo-900",
  emerald: "from-emerald-200 to-emerald-400 text-emerald-900",
  rose: "from-rose-200 to-rose-400 text-rose-900",
  sky: "from-sky-200 to-sky-400 text-sky-900",
  amber: "from-amber-200 to-amber-400 text-amber-900",
  violet: "from-violet-200 to-violet-400 text-violet-900",
}

export function AvatarBadge({
  name,
  initials: initialsProp,
  variant,
  size = "md",
  className,
}: {
  name?: string
  initials?: string
  variant?: keyof typeof variantMap
  size?: "xs" | "sm" | "md" | "lg"
  className?: string
}) {
  const source = name ?? initialsProp ?? ""

  const initials = initialsProp
    ? initialsProp.slice(0, 2).toUpperCase()
    : source
        .split(/\s+/)
        .filter(Boolean)
        .slice(0, 2)
        .map((w) => w[0])
        .join("")
        .toUpperCase() || "??"

  const paletteClass = variant
    ? variantMap[variant]
    : palette[
        (source.split("").reduce((a, c) => a + c.charCodeAt(0), 0) || 0) % palette.length
      ]

  const dims =
    size === "xs"
      ? "h-6 w-6 text-[9.5px]"
      : size === "sm"
        ? "h-8 w-8 text-[11px]"
        : size === "lg"
          ? "h-12 w-12 text-[15px]"
          : "h-10 w-10 text-[12.5px]"

  return (
    <div
      className={cn(
        "inline-flex items-center justify-center rounded-full bg-gradient-to-br font-bold shrink-0",
        paletteClass,
        dims,
        className,
      )}
    >
      {initials}
    </div>
  )
}
