import { toConsumableArray as _toConsumableArray, extends as _extends, objectSpread2 as _objectSpread2 } from '../../_virtual/_rollupPluginBabelHelpers.js';
import { useFloating, autoUpdate, offset, flip, shift, useDismiss, useInteractions, FloatingPortal } from '@floating-ui/react';
import React__default, { forwardRef } from 'react';
import { FloatingWrapper, FloatingTarget, FloatingContent } from './DatePickerBase.styles.js';
import { safeUseId } from '../../utils/react.js';

var resolveFloatingPlacement = function resolveFloatingPlacement(placement) {
  if (Array.isArray(placement)) {
    return placement[0] || 'bottom';
  }
  if (placement === 'auto') return 'bottom';
  return placement;
};
var getFloatingPortalProps = function getFloatingPortalProps(portal, wrappedId) {
  if (!portal) {
    return {
      id: wrappedId
    };
  }
  if (typeof portal === 'string') {
    return {
      id: portal
    };
  }
  return {
    root: portal
  };
};
var FloatingPopover = /*#__PURE__*/forwardRef(function (_ref, ref) {
  var _offset$, _offset$2;
  var target = _ref.target,
    children = _ref.children,
    opened = _ref.opened,
    onToggle = _ref.onToggle,
    placement = _ref.placement,
    portal = _ref.portal,
    offset$1 = _ref.offset,
    zIndex = _ref.zIndex,
    disableFlip = _ref.disableFlip,
    closeOnOverlayClick = _ref.closeOnOverlayClick,
    closeOnEsc = _ref.closeOnEsc;
  var _useFloating = useFloating({
      whileElementsMounted: function whileElementsMounted(referenceEl, floatingEl, update) {
        return autoUpdate(referenceEl, floatingEl, update, {
          ancestorScroll: false,
          ancestorResize: false,
          layoutShift: false
        });
      },
      placement: resolveFloatingPlacement(placement),
      open: opened,
      onOpenChange: onToggle,
      middleware: [offset({
        mainAxis: (_offset$ = offset$1 === null || offset$1 === void 0 ? void 0 : offset$1[1]) !== null && _offset$ !== void 0 ? _offset$ : 0,
        crossAxis: (_offset$2 = offset$1 === null || offset$1 === void 0 ? void 0 : offset$1[0]) !== null && _offset$2 !== void 0 ? _offset$2 : 0
      })].concat(_toConsumableArray(disableFlip ? [] : [flip({
        fallbackAxisSideDirection: 'end'
      })]), [shift()])
    }),
    refs = _useFloating.refs,
    floatingStyles = _useFloating.floatingStyles,
    context = _useFloating.context;
  var dismiss = useDismiss(context, {
    enabled: true,
    outsidePress: closeOnOverlayClick,
    escapeKey: closeOnEsc
  });
  var _useInteractions = useInteractions([dismiss]),
    getReferenceProps = _useInteractions.getReferenceProps,
    getFloatingProps = _useInteractions.getFloatingProps;
  var wrappedId = safeUseId();
  var handleClick = function handleClick(event) {
    onToggle(!opened, event);
  };

  // Проверка на target. Это может быть как ReactNode, так и функция, в которую пробрасывается ref.
  // Это нужно для более тонкой настройки reference-элемента, вокруг которого и будет позиционироваться выпадашка.
  // Пример: когда в Textfield под инпутом находится helperText (или еще что-либо),
  // но выпадающий список должен позиционироваться непосредственно возле самого инпута.
  var isTargetAsFunction = typeof target === 'function';
  return /*#__PURE__*/React__default.createElement(FloatingWrapper, {
    ref: ref,
    id: wrappedId
  }, /*#__PURE__*/React__default.createElement(FloatingTarget, _extends({
    ref: isTargetAsFunction ? undefined : refs.setReference
  }, getReferenceProps({
    onClick: handleClick
  })), typeof target === 'function' ? target(refs.setReference) : target), opened && /*#__PURE__*/React__default.createElement(FloatingPortal, getFloatingPortalProps(portal, wrappedId), /*#__PURE__*/React__default.createElement(FloatingContent, _extends({
    ref: refs.setFloating,
    style: _objectSpread2(_objectSpread2({}, floatingStyles), {}, {
      zIndex: zIndex || 1000
    })
  }, getFloatingProps()), children)));
});

export { FloatingPopover, resolveFloatingPlacement };
