"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useListNavigation = useListNavigation;
var _react = require("react");
var _utils = require("./utils");
function useListNavigation({
  adapter,
  list,
  isDisabled = false,
  container,
  listId
}) {
  const [items, setItems] = (0, _react.useState)(adapter.getFocusableItems(list.map(adapter.getItem)));
  const itemsMap = (0, _react.useMemo)(() => (0, _utils.getItemsMap)(items), [items]);
  const refs = (0, _react.useRef)(new Map());
  const focused = (0, _react.useMemo)(() => items.find(n => n.isFocused) ?? null, [items]);
  const [lastFocused, setLastFocused] = (0, _react.useState)(focused?.id ?? null);
  const [lastFocusedIsPresent, setLastFocusedIsPresent] = (0, _react.useState)(!!focused?.id);
  const selected = (0, _react.useMemo)(() => items.filter(i => !!i.isSelected).map(({
    id
  }) => id), [items]);
  const setFocused = (0, _react.useCallback)(id => {
    setLastFocused(id);
    setLastFocusedIsPresent(true);
    setItems(state => {
      const unselectedState = (0, _utils.setAllItemsState)({
        isFocused: false
      }, state);
      return (0, _utils.setItemState)(id, {
        isFocused: true
      }, unselectedState);
    });
  }, []);
  const toggleSelected = (0, _react.useCallback)(id => {
    setItems(state => {
      const item = itemsMap.get(id);
      return (0, _utils.setItemState)(id, {
        isSelected: !item?.isSelected
      }, state);
    });
  }, [itemsMap]);
  const setBlurred = (0, _react.useCallback)(id => {
    setItems(state => {
      return (0, _utils.setItemState)(id, {
        isFocused: false
      }, state);
    });
  }, []);
  (0, _react.useEffect)(() => {
    const nextItems = adapter.getFocusableItems(list.map(adapter.getItem));
    const nextItemsWithFocus = focused?.id ? (0, _utils.setItemState)(focused.id, {
      isFocused: true
    }, nextItems) : nextItems;
    const nextHasLastFocused = nextItems.find(({
      id
    }) => id === lastFocused);
    setItems(nextItemsWithFocus);
    if (lastFocused && !nextHasLastFocused && lastFocusedIsPresent) {
      setLastFocusedIsPresent(false);
    }
    if (lastFocused && nextHasLastFocused && !lastFocusedIsPresent) {
      setLastFocusedIsPresent(true);
    }
  }, [list, adapter.getFocusableItems, adapter.getItem]);
  (0, _react.useLayoutEffect)(() => {
    if (container?.current) {
      if (focused?.id) {
        container.current.setAttribute('aria-activedescendant', (0, _utils.getElementId)(listId, focused.id));
      } else {
        container.current.removeAttribute('aria-activedescendant');
      }
    }
  }, [focused]);
  const context = {
    items,
    setItems,
    itemsMap,
    isDisabled,
    focused,
    lastFocused,
    lastFocusedIsPresent,
    selected,
    refs,
    toggleSelected,
    setFocused,
    setBlurred,
    listId
  };
  return (0, _react.useMemo)(() => context, Object.values(context));
}