import { jsx as _jsx, Fragment as _Fragment } from "react/jsx-runtime";
import { useEffect, useState } from 'react';
import { omitThemingProps, styled, useStyleConfig, vui } from '../core';
import Icon from '../icon';
import Image from '../image';
import { cs, filterUndefined } from '../utils';
import { loadImageUrl } from '../utils/images';
import { defaultGetInitials } from './helpers';
export const AvatarBase = styled.spanBox `
  align-items: center;
  display: inline-flex;
  flex-shrink: 0;
  font-weight: medium;
  justify-content: center;
  line-height: normal;
  outline: none;
  overflow: hidden;
  transition-duration: fast;

  &:focus {
    border-color: transparent;
  }

  &[aria-disabled='true'] {
    opacity: 0.5;
    cursor: not-allowed;
    user-select: none;
  }
`;
/** Displays user data, such as name initials or profile image. */
export const Avatar = vui((props, ref) => {
    const { children, className, disabled, getInitials = defaultGetInitials, icon, isInteractive = props.onClick !== undefined, isSquare, name = '', src, ...rest } = omitThemingProps(props);
    const { activeBg, h, hoverBg, iconSize, ...styles } = useStyleConfig('Avatar', props);
    const borderRadius = isSquare ? (props.size === 'sm' ? '3px' : '6px') : '50%';
    const initials = getInitials(name);
    const interactiveProps = !disabled && isInteractive
        ? {
            cursor: 'pointer',
            hoverBg,
            hoverOpacity: src ? 0.85 : 1,
            activeOpacity: src ? 0.7 : 1,
            activeBg,
            focusRing: 3,
            tabIndex: 0,
            userSelect: 'none',
        }
        : {};
    const aliasedProps = filterUndefined({
        borderRadius: borderRadius,
        'aria-disabled': disabled,
    });
    return (_jsx(AvatarBase, { borderRadius: borderRadius, className: cs('vui-avatar', className), h: h, ref: ref, w: h, ...styles, ...interactiveProps, ...aliasedProps, ...rest, children: children ? (children) : src ? (_jsx(LazyImageOrDefault, { borderRadius: borderRadius, icon: icon, iconSize: iconSize, initials: initials, src: src })) : icon ? (_jsx(Icon, { name: icon, size: iconSize })) : initials ? (initials) : (_jsx(Icon, { name: "falUser", size: iconSize })) }));
});
function LazyImageOrDefault({ src, borderRadius, icon, iconSize, initials, }) {
    const [imgLoaded, setImgLoaded] = useState(false);
    useEffect(() => {
        let cancelled = false;
        loadImageUrl(src).then(res => {
            if (!cancelled)
                setImgLoaded(res);
        });
        return () => {
            cancelled = true;
        };
    }, [src]);
    return imgLoaded ? (_jsx(Image, { borderRadius: borderRadius, src: src })) : icon ? (_jsx(Icon, { name: icon, size: iconSize })) : initials ? (_jsx(_Fragment, { children: initials })) : (_jsx(Icon, { name: "falUser", size: iconSize }));
}
Avatar.displayName = 'Avatar';
export default Avatar;
//# sourceMappingURL=avatar.js.map