import { jsxs, jsx } from "react/jsx-runtime";
import * as React from "react";
import * as ToggleGroupPrimitive from "@radix-ui/react-toggle-group";
import { cva } from "class-variance-authority";
import { cn } from "../../lib/utils.js";
import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuCheckboxItem } from "../DropdownMenu/dropdown-menu.js";
import { useScrollByPage, buildFadeMask, ARROW_BUTTON_WIDTH, OverflowScrollArrow, OverflowMenuTriggerButton } from "../../patterns/horizontal-overflow/horizontal-overflow.js";
import { useScrollEdges } from "../../hooks/use-overflow-items.js";
const chipVariants = cva(
  [
    "inline-flex items-center justify-center",
    "h-field-sm px-3 gap-1",
    "rounded-full border border-border",
    // 預設文字: text-fg-secondary (neutral-8) — 對齊 SegmentedControl / Tabs 未選狀態
    "bg-surface text-fg-secondary",
    "text-body leading-compact font-medium whitespace-nowrap",
    "transition-colors duration-150",
    "cursor-pointer select-none",
    "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1",
    // hover（未選）：border 加深一階 + 文字轉深，對齊 Input / SegmentedControl hover
    "hover:border-border-hover hover:text-foreground",
    // selected: 文字 + 邊框都用 primary-hover,底色維持 bg-surface 不變
    //   ── pill 風格 canonical 選中規則,跟 SegmentedControl 完全一致:
    //      primary-hover 同時染文字和線條;底色不改 (不用 primary-subtle)。
    "data-[state=on]:border-primary-hover data-[state=on]:text-primary-hover",
    // disabled：cursor-not-allowed + 鎖 hover 不變色
    // 不用 pointer-events-none（否則 cursor-not-allowed 不會顯示）
    "disabled:cursor-not-allowed disabled:text-fg-disabled",
    "disabled:hover:border-border disabled:hover:text-fg-disabled"
  ]
);
const Chip = React.forwardRef(({ className, startIcon: StartIcon, badge, endIcon: EndIcon, children, ...props }, ref) => {
  const hasSuffix = badge != null || EndIcon !== void 0;
  return /* @__PURE__ */ jsxs(
    ToggleGroupPrimitive.Item,
    {
      ref,
      className: cn(chipVariants(), className),
      ...props,
      children: [
        StartIcon && /* @__PURE__ */ jsx(StartIcon, { size: 16, "aria-hidden": true }),
        children != null && /* @__PURE__ */ jsx("span", { className: "px-1", children }),
        hasSuffix && /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-1", children: [
          badge,
          EndIcon && /* @__PURE__ */ jsx(EndIcon, { size: 16, "aria-hidden": true })
        ] })
      ]
    }
  );
});
Chip.displayName = "Chip";
const ChipGroup = React.forwardRef(
  ({ layout = "wrap", className, children, ...props }, ref) => {
    if (layout === "scroll") {
      return /* @__PURE__ */ jsx(ScrollChipGroup, { ref, className, ...props, children });
    }
    if (layout === "menu") {
      return /* @__PURE__ */ jsx(MenuChipGroup, { ref, className, ...props, children });
    }
    return /* @__PURE__ */ jsx(
      ToggleGroupPrimitive.Root,
      {
        ref,
        className: cn("flex flex-wrap gap-2", className),
        ...props,
        children
      }
    );
  }
);
ChipGroup.displayName = "ChipGroup";
const ScrollChipGroup = React.forwardRef(({ className, children, ...props }, ref) => {
  const { scrollRef, atStart, atEnd, canScroll } = useScrollEdges();
  const scrollByPage = useScrollByPage(scrollRef);
  const maskImage = buildFadeMask({
    canScroll,
    atStart,
    atEnd,
    reserveArrowWidth: ARROW_BUTTON_WIDTH
  });
  return /* @__PURE__ */ jsxs("div", { className: "relative", children: [
    /* @__PURE__ */ jsx(
      "div",
      {
        ref: scrollRef,
        className: "overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",
        style: { maskImage, WebkitMaskImage: maskImage },
        children: /* @__PURE__ */ jsx(
          ToggleGroupPrimitive.Root,
          {
            ref,
            className: cn("flex flex-nowrap gap-2 w-fit", className),
            ...props,
            children
          }
        )
      }
    ),
    !atStart && canScroll && /* @__PURE__ */ jsx(OverflowScrollArrow, { direction: "left", onClick: () => scrollByPage("left") }),
    !atEnd && canScroll && /* @__PURE__ */ jsx(OverflowScrollArrow, { direction: "right", onClick: () => scrollByPage("right") })
  ] });
});
ScrollChipGroup.displayName = "ScrollChipGroup";
const MenuChipGroup = React.forwardRef(({ className, children, ...props }, ref) => {
  const { scrollRef, atStart, atEnd, canScroll } = useScrollEdges();
  const itemRefs = React.useRef(/* @__PURE__ */ new Map());
  const scrollRafIdRef = React.useRef(0);
  React.useEffect(() => () => {
    if (scrollRafIdRef.current) cancelAnimationFrame(scrollRafIdRef.current);
  }, []);
  const registerItem = React.useCallback(
    (index) => (el) => {
      if (el) itemRefs.current.set(index, el);
      else itemRefs.current.delete(index);
    },
    []
  );
  const menuMaskImage = buildFadeMask({ canScroll, atStart, atEnd, reserveArrowWidth: 0 });
  const items = React.useMemo(
    () => React.Children.toArray(children).filter(React.isValidElement),
    [children]
  );
  const groupType = props.type ?? "single";
  const groupValue = props.value;
  const groupOnValueChange = props.onValueChange;
  const isSelected = React.useCallback(
    (chipValue) => {
      if (groupType === "multiple") {
        return Array.isArray(groupValue) && groupValue.includes(chipValue);
      }
      return groupValue === chipValue;
    },
    [groupType, groupValue]
  );
  const toggleFromMenu = React.useCallback(
    (chipValue, index) => {
      if (!groupOnValueChange) {
        return;
      }
      if (groupType === "multiple") {
        const current = Array.isArray(groupValue) ? groupValue : [];
        const next = current.includes(chipValue) ? current.filter((v) => v !== chipValue) : [...current, chipValue];
        groupOnValueChange(next);
      } else {
        groupOnValueChange(chipValue);
      }
      if (scrollRafIdRef.current) cancelAnimationFrame(scrollRafIdRef.current);
      scrollRafIdRef.current = requestAnimationFrame(() => {
        var _a;
        scrollRafIdRef.current = 0;
        (_a = itemRefs.current.get(index)) == null ? void 0 : _a.scrollIntoView({ behavior: "smooth", inline: "center", block: "nearest" });
      });
    },
    [groupType, groupValue, groupOnValueChange]
  );
  const enhancedItems = items.map(
    (child, i) => React.cloneElement(
      child,
      { ref: registerItem(i) }
    )
  );
  return /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
    /* @__PURE__ */ jsx(
      "div",
      {
        ref: scrollRef,
        className: "flex-1 min-w-0 overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",
        style: { maskImage: menuMaskImage, WebkitMaskImage: menuMaskImage },
        children: /* @__PURE__ */ jsx(
          ToggleGroupPrimitive.Root,
          {
            ref,
            className: cn("flex flex-nowrap gap-2 w-fit", className),
            ...props,
            children: enhancedItems
          }
        )
      }
    ),
    canScroll && /* @__PURE__ */ jsxs(DropdownMenu, { children: [
      /* @__PURE__ */ jsx(DropdownMenuTrigger, { asChild: true, children: /* @__PURE__ */ jsx(
        OverflowMenuTriggerButton,
        {
          "aria-label": `選項選單(共 ${items.length} 個)`
        }
      ) }),
      /* @__PURE__ */ jsx(DropdownMenuContent, { align: "end", children: items.map((chip, index) => {
        const chipProps = chip.props;
        const chipValue = chipProps.value;
        if (typeof chipValue !== "string") return null;
        return /* @__PURE__ */ jsx(
          DropdownMenuCheckboxItem,
          {
            checked: isSelected(chipValue),
            disabled: chipProps.disabled,
            onCheckedChange: () => toggleFromMenu(chipValue, index),
            children: chipProps.children
          },
          chipValue
        );
      }) })
    ] })
  ] });
});
MenuChipGroup.displayName = "MenuChipGroup";
const chipMeta = {
  component: "Chip",
  family: 3,
  variants: {},
  sizes: {},
  states: ["default", "hover", "selected", "focus-visible", "disabled"],
  // selected = data-[state=on](primary-hover);cva 無 active 樣式
  tokens: {
    bg: ["bg-surface"],
    fg: ["text-fg-disabled", "text-fg-secondary", "text-foreground", "text-primary-hover"],
    ring: ["ring-ring"]
  }
};
export {
  Chip,
  ChipGroup,
  chipMeta,
  chipVariants
};
//# sourceMappingURL=chip.js.map
