import { newFocus, NEW_FOCUS } from "./solver.js";
import { getAllTabbableNodes, getTabbableNodes } from "./utils/DOMutils.js";
import { getAllAffectedNodes } from "./utils/all-affected.js";
import { pickAutofocus } from "./utils/auto-focus.js";
import { getActiveElement } from "./utils/getActiveElement.js";
import { isNotAGuard, isDefined } from "./utils/is.js";
import { getTopCommonParent, allParentAutofocusables } from "./utils/parenting.js";
var reorderNodes = function(srcNodes, dstNodes) {
  var remap = /* @__PURE__ */ new Map();
  dstNodes.forEach(function(entity) {
    return remap.set(entity.node, entity);
  });
  return srcNodes.map(function(node) {
    return remap.get(node);
  }).filter(isDefined);
};
var getFocusMerge = function(topNode, lastNode) {
  var activeElement = document && getActiveElement();
  var entries = getAllAffectedNodes(topNode).filter(isNotAGuard);
  var commonParent = getTopCommonParent(activeElement || topNode, topNode, entries);
  var visibilityCache = /* @__PURE__ */ new Map();
  var anyFocusable = getAllTabbableNodes(entries, visibilityCache);
  var innerElements = getTabbableNodes(entries, visibilityCache).filter(function(_a) {
    var node = _a.node;
    return isNotAGuard(node);
  });
  if (!innerElements[0]) {
    innerElements = anyFocusable;
    if (!innerElements[0]) {
      return void 0;
    }
  }
  var outerNodes = getAllTabbableNodes([commonParent], visibilityCache).map(function(_a) {
    var node = _a.node;
    return node;
  });
  var orderedInnerElements = reorderNodes(outerNodes, innerElements);
  var innerNodes = orderedInnerElements.map(function(_a) {
    var node = _a.node;
    return node;
  });
  var newId = newFocus(innerNodes, outerNodes, activeElement, lastNode);
  if (newId === NEW_FOCUS) {
    return { node: pickAutofocus(anyFocusable, innerNodes, allParentAutofocusables(entries, visibilityCache)) };
  }
  if (newId === void 0) {
    return newId;
  }
  return orderedInnerElements[newId];
};
export {
  getFocusMerge
};
//# sourceMappingURL=focusMerge.js.map
