'use client';

import { cn } from '@/lib/utils';
import * as React from 'react';

/*
 * Sin `@radix-ui/react-avatar`: el sistema no tiene fotos de usuario (no hay
 * upload de avatar en ningún flujo), así que el caso real es siempre el
 * fallback de iniciales — igual al círculo que ya arma `dashboard-shell.tsx`
 * a mano (`bg-muted text-muted-foreground`, primera letra del nombre). Traer
 * una dependencia nueva sólo para el manejo de error de `<img>` no se
 * justificaba; `AvatarImage` maneja el fallo con `onError` y estado local.
 */
const avatarSizeClasses = {
    sm: 'h-8 w-8 text-xs',
    default: 'h-9 w-9 text-sm',
    lg: 'h-11 w-11 text-base',
} as const;

type AvatarSize = keyof typeof avatarSizeClasses;

type AvatarContextValue = {
    imageLoaded: boolean;
    setImageLoaded: (loaded: boolean) => void;
};

const AvatarContext = React.createContext<AvatarContextValue | null>(null);

export interface AvatarProps extends React.HTMLAttributes<HTMLSpanElement> {
    size?: AvatarSize;
}

const Avatar = React.forwardRef<HTMLSpanElement, AvatarProps>(
    ({ className, size = 'default', ...props }, ref) => {
        const [imageLoaded, setImageLoaded] = React.useState(false);

        return (
            <AvatarContext.Provider value={{ imageLoaded, setImageLoaded }}>
                <span
                    ref={ref}
                    className={cn(
                        'relative flex shrink-0 items-center justify-center overflow-hidden rounded-full bg-muted text-muted-foreground',
                        avatarSizeClasses[size],
                        className
                    )}
                    {...props}
                />
            </AvatarContext.Provider>
        );
    }
);
Avatar.displayName = 'Avatar';

export interface AvatarImageProps extends React.ImgHTMLAttributes<HTMLImageElement> {}

const AvatarImage = React.forwardRef<HTMLImageElement, AvatarImageProps>(
    ({ className, onError, onLoad, ...props }, ref) => {
        const context = React.useContext(AvatarContext);
        const [failed, setFailed] = React.useState(false);

        if (!context || failed || !props.src) return null;

        return (
            <img
                ref={ref}
                className={cn('aspect-square h-full w-full object-cover', className)}
                onLoad={(event) => {
                    context.setImageLoaded(true);
                    onLoad?.(event);
                }}
                onError={(event) => {
                    setFailed(true);
                    context.setImageLoaded(false);
                    onError?.(event);
                }}
                {...props}
            />
        );
    }
);
AvatarImage.displayName = 'AvatarImage';

export interface AvatarFallbackProps extends React.HTMLAttributes<HTMLSpanElement> {}

const AvatarFallback = React.forwardRef<HTMLSpanElement, AvatarFallbackProps>(
    ({ className, children, ...props }, ref) => {
        const context = React.useContext(AvatarContext);
        if (context?.imageLoaded) return null;

        return (
            <span
                ref={ref}
                className={cn('font-semibold uppercase leading-none', className)}
                {...props}
            >
                {children}
            </span>
        );
    }
);
AvatarFallback.displayName = 'AvatarFallback';

export { Avatar, AvatarImage, AvatarFallback };
