import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { ChevronDown } from "lucide-react";
import { cn } from "../../lib/utils.js";
import { EMPTY_DISPLAY, nakedCellRowModeAlign, fieldWrapperStyles } from "../Field/field-wrapper.js";
import { ICON_SIZE, ItemSuffix } from "../../patterns/element-anatomy/item-anatomy.js";
import { useFieldSurface, useResolvedFieldSize, useResolvedFieldDisabled, useResolvedFieldMode, useResolvedFieldVariant } from "../Field/field-context.js";
import { Avatar } from "../Avatar/avatar.js";
import { Tag } from "../Tag/tag.js";
import { Select } from "../Select/select.js";
import { Combobox } from "../Combobox/combobox.js";
import { MultiPersonDisplay, PersonDisplay, resolvePerson, buildPersonProfileCard, PersonAvatarTag } from "./person-display.js";
import { getAvatarStackVisibleCount, AVATAR_STACK_AVATAR_PX, AVATAR_STACK_OVERFLOW_CHIP_PX } from "./avatar-stack-overflow.js";
import { findPerson, personToSelectOption, getPeoplePickerTagWrapperClass } from "./people-picker-helpers.js";
import { PEOPLE_PICKER_LENGTH1_WRAPPER_CLASS } from "./people-picker-helpers.js";
const PeoplePicker = React.forwardRef(function PeoplePicker2({
  mode: modeProp,
  variant: variantProp,
  size: sizeProp,
  value,
  onChange,
  people = [],
  placeholder = "請選擇人員",
  // i18n-allow: DS default(2026-05-12 Stream C Issue 4)
  searchPlaceholder = "搜尋人員…",
  // i18n-allow: DS default
  emptyText = "沒有符合的人員",
  // i18n-allow: DS default — only for SelectMenu noResultsText
  className,
  disabled: disabledProp,
  defaultOpen = false,
  onOpenChange,
  multiDisplay = "stack",
  pillShowAvatar = true,
  pillWrap = true,
  searchIn = "menu",
  showDisplayEndIcon = false,
  "aria-label": ariaLabel,
  ...rest
}, ref) {
  const surface = useFieldSurface();
  const size = useResolvedFieldSize(sizeProp);
  const disabled = useResolvedFieldDisabled(disabledProp);
  const resolvedMode = useResolvedFieldMode({ mode: modeProp, disabled });
  const resolvedVariant = useResolvedFieldVariant(variantProp);
  const isMulti = Array.isArray(value);
  const isEmpty = !value || isMulti && value.length === 0;
  if (resolvedMode === "display") {
    if (!showDisplayEndIcon) {
      if (isEmpty) return /* @__PURE__ */ jsx("span", { className: "text-fg-muted", children: EMPTY_DISPLAY });
      return isMulti ? /* @__PURE__ */ jsx(MultiPersonDisplay, { value, size, measured: true }) : /* @__PURE__ */ jsx(PersonDisplay, { value, size });
    }
    const iconSize = ICON_SIZE[size];
    return /* @__PURE__ */ jsxs(
      "div",
      {
        className: cn(fieldWrapperStyles({ mode: "display", variant: resolvedVariant, size }), className),
        "data-field-mode": "display",
        children: [
          /* @__PURE__ */ jsx("span", { className: cn("flex-1 min-w-0 inline-flex items-center", nakedCellRowModeAlign), children: isEmpty ? /* @__PURE__ */ jsx("span", { className: "text-fg-muted", children: EMPTY_DISPLAY }) : isMulti ? /* @__PURE__ */ jsx(MultiPersonDisplay, { value, size, measured: true }) : /* @__PURE__ */ jsx(PersonDisplay, { value, size }) }),
          /* @__PURE__ */ jsx(ItemSuffix, { className: "pointer-events-none", children: /* @__PURE__ */ jsx(ChevronDown, { size: iconSize, className: "shrink-0 text-fg-muted", "aria-hidden": true }) })
        ]
      }
    );
  }
  if (resolvedMode !== "edit") {
    return /* @__PURE__ */ jsxs(
      "div",
      {
        ref,
        className: cn(fieldWrapperStyles({ mode: resolvedMode, variant: resolvedVariant, size }), className),
        "data-field-mode": resolvedMode,
        "aria-disabled": resolvedMode === "disabled" ? true : void 0,
        "aria-label": ariaLabel,
        ...rest,
        children: [
          /* @__PURE__ */ jsx("span", { className: cn("flex-1 min-w-0 inline-flex items-center", nakedCellRowModeAlign, resolvedMode === "disabled" && "text-fg-disabled"), children: isEmpty ? /* @__PURE__ */ jsx("span", { className: "text-fg-muted", children: EMPTY_DISPLAY }) : isMulti ? /* @__PURE__ */ jsx(MultiPersonDisplay, { value, size, measured: true }) : /* @__PURE__ */ jsx(PersonDisplay, { value, size }) }),
          (resolvedVariant === "naked" ? showDisplayEndIcon : true) && /* @__PURE__ */ jsx(ItemSuffix, { className: "pointer-events-none", children: /* @__PURE__ */ jsx(ChevronDown, { size: ICON_SIZE[size], className: cn("shrink-0", resolvedMode === "disabled" ? "text-fg-disabled" : "text-fg-muted"), "aria-hidden": true }) })
        ]
      }
    );
  }
  const selectedNames = !value ? [] : Array.isArray(value) ? value.map((v) => resolvePerson(v).name) : [resolvePerson(value).name];
  if (!isMulti) {
    const handleSingleChange = (name) => onChange == null ? void 0 : onChange([findPerson(people, name)]);
    return /* @__PURE__ */ jsx(
      Select,
      {
        ref,
        size,
        variant: resolvedVariant,
        options: people.map(personToSelectOption),
        value: selectedNames[0] ?? null,
        onChange: handleSingleChange,
        searchable: true,
        placeholder,
        defaultOpen,
        onOpenChange,
        className,
        "aria-label": ariaLabel,
        selectedItemRenderer: (opt) => /* @__PURE__ */ jsx(PersonDisplay, { value: findPerson(people, opt.value), size }),
        ...rest
      }
    );
  }
  if (multiDisplay === "pill") {
    const handleMultiChange2 = (next) => {
      onChange == null ? void 0 : onChange(next.map((name) => findPerson(people, name)));
    };
    return /* @__PURE__ */ jsx(
      Combobox,
      {
        ref,
        size,
        variant: resolvedVariant,
        options: people.map(personToSelectOption),
        value: selectedNames,
        onChange: handleMultiChange2,
        searchable: true,
        searchPlaceholder,
        placeholder,
        emptyPlaceholder: emptyText,
        wrap: pillWrap,
        defaultOpen,
        onOpenChange,
        className,
        "aria-label": ariaLabel,
        ...rest,
        tagRenderer: (item, onRemove) => {
          const p = resolvePerson(findPerson(people, item.value));
          return /* @__PURE__ */ jsx(
            Tag,
            {
              size,
              color: "neutral",
              avatar: pillShowAvatar ? /* @__PURE__ */ jsx(Avatar, { src: p.avatarUrl, alt: p.name, size: 16, hoverCard: buildPersonProfileCard(p) }) : void 0,
              onRemove,
              children: p.name
            },
            item.value
          );
        }
      }
    );
  }
  const handleMultiChange = (next) => {
    onChange == null ? void 0 : onChange(next.map((name) => findPerson(people, name)));
  };
  const stackContainerRef = React.useRef(null);
  const [stackVisibleCount, setStackVisibleCount] = React.useState(void 0);
  React.useLayoutEffect(() => {
    if (!isMulti || selectedNames.length <= 1) {
      setStackVisibleCount(void 0);
      return;
    }
    const root = stackContainerRef.current;
    if (!root) return;
    const calc = () => {
      const trigger = root.matches('[role="combobox"]') ? root : root.querySelector('[role="combobox"]');
      const tagArea = trigger == null ? void 0 : trigger.querySelector('div[class*="flex-1"][class*="min-w-0"]');
      const available = (tagArea == null ? void 0 : tagArea.clientWidth) ?? (trigger == null ? void 0 : trigger.clientWidth) ?? 0;
      const visible = getAvatarStackVisibleCount({
        availablePx: available,
        total: selectedNames.length,
        avatarPx: AVATAR_STACK_AVATAR_PX[size],
        overflowChipPx: AVATAR_STACK_OVERFLOW_CHIP_PX[size]
      });
      setStackVisibleCount(visible);
    };
    calc();
    const ro = new ResizeObserver(calc);
    ro.observe(root);
    return () => ro.disconnect();
  }, [isMulti, multiDisplay, selectedNames.length, size]);
  const mergedStackRef = React.useCallback((el) => {
    stackContainerRef.current = el;
    if (typeof ref === "function") ref(el);
    else if (ref) ref.current = el;
  }, [ref]);
  return /* @__PURE__ */ jsx(
    Combobox,
    {
      ref: mergedStackRef,
      size,
      variant: resolvedVariant,
      options: people.map(personToSelectOption),
      value: selectedNames,
      onChange: handleMultiChange,
      searchable: true,
      searchIn,
      searchPlaceholder,
      placeholder,
      emptyPlaceholder: emptyText,
      wrap: false,
      defaultOpen,
      onOpenChange,
      className: cn(className, !isEmpty && surface === "form" && "!px-3"),
      "aria-label": ariaLabel,
      tagWrapperClassName: getPeoplePickerTagWrapperClass(selectedNames.length),
      overflowWrapperClassName: "-ml-0.5 first:ml-0 relative inline-flex",
      tagAreaGapPx: 0,
      tagAreaPaddingLeftPx: void 0,
      overflowShape: "circle",
      visibleCountOverride: stackVisibleCount,
      renderHiddenTag: (item) => {
        const p = resolvePerson(findPerson(people, item.value));
        return /* @__PURE__ */ jsx(
          Tag,
          {
            color: "neutral",
            size: "sm",
            avatar: /* @__PURE__ */ jsx(
              Avatar,
              {
                src: p.avatarUrl,
                alt: p.name,
                size: 16,
                hoverCard: buildPersonProfileCard(p)
              }
            ),
            onRemove: () => {
              onChange == null ? void 0 : onChange(selectedNames.filter((n) => n !== item.value).map((n) => findPerson(people, n)));
            },
            children: p.name
          },
          item.value
        );
      },
      ...rest,
      tagRenderer: (item, onRemove) => {
        const p = resolvePerson(findPerson(people, item.value));
        if (selectedNames.length === 1) {
          return /* @__PURE__ */ jsx(PersonDisplay, { value: p, size }, item.value);
        }
        return /* @__PURE__ */ jsx(
          PersonAvatarTag,
          {
            person: p,
            size,
            onRemove
          },
          item.value
        );
      }
    }
  );
});
PeoplePicker.displayName = "PeoplePicker";
const peoplePickerMeta = {
  component: "PeoplePicker",
  family: 4,
  variants: {},
  sizes: {},
  states: ["default", "hover", "active", "focus-visible", "disabled"],
  tokens: {
    bg: [],
    fg: ["text-fg-disabled", "text-fg-muted"],
    ring: []
  }
};
export {
  PEOPLE_PICKER_LENGTH1_WRAPPER_CLASS,
  PeoplePicker,
  getPeoplePickerTagWrapperClass,
  peoplePickerMeta
};
//# sourceMappingURL=people-picker.js.map
