import { jsxs, jsx } from "react/jsx-runtime";
import * as React from "react";
import { User } from "lucide-react";
import { cn } from "../../lib/utils.js";
import { CAT_SOLID_TOKENS, CAT_SUBTLE_TOKENS } from "../../tokens/categorical-color.js";
import { HoverCard, HoverCardTrigger, HoverCardContent } from "../HoverCard/hover-card.js";
import { HOVER_DELAY_CLOSE_MS, HOVER_DELAY_RICH_MS } from "../../tokens/motion/motion.js";
import { Badge } from "../Badge/badge.js";
import { useTableIsScrolling, useResolvedFieldDisabled } from "../Field/field-context.js";
const COLOR_MAP = {
  subtle: {
    neutral: { bg: "var(--muted)", text: "var(--foreground)" },
    ...CAT_SUBTLE_TOKENS
  },
  solid: {
    neutral: { bg: "var(--color-neutral-9)", text: "var(--inverse-fg)" },
    ...CAT_SOLID_TOKENS
  }
};
function getIconSize(avatarSize) {
  return Math.round(avatarSize * 0.6 / 2) * 2;
}
function getInitial(text) {
  return text.trim().charAt(0).toUpperCase();
}
const STATUS_DOT_COLOR = {
  online: "var(--status-online)",
  away: "var(--status-away)",
  busy: "var(--status-busy)",
  offline: "var(--status-offline)"
};
function useDocumentTheme() {
  const [theme, setTheme] = React.useState(
    () => typeof document !== "undefined" ? document.documentElement.getAttribute("data-theme") : null
  );
  React.useEffect(() => {
    if (typeof document === "undefined") return;
    const root = document.documentElement;
    const update = () => setTheme(root.getAttribute("data-theme"));
    update();
    const obs = new MutationObserver(update);
    obs.observe(root, { attributes: true, attributeFilter: ["data-theme"] });
    return () => obs.disconnect();
  }, []);
  return theme;
}
const AvatarInner = React.forwardRef(
  ({ size = 32, shape = "circle", src, alt, icon: Icon, color = "neutral", solid = false, status, badgeCount, hoverCard, className, style, ...props }, ref) => {
    var _a;
    const [imgError, setImgError] = React.useState(false);
    const documentTheme = useDocumentTheme();
    const isTableScrolling = useTableIsScrolling();
    const isDisabledInField = useResolvedFieldDisabled();
    const isFill = size === "fill";
    const numSize = isFill ? 32 : size;
    const iconPx = getIconSize(numSize);
    const fontSizePx = Math.round(numSize * 0.5);
    const variantKey = solid ? "solid" : "subtle";
    const colors = ((_a = COLOR_MAP[variantKey]) == null ? void 0 : _a[color]) ?? COLOR_MAP.subtle.neutral;
    const radius = shape === "circle" ? "9999px" : "4px";
    const showImage = src && !imgError;
    const showIcon = !showImage && (Icon || !alt);
    const showText = !showImage && !showIcon && alt;
    const FallbackIcon = Icon ?? User;
    const dotSize = isFill ? 10 : Math.max(8, Math.min(16, Math.round(numSize * 0.28)));
    const dotBorder = dotSize >= 12 ? 3 : 2;
    const avatarEl = /* @__PURE__ */ jsxs(
      "div",
      {
        className: cn(
          "inline-flex items-center justify-center shrink-0 overflow-hidden select-none",
          isFill && "w-full h-full",
          // 2026-05-13 R3.5 self-dim:Avatar 在 disabled Field wrapper context 內自 dim
          // (取代 field-wrapper.tsx default/bare/naked disabled blanket opacity-disabled 逃生艙)
          isDisabledInField && "opacity-disabled"
        ),
        style: {
          ...isFill ? { containerType: "inline-size" } : { width: numSize, height: numSize },
          borderRadius: radius,
          backgroundColor: showImage ? void 0 : colors.bg,
          color: showImage ? void 0 : colors.text
        },
        "data-avatar-size": isFill ? "fill" : numSize,
        role: !showImage && alt && !hoverCard ? "img" : void 0,
        "aria-label": !showImage && alt && !hoverCard ? alt : void 0,
        children: [
          showImage && /* @__PURE__ */ jsx(
            "img",
            {
              src,
              alt: alt ?? "",
              className: "w-full h-full object-cover",
              onError: () => setImgError(true)
            }
          ),
          showIcon && (isFill ? /* @__PURE__ */ jsx(FallbackIcon, { className: "w-[60%] h-[60%]", "aria-hidden": true }) : /* @__PURE__ */ jsx(FallbackIcon, { size: iconPx, "aria-hidden": true })),
          showText && /* @__PURE__ */ jsx(
            "span",
            {
              className: "font-medium leading-none",
              style: { fontSize: isFill ? "50cqi" : fontSizePx },
              "aria-hidden": true,
              children: getInitial(alt)
            }
          )
        ]
      }
    );
    const hasOverlay = status || typeof badgeCount === "number";
    const focusableProps = hoverCard ? {
      tabIndex: 0,
      role: "button",
      "aria-haspopup": "dialog",
      "aria-label": alt ?? "View profile"
    } : {};
    const focusableClass = hoverCard ? cn("focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1", shape === "circle" ? "rounded-full" : "rounded-md") : "";
    const baseEl = !hasOverlay ? /* @__PURE__ */ jsx("div", { ref, className: cn("inline-flex shrink-0", focusableClass, className), style, ...focusableProps, ...props, children: avatarEl }) : /* @__PURE__ */ jsxs("div", { ref, className: cn("relative inline-flex shrink-0", focusableClass, className), style, ...focusableProps, ...props, children: [
      avatarEl,
      status && /* @__PURE__ */ jsx(
        "span",
        {
          className: "absolute block rounded-full",
          style: {
            width: dotSize,
            height: dotSize,
            bottom: 0,
            right: 0,
            backgroundColor: STATUS_DOT_COLOR[status],
            boxShadow: `0 0 0 ${dotBorder}px var(--surface-raised, var(--canvas))`
          },
          "aria-hidden": true
        }
      ),
      typeof badgeCount === "number" && badgeCount > 0 && /* @__PURE__ */ jsx(
        Badge,
        {
          variant: "critical",
          count: badgeCount,
          max: 99,
          className: "absolute -top-1 -right-1",
          style: {
            boxShadow: `0 0 0 2px var(--surface-raised, var(--canvas))`
          },
          "aria-label": `${badgeCount} unread`
        }
      )
    ] });
    if (!hoverCard || isTableScrolling) return baseEl;
    return /* @__PURE__ */ jsxs(HoverCard, { openDelay: HOVER_DELAY_RICH_MS, closeDelay: HOVER_DELAY_CLOSE_MS, children: [
      /* @__PURE__ */ jsx(HoverCardTrigger, { asChild: true, children: baseEl }),
      /* @__PURE__ */ jsx(
        HoverCardContent,
        {
          "data-theme": documentTheme ?? void 0,
          className: "bg-surface-raised rounded-lg border border-border overflow-hidden",
          style: { boxShadow: "var(--elevation-200)" },
          children: hoverCard
        }
      )
    ] });
  }
);
AvatarInner.displayName = "AvatarInner";
const avatarMeta = {
  component: "Avatar",
  family: null,
  // non-family composite / overlay / layout
  variants: {},
  sizes: {},
  states: ["default", "focus-visible", "disabled"],
  // 2026-06-11 R2:本身無自有 hover/active(spec L279;hoverCard 互動屬 HoverCard),
  tokens: {
    bg: ["bg-surface-raised"],
    fg: ["--foreground", "--on-emphasis"],
    ring: ["ring-ring"]
  }
};
AvatarInner.displayName = "Avatar";
const Avatar = React.memo(AvatarInner);
export {
  Avatar,
  avatarMeta
};
//# sourceMappingURL=avatar.js.map
