import * as React from 'react'
import * as AvatarPrimitive from '@radix-ui/react-avatar'
import { cn } from '../lib/cn'

export interface AvatarProps
  extends React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Root> {
  size?: 'sm' | 'md' | 'lg'
  src?: string
  alt?: string
  /** Fallback initials/content shown while/if the image is unavailable. */
  fallback?: React.ReactNode
}

const sizeMap: Record<NonNullable<AvatarProps['size']>, string> = {
  sm: 'h-8 w-8 text-meta',
  md: 'h-8 w-8 text-body-2',
  lg: 'h-12 w-12 text-body-1',
}

export const Avatar = React.forwardRef<
  React.ElementRef<typeof AvatarPrimitive.Root>,
  AvatarProps
>(({ className, size = 'md', src, alt, fallback, ...props }, ref) => (
  <AvatarPrimitive.Root
    ref={ref}
    className={cn(
      'relative inline-flex shrink-0 items-center justify-center overflow-hidden rounded bg-hover text-ink',
      sizeMap[size],
      className,
    )}
    {...props}
  >
    {src ? (
      <AvatarPrimitive.Image src={src} alt={alt ?? ''} className="h-full w-full object-cover" />
    ) : null}
    <AvatarPrimitive.Fallback className="flex h-full w-full items-center justify-center font-sans font-medium">
      {fallback}
    </AvatarPrimitive.Fallback>
  </AvatarPrimitive.Root>
))
Avatar.displayName = 'Avatar'
