import { _ as __assign } from '../tslib.es6-20a2a300.js';
import { jsxs, jsx } from 'react/jsx-runtime';
import * as React from 'react';
import { useState } from 'react';
import Icon from './Icon.js';
import Button from './Button.js';
import InputLabel from './InputLabel.js';
import { P as Popper, A as AutocompleteDropdown } from '../AutocompleteDropdown-d9450bc7.js';
import { a as withStyles } from '../withStyles-99aeb25b.js';
import { F as FormControl } from '../FormControl-1f6cf8f3.js';
import { B as Box } from '../Box-581dc061.js';
import * as ReactDOM from 'react-dom';
import { P as PropTypes, i as exactProp } from '../defaultTheme-49a26576.js';
import { o as ownerDocument } from '../ownerDocument-e276d08d.js';
import { u as useForkRef } from '../useForkRef-4ff8cc89.js';
import { u as useEventCallback } from '../useEventCallback-8817ed1c.js';
import { e as elementAcceptingRef } from '../elementAcceptingRef-29f38505.js';
import { F as Fade } from '../Fade-e167cb2c.js';
import '../icons/ArrowRight.js';
import '../icons/ArrowRightCircle.js';
import '../icons/Check.js';
import '../icons/CheckCircle.js';
import '../icons/ChevronRight.js';
import '../icons/CrossCircle.js';
import '../icons/DollarSign.js';
import '../icons/InfoCircle.js';
import '../icons/Link.js';
import '../icons/TriangleUp.js';
import '../icons/TriangleDown.js';
import '../icons/TriangleLeft.js';
import '../icons/Copy.js';
import '../icons/SortUp.js';
import '../icons/Cross.js';
import '../icons/Search.js';
import '../icons/Range.js';
import '../theme/colors.js';
import '../makeStyles-c9a99c7a.js';
import '../createStyles-16423e9e.js';
import '../clsx.m-6243b874.js';
import '../capitalize-5d3e9aac.js';
import '../ButtonBase-11d3cdb5.js';
import '../deprecatedPropType-0232df1e.js';
import '../useIsFocusVisible-c048447c.js';
import '../TransitionGroupContext-2ba64e99.js';
import '../refType-5cc24a92.js';
import '../elementTypeAcceptingRef-7677eeee.js';
import '../hoist-non-react-statics.cjs-b718ab87.js';
import './Typography.js';
import '../_commonjsHelpers-57e89916.js';
import '../theme/fontSize.js';
import '../theme/fontWeight.js';
import '../theme/fontFamily.js';
import '../theme/lineHeight.js';
import '../Typography-649a8eff.js';
import '../formControlState-da4d15f8.js';
import '../useFormControl-dc7cf5d6.js';
import '../FormControlContext-64eed5c2.js';
import './TextField.js';
import './Input.js';
import '../Input-d5c36a50.js';
import './FormHelperText.js';
import '../styled-339d0187.js';
import '../Close-9f6801e0.js';
import '../createSvgIcon-6fb7d1b7.js';
import '../useControlled-ca779f8e.js';
import '../IconButton-7563dc0d.js';
import '../Paper-cfd8f963.js';
import '../Portal-ea11d671.js';
import '../HTMLElementType-a5d51d34.js';
import '../useTheme-27496d89.js';
import '../utils-2b600105.js';

function mapEventPropToEvent(eventProp) {
  return eventProp.substring(2).toLowerCase();
}

function clickedRootScrollbar(event) {
  return document.documentElement.clientWidth < event.clientX || document.documentElement.clientHeight < event.clientY;
}
/**
 * Listen for click events that occur somewhere in the document, outside of the element itself.
 * For instance, if you need to hide a menu when people click anywhere else on your page.
 */


