import { jsx, jsxs, Fragment } from "react/jsx-runtime";
import * as React from "react";
import { forwardRef, useId } from "react";
import { u as useComposedRefs } from "../../index-DcJYRxi-.js";
import { c as createContextScope } from "../../index-voAj_M6Q.js";
import { c as composeEventHandlers } from "../../index-B-mNdDrH.js";
import { u as useControllableState } from "../../index-vuqbEv5O.js";
import { u as usePrevious } from "../../index-CshadhlS.js";
import { u as useSize } from "../../index-DzFPFHc9.js";
import { P as Presence } from "../../index-BYmdwF6l.js";
import { P as Primitive } from "../../index-BEpjRf6p.js";
import { S as StCheck } from "../../StCheck-DWjoYM69.js";
import { c as cn } from "../../cn-FAaWYZ6x.js";
var CHECKBOX_NAME = "Checkbox";
var [createCheckboxContext, createCheckboxScope] = createContextScope(CHECKBOX_NAME);
var [CheckboxProviderImpl, useCheckboxContext] = createCheckboxContext(CHECKBOX_NAME);
function CheckboxProvider(props) {
  const {
    __scopeCheckbox,
    checked: checkedProp,
    children,
    defaultChecked,
    disabled,
    form,
    name,
    onCheckedChange,
    required,
    value = "on",
    // @ts-expect-error
    internal_do_not_use_render
  } = props;
  const [checked, setChecked] = useControllableState({
    prop: checkedProp,
    defaultProp: defaultChecked ?? false,
    onChange: onCheckedChange,
    caller: CHECKBOX_NAME
  });
  const [control, setControl] = React.useState(null);
  const [bubbleInput, setBubbleInput] = React.useState(null);
  const hasConsumerStoppedPropagationRef = React.useRef(false);
  const isFormControl = control ? !!form || !!control.closest("form") : (
    // We set this to true by default so that events bubble to forms without JS (SSR)
    true
  );
  const context = {
    checked,
    disabled,
    setChecked,
    control,
    setControl,
    name,
    form,
    value,
    hasConsumerStoppedPropagationRef,
    required,
    defaultChecked: isIndeterminate(defaultChecked) ? false : defaultChecked,
    isFormControl,
    bubbleInput,
    setBubbleInput
  };
  return /* @__PURE__ */ jsx(
    CheckboxProviderImpl,
    {
      scope: __scopeCheckbox,
      ...context,
      children: isFunction(internal_do_not_use_render) ? internal_do_not_use_render(context) : children
    }
  );
}
var TRIGGER_NAME = "CheckboxTrigger";
var CheckboxTrigger = React.forwardRef(
  ({ __scopeCheckbox, onKeyDown, onClick, ...checkboxProps }, forwardedRef) => {
    const {
      control,
      value,
      disabled,
      checked,
      required,
      setControl,
      setChecked,
      hasConsumerStoppedPropagationRef,
      isFormControl,
      bubbleInput
    } = useCheckboxContext(TRIGGER_NAME, __scopeCheckbox);
    const composedRefs = useComposedRefs(forwardedRef, setControl);
    const initialCheckedStateRef = React.useRef(checked);
    React.useEffect(() => {
      const form = control?.form;
      if (form) {
        const reset = () => setChecked(initialCheckedStateRef.current);
        form.addEventListener("reset", reset);
        return () => form.removeEventListener("reset", reset);
      }
    }, [control, setChecked]);
    return /* @__PURE__ */ jsx(
      Primitive.button,
      {
        type: "button",
        role: "checkbox",
        "aria-checked": isIndeterminate(checked) ? "mixed" : checked,
        "aria-required": required,
        "data-state": getState(checked),
        "data-disabled": disabled ? "" : void 0,
        disabled,
        value,
        ...checkboxProps,
        ref: composedRefs,
        onKeyDown: composeEventHandlers(onKeyDown, (event) => {
          if (event.key === "Enter") event.preventDefault();
        }),
        onClick: composeEventHandlers(onClick, (event) => {
          setChecked((prevChecked) => isIndeterminate(prevChecked) ? true : !prevChecked);
          if (bubbleInput && isFormControl) {
            hasConsumerStoppedPropagationRef.current = event.isPropagationStopped();
            if (!hasConsumerStoppedPropagationRef.current) event.stopPropagation();
          }
        })
      }
    );
  }
);
CheckboxTrigger.displayName = TRIGGER_NAME;
var Checkbox$1 = React.forwardRef(
  (props, forwardedRef) => {
    const {
      __scopeCheckbox,
      name,
      checked,
      defaultChecked,
      required,
      disabled,
      value,
      onCheckedChange,
      form,
      ...checkboxProps
    } = props;
    return /* @__PURE__ */ jsx(
      CheckboxProvider,
      {
        __scopeCheckbox,
        checked,
        defaultChecked,
        disabled,
        required,
        onCheckedChange,
        name,
        form,
        value,
        internal_do_not_use_render: ({ isFormControl }) => /* @__PURE__ */ jsxs(Fragment, { children: [
          /* @__PURE__ */ jsx(
            CheckboxTrigger,
            {
              ...checkboxProps,
              ref: forwardedRef,
              __scopeCheckbox
            }
          ),
          isFormControl && /* @__PURE__ */ jsx(
            CheckboxBubbleInput,
            {
              __scopeCheckbox
            }
          )
        ] })
      }
    );
  }
);
Checkbox$1.displayName = CHECKBOX_NAME;
var INDICATOR_NAME = "CheckboxIndicator";
var CheckboxIndicator = React.forwardRef(
  (props, forwardedRef) => {
    const { __scopeCheckbox, forceMount, ...indicatorProps } = props;
    const context = useCheckboxContext(INDICATOR_NAME, __scopeCheckbox);
    return /* @__PURE__ */ jsx(
      Presence,
      {
        present: forceMount || isIndeterminate(context.checked) || context.checked === true,
        children: /* @__PURE__ */ jsx(
          Primitive.span,
          {
            "data-state": getState(context.checked),
            "data-disabled": context.disabled ? "" : void 0,
            ...indicatorProps,
            ref: forwardedRef,
            style: { pointerEvents: "none", ...props.style }
          }
        )
      }
    );
  }
);
CheckboxIndicator.displayName = INDICATOR_NAME;
var BUBBLE_INPUT_NAME = "CheckboxBubbleInput";
var CheckboxBubbleInput = React.forwardRef(
  ({ __scopeCheckbox, ...props }, forwardedRef) => {
    const {
      control,
      hasConsumerStoppedPropagationRef,
      checked,
      defaultChecked,
      required,
      disabled,
      name,
      value,
      form,
      bubbleInput,
      setBubbleInput
    } = useCheckboxContext(BUBBLE_INPUT_NAME, __scopeCheckbox);
    const composedRefs = useComposedRefs(forwardedRef, setBubbleInput);
    const prevChecked = usePrevious(checked);
    const controlSize = useSize(control);
    React.useEffect(() => {
      const input = bubbleInput;
      if (!input) return;
      const inputProto = window.HTMLInputElement.prototype;
      const descriptor = Object.getOwnPropertyDescriptor(
        inputProto,
        "checked"
      );
      const setChecked = descriptor.set;
      const bubbles = !hasConsumerStoppedPropagationRef.current;
      if (prevChecked !== checked && setChecked) {
        const event = new Event("click", { bubbles });
        input.indeterminate = isIndeterminate(checked);
        setChecked.call(input, isIndeterminate(checked) ? false : checked);
        input.dispatchEvent(event);
      }
    }, [bubbleInput, prevChecked, checked, hasConsumerStoppedPropagationRef]);
    const defaultCheckedRef = React.useRef(isIndeterminate(checked) ? false : checked);
    return /* @__PURE__ */ jsx(
      Primitive.input,
      {
        type: "checkbox",
        "aria-hidden": true,
        defaultChecked: defaultChecked ?? defaultCheckedRef.current,
        required,
        disabled,
        name,
        value,
        form,
        ...props,
        tabIndex: -1,
        ref: composedRefs,
        style: {
          ...props.style,
          ...controlSize,
          position: "absolute",
          pointerEvents: "none",
          opacity: 0,
          margin: 0,
          // We transform because the input is absolutely positioned but we have
          // rendered it **after** the button. This pulls it back to sit on top
          // of the button.
          transform: "translateX(-100%)"
        }
      }
    );
  }
);
CheckboxBubbleInput.displayName = BUBBLE_INPUT_NAME;
function isFunction(value) {
  return typeof value === "function";
}
function isIndeterminate(checked) {
  return checked === "indeterminate";
}
function getState(checked) {
  return isIndeterminate(checked) ? "indeterminate" : checked ? "checked" : "unchecked";
}
const Checkbox = forwardRef(({ className, label, description, ...props }, ref) => {
  const id = useId();
  const descriptionId = `${id}-description`;
  const checkboxElement = /* @__PURE__ */ jsx(
    Checkbox$1,
    {
      ref,
      id,
      "data-slot": "checkbox",
      "aria-describedby": description ? descriptionId : void 0,
      className: cn(
        "peer cursor-pointer border-gray-400/80 dark:bg-input/30 hover:border-gray-500 hover:ring-1 hover:ring-gray-500 active:border-gray-500 active:ring-1 active:ring-gray-500 data-[state=checked]:bg-accent data-[state=checked]:text-white data-[state=checked]:border-accent data-[state=checked]:hover:ring-1 data-[state=checked]:hover:ring-accent data-[state=checked]:active:border-action data-[state=checked]:active:ring-1 data-[state=checked]:active:ring-action data-[state=indeterminate]:bg-action data-[state=indeterminate]:text-white dark:data-[state=indeterminate]:bg-action data-[state=indeterminate]:border-action data-[state=indeterminate]:hover:border-action data-[state=indeterminate]:hover:ring-1 data-[state=indeterminate]:hover:ring-action data-[state=indeterminate]:active:border-action data-[state=indeterminate]:active:ring-1 data-[state=indeterminate]:active:ring-action focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border transition-all duration-100 outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 disabled:shadow-none disabled:hover:ring-0",
        className
      ),
      ...props,
      children: /* @__PURE__ */ jsx(
        CheckboxIndicator,
        {
          "data-slot": "checkbox-indicator",
          className: "flex justify-center items-center text-current transition-none",
          children: props.checked === "indeterminate" ? /* @__PURE__ */ jsx(
            StCheck,
            {
              width: 14,
              height: 14,
              style: { transform: "rotate(45deg)" }
            }
          ) : /* @__PURE__ */ jsx(StCheck, { width: 14, height: 14 })
        }
      )
    }
  );
  if (!label) {
    return checkboxElement;
  }
  return /* @__PURE__ */ jsx("div", { className: "py-2 space-y-1", children: /* @__PURE__ */ jsxs("label", { htmlFor: id, className: "flex space-x-2 cursor-pointer", children: [
    /* @__PURE__ */ jsx("div", { className: "flex items-center h-5", children: checkboxElement }),
    /* @__PURE__ */ jsxs("div", { className: "flex-1", children: [
      /* @__PURE__ */ jsx("span", { className: "block font-medium text-primary leading-5", children: label }),
      description && /* @__PURE__ */ jsx("span", { id: descriptionId, className: "block text-sm text-secondary", children: description })
    ] })
  ] }) });
});
Checkbox.displayName = "Checkbox";
export {
  Checkbox
};
