import { __ } from '@wordpress/i18n';

const UserAvatar = ({ user, attributes, context }) => {
    const {
        avatarSize = 'thumbnail',
        avatarShape = 'circle',
        fallbackAvatar = 'wordpress_default',
        customSize = 150
    } = attributes || {};

    // Get avatar URL based on size
    const getAvatarUrl = () => {
        if (!user) return null;

        // Handle both old and new avatar formats
        const avatarUrls = user.avatar_urls || {};
        
        // If user has avatar_urls object, use it
        if (Object.keys(avatarUrls).length > 0) {
            const avatarSizes = {
                thumbnail: 150,
                medium: 300,
                large: 600,
                custom: customSize
            };

            const requestedSize = avatarSizes[avatarSize] || 150;

            // Try to get the exact size first, then fallback to closest available
            if (avatarUrls[requestedSize]) {
                return avatarUrls[requestedSize];
            }

            // Find the closest available size
            const availableSizes = Object.keys(avatarUrls).map(Number).sort((a, b) => b - a);
            const closestSize = availableSizes.find(size => size >= requestedSize) || availableSizes[0];

            return avatarUrls[closestSize] || avatarUrls['96'] || '';
        }

        // Fallback to old avatar format
        if (user.avatar) {
            return user.avatar;
        }

        return null;
    };

    // Get display size for avatar
    const getDisplaySize = () => {
        const avatarSizes = {
            thumbnail: 150,
            medium: 300,
            large: 600,
            custom: customSize
        };
        return avatarSizes[avatarSize] || 150;
    };

    // Get CSS classes for avatar shape and size
    const getAvatarClasses = () => {
        const classes = ['wpuf-avatar'];

        // Add shape class
        classes.push(`wpuf-avatar--${avatarShape}`);

        // Add size class
        classes.push(`wpuf-avatar--${avatarSize}`);

        return classes.join(' ');
    };

    // Helper function to get user initials
    const getInitials = (name) => {
        if (!name) return '?';
        return name.split(' ')
            .map(word => word.charAt(0))
            .join('')
            .toUpperCase()
            .substring(0, 2);
    };

    // Get user display name for initials
    const getUserDisplayName = () => {
        if (!user) return '';
        
        // Try different name fields in order of preference
        return user.display_name || user.name || user.first_name || user.user_login || '';
    };

    // Render initials fallback
    const renderInitials = () => {
        const displaySize = getDisplaySize();
        const displayName = getUserDisplayName();
        const initials = getInitials(displayName);

        return (
            <div
                className={`${getAvatarClasses()} wpuf-avatar--initials`}
                style={{
                    width: displaySize,
                    height: displaySize,
                    fontSize: Math.max(displaySize / 3, 16) + 'px',
                    lineHeight: 1
                }}
            >
                <span className="wpuf-avatar-initials-text">{initials}</span>
            </div>
        );
    };

    // Render avatar image
    const renderAvatarImage = () => {
        const avatarUrl = getAvatarUrl();
        const displaySize = getDisplaySize();

        if (!avatarUrl) {
            return null;
        }

        return (
            <img
                src={avatarUrl}
                alt={getUserDisplayName() || __('User Avatar', 'wpuf-pro')}
                className={`${getAvatarClasses()} wpuf-avatar--image`}
                style={{
                    width: displaySize,
                    height: displaySize
                }}
                onError={(e) => {
                    // On image error, replace with initials
                    const displayName = getUserDisplayName();
                    const initials = getInitials(displayName);
                    e.target.style.display = 'none';
                    const initialsDiv = document.createElement('div');
                    initialsDiv.className = `${getAvatarClasses()} wpuf-avatar--initials`;
                    initialsDiv.style.width = displaySize + 'px';
                    initialsDiv.style.height = displaySize + 'px';
                    initialsDiv.style.fontSize = Math.max(displaySize / 3, 16) + 'px';
                    initialsDiv.style.lineHeight = '1';
                    initialsDiv.innerHTML = `<span class="wpuf-avatar-initials-text">${initials}</span>`;
                    e.target.parentNode.appendChild(initialsDiv);
                }}
            />
        );
    };

    // Render the complete avatar with fallback logic
    const renderAvatar = () => {
        const avatarUrl = getAvatarUrl();

        // If initials_only is selected, always show initials
        if (fallbackAvatar === 'initials_only') {
            return (
                <div className="wpuf-avatar-container">
                    {renderInitials()}
                </div>
            );
        }

        // For wordpress_default, show image if available, otherwise let WordPress handle the default
        if (avatarUrl) {
            return (
                <div className="wpuf-avatar-container">
                    {renderAvatarImage()}
                </div>
            );
        }

        // No image available and using WordPress default - show placeholder or WordPress will handle
        return (
            <div className="wpuf-avatar-container">
                {renderInitials()}
            </div>
        );
    };

    return renderAvatar();
};

export default UserAvatar; 