import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import React, { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { useFloating, offset, flip, shift, autoUpdate } from '@floating-ui/react-dom';
var Menu = function Menu(_ref) {
  var anchor = _ref.anchor,
    children = _ref.children,
    _ref$placement = _ref.placement,
    placement = _ref$placement === void 0 ? 'bottom-start' : _ref$placement;
  var _useState = useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    open = _useState2[0],
    setOpen = _useState2[1];
  var _useFloating = useFloating({
      placement: placement,
      middleware: [offset(8), flip(), shift({
        padding: 8
      })]
    }),
    refs = _useFloating.refs,
    x = _useFloating.x,
    y = _useFloating.y,
    strategy = _useFloating.strategy,
    update = _useFloating.update;

  // Auto-update on layout changes
  useEffect(function () {
    if (open && refs.reference.current && refs.floating.current) {
      return autoUpdate(refs.reference.current, refs.floating.current, update);
    }
  }, [open, refs.reference, refs.floating, update]);

  // Close when clicking outside
  useEffect(function () {
    var handleClickOutside = function handleClickOutside(event) {
      if (refs.reference.current && refs.floating.current && !refs.floating.current.contains(event.target)) {
        setOpen(false);
      }
    };
    document.addEventListener('mousedown', handleClickOutside);
    return function () {
      return document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [refs]);
  return /*#__PURE__*/React.createElement("div", {
    style: {
      display: 'inline-block'
    }
  }, /*#__PURE__*/React.createElement("div", {
    ref: refs.setReference,
    onClick: function onClick() {
      return setOpen(function (prev) {
        return !prev;
      });
    },
    style: {
      cursor: 'pointer'
    }
  }, anchor), /*#__PURE__*/React.createElement(AnimatePresence, null, open && /*#__PURE__*/React.createElement(motion.div, {
    ref: refs.setFloating,
    initial: {
      opacity: 0,
      scale: 0.95,
      y: -5
    },
    animate: {
      opacity: 1,
      scale: 1,
      y: 0
    },
    exit: {
      opacity: 0,
      scale: 0.95,
      y: -5
    },
    transition: {
      duration: 0.2,
      ease: 'easeOut'
    },
    style: {
      position: strategy,
      top: y !== null && y !== void 0 ? y : 0,
      left: x !== null && x !== void 0 ? x : 0,
      zIndex: 1000,
      boxShadow: '0 2px 8px rgba(0,0,0,0.15)',
      minWidth: '150px'
    }
  }, typeof children === 'function' ? children(function () {
    return setOpen(false);
  }) : children)));
};
export default Menu;