/** @license MIT | @cube-dev/ui-kit v0.147.0 | Cube Dev Team */
import { getCaretRect } from "./caretPosition.js";
import { useEffect, useLayoutEffect, useRef } from "react";

//#region src/components/fields/CommandTextArea/useCaretAnchor.ts
/**
* Keeps a zero-size "caret anchor" element positioned at the textarea's caret
* (both axes), inside the (position: relative) input wrapper. The anchor is a
* real DOM node so react-aria's `useOverlayPosition` can measure it with
* `getBoundingClientRect`, while interaction/outside-click stays on the
* wrapper via a separate `triggerRef`.
*/
function useCaretAnchor({ inputRef, wrapperRef, caret, value, isActive }) {
	const anchorRef = useRef(null);
	const positionApiRef = useRef(null);
	useEffect(() => {
		const wrapper = wrapperRef.current;
		if (!wrapper) return;
		const anchor = document.createElement("span");
		anchor.setAttribute("data-caret-anchor", "");
		anchor.style.position = "absolute";
		anchor.style.top = "0";
		anchor.style.left = "0";
		anchor.style.width = "0";
		anchor.style.height = "0";
		anchor.style.pointerEvents = "none";
		anchor.style.overflow = "hidden";
		anchor.style.opacity = "0";
		wrapper.appendChild(anchor);
		anchorRef.current = anchor;
		return () => {
			anchor.remove();
			anchorRef.current = null;
		};
	}, [wrapperRef]);
	useLayoutEffect(() => {
		const anchor = anchorRef.current;
		const wrapper = wrapperRef.current;
		const input = inputRef.current;
		if (!anchor || !wrapper || !input) return;
		if (!isActive) {
			anchor.style.transform = "translate(0px, 0px)";
			return;
		}
		const rect = getCaretRect(input, caret);
		if (!rect) return;
		const wrapperRect = wrapper.getBoundingClientRect();
		const x = rect.left - wrapperRect.left;
		const y = rect.top - wrapperRect.top;
		anchor.style.transform = `translate(${x}px, ${y}px)`;
		anchor.style.height = `${rect.height}px`;
		positionApiRef.current?.updatePosition();
	}, [
		caret,
		value,
		isActive,
		inputRef,
		wrapperRef
	]);
	return {
		anchorRef,
		positionApiRef
	};
}

//#endregion
export { useCaretAnchor };
//# sourceMappingURL=useCaretAnchor.js.map