import { cn } from '@/lib/cn';

interface AvatarProps {
  src?: string | null;
  username: string;
  size?: 'sm' | 'md' | 'lg' | 'xl';
  online?: boolean;
  className?: string;
}

const sizes = {
  sm: 'w-6 h-6 text-[10px]',
  md: 'w-9 h-9 text-sm',
  lg: 'w-12 h-12 text-base',
  xl: 'w-24 h-24 text-2xl',
};

function hashColor(str: string): string {
  let hash = 0;
  for (let i = 0; i < str.length; i++) {
    hash = str.charCodeAt(i) + ((hash << 5) - hash);
  }
  const h = Math.abs(hash) % 360;
  return `hsl(${h}, 60%, 40%)`;
}

export function Avatar({ src, username, size = 'md', online, className }: AvatarProps) {
  const bgColor = hashColor(username);
  const initial = username.charAt(0).toUpperCase();

  return (
    <div className={cn('relative inline-flex flex-shrink-0', className)}>
      {src ? (
        <img
          src={src}
          alt={username}
          className={cn('rounded-full object-cover', sizes[size])}
        />
      ) : (
        <div
          className={cn(
            'rounded-full flex items-center justify-center font-bold text-white',
            sizes[size]
          )}
          style={{ background: `linear-gradient(135deg, ${bgColor}, ${bgColor}dd)` }}
        >
          {initial}
        </div>
      )}
      {online !== undefined && (
        <span
          className={cn(
            'absolute bottom-0 right-0 rounded-full border-2 border-bg-base',
            online ? 'bg-green-500' : 'bg-gray-500',
            size === 'sm' ? 'w-2 h-2' : size === 'md' ? 'w-2.5 h-2.5' : 'w-3 h-3'
          )}
        >
          {online && (
            <span className="absolute inset-0 rounded-full bg-green-500 animate-ping opacity-50" />
          )}
        </span>
      )}
    </div>
  );
}
