'use client';

/**
 * Displays the current user's avatar (image or initials fallback).
 * Image is loaded from /zen/api/storage/{key}; session cookie is sent automatically.
 *
 * @param {Object} props
 * @param {Object} props.user - User object with optional image (storage key) and name
 * @param {'sm'|'md'|'lg'} [props.size='md'] - Size of the avatar
 * @param {string} [props.className] - Additional CSS classes for the wrapper
 */

function getImageUrl(imageKey) {
  if (!imageKey) return null;
  return `/zen/api/storage/${imageKey}`;
}

function getInitials(name) {
  if (!name || !name.trim()) return '?';
  return name
    .trim()
    .split(/\s+/)
    .map((n) => n[0])
    .join('')
    .toUpperCase()
    .slice(0, 2);
}

const sizeClasses = {
  sm: 'w-8 h-8 text-xs',
  md: 'w-10 h-10 text-sm',
  lg: 'w-12 h-12 text-base',
};

export default function UserAvatar({ user, size = 'md', className = '' }) {
  const sizeClass = sizeClasses[size] || sizeClasses.md;
  const imageUrl = user?.image ? getImageUrl(user.image) : null;

  return (
    <div
      className={`rounded-full overflow-hidden flex items-center justify-center bg-neutral-700 text-white font-medium shrink-0 ${sizeClass} ${className}`}
      aria-hidden
    >
      {imageUrl ? (
        <img
          src={imageUrl}
          alt={user?.name ? `${user.name} avatar` : 'Avatar'}
          className="w-full h-full object-cover"
        />
      ) : (
        <span>{getInitials(user?.name)}</span>
      )}
    </div>
  );
}
