/**
 * 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 { pkg } from "../../settings.js";
import { useCallback, useLayoutEffect, useState } from "react";

//#region src/components/Tearsheet/usePresence.ts
/**
* Copyright IBM Corp. 2025
*
* 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 usePresence = (ref, isOpen) => {
	const [exitState, setExitState] = useState(isOpen ? "idle" : "finished");
	const isExiting = exitState === "active";
	if (!isOpen && exitState === "idle") setExitState("active");
	if (isOpen && exitState !== "idle") setExitState("idle");
	const handleAnimationEnd = useCallback(() => {
		setExitState("finished");
	}, []);
	useLayoutEffect(() => {
		if (!ref.current || !isExiting) return;
		if (!("getAnimations" in ref.current)) {
			handleAnimationEnd();
			return;
		}
		const animations = ref.current.getAnimations({ subtree: true }).filter((animation) => animation instanceof CSSAnimation && animation.animationName.startsWith(`${pkg.prefix}`));
		if (!animations.length) {
			handleAnimationEnd();
			return;
		}
		let cancelled = false;
		Promise.all(animations.map((animation) => animation.finished)).finally(() => {
			if (cancelled) return;
			handleAnimationEnd();
		});
		return () => {
			cancelled = true;
		};
	}, [
		ref,
		isExiting,
		handleAnimationEnd
	]);
	return {
		isPresent: isOpen || exitState !== "finished",
		isExiting
	};
};

//#endregion
export { usePresence };