import selectors from "focusable-selectors";

function getNextFocusableElement(
    element: HTMLElement,
    {
        skipClosest = "",
        include = [],
        backwards,
    }: { skipClosest?: string; include?: string[]; backwards?: boolean } = {},
) {
    const useSelectors = [...selectors, ...include].join(",");
    let focusableElements = Array.from(document.querySelectorAll<HTMLElement>(useSelectors));
    if (backwards) {
        focusableElements = focusableElements.reverse();
    }

    const idx = focusableElements.indexOf(element);

    if (idx > -1) {
        for (let i = idx; i < focusableElements.length; i++) {
            const focusable = focusableElements[i];

            if (
                focusable !== element &&
                focusable.offsetParent &&
                (skipClosest ? !focusable.closest(skipClosest) : true)
            ) {
                return focusable;
            }
        }
    }

    return undefined;
}

export { getNextFocusableElement };
