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

// Soft gradients built only from design tokens; picked deterministically per name.
const gradients = [
  'from-primary to-accent',
  'from-info to-primary',
  'from-accent to-danger',
  'from-success to-info',
  'from-warning to-danger',
  'from-primary to-info',
] as const;

const hash = (value: string): number => {
  let result = 0;
  for (let index = 0; index < value.length; index += 1) result = (result * 31 + value.charCodeAt(index)) >>> 0;
  return result;
};

export const initialsOf = (name: string): string => {
  const parts = name.trim().split(/\s+/).filter(Boolean);
  if (parts.length === 0) return '?';
  const first = parts[0]?.[0] ?? '';
  const last = parts.length > 1 ? (parts[parts.length - 1]?.[0] ?? '') : (parts[0]?.[1] ?? '');
  return `${first}${last}`.toUpperCase();
};

const sizes = {
  xs: 'h-6 w-6 text-[10px]',
  sm: 'h-8 w-8 text-[11px]',
  md: 'h-9 w-9 text-caption',
  lg: 'h-11 w-11 text-small',
  xl: 'h-[72px] w-[72px] text-h3',
} as const;

export function Avatar({
  name,
  size = 'md',
  shape = 'circle',
  className,
}: {
  name: string;
  size?: keyof typeof sizes;
  shape?: 'circle' | 'square';
  className?: string;
}) {
  const gradient = gradients[hash(name) % gradients.length];
  return (
    <span
      aria-hidden="true"
      className={cn(
        'grid shrink-0 select-none place-items-center bg-gradient-to-br font-bold text-primary-foreground',
        shape === 'circle' ? 'rounded-full' : 'rounded-md',
        gradient,
        sizes[size],
        className,
      )}
    >
      {initialsOf(name)}
    </span>
  );
}
