'use client';

import { Avatar, AvatarFallback } from '@kit/ui/avatar';
import { cn } from '@kit/ui/utils';

interface MemberAvatarProps {
  firstName: string;
  lastName: string;
  size?: 'default' | 'sm' | 'lg';
  className?: string;
}

function getInitials(firstName: string, lastName: string): string {
  const f = firstName.trim().charAt(0).toUpperCase();
  const l = lastName.trim().charAt(0).toUpperCase();
  return `${f}${l}`;
}

function getColorClass(firstName: string, lastName: string): string {
  const name = `${firstName}${lastName}`;
  let hash = 0;
  for (let i = 0; i < name.length; i++) {
    hash = name.charCodeAt(i) + ((hash << 5) - hash);
  }
  const colors = [
    'bg-blue-100 text-blue-700 dark:bg-blue-900 dark:text-blue-300',
    'bg-green-100 text-green-700 dark:bg-green-900 dark:text-green-300',
    'bg-purple-100 text-purple-700 dark:bg-purple-900 dark:text-purple-300',
    'bg-amber-100 text-amber-700 dark:bg-amber-900 dark:text-amber-300',
    'bg-rose-100 text-rose-700 dark:bg-rose-900 dark:text-rose-300',
    'bg-cyan-100 text-cyan-700 dark:bg-cyan-900 dark:text-cyan-300',
    'bg-orange-100 text-orange-700 dark:bg-orange-900 dark:text-orange-300',
    'bg-teal-100 text-teal-700 dark:bg-teal-900 dark:text-teal-300',
  ];
  return colors[Math.abs(hash) % colors.length]!;
}

export function MemberAvatar({
  firstName,
  lastName,
  size = 'default',
  className,
}: MemberAvatarProps) {
  const initials = getInitials(firstName, lastName);
  const colorClass = getColorClass(firstName, lastName);

  return (
    <Avatar size={size} className={cn('rounded-full', className)}>
      <AvatarFallback className={cn('rounded-full font-medium', colorClass)}>
        {initials}
      </AvatarFallback>
    </Avatar>
  );
}