function ClickAwayListener(props) {
  var children = props.children,
      _props$disableReactTr = props.disableReactTree,
      disableReactTree = _props$disableReactTr === void 0 ? false : _props$disableReactTr,
      _props$mouseEvent = props.mouseEvent,
      mouseEvent = _props$mouseEvent === void 0 ? 'onClick' : _props$mouseEvent,
      onClickAway = props.onClickAway,
      _props$touchEvent = props.touchEvent,
      touchEvent = _props$touchEvent === void 0 ? 'onTouchEnd' : _props$touchEvent;
  var movedRef = React.useRef(false);
  var nodeRef = React.useRef(null);
  var activatedRef = React.useRef(false);
  var syntheticEventRef = React.useRef(false);
  React.useEffect(function () {
    // Ensure that this component is not "activated" synchronously.
    // https://github.com/facebook/react/issues/20074
    setTimeout(function () {
      activatedRef.current = true;
    }, 0);
    return function () {
      activatedRef.current = false;
    };
  }, []); // can be removed once we drop support for non ref forwarding class components

  var handleOwnRef = React.useCallback(function (instance) {
    // #StrictMode ready
    nodeRef.current = ReactDOM.findDOMNode(instance);
  }, []);
  var handleRef = useForkRef(children.ref, handleOwnRef); // The handler doesn't take event.defaultPrevented into account:
  //
  // event.preventDefault() is meant to stop default behaviours like
  // clicking a checkbox to check it, hitting a button to submit a form,
  // and hitting left arrow to move the cursor in a text input etc.
  // Only special HTML elements have these default behaviors.

  var handleClickAway = useEventCallback(function (event) {
    // Given developers can stop the propagation of the synthetic event,
    // we can only be confident with a positive value.
    var insideReactTree = syntheticEventRef.current;
    syntheticEventRef.current = false; // 1. IE 11 support, which trigger the handleClickAway even after the unbind
    // 2. The child might render null.
    // 3. Behave like a blur listener.

    if (!activatedRef.current || !nodeRef.current || clickedRootScrollbar(event)) {
      return;
    } // Do not act if user performed touchmove


    if (movedRef.current) {
      movedRef.current = false;
      return;
    }

    var insideDOM; // If not enough, can use https://github.com/DieterHolvoet/event-propagation-path/blob/master/propagationPath.js

    if (event.composedPath) {
      insideDOM = event.composedPath().indexOf(nodeRef.current) > -1;
    } else {
      // TODO v6 remove dead logic https://caniuse.com/#search=composedPath.
      var doc = ownerDocument(nodeRef.current);
      insideDOM = !doc.documentElement.contains(event.target) || nodeRef.current.contains(event.target);
    }

    if (!insideDOM && (disableReactTree || !insideReactTree)) {
      onClickAway(event);
    }
  }); // Keep track of mouse/touch events that bubbled up through the portal.

  var createHandleSynthetic = function createHandleSynthetic(handlerName) {
    return function (event) {
      syntheticEventRef.current = true;
      var childrenPropsHandler = children.props[handlerName];

      if (childrenPropsHandler) {
        childrenPropsHandler(event);
      }
    };
  };

  var childrenProps = {
    ref: handleRef
  };

  if (touchEvent !== false) {
    childrenProps[touchEvent] = createHandleSynthetic(touchEvent);
  }

  React.useEffect(function () {
    if (touchEvent !== false) {
      var mappedTouchEvent = mapEventPropToEvent(touchEvent);
      var doc = ownerDocument(nodeRef.current);

      var handleTouchMove = function handleTouchMove() {
        movedRef.current = true;
      };

      doc.addEventListener(mappedTouchEvent, handleClickAway);
      doc.addEventListener('touchmove', handleTouchMove);
      return function () {
        doc.removeEventListener(mappedTouchEvent, handleClickAway);
        doc.removeEventListener('touchmove', handleTouchMove);
      };
    }

    return undefined;
  }, [handleClickAway, touchEvent]);

  if (mouseEvent !== false) {
    childrenProps[mouseEvent] = createHandleSynthetic(mouseEvent);
  }

  React.useEffect(function () {
    if (mouseEvent !== false) {
      var mappedMouseEvent = mapEventPropToEvent(mouseEvent);
      var doc = ownerDocument(nodeRef.current);
      doc.addEventListener(mappedMouseEvent, handleClickAway);
      return function () {
        doc.removeEventListener(mappedMouseEvent, handleClickAway);
      };
    }

    return undefined;
  }, [handleClickAway, mouseEvent]);
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.cloneElement(children, childrenProps));
}

process.env.NODE_ENV !== "production" ? ClickAwayListener.propTypes = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------

  /**
   * The wrapped element.
   */
  children: elementAcceptingRef.isRequired,

  /**
   * If `true`, the React tree is ignored and only the DOM tree is considered.
   * This prop changes how portaled elements are handled.
   */
  disableReactTree: PropTypes.bool,

  /**
   * The mouse event to listen to. You can disable the listener by providing `false`.
   */
  mouseEvent: PropTypes.oneOf(['onClick', 'onMouseDown', 'onMouseUp', false]),

  /**
   * Callback fired when a "click away" event is detected.
   */
  onClickAway: PropTypes.func.isRequired,

  /**
   * The touch event to listen to. You can disable the listener by providing `false`.
   */
  touchEvent: PropTypes.oneOf(['onTouchEnd', 'onTouchStart', false])
} : void 0;

if (process.env.NODE_ENV !== 'production') {
  // eslint-disable-next-line
  ClickAwayListener['propTypes' + ''] = exactProp(ClickAwayListener.propTypes);
}

