import { jsxs, jsx } from "react/jsx-runtime";
import * as React from "react";
import { Slot } from "@radix-ui/react-slot";
import { cva } from "class-variance-authority";
import { CircularProgress } from "../CircularProgress/circular-progress.js";
import { cn } from "../../lib/utils.js";
import { useResolvedFieldSize } from "../Field/field-context.js";
import { Tooltip, TooltipTrigger, TooltipContent } from "../Tooltip/tooltip.js";
const buttonVariants = cva(
  [
    "inline-flex items-center justify-center",
    "whitespace-nowrap font-medium",
    "border border-transparent",
    "transition-colors duration-150",
    "cursor-pointer select-none disabled:cursor-not-allowed aria-disabled:cursor-not-allowed",
    "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1",
    // 2026-05-12 Round 4.5 fix(codex M31 Layer C 抓):`aria-disabled` visual 分支補(per WAI-ARIA APG —
    // aria-disabled 給語意 + visual,但不 suppress functionality;functionality 由 consumer 阻 e.g.
    // RowDragHandle listeners 只在 canDrag spread)。**故意不加** `aria-disabled:pointer-events-none`
    // — Round 4 RowDragHandle Tooltip flicker fix root cause:aria-disabled buttons 必保 pointer events
    // 讓 Radix Tooltip pointerenter 通過。HTML `disabled` 保 PE:none(完全 inactive)。
    "disabled:pointer-events-none",
    // 2026-05-12 fix v2(playwright pixel-quantified verify 抓 opacity=1 不生效):
    // `opacity-disabled` 是 custom Tailwind v4 `@utility`(opacity.css:21),variant prefix
    // `aria-disabled:` 跟 custom @utility 不 compose(`aria-disabled:cursor-not-allowed` 標準
    // utility 能 work,custom 不行)。改 arbitrary value `opacity-[var(--opacity-disabled)]`
    // 繞 custom @utility 限制(Tailwind v4 arbitrary value 直接生 `opacity: var(--opacity-disabled)`)。
    "aria-disabled:opacity-[var(--opacity-disabled)]",
    "rounded-md",
    // Defensive:SVG 不被 flex shrink 擠扁(防 inner-area 計算誤差導致 icon 被擠成
    // width<intrinsic 的 asymmetric 顯示)。詳 ICON_ONLY_PX 段 rationale。
    "[&_svg]:shrink-0"
  ],
  {
    variants: {
      variant: {
        primary: [
          "bg-primary text-on-emphasis",
          "hover:bg-primary-hover",
          "active:bg-primary-active",
          "disabled:bg-disabled disabled:text-fg-disabled disabled:border-transparent"
        ],
        secondary: [
          "bg-surface text-primary border-primary",
          "hover:text-primary-hover hover:border-primary-hover",
          "active:text-primary-active active:border-primary-active",
          // Overlay trigger active(asChild Popover/DropdownMenu trigger)— 維持 hover 樣式
          // (canonical 對齊 inline-action.spec.md:trigger 維持 host hover 直到 overlay 關閉)
          "data-[state=open]:text-primary-hover data-[state=open]:border-primary-hover",
          "disabled:bg-transparent disabled:text-fg-disabled disabled:border-border"
          // 2026-05-21 v12:Toggle pressed 視覺移到 compoundVariants(variant × pressedTone),
          // 同時支援 emphasis(藍底)/ neutral(灰底)兩 tone。詳 cva.compoundVariants 段。
        ],
        tertiary: [
          "bg-surface text-foreground border-border",
          "hover:text-primary-hover hover:border-primary-hover",
          "active:text-primary-active active:border-primary-active",
          // Overlay trigger active — 維持 hover 樣式(同 secondary 邏輯)
          "data-[state=open]:text-primary-hover data-[state=open]:border-primary-hover",
          "disabled:bg-transparent disabled:text-fg-disabled disabled:border-border"
        ],
        text: [
          "bg-transparent text-foreground border-transparent",
          "hover:bg-neutral-hover",
          "active:bg-neutral-active",
          // Overlay trigger active — 維持 hover 樣式(canonical 2026-05-02 改:hover token,
          // 不另開 selected 4% — 對齊 shadcn/Radix/Material 狀態極簡派,跨 host 一致)
          "data-[state=open]:bg-neutral-hover",
          "disabled:bg-transparent disabled:text-fg-disabled"
        ],
        link: [
          "bg-transparent text-primary border-transparent",
          "hover:text-primary-hover",
          "active:text-primary-active",
          "disabled:text-fg-disabled"
        ]
      },
      danger: {
        true: ""
        // 實際樣式由 compoundVariants 提供
      },
      /**
       * 2026-05-21 v12 — pressed visual tone(per user「我認同這一個方向,然後預設emphasis」):
       * emphasis = 淡藍底(toolbar functional toggle / 篩選啟用 / 面板開關 — Figma toolbar /
       *            Linear toolbar / Material ToggleButton 共識)
       * neutral  = 灰底(sidebar/contextual nav row pressed — Linear / Notion / VS Code Activity Bar 共識)
       * 預設 `emphasis` per user directive。實際樣式由 compoundVariants(variant × pressedTone)套用。
       * 只在 secondary / tertiary / text variant 觸發 toggle 視覺;primary / link 無視覺效果。
       */
      pressedTone: {
        emphasis: "",
        neutral: ""
      },
      size: {
        xs: "h-field-xs px-2 text-caption leading-compact gap-0",
        sm: "h-field-sm px-3 min-w-14 text-body leading-compact gap-1",
        md: "h-field-md px-3 min-w-16 text-body leading-compact gap-1",
        lg: "h-field-lg px-3 min-w-20 text-body-lg leading-compact gap-1"
      }
    },
    compoundVariants: [
      // primary + danger → 紅底白字（立即不可逆操作）
      {
        variant: "primary",
        danger: true,
        class: [
          "bg-error text-on-emphasis border-transparent",
          "hover:bg-error-hover",
          "active:bg-error-active"
        ]
      },
      // secondary + danger → 紅框紅字（有確認步驟的危險操作）
      {
        variant: "secondary",
        danger: true,
        class: [
          "bg-surface text-error border-error",
          "hover:text-error-hover hover:border-error-hover",
          "active:text-error-active active:border-error-active"
        ]
      },
      // text + danger → 紅字，hover 灰底
      {
        variant: "text",
        danger: true,
        class: [
          "text-error",
          "hover:bg-neutral-hover hover:text-error-hover",
          "active:bg-neutral-active active:text-error-active"
        ]
      },
      // ── 2026-05-21 v12 Toggle pressed(variant × pressedTone)──────────────────
      // 視覺由 data-[state=on] + aria-pressed(Radix overlay trigger fallback)觸發
      //
      // emphasis tone:藍底(primary-subtle / primary 字)— functional toggle
      {
        variant: ["secondary", "tertiary", "text"],
        pressedTone: "emphasis",
        class: [
          "data-[state=on]:bg-primary-subtle data-[state=on]:text-primary data-[state=on]:border-transparent",
          "data-[state=on]:hover:text-primary-hover",
          "data-[state=on]:active:text-primary-active",
          "data-[state=on]:disabled:bg-disabled data-[state=on]:disabled:text-fg-disabled data-[state=on]:disabled:border-transparent",
          // aria-pressed fallback(Radix overlay trigger override data-state 時仍生效)
          "aria-pressed:bg-primary-subtle aria-pressed:text-primary aria-pressed:border-transparent",
          "aria-pressed:hover:text-primary-hover"
        ]
      },
      // neutral tone:灰底(neutral-selected family)— sidebar/contextual nav pressed
      {
        variant: ["secondary", "tertiary", "text"],
        pressedTone: "neutral",
        class: [
          "data-[state=on]:bg-neutral-selected data-[state=on]:text-foreground data-[state=on]:border-transparent",
          "data-[state=on]:hover:bg-neutral-selected-hover",
          "data-[state=on]:active:bg-neutral-selected-active",
          "data-[state=on]:disabled:bg-transparent data-[state=on]:disabled:text-fg-disabled",
          // aria-pressed fallback
          "aria-pressed:bg-neutral-selected aria-pressed:text-foreground aria-pressed:border-transparent",
          "aria-pressed:hover:bg-neutral-selected-hover"
        ]
      }
    ],
    defaultVariants: {
      // labeled 預設 = tertiary(2026-06-06 從 primary 改;iconOnly 預設 = text,由 resolvedVariant 注入)。
      // 真正預設邏輯在元件 resolvedVariant(L394);此 cva default 供直接 buttonVariants() 呼叫者一致。
      variant: "tertiary",
      size: "md",
      pressedTone: "emphasis"
    }
  }
);
const ButtonGroupContext = React.createContext({});
const ICON_ONLY_BASE = "aspect-square p-0 min-w-0 gap-0";
const Button = React.forwardRef(
  ({
    className,
    variant: variantProp,
    danger: dangerProp,
    size,
    asChild = false,
    startIcon: StartIcon,
    badge,
    overlayBadge,
    endIcon: EndIcon,
    iconOnly = false,
    dismiss = false,
    loading = false,
    fullWidth = false,
    pressed,
    pressedTone,
    // 2026-06-05 fix(deep-audit P0):原漏 destructure → 落入 ...props 噴到 DOM + 永遠用 cva default
    children,
    disabled,
    ...props
  }, ref) => {
    const resolvedSize = useResolvedFieldSize(size, "md");
    const resolvedIconOnly = iconOnly || dismiss;
    if (process.env.NODE_ENV !== "production" && overlayBadge && !iconOnly) {
      console.warn(
        "[DS Button] `overlayBadge` 只適用於 `iconOnly` Button。有 label 的 Button 請改用 `badge` prop(inline 位置,跟 label 並列),或移除 label 改為 iconOnly。SSOT:badge.spec.md「Overlay 適用元件 canonical」節。"
      );
    }
    if (process.env.NODE_ENV !== "production" && iconOnly && (EndIcon !== void 0 || badge != null)) {
      console.warn(
        "[DS Button] `iconOnly` 嚴格定義為「只有一個 icon,正方形」,不可與 `endIcon` 或 `badge` 並用。若需 icon + 下拉指示 → 不加 iconOnly + startIcon + endIcon + aria-label;若需 icon + 角標 → iconOnly + overlayBadge。SSOT:button.spec.md `iconOnly 的邊界` 節 + `badge.spec.md` Overlay 適用元件 canonical。"
      );
    }
    const resolvedVariant = dismiss ? "text" : variantProp === "destructive" ? "primary" : variantProp === "ghost" ? "text" : variantProp ?? (iconOnly ? "text" : "tertiary");
    const resolvedDanger = dangerProp || variantProp === "destructive";
    const groupCtx = React.useContext(ButtonGroupContext);
    const resolvedFullWidth = fullWidth || !!groupCtx.fullWidth;
    const Comp = asChild ? Slot : "button";
    const iconSize = resolvedSize === "lg" ? 20 : 16;
    const hasSuffix = badge != null || EndIcon !== void 0;
    const { "aria-label": ariaLabel, ...restProps } = props;
    const toggleAttrs = pressed === void 0 ? {} : { "aria-pressed": pressed, "data-state": pressed ? "on" : "off" };
    const unboundedAttr = resolvedVariant === "text" || dismiss ? { "data-unbounded": "true" } : {};
    const buttonEl = /* @__PURE__ */ jsxs(
      Comp,
      {
        className: cn(
          buttonVariants({ variant: resolvedVariant, danger: resolvedDanger, size: resolvedSize, pressedTone, className }),
          // iconOnly 鐵律:padding-free + aspect-square + flex-center (Polaris idiom)
          // 0 magic-number 0 公式自動正方形。詳 ICON_ONLY_BASE rationale。
          resolvedIconOnly && ICON_ONLY_BASE,
          // Dismiss 視覺弱化:override Button text variant 預設 foreground 為 fg-muted → hover foreground
          // 跟 Inline Action dismiss 視覺一致(cross-implementation dimming canonical)
          dismiss && "text-fg-muted hover:text-foreground",
          resolvedFullWidth && "w-full"
        ),
        ref,
        type: "button",
        disabled: disabled || loading,
        "aria-busy": loading || void 0,
        "aria-label": ariaLabel,
        ...toggleAttrs,
        ...unboundedAttr,
        ...restProps,
        children: [
          loading ? /* @__PURE__ */ jsx(CircularProgress, { size: iconSize, className: "text-current" }) : StartIcon ? resolvedIconOnly && overlayBadge ? (
            // Overlay badge canonical:wrapper 貼 icon 尺寸,badge 中心對齊 icon top-right corner
            // (Material BadgedBox / iOS App icon),不是 button chrome 角。
            //
            // CSS 細節(2026-04-20 bug fix):用 `inline-block` + 明確 width/height + `leading-none`
            // 避免 `inline-flex` span 在 Button flex container 內被撐高/撐寬(inline-flex 的 span
            // 在某些瀏覽器下會把絕對定位子元素的 translate 計算基準搞錯,造成 badge 噴飛、Button
            // aspect-square 失效)。明確給 span width/height = iconSize 鎖住 positioning context。
            /* @__PURE__ */ jsxs(
              "span",
              {
                className: "relative inline-block leading-none shrink-0 pointer-events-none",
                style: { width: iconSize, height: iconSize },
                children: [
                  /* @__PURE__ */ jsx(StartIcon, { size: iconSize, "aria-hidden": true }),
                  /* @__PURE__ */ jsx("span", { className: "absolute top-0 right-0 translate-x-1/2 -translate-y-1/2 pointer-events-auto", children: overlayBadge })
                ]
              }
            )
          ) : /* @__PURE__ */ jsx(StartIcon, { size: iconSize, "aria-hidden": true }) : null,
          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: iconSize, "aria-hidden": true })
          ] })
        ]
      }
    );
    if (resolvedIconOnly && typeof ariaLabel === "string" && !asChild) {
      return /* @__PURE__ */ jsxs(Tooltip, { children: [
        /* @__PURE__ */ jsx(TooltipTrigger, { asChild: true, children: buttonEl }),
        /* @__PURE__ */ jsx(TooltipContent, { children: ariaLabel })
      ] });
    }
    return buttonEl;
  }
);
Button.displayName = "Button";
const buttonMeta = {
  component: "Button",
  family: 3,
  // Pill Layout
  variants: {
    primary: { purpose: "主要 action / CTA" },
    secondary: { purpose: "次要 action(陪襯 primary)" },
    tertiary: { purpose: "第三級 action(tool-like)" },
    text: { purpose: "文字樣式 action(low emphasis / toolbar)" },
    link: { purpose: "內文連結(inline reading)" }
  },
  sizes: {
    xs: { fieldHeight: 24, iconSize: 16, typography: "caption" },
    sm: { fieldHeight: 28, iconSize: 16, typography: "body" },
    md: { fieldHeight: 32, iconSize: 16, typography: "body" },
    lg: { fieldHeight: 36, iconSize: 20, typography: "body-lg" }
  },
  states: ["default", "hover", "active", "focus-visible", "disabled"],
  tokens: {
    bg: ["--primary", "--primary-hover", "--primary-active", "--bg-disabled"],
    fg: ["--on-emphasis", "--fg-disabled"],
    ring: ["--ring"]
  },
  defaultVariant: "tertiary",
  // 2026-06-10 修 stale:對齊 cva defaultVariants(2026-06-06 labeled 預設改 tertiary,meta 漏同步)
  defaultSize: "md"
};
export {
  Button,
  ButtonGroupContext,
  buttonMeta,
  buttonVariants
};
//# sourceMappingURL=button.js.map
