"use client";
import * as React from "react";
import { ownerDocument } from "../../../../utils/esm/owner.js";
import { useTimeout } from "../../../../utils/esm/useTimeout.js";
import { useStableCallback } from "../../../../utils/esm/useStableCallback.js";
import { useMergedRefs } from "../../../../utils/esm/useMergedRefs.js";
import { useValueAsRef } from "../../../../utils/esm/useValueAsRef.js";
import { useSelectRootContext } from "../root/SelectRootContext.js";
import { useFieldRootContext } from "../../field/root/FieldRootContext.js";
import { useLabelableContext } from "../../labelable-provider/LabelableContext.js";
import { pressableTriggerOpenStateMapping } from "../../utils/popupStateMapping.js";
import { fieldValidityMapping } from "../../field/utils/constants.js";
import { useRenderElement } from "../../utils/useRenderElement.js";
import { selectors } from "../store.js";
import { getPseudoElementBounds } from "../../utils/getPseudoElementBounds.js";
import { createChangeEventDetails } from "../../utils/createBaseUIEventDetails.js";
import { useButton } from "../../use-button/useButton.js";
import { useStore } from "../../../../utils/esm/store/useStore.js";
import { getFloatingFocusElement, contains } from "../../floating-ui-react/utils/element.js";
import { mergeProps } from "../../merge-props/mergeProps.js";
import { focusOut, cancelOpen } from "../../utils/reason-parts.js";
const BOUNDARY_OFFSET = 2;
const stateAttributesMapping = {
  ...pressableTriggerOpenStateMapping,
  ...fieldValidityMapping,
  value: () => null
};
const SelectTrigger = /* @__PURE__ */ React.forwardRef(function SelectTrigger2(componentProps, forwardedRef) {
  const {
    render,
    className,
    disabled: disabledProp = false,
    nativeButton = true,
    ...elementProps
  } = componentProps;
  const {
    setTouched,
    setFocused,
    validationMode,
    state: fieldState,
    disabled: fieldDisabled
  } = useFieldRootContext();
  const {
    labelId
  } = useLabelableContext();
  const {
    store,
    setOpen,
    selectionRef,
    validation,
    readOnly,
    alignItemWithTriggerActiveRef,
    disabled: selectDisabled,
    keyboardActiveRef
  } = useSelectRootContext();
  const disabled = fieldDisabled || selectDisabled || disabledProp;
  const open = useStore(store, selectors.open);
  const value = useStore(store, selectors.value);
  const triggerProps = useStore(store, selectors.triggerProps);
  const positionerElement = useStore(store, selectors.positionerElement);
  const listElement = useStore(store, selectors.listElement);
  const serializedValue = useStore(store, selectors.serializedValue);
  const positionerRef = useValueAsRef(positionerElement);
  const triggerRef = React.useRef(null);
  const timeoutFocus = useTimeout();
  const timeoutMouseDown = useTimeout();
  const {
    getButtonProps,
    buttonRef
  } = useButton({
    disabled,
    native: nativeButton
  });
  const setTriggerElement = useStableCallback((element) => {
    store.set("triggerElement", element);
  });
  const mergedRef = useMergedRefs(forwardedRef, triggerRef, buttonRef, setTriggerElement);
  const timeout1 = useTimeout();
  const timeout2 = useTimeout();
  React.useEffect(() => {
    if (open) {
      timeout2.start(200, () => {
        selectionRef.current.allowUnselectedMouseUp = true;
        timeout1.start(200, () => {
          selectionRef.current.allowSelectedMouseUp = true;
        });
      });
      return () => {
        timeout1.clear();
        timeout2.clear();
      };
    }
    selectionRef.current = {
      allowSelectedMouseUp: false,
      allowUnselectedMouseUp: false
    };
    timeoutMouseDown.clear();
    return void 0;
  }, [open, selectionRef, timeoutMouseDown, timeout1, timeout2]);
  const ariaControlsId = React.useMemo(() => {
    return listElement?.id ?? getFloatingFocusElement(positionerElement)?.id;
  }, [listElement, positionerElement]);
  const props = mergeProps(triggerProps, {
    role: "combobox",
    "aria-expanded": open ? "true" : "false",
    "aria-haspopup": "listbox",
    "aria-controls": open ? ariaControlsId : void 0,
    "aria-labelledby": labelId,
    "aria-readonly": readOnly || void 0,
    tabIndex: disabled ? -1 : 0,
    ref: mergedRef,
    onFocus(event) {
      setFocused(true);
      if (open && alignItemWithTriggerActiveRef.current) {
        setOpen(false, createChangeEventDetails(focusOut, event.nativeEvent));
      }
      timeoutFocus.start(0, () => {
        store.set("forceMount", true);
      });
    },
    onBlur() {
      setTouched(true);
      setFocused(false);
      if (validationMode === "onBlur") {
        validation.commit(value);
      }
    },
    onPointerMove() {
      keyboardActiveRef.current = false;
    },
    onKeyDown() {
      keyboardActiveRef.current = true;
    },
    onMouseDown(event) {
      if (open) {
        return;
      }
      const doc = ownerDocument(event.currentTarget);
      function handleMouseUp(mouseEvent) {
        if (!triggerRef.current) {
          return;
        }
        const mouseUpTarget = mouseEvent.target;
        if (contains(triggerRef.current, mouseUpTarget) || contains(positionerRef.current, mouseUpTarget) || mouseUpTarget === triggerRef.current) {
          return;
        }
        const bounds = getPseudoElementBounds(triggerRef.current);
        if (mouseEvent.clientX >= bounds.left - BOUNDARY_OFFSET && mouseEvent.clientX <= bounds.right + BOUNDARY_OFFSET && mouseEvent.clientY >= bounds.top - BOUNDARY_OFFSET && mouseEvent.clientY <= bounds.bottom + BOUNDARY_OFFSET) {
          return;
        }
        setOpen(false, createChangeEventDetails(cancelOpen, mouseEvent));
      }
      timeoutMouseDown.start(0, () => {
        doc.addEventListener("mouseup", handleMouseUp, {
          once: true
        });
      });
    }
  }, validation.getValidationProps, elementProps, getButtonProps);
  props.role = "combobox";
  const state = React.useMemo(() => ({
    ...fieldState,
    open,
    disabled,
    value,
    readOnly,
    placeholder: !serializedValue
  }), [fieldState, open, disabled, value, readOnly, serializedValue]);
  return useRenderElement("button", componentProps, {
    ref: [forwardedRef, triggerRef],
    state,
    stateAttributesMapping,
    props
  });
});
if (process.env.NODE_ENV !== "production") SelectTrigger.displayName = "SelectTrigger";
export {
  SelectTrigger
};
//# sourceMappingURL=SelectTrigger.js.map
