import { useCallback, useMemo, useRef, useState, useEffect } from 'react';
import { getNodesMap, setAllNodesState, setNodeState } from './utils';
export function useTreeNavigation({
  adapter,
  tree,
  isDisabled = false
}) {
  const [nodes, setNodes] = useState(() => adapter.getFocusableNodes(adapter.getFlatNodes(tree)));
  const nodesMap = useMemo(() => getNodesMap(nodes), [nodes]);
  const refs = useRef(new Map());
  const focused = useMemo(() => nodes.find(n => n.isFocused) ?? null, [nodes]);
  const selected = [];
  const setFocused = useCallback(id => {
    setNodes(state => {
      const unselectedState = setAllNodesState({
        isFocused: false
      }, state);
      return setNodeState(id, {
        isFocused: true
      }, unselectedState);
    });
  }, []);
  const setBlurred = useCallback(id => {
    setNodes(state => {
      return setNodeState(id, {
        isFocused: false
      }, state);
    });
  }, []);
  useEffect(() => {
    setNodes(state => {
      const currentFocus = state.find(n => n.isFocused);
      const nextNodes = adapter.getFocusableNodes(adapter.getFlatNodes(tree));
      const nextNodesWithFocus = currentFocus?.id ? 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 useMemo(() => context, Object.values(context));
}