import React from 'react';
import { getMediaUrl } from '@/lib/media';

interface AvatarProps {
  name: string;
  avatarUrl?: string;
  size?: number;
  className?: string;
}

export default function Avatar({ name, avatarUrl, size = 40, className = '' }: AvatarProps) {
  const getInitials = (name: string) => {
    if (!name) return '?';
    return name.trim().charAt(0).toUpperCase();
  };

  const baseStyle = {
    width: size,
    height: size,
    minWidth: size,
    minHeight: size,
    borderRadius: '50%',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    overflow: 'hidden',
    backgroundColor: '#FECE00',
    color: '#000',
    fontWeight: 'bold',
    fontSize: `${size * 0.4}px`,
  };

  return (
    <div style={baseStyle} className={`shrink-0 ${className}`}>
      {avatarUrl ? (
        <img
          src={getMediaUrl(avatarUrl, 'images')}
          alt={`${name}'s avatar`}
          style={{ width: '100%', height: '100%', objectFit: 'cover' }}
          onError={(e) => {
            // Fallback to initials if image fails to load
            e.currentTarget.style.display = 'none';
            if (e.currentTarget.nextElementSibling) {
              (e.currentTarget.nextElementSibling as HTMLElement).style.display = 'flex';
            }
          }}
        />
      ) : null}
      <div 
        style={{ 
          display: avatarUrl ? 'none' : 'flex', 
          width: '100%', 
          height: '100%', 
          alignItems: 'center', 
          justifyContent: 'center' 
        }}
      >
        {getInitials(name)}
      </div>
    </div>
  );
}
