import styles from './Avatar.module.css'
import { hashColor } from '../../utils/hashColor'
import { useTheme } from '../../providers/ThemeProvider'

interface AvatarProps {
  name: string
  size?: 'sm' | 'md' | 'lg'
  className?: string
}

function getInitials(name: string): string {
  const parts = name.split(/[\s-]+/).filter(Boolean)
  if (parts.length >= 2) return (parts[0][0] + parts[1][0]).toUpperCase()
  return name.slice(0, 2).toUpperCase()
}

export function Avatar({ name, size = 'md', className }: AvatarProps) {
  const { theme } = useTheme()
  const colors = hashColor(name, theme)
  return (
    <span
      className={`${styles.avatar} ${styles[size]} ${className ?? ''}`}
      style={{ backgroundColor: colors.bg, color: colors.text, borderColor: colors.border }}
      aria-label={name}
    >
      {getInitials(name)}
    </span>
  )
}
