"use client"

import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { gravatarUrl } from "@/lib/contact-avatar"
import { avatarColor, senderInitial } from "@/lib/sender-display"
import { cn } from "@/lib/utils"

interface AccountAvatarProps {
  account: { name: string; email: string; avatarUrl?: string }
  size?: "sm" | "md" | "lg"
  className?: string
}

const sizeClasses = {
  sm: { box: "size-8", text: "text-sm", gravatar: 64 },
  md: { box: "size-10", text: "text-base", gravatar: 80 },
  lg: { box: "size-20", text: "text-3xl", gravatar: 160 },
} as const

export function AccountAvatar({
  account,
  size = "md",
  className,
}: AccountAvatarProps) {
  const displayName = account.name || account.email
  const initial = senderInitial(displayName)
  const color = avatarColor(displayName)
  const config = sizeClasses[size]
  const gravatar = account.email
    ? gravatarUrl(account.email, config.gravatar)
    : undefined

  return (
    <Avatar className={cn("shrink-0", config.box, className)}>
      {account.avatarUrl ? (
        <AvatarImage src={account.avatarUrl} alt={displayName} />
      ) : null}
      {gravatar ? <AvatarImage src={gravatar} alt={displayName} /> : null}
      <AvatarFallback
        className={cn("font-medium text-white", config.text)}
        style={{ backgroundColor: color }}
      >
        {initial}
      </AvatarFallback>
    </Avatar>
  )
}
