/** @license MIT | @cube-dev/ui-kit v0.0.0-canary-af8d194 | Cube Dev Team */
import { useLayoutEffect as useLayoutEffect$1 } from "./useLayoutEffect.js";
import { useEffect, useRef, useState } from "react";
import { useSSRSafeId } from "@react-aria/ssr";

//#region src/utils/react/useId.tsx
let idsUpdaterMap = /* @__PURE__ */ new Map();
/**
* If a default is not provided, generate an id.
* @param defaultId - Default component id.
*/
function useId$1(defaultId) {
	let isRendering = useRef(true);
	isRendering.current = true;
	let [value, setValue] = useState(defaultId);
	let nextId = useRef(null);
	let updateValue = (val) => {
		if (!isRendering.current) setValue(val);
		else nextId.current = val;
	};
	useLayoutEffect$1(() => {
		isRendering.current = false;
	});
	useEffect(() => {
		let newId = nextId.current;
		if (newId) {
			setValue(newId);
			nextId.current = null;
		}
	}, [setValue, updateValue]);
	let res = useSSRSafeId(value);
	idsUpdaterMap.set(res, updateValue);
	return res;
}
/**
* Merges two ids.
* Different ids will trigger a side-effect and re-render components hooked up with `useId`.
*/
function mergeIds(idA, idB) {
	if (idA === idB) return idA;
	let setIdA = idsUpdaterMap.get(idA);
	if (setIdA) {
		setIdA(idB);
		return idB;
	}
	let setIdB = idsUpdaterMap.get(idB);
	if (setIdB) {
		setIdB(idA);
		return idA;
	}
	return idB;
}

//#endregion
export { mergeIds, useId$1 as useId };
//# sourceMappingURL=useId.js.map