/**
 * Copyright IBM Corp. 2020, 2026
 *
 * This source code is licensed under the Apache-2.0 license found in the
 * LICENSE file in the root directory of this source tree.
 */

import wait from "../utils/wait.js";
import { useEffect } from "react";
//#region src/global/js/hooks/useCreateComponentFocus.js
/**
* Copyright IBM Corp. 2021, 2021
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
const useCreateComponentFocus = ({ previousState, currentStep, blockClass, onMount, firstFocusElement }) => {
	useEffect(() => {
		if (typeof onMount === "function") onMount();
	}, [onMount]);
	useEffect(() => {
		const awaitFocus = async (elm) => {
			await wait(10);
			elm.focus();
		};
		const isNotContainedInInert = (elm) => {
			if (!elm) return false;
			const inertParent = elm.closest("[inert]");
			return !inertParent || !inertParent.hasAttribute("inert") && !elm.disabled;
		};
		const getActiveStep = () => {
			return Array.from(document.querySelectorAll(blockClass)).find((el) => {
				let currentStep = el;
				while (currentStep) {
					if (currentStep.hasAttribute("inert")) return false;
					currentStep = currentStep.parentElement;
				}
				return true;
			});
		};
		const getFocusableElement = (containingElement) => {
			const focusElementQuery = `button, input[type="button"], input, select, textarea, a[href]`;
			const firstFocusEl = containingElement.querySelector(firstFocusElement);
			if (firstFocusEl && isNotContainedInInert(firstFocusEl) && !firstFocusEl.disabled) return firstFocusEl;
			return Array.from(containingElement.querySelectorAll(focusElementQuery)).find((el) => isNotContainedInInert(el) && !el.disabled);
		};
		if (previousState?.currentStep !== currentStep && currentStep > 0) {
			const activeStepElement = getActiveStep();
			if (activeStepElement && isNotContainedInInert(activeStepElement)) {
				const focusEl = getFocusableElement(activeStepElement);
				if (focusEl) awaitFocus(focusEl);
			}
		}
	}, [
		currentStep,
		previousState,
		blockClass,
		onMount,
		firstFocusElement
	]);
};
//#endregion
export { useCreateComponentFocus };
