"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useMenuContext = exports.MenuProvider = void 0;
var _react = _interopRequireWildcard(require("react"));
var _jsxRuntime = require("react/jsx-runtime");
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
/*
 * Copyright OpenSearch Contributors
 * SPDX-License-Identifier: Apache-2.0
 */

const MenuContext = /*#__PURE__*/(0, _react.createContext)(undefined);
const MenuProvider = ({
  children
}) => {
  const [activeMenuNodeId, setActiveMenuNodeId] = (0, _react.useState)(null);
  const [menuPosition, setMenuPosition] = (0, _react.useState)(null);
  const nodeRefs = (0, _react.useRef)({});
  const registerNodeRef = (id, ref) => {
    nodeRefs.current[id] = ref;
  };
  const onToggleMenu = (event, nodeId) => {
    event.stopPropagation();
    if (activeMenuNodeId === nodeId) {
      setActiveMenuNodeId(null);
    } else {
      setActiveMenuNodeId(nodeId);
    }
  };
  const isMenuOpen = nodeId => activeMenuNodeId === nodeId;
  (0, _react.useEffect)(() => {
    var _nodeRefs$current$act;
    if (activeMenuNodeId && (_nodeRefs$current$act = nodeRefs.current[activeMenuNodeId]) !== null && _nodeRefs$current$act !== void 0 && _nodeRefs$current$act.current) {
      const rect = nodeRefs.current[activeMenuNodeId].current.getBoundingClientRect();
      setMenuPosition({
        top: rect.top,
        left: rect.right + 4 // keep it to the right of the node
      });
    }
  }, [activeMenuNodeId]);
  return /*#__PURE__*/(0, _jsxRuntime.jsx)(MenuContext.Provider, {
    value: {
      activeMenuNodeId,
      setActiveMenuNodeId,
      menuPosition,
      registerNodeRef,
      onToggleMenu,
      isMenuOpen
    },
    children: children
  });
};
exports.MenuProvider = MenuProvider;
const useMenuContext = () => {
  const context = (0, _react.useContext)(MenuContext);
  if (context === undefined) {
    throw new Error('useMenuContext must be used within a MenuProvider');
  }
  return context;
};
exports.useMenuContext = useMenuContext;