"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useTreeNavigation = useTreeNavigation;
var _react = require("react");
var _utils = require("./utils");
function useTreeNavigation({
  adapter,
  tree,
  isDisabled = false
}) {
  const [nodes, setNodes] = (0, _react.useState)(() => adapter.getFocusableNodes(adapter.getFlatNodes(tree)));
  const nodesMap = (0, _react.useMemo)(() => (0, _utils.getNodesMap)(nodes), [nodes]);
  const refs = (0, _react.useRef)(new Map());
  const focused = (0, _react.useMemo)(() => nodes.find(n => n.isFocused) ?? null, [nodes]);
  const selected = [];
  const setFocused = (0, _react.useCallback)(id => {
    setNodes(state => {
      const unselectedState = (0, _utils.setAllNodesState)({
        isFocused: false
      }, state);
      return (0, _utils.setNodeState)(id, {
        isFocused: true
      }, unselectedState);
    });
  }, []);
  const setBlurred = (0, _react.useCallback)(id => {
    setNodes(state => {
      return (0, _utils.setNodeState)(id, {
        isFocused: false
      }, state);
    });
  }, []);
  (0, _react.useEffect)(() => {
    setNodes(state => {
      const currentFocus = state.find(n => n.isFocused);
      const nextNodes = adapter.getFocusableNodes(adapter.getFlatNodes(tree));
      const nextNodesWithFocus = currentFocus?.id ? (0, _utils.setNodeState)(currentFocus.id, {
        isFocused: true
      }, nextNodes) : nextNodes;
      return nextNodesWithFocus;
    });
  }, [tree]);
  const context = {
    nodes,
    setNodes,
    nodesMap,
    isDisabled,
    focused,
    selected,
    refs,
    setFocused,
    setBlurred,
    isNodeExpandedByDefault: adapter.isExpandedByDefault || false
  };
  return (0, _react.useMemo)(() => context, Object.values(context));
}