'use client'

import { cn, getAvatarColor } from '@/lib/utils'

interface AvatarProps {
  initials: string
  color?: string
  size?: 'xs' | 'sm' | 'md' | 'lg'
  className?: string
  title?: string
}

const SIZES = {
  xs: 'w-5 h-5 text-[9px]',
  sm: 'w-7 h-7 text-[10px]',
  md: 'w-9 h-9 text-xs',
  lg: 'w-11 h-11 text-sm',
}

export function Avatar({ initials, color, size = 'sm', className, title }: AvatarProps) {
  const bg = color || getAvatarColor(initials)
  return (
    <div
      title={title || initials}
      className={cn(
        'rounded-full border-2 border-white flex items-center justify-center font-bold flex-shrink-0 select-none',
        SIZES[size],
        className
      )}
      style={{ background: bg, color: '#444' }}
    >
      {initials}
    </div>
  )
}

interface AvatarGroupProps {
  members: { id: string; initials: string; color?: string; name?: string }[]
  max?: number
  size?: AvatarProps['size']
}

export function AvatarGroup({ members, max = 4, size = 'sm' }: AvatarGroupProps) {
  const show = members.slice(0, max)
  const extra = members.length - max

  return (
    <div className="flex items-center">
      {show.map((m, i) => (
        <Avatar
          key={m.id}
          initials={m.initials}
          color={m.color}
          size={size}
          title={m.name || m.initials}
          className="-mr-1.5 last:mr-0"
          style={{ zIndex: show.length - i } as React.CSSProperties}
        />
      ))}
      {extra > 0 && (
        <div
          className={cn(
            'rounded-full border-2 border-white bg-gray-150 text-gray-600 flex items-center justify-center font-bold flex-shrink-0 -mr-1.5',
            SIZES[size]
          )}
        >
          +{extra}
        </div>
      )}
    </div>
  )
}
