import { jsx, jsxs, Fragment } from "react/jsx-runtime";
import * as React from "react";
import { X } from "lucide-react";
import { EMPTY_DISPLAY } from "../Field/field-wrapper.js";
import { Tag } from "../Tag/tag.js";
import { OverflowIndicator } from "../OverflowIndicator/overflow-indicator.js";
import { Avatar } from "../Avatar/avatar.js";
import { ProfileCard, ProfileCardDefaultActions } from "../ProfileCard/profile-card.js";
import { useTableIsScrolling } from "../Field/field-context.js";
import { ItemPrefix } from "../../patterns/element-anatomy/item-anatomy.js";
import { getAvatarStackVisibleCount, AVATAR_STACK_AVATAR_PX, AVATAR_STACK_OVERFLOW_CHIP_PX } from "./avatar-stack-overflow.js";
function resolvePerson(value) {
  return typeof value === "string" ? { name: value } : value;
}
function buildPersonProfileCard(person) {
  return /* @__PURE__ */ jsx(
    ProfileCard,
    {
      name: person.name,
      subtitle: person.description,
      avatar: { src: person.avatarUrl, alt: person.name },
      status: person.status,
      statusMessage: person.statusMessage,
      defaultFieldValues: {
        id: person.id,
        employeeNumber: person.employeeNumber
      },
      fields: person.fields,
      actions: /* @__PURE__ */ jsx(ProfileCardDefaultActions, {}),
      onViewMore: person.onViewProfile ?? (() => {
      })
    }
  );
}
const AVATAR_PX = { sm: 20, md: 24, lg: 24 };
function PersonAvatar({
  person,
  size = "md",
  className = "",
  style
}) {
  const isTableScrolling = useTableIsScrolling();
  const nameCard = React.useMemo(
    () => isTableScrolling ? void 0 : buildPersonProfileCard(person),
    [person, isTableScrolling]
  );
  return /* @__PURE__ */ jsx(
    Avatar,
    {
      src: person.avatarUrl,
      alt: person.name,
      size: AVATAR_PX[size],
      className,
      style,
      hoverCard: nameCard
    }
  );
}
function PersonDisplay({ value, size = "md" }) {
  if (!value) return /* @__PURE__ */ jsx("span", { className: "text-fg-muted", children: EMPTY_DISPLAY });
  const person = resolvePerson(value);
  return /* @__PURE__ */ jsxs("span", { className: "flex items-start gap-2 min-w-0 w-full", children: [
    /* @__PURE__ */ jsx(ItemPrefix, { children: /* @__PURE__ */ jsx(PersonAvatar, { person, size }) }),
    /* @__PURE__ */ jsx("span", { className: "truncate flex-1 min-w-0", children: person.name })
  ] });
}
PersonDisplay.displayName = "PersonDisplay";
function MultiPersonDisplay({
  value,
  size = "md",
  max,
  measured = false,
  onRemove
}) {
  if (!value || value.length === 0) return /* @__PURE__ */ jsx("span", { className: "text-fg-muted", children: EMPTY_DISPLAY });
  const containerRef = React.useRef(null);
  const [measuredCount, setMeasuredCount] = React.useState(null);
  React.useLayoutEffect(() => {
    if (!measured) return;
    const el = containerRef.current;
    if (!el) return;
    const calc = () => {
      const visible2 = getAvatarStackVisibleCount({
        availablePx: el.clientWidth,
        total: value.length,
        avatarPx: AVATAR_STACK_AVATAR_PX[size],
        overflowChipPx: AVATAR_STACK_OVERFLOW_CHIP_PX[size]
      });
      setMeasuredCount(visible2);
    };
    calc();
    const ro = new ResizeObserver(calc);
    ro.observe(el);
    return () => ro.disconnect();
  }, [measured, size, value]);
  const resolvedMax = measured && measuredCount !== null ? measuredCount : max ?? 3;
  const people = value.map(resolvePerson);
  const visible = people.slice(0, resolvedMax);
  const hidden = people.slice(resolvedMax);
  const overflow = hidden.length;
  if (people.length === 1) {
    return /* @__PURE__ */ jsx(PersonDisplay, { value: value[0], size });
  }
  return /* @__PURE__ */ jsx("span", { ref: containerRef, className: "inline-flex items-start min-w-0", children: /* @__PURE__ */ jsx(ItemPrefix, { className: "!justify-start", children: /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center min-w-0", children: [
    visible.map((person, i) => {
      const handleDismiss = onRemove ? () => onRemove(value[i]) : void 0;
      return /* @__PURE__ */ jsxs("span", { className: `relative inline-flex group/avatar ${i > 0 ? "-ml-0.5" : ""}`, style: { zIndex: visible.length - i }, children: [
        /* @__PURE__ */ jsx(
          PersonAvatar,
          {
            person,
            size,
            className: "ring-2 ring-[var(--surface)]"
          }
        ),
        handleDismiss && /* @__PURE__ */ jsx(AvatarDismissOverlay, { onRemove: handleDismiss, label: person.name })
      ] }, person.name + i);
    }),
    overflow > 0 && /* @__PURE__ */ jsx(
      OverflowIndicator,
      {
        count: overflow,
        size,
        className: "ring-2 ring-[var(--surface)] -ml-0.5",
        children: hidden.map((person, i) => /* @__PURE__ */ jsx(
          Tag,
          {
            color: "neutral",
            size: "sm",
            avatar: /* @__PURE__ */ jsx(
              Avatar,
              {
                src: person.avatarUrl,
                alt: person.name,
                size: 16,
                hoverCard: buildPersonProfileCard(person)
              }
            ),
            onRemove: onRemove ? () => onRemove(value[resolvedMax + i]) : void 0,
            children: person.name
          },
          person.name + i
        ))
      }
    )
  ] }) }) });
}
MultiPersonDisplay.displayName = "MultiPersonDisplay";
function AvatarDismissOverlay({ onRemove, label }) {
  return /* @__PURE__ */ jsx(
    "button",
    {
      type: "button",
      onClick: (e) => {
        e.stopPropagation();
        onRemove();
      },
      "aria-label": `移除 ${label}`,
      className: [
        // **Position(2026-05-07 v15.15 user-confirmed)**:asymmetric `-top-px -right-1`
        // (top -1px / right -4px)— field padding-y(4px sm/md)緊 → top 只 -1px 安全;
        // padding-x 12px 寬鬆 → right 凸 4px 達 badge canonical visual。對齊 ClickUp
        // 世界級 idiom(asymmetric offset by avatar/field size constraint)。
        "absolute -top-px -right-1 z-10",
        "inline-flex items-center justify-center",
        // **12×12 + 2px white ring**(SSOT match stacked avatar,Slack/Material/iOS
        // notification badge 2px ring canonical)。改用 `[box-shadow:...]` 而非 `ring-2`
        // 避免跟下方 `focus-visible:ring-2` 在 tailwind-merge 衝突(同 ring family
        // override 互殺)。Box-shadow inset 0 不影響 layout,也不被 focus-visible ring
        // 蓋掉(focus 那邊另一條 outline ring 不同 layer)。
        "w-3 h-3 rounded-full [box-shadow:0_0_0_2px_var(--surface)]",
        // bg-surface-strong = neutral-6-opaque / hover = neutral-7-opaque(both modes,
        // step-7 dark 公式自動 lighter → engaged 跨 mode 對稱)
        "bg-surface-strong text-on-emphasis hover:bg-surface-strong-hover",
        // a11y(codex P1 fix):opacity 而非 display:none — element 在 DOM/tab-order,
        // keyboard 可達。Hover / focus-within / focus-visible 三條件之一觸發。
        "opacity-0 group-hover/avatar:opacity-100 group-focus-within/avatar:opacity-100 focus-visible:opacity-100",
        "transition-opacity duration-150",
        "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
      ].join(" "),
      children: /* @__PURE__ */ jsx(X, { size: 12, strokeWidth: 3, "aria-hidden": true })
    }
  );
}
function PersonAvatarTag({
  person,
  size = "md",
  onRemove
}) {
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(PersonAvatar, { person, size, className: "ring-2 ring-[var(--surface)]" }),
    onRemove && /* @__PURE__ */ jsx(AvatarDismissOverlay, { onRemove, label: person.name })
  ] });
}
PersonAvatarTag.displayName = "PersonAvatarTag";
export {
  MultiPersonDisplay,
  PersonAvatarTag,
  PersonDisplay,
  buildPersonProfileCard,
  resolvePerson
};
//# sourceMappingURL=person-display.js.map
