'use client';

import * as React from 'react';
import * as AvatarPrimitive from '@radix-ui/react-avatar';

import { cn } from '../../shared/utils';

/**
 * User identity image with automatic fallback.
 *
 * @description
 * Natively handles 404 errors and image loading timeouts by showing a
 * text fallback (initials). Supports 5 sizes via the `size` prop.
 *
 * @ai-rules
 * 1. NEVER use a raw `<img>` for user profile images — the internal fallback prevents broken UI.
 * 2. Always compose as `<Avatar> > <AvatarImage> + <AvatarFallback>` — both sub-components are required.
 * 3. In `<AvatarFallback>`, render initials (1–2 characters) using `<span>`, not a full name.
 */
function Avatar({
  className,
  size = 'md',
  ...props
}: React.ComponentProps<typeof AvatarPrimitive.Root> & {
  size?: 'xs' | 'sm' | 'md' | 'lg' | 'xl';
}) {
  const sizeClasses = {
    xs: 'size-6',
    sm: 'size-8',
    md: 'size-10',
    lg: 'size-12',
    xl: 'size-16',
  };

  return (
    <AvatarPrimitive.Root
      data-slot="avatar"
      className={cn(
        'relative flex shrink-0 overflow-hidden rounded-full',
        sizeClasses[size],
        className
      )}
      {...props}
    />
  );
}

function AvatarImage({ className, ...props }: React.ComponentProps<typeof AvatarPrimitive.Image>) {
  return (
    <AvatarPrimitive.Image
      data-slot="avatar-image"
      className={cn('aspect-square size-full', className)}
      {...props}
    />
  );
}

function AvatarFallback({
  className,
  ...props
}: React.ComponentProps<typeof AvatarPrimitive.Fallback>) {
  return (
    <AvatarPrimitive.Fallback
      data-slot="avatar-fallback"
      className={cn('bg-muted flex size-full items-center justify-center rounded-full', className)}
      {...props}
    />
  );
}

export { Avatar, AvatarImage, AvatarFallback };
