/**
 * 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 { usePresence } from "./usePresence.js";
import { useCallback, useMemo, useRef } from "react";

//#region src/components/Tearsheet/usePresenceContext.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.
*/
/**
* Returns if the presence node is present and the context value to be used by a presence context, e.g. ModalPresence.
*/
const usePresenceContext = (open, initialPresenceId) => {
	const presenceIdRef = useRef(initialPresenceId);
	const presenceRef = useRef(null);
	const prevPresenceRef = useRef(null);
	if (!initialPresenceId && prevPresenceRef.current && !presenceRef.current) presenceIdRef.current = null;
	prevPresenceRef.current = presenceRef.current;
	const { isPresent, isExiting } = usePresence(presenceRef, open);
	const isPresenceExclusive = useCallback((id) => {
		if (!id) return false;
		if (presenceIdRef.current && presenceIdRef.current !== id) return false;
		presenceIdRef.current = id;
		return true;
	}, []);
	return [isPresent, useMemo(() => ({
		presenceRef,
		isPresenceExclusive,
		isExiting
	}), [
		presenceRef,
		isPresenceExclusive,
		isExiting
	])];
};

//#endregion
export { usePresenceContext };