import f from "../../../@babel/runtime/helpers/esm/extends.js";
import { forwardRef as i, useState as b, createElement as $, useEffect as v } from "react";
import { createContextScope as A } from "../../react-context/dist/index.js";
import { useCallbackRef as x } from "../../react-use-callback-ref/dist/index.js";
import { useLayoutEffect as p } from "../../react-use-layout-effect/dist/index.js";
import { Primitive as u } from "../../react-primitive/dist/index.js";
const m = "Avatar", [S, N] = A(m), [_, l] = S(m), L = /* @__PURE__ */ i((a, r) => {
  const { __scopeAvatar: t, ...e } = a, [o, c] = b("idle");
  return /* @__PURE__ */ $(_, {
    scope: t,
    imageLoadingStatus: o,
    onImageLoadingStatusChange: c
  }, /* @__PURE__ */ $(u.span, f({}, e, {
    ref: r
  })));
}), C = "AvatarImage", I = /* @__PURE__ */ i((a, r) => {
  const { __scopeAvatar: t, src: e, onLoadingStatusChange: o = () => {
  }, ...c } = a, d = l(C, t), n = M(e), s = x((g) => {
    o(g), d.onImageLoadingStatusChange(g);
  });
  return p(() => {
    n !== "idle" && s(n);
  }, [
    n,
    s
  ]), n === "loaded" ? /* @__PURE__ */ $(u.img, f({}, c, {
    ref: r,
    src: e
  })) : null;
}), w = "AvatarFallback", E = /* @__PURE__ */ i((a, r) => {
  const { __scopeAvatar: t, delayMs: e, ...o } = a, c = l(w, t), [d, n] = b(e === void 0);
  return v(() => {
    if (e !== void 0) {
      const s = window.setTimeout(
        () => n(!0),
        e
      );
      return () => window.clearTimeout(s);
    }
  }, [
    e
  ]), d && c.imageLoadingStatus !== "loaded" ? /* @__PURE__ */ $(u.span, f({}, o, {
    ref: r
  })) : null;
});
function M(a) {
  const [r, t] = b("idle");
  return p(() => {
    if (!a) {
      t("error");
      return;
    }
    let e = !0;
    const o = new window.Image(), c = (d) => () => {
      e && t(d);
    };
    return t("loading"), o.onload = c("loaded"), o.onerror = c("error"), o.src = a, () => {
      e = !1;
    };
  }, [
    a
  ]), r;
}
const T = L, B = I, G = E;
export {
  L as Avatar,
  E as AvatarFallback,
  I as AvatarImage,
  G as Fallback,
  B as Image,
  T as Root,
  N as createAvatarScope
};
