import { jsxs, jsx } from 'react/jsx-runtime';
import { forwardRef, useRef, useState, useContext, useMemo, useEffect, Children, isValidElement, cloneElement } from 'react';
import { c as cx } from './index-De1g9FRV.js';
import { u as useAccessibleColor, t as tinycolor } from './useAccessibleColor-BYKjkGRg.js';
import { S as SrOnly } from './SrOnly-pnf8ajnh.js';
import { T as ThemeProviderContext } from './ThemeProviderContext-l52GohYT.js';
import { u as usePrefersColorScheme } from './usePrefersColorScheme-_hT7dK7_.js';
import { u as useMergeRefs } from './useMergeRefs-Dfmtq9cI.js';
import { u as useLayoutPropsUtil } from './useLayoutPropsUtil-DjqeAJZ9.js';

import './Avatar.css';function getInitial(name) {
  if (!name) return void 0;
  const nameArray = name.split(" ").filter(Boolean);
  if (nameArray.length > 1)
    return `${nameArray[0][0]?.toUpperCase()}${nameArray[nameArray.length - 1][0].toUpperCase()}`;
  if (nameArray[0][1]) {
    return `${nameArray[0][0].toUpperCase()}${nameArray[0][1].toLowerCase()}`;
  }
  return `${nameArray[0][0].toUpperCase()}`;
}

const small$1 = "_small_1op2x_22";
const medium = "_medium_1op2x_27";
const large$1 = "_large_1op2x_32";
const styles = {
	"avatar-group": "_avatar-group_1op2x_1",
	small: small$1,
	medium: medium,
	large: large$1
};

const initial = "_initial_1orn6_45";
const img = "_img_1orn6_54";
const indicator = "_indicator_1orn6_64";
const online = "_online_1orn6_77";
const offline = "_offline_1orn6_81";
const xsmall = "_xsmall_1orn6_85";
const small = "_small_1orn6_91";
const large = "_large_1orn6_97";
const avatarBaseStyles = {
	"avatar-base": "_avatar-base_1orn6_1",
	initial: initial,
	img: img,
	indicator: indicator,
	online: online,
	offline: offline,
	xsmall: xsmall,
	small: small,
	large: large,
	"overflow-ten-plus": "_overflow-ten-plus_1orn6_105"
};

const AvatarBase = forwardRef(
  (props, ref) => {
    const {
      className,
      color,
      status,
      name,
      image,
      initials,
      style,
      size,
      ...rest
    } = props;
    const elRef = useRef(null);
    const imgRef = useRef(null);
    const [hasImageErrored, setHasImageErrored] = useState(false);
    const avatarBaseClassNames = cx(avatarBaseStyles["avatar-base"], className, {
      [avatarBaseStyles[`${size}`]]: size && size !== "medium"
    });
    const onlineIndicatorClassNames = cx(avatarBaseStyles["indicator"], {
      [avatarBaseStyles["offline"]]: !status || status === "offline",
      [avatarBaseStyles["online"]]: status && status === "online"
    });
    const { mode: themeMode } = useContext(ThemeProviderContext);
    const { mode: sysMode } = usePrefersColorScheme();
    const mode = themeMode ?? sysMode;
    const { foreground, background, border } = useAccessibleColor(color, mode);
    const styleWithColor = {
      "--a2-inline-avatar-background-color": color && background,
      "--a2-inline-avatar-font-color": color && foreground,
      "--a2-inline-avatar-border-color": color && border,
      ...style
    };
    const onlineIndicatorBorderColor = useMemo(() => {
      if (mode === "dark") {
        if (color) {
          return tinycolor(background).brighten(20).toHexString();
        }
      }
      return "var(--a2-background-color-default)";
    }, [color, mode, background]);
    const onlineIndicatorStyles = {
      "--a2-inline-avatar-border-color": onlineIndicatorBorderColor
    };
    const onlineString = status;
    const srOnly = [name, onlineString].filter(Boolean).join(" ");
    useEffect(() => {
      if (image) {
        setHasImageErrored(false);
      }
    }, [image]);
    useEffect(() => {
      if (image && imgRef.current && imgRef.current.complete) {
        const img = new Image();
        const handleError = () => setHasImageErrored(true);
        img.addEventListener("error", handleError);
        img.src = image;
        return () => {
          img.removeEventListener("error", handleError);
          img.src = "";
        };
      }
    }, []);
    return /* @__PURE__ */ jsxs(
      "span",
      {
        className: avatarBaseClassNames,
        style: styleWithColor,
        "data-anv": "avatarBase",
        ...rest,
        ref: useMergeRefs([elRef, ref]),
        children: [
          image && !hasImageErrored ? /* @__PURE__ */ jsx(
            "img",
            {
              className: avatarBaseStyles["img"],
              "aria-hidden": true,
              src: image,
              alt: name,
              onError: () => setHasImageErrored(true),
              ref: imgRef
            }
          ) : initials ? /* @__PURE__ */ jsx("span", { className: avatarBaseStyles["initial"], "aria-hidden": true, children: initials }) : /* @__PURE__ */ jsx("span", { "aria-hidden": true, children: "?" }),
          status && /* @__PURE__ */ jsx(
            "span",
            {
              "aria-hidden": true,
              className: onlineIndicatorClassNames,
              style: onlineIndicatorStyles
            }
          ),
          /* @__PURE__ */ jsx(SrOnly, { children: srOnly })
        ]
      }
    );
  }
);
AvatarBase.displayName = "AvatarBase";

