import React from 'react';

const USER_COLORS = ['#5865F2', '#EBA7CD', '#57F287', '#FEE75C', '#EB459E', '#ED4245'];

function getUserColor(name) {
    let hash = 0;
    for (let i = 0; i < (name || '').length; i++) {
        hash = name.charCodeAt(i) + ((hash << 5) - hash);
    }
    return USER_COLORS[Math.abs(hash) % USER_COLORS.length];
}

const Avatar = ({ username, avatarUrl, size = 40, className = '', style = {}, onClick }) => {
    const sizeStr = `${size}px`;
    const fontSize = `${Math.max(size * 0.45, 10)}px`;

    if (avatarUrl) {
        return (
            <img
                className={className}
                src={avatarUrl}
                alt={username || '?'}
                onClick={onClick}
                style={{
                    width: sizeStr,
                    height: sizeStr,
                    borderRadius: '50%',
                    objectFit: 'cover',
                    cursor: onClick ? 'pointer' : 'default',
                    ...style,
                }}
            />
        );
    }

    return (
        <div
            className={className}
            onClick={onClick}
            style={{
                width: sizeStr,
                height: sizeStr,
                borderRadius: '50%',
                backgroundColor: getUserColor(username || 'U'),
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                color: 'white',
                fontWeight: 600,
                fontSize,
                userSelect: 'none',
                flexShrink: 0,
                cursor: onClick ? 'pointer' : 'default',
                ...style,
            }}
        >
            {(username || '?').substring(0, 1).toUpperCase()}
        </div>
    );
};

export default Avatar;