var StyledFormControl = withStyles(function (theme) { return ({
    root: {
        "& .MuiInputLabel-formControl": {
            position: "relative"
        }
    }
}); })(FormControl);
var StyledButton = withStyles(function (theme) { return ({
    root: {
        "&.MuiButton-contained": {
            color: theme.palette.icon.secondary,
            backgroundColor: theme.palette.input.main + " !important" // TODO: use button prop color
        },
        "& .MuiButton-endIcon": {
            marginLeft: theme.spacing(3)
        }
    }
}); })(Button);
var StyledMenu = withStyles(function (theme) { return ({
    root: {
        background: theme.palette.gray.white,
        borderRadius: theme.borders.radius.secondary + "px " + theme.borders.radius.secondary + "px 0 0",
        boxShadow: "0 24px 32px 0 rgba(0, 0, 0, 0.08)",
        "& .MuiFormControl-root": {
            padding: theme.spacing(2, 2, 0, 2)
        },
        "& .MuiInputBase-adornedEnd .icon": {
            display: "none"
        }
    }
}); })(Box);
var SelectAutocompleteDropdown = function (_a) {
    var id = _a.id, label = _a.label, fullWidth = _a.fullWidth, options = _a.options, getOptionLabel = _a.getOptionLabel, renderOption = _a.renderOption, placeholder = _a.placeholder, inputFieldColor = _a.inputFieldColor, buttonProps = _a.buttonProps, _b = _a.centerPopper, centerPopper = _b === void 0 ? false : _b, formControlProps = _a.formControlProps;
    var getPlaceholderEl = buttonProps.getPlaceholderEl, getOptionLabelEl = buttonProps.getOptionLabelEl;
    var _c = useState(null), anchorEl = _c[0], setAnchorEl = _c[1];
    var _d = useState(null), value = _d[0], setValue = _d[1];
    var _e = useState(Boolean(anchorEl)), isOpen = _e[0], setIsOpen = _e[1];
    var formId = isOpen ? id : undefined;
    var handleButtonClick = function (event) {
        setAnchorEl(!isOpen ? event.currentTarget : null);
        setIsOpen(!isOpen);
    };
    var handleMenuClose = function (event, reason) {
        if (reason === "toggleInput")
            return;
        if (anchorEl)
            anchorEl.focus();
        setIsOpen(false);
        setAnchorEl(null);
    };
    var handleOptionChange = function (event, newValue) {
        setValue(newValue);
    };
    var centerPopperModifiers = centerPopper
        ? {
            modifiers: {
                enabled: true,
                computeStyle: {
                    enabled: true,
                    fn: function (data) {
                        data.styles = __assign(__assign({}, data.styles), { left: (window.innerWidth - data.popper.width) / 2 + "px" });
                        return data;
                    }
                }
            }
        }
        : undefined;
    return (jsxs(StyledFormControl, __assign({ fullWidth: fullWidth }, formControlProps, { children: [label && jsx(InputLabel, __assign({ htmlFor: id }, { children: label }), void 0), jsxs(StyledButton, __assign({ size: "small", onClick: handleButtonClick, fullWidth: fullWidth, align: "left", endIcon: jsx(Icon, { iconKey: "triangleUp", rotate: isOpen ? 0 : 180 }, void 0) }, { children: [value && getOptionLabelEl(value), !value && getPlaceholderEl()] }), void 0), jsx(ClickAwayListener, __assign({ onClickAway: function (event) {
                    setIsOpen(!!(anchorEl === null || anchorEl === void 0 ? void 0 : anchorEl.contains(event.target)));
                } }, { children: jsx(Popper, __assign({ transition: true, id: formId, open: isOpen, anchorEl: anchorEl, placement: "bottom-start", style: { width: "100%", maxWidth: "590px", marginTop: "12px" } }, centerPopperModifiers, { children: function (_a) {
                        var TransitionProps = _a.TransitionProps;
                        return (jsx(Fade, __assign({}, TransitionProps, { timeout: 10 }, { children: jsx(StyledMenu, { children: jsx(AutocompleteDropdown, { open: true, style: { marginTop: "12px" }, fullWidth: fullWidth, id: formId, options: options, value: value, getOptionLabel: getOptionLabel, renderOption: renderOption, placeholder: placeholder, inputFieldColor: inputFieldColor, onChange: handleOptionChange, onClose: handleMenuClose, popperProps: {
                                        className: "select-autocomplete-popper",
                                        modifiers: {
                                            flip: {
                                                enabled: false
                                            }
                                        }
                                    } }, void 0) }, void 0) }), void 0));
                    } }), void 0) }), void 0)] }), void 0));
};

export { SelectAutocompleteDropdown as default };
