import React, { ComponentProps, forwardRef } from 'react';
import { AvatarImage } from 'folds';
import { useAuthenticatedMediaUrl } from '../../hooks/useAuthenticatedMediaUrl';
import { useMediaAuthentication } from '../../hooks/useMediaAuthentication';

export type AuthenticatedAvatarImageProps = ComponentProps<typeof AvatarImage>;

/**
 * AvatarImage component that handles Matrix authenticated media.
 * Automatically fetches authenticated media URLs with the proper Authorization header
 * and renders them as blob URLs.
 */
export const AuthenticatedAvatarImage = forwardRef<HTMLImageElement, AuthenticatedAvatarImageProps>(
  ({ src, ...props }, ref) => {
    const useAuthentication = useMediaAuthentication();
    const authenticatedSrc = useAuthenticatedMediaUrl(src, useAuthentication);

    return <AvatarImage ref={ref} {...props} src={authenticatedSrc} />;
  }
);

AuthenticatedAvatarImage.displayName = 'AuthenticatedAvatarImage';
