import { emojiFromId } from '../utils/avatat';

type AvatarProps = {
  id?: string | null;
  size?: number;
  className?: string;
  online?: boolean;
};

const colors = [
  ['#FF885E', '#FF516A'],
  ['#FFCD6A', '#FFA85C'],
  ['#82B1FF', '#665FFF'],
  ['#A0DE7E', '#54CB68'],
  ['#53EDD6', '#28C9B7'],
  ['#72D5FD', '#2A9EF1'],
  ['#E0A2F3', '#D669ED'],
  ['#FF8AAC', '#F95887'],
];

const colorFromId = (id: string) => {
  let hash = 0;
  for (let i = 0; i < id.length; i++) {
    hash = id.charCodeAt(i) + ((hash << 5) - hash);
  }
  return colors[Math.abs(hash) % colors.length];
};

const Avatar = ({ id, size = 40, className = '', online }: AvatarProps) => {
  const safeId = id ?? '';
  const [c1, c2] = colorFromId(safeId);
  const emoji = emojiFromId(safeId);
  const fontSize = Math.round(size * 0.55);

  return (
    <div
      className={`relative shrink-0 ${className}`}
      style={{ width: size, height: size }}
    >
      <div
        className="w-full h-full rounded-full overflow-hidden flex items-center justify-center"
        style={{
          background: `linear-gradient(135deg, ${c1} 0%, ${c2} 100%)`,
          fontSize,
          lineHeight: 1,
        }}
      >
        <span style={{ filter: 'drop-shadow(0 1px 1px rgba(0,0,0,0.15))' }}>
          {emoji}
        </span>
      </div>
      {online && (
        <div
          className="absolute bottom-0 right-0 rounded-full ring-2"
          style={{
            width: Math.max(8, size * 0.25),
            height: Math.max(8, size * 0.25),
            background: '#4fae4e',
            //@ts-ignore
            '--tw-ring-color': 'var(--tg-bg)',
          }}
        />
      )}
    </div>
  );
};

export default Avatar;