const AvatarGroup = forwardRef(
  (props, ref) => {
    const { layoutStyles, componentProps } = useLayoutPropsUtil(props);
    const { className, max, style, children, ...rest } = componentProps;
    const childrenArr = Children.toArray(children);
    const inferredSize = (isValidElement(childrenArr[0]) && childrenArr[0].props.size) ?? "medium";
    const isOverflowing = max ? max < childrenArr.length : false;
    const overflowCount = max && childrenArr.length - max;
    const avatarGroupClassNames = cx(styles["avatar-group"], className, {
      [styles[`${inferredSize}`]]: inferredSize
    });
    const avatarBaseOverflowClassNames = cx(
      avatarBaseStyles["avatar-base-overflow"],
      {
        [avatarBaseStyles["overflow-ten-plus"]]: overflowCount && overflowCount > 9
      }
    );
    const styleCombined = {
      ...style,
      ...layoutStyles
    };
    return /* @__PURE__ */ jsxs(
      "span",
      {
        ref,
        className: avatarGroupClassNames,
        style: styleCombined,
        "data-anv": "avatar-group",
        ...rest,
        children: [
          childrenArr.map((child, i) => {
            let childEl = child;
            if (isValidElement(child)) {
              const nIndex = childrenArr.length - i;
              const nStyle = {
                ...child.props.style,
                zIndex: nIndex
              };
              childEl = cloneElement(child, {
                style: nStyle
              });
            }
            if (!max) return childEl;
            if (i < max) return childEl;
            return null;
          }),
          isOverflowing && max && /* @__PURE__ */ jsx(
            AvatarBase,
            {
              className: avatarBaseOverflowClassNames,
              name: `+${overflowCount}`,
              initials: `+${overflowCount}`,
              size: inferredSize
            }
          )
        ]
      }
    );
  }
);
AvatarGroup.displayName = "AvatarGroup";

const Avatar = Object.assign(
  forwardRef(function AvatarInner(props, ref) {
    const { layoutStyles, componentProps } = useLayoutPropsUtil(props);
    const { name, style, ...rest } = componentProps;
    const styleWithLayout = useMemo(() => {
      return {
        ...layoutStyles,
        ...style
      };
    }, [layoutStyles, style]);
    const initials = getInitial(name);
    return /* @__PURE__ */ jsx(
      AvatarBase,
      {
        style: styleWithLayout,
        "data-anv": "avatar",
        name,
        ref,
        initials: rest.size === "small" ? initials?.[0] : initials,
        ...rest
      }
    );
  }),
  {
    /**
     * AvatarGroup component for displaying multiple avatars in a group.
     *
     * Features:
     * - Displays multiple avatars in a stacked layout
     * - Handles overflow with a count indicator
     * - Maintains consistent sizing across all avatars
     * - Supports custom styling and layout
     * - Automatically adjusts z-index for proper stacking
     * - Fully accessible with screen reader support
     *
     * @example
     * <Avatar.Group max={3}>
     *   <Avatar name="John Doe" />
     *   <Avatar name="Jane Smith" />
     *   <Avatar name="Bob Johnson" />
     *   <Avatar name="Alice Brown" />
     * </Avatar.Group>
     */
    Group: AvatarGroup
  }
);
Avatar.displayName = "Avatar";

export { AvatarGroup as A, Avatar as a };
//# sourceMappingURL=Avatar-CoQcOHWU.js.map
