/* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
import { makeGenericController } from "@arcgis/lumina/controllers";
import { c as componentFocusable } from "./component.js";
import { e as getRootNode, i as focusElement } from "./dom.js";
const useSetFocus = () => {
  return makeGenericController((component, controller) => {
    let abortController;
    function handleFocusOut() {
      abortController?.abort();
    }
    controller.onLoad(() => {
      component.listen("focus", () => {
        abortController = new AbortController();
        component.el.addEventListener("focusout", handleFocusOut, { signal: abortController.signal });
      });
    });
    controller.onDisconnected(() => {
      component.el.removeEventListener("focusout", handleFocusOut);
    });
    return async (getFocusTarget, options) => {
      if (component.disabled) {
        return;
      }
      const focusConfig = toFocusConfig(getFocusTarget());
      if (!focusConfig) {
        return;
      }
      const { target, includeContainer, strategy } = focusConfig;
      const rootNode = getRootNode(component.el);
      const currentActiveElement = rootNode.activeElement;
      await componentFocusable(component);
      const focusAlreadyChanged = currentActiveElement !== rootNode.activeElement;
      if (focusAlreadyChanged || abortController && !abortController?.signal.aborted) {
        return;
      }
      component.el.removeEventListener("focus", handleFocusOut);
      return focusElement(target, includeContainer, strategy, component.el, options);
    };
  });
};
function isFocusOverride(focusTarget) {
  return "target" in focusTarget && ("includeContainer" in focusTarget || "strategy" in focusTarget);
}
function toFocusConfig(focusTarget) {
  if (!focusTarget) {
    return;
  }
  return isFocusOverride(focusTarget) ? focusTarget : { target: focusTarget };
}
export {
  useSetFocus as u
};
