"use client";
import * as React from "react";
import { useStableCallback } from "../../../utils/esm/useStableCallback.js";
import { useControlled } from "../../../utils/esm/useControlled.js";
import { useBaseUiId } from "../utils/useBaseUiId.js";
import { useRenderElement } from "../utils/useRenderElement.js";
import { useToggleGroupContext } from "../toggle-group/ToggleGroupContext.js";
import { useButton } from "../use-button/useButton.js";
import { CompositeItem } from "../composite/item/CompositeItem.js";
import { createChangeEventDetails } from "../utils/createBaseUIEventDetails.js";
import { jsx } from "react/jsx-runtime";
import { none } from "../utils/reason-parts.js";
const Toggle = /* @__PURE__ */ React.forwardRef(function Toggle2(componentProps, forwardedRef) {
  const {
    className,
    defaultPressed: defaultPressedProp = false,
    disabled: disabledProp = false,
    form,
    // never participates in form validation
    onPressedChange: onPressedChangeProp,
    pressed: pressedProp,
    render,
    type,
    // cannot change button type
    value: valueProp,
    nativeButton = true,
    ...elementProps
  } = componentProps;
  const value = useBaseUiId(valueProp || void 0);
  const groupContext = useToggleGroupContext();
  const groupValue = groupContext?.value ?? [];
  const defaultPressed = groupContext ? void 0 : defaultPressedProp;
  const disabled = (disabledProp || groupContext?.disabled) ?? false;
  const [pressed, setPressedState] = useControlled({
    controlled: groupContext ? groupValue?.indexOf(value) > -1 : pressedProp,
    default: defaultPressed,
    name: "Toggle",
    state: "pressed"
  });
  const onPressedChange = useStableCallback((nextPressed, eventDetails) => {
    if (value) {
      groupContext?.setGroupValue?.(value, nextPressed, eventDetails);
    }
    onPressedChangeProp?.(nextPressed, eventDetails);
  });
  const {
    getButtonProps,
    buttonRef
  } = useButton({
    disabled,
    native: nativeButton
  });
  const state = React.useMemo(() => ({
    disabled,
    pressed
  }), [disabled, pressed]);
  const refs = [buttonRef, forwardedRef];
  const props = [{
    "aria-pressed": pressed,
    onClick(event) {
      const nextPressed = !pressed;
      const details = createChangeEventDetails(none, event.nativeEvent);
      onPressedChange(nextPressed, details);
      if (details.isCanceled) {
        return;
      }
      setPressedState(nextPressed);
    }
  }, elementProps, getButtonProps];
  const element = useRenderElement("button", componentProps, {
    enabled: !groupContext,
    state,
    ref: refs,
    props
  });
  if (groupContext) {
    return /* @__PURE__ */ jsx(CompositeItem, {
      tag: "button",
      render,
      className,
      state,
      refs,
      props
    });
  }
  return element;
});
if (process.env.NODE_ENV !== "production") Toggle.displayName = "Toggle";
export {
  Toggle
};
//# sourceMappingURL=Toggle.js.map
