/** @license MIT | @cube-dev/ui-kit v0.127.0 | Cube Dev Team */
import { chainRaf } from "../../../utils/raf.js";
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";

//#region src/components/navigation/Tabs/use-tab-indicator.ts
/**
* Hook to track and animate tab indicator position.
*
* Calculates the position and width of the selection indicator
* based on the currently selected tab. Returns null if disabled
* (e.g., for non-default tab types).
*
* @param containerRef - Ref to the tab container element
* @param selectedKey - Currently selected tab key
* @param enabled - Whether the indicator should be shown
* @param orderToken - Optional token that changes when tab order changes (triggers recalculation)
* @returns Indicator style (left, width) or null if disabled/not ready
*/
function useTabIndicator(containerRef, selectedKey, enabled, orderToken) {
	const [style, setStyle] = useState(null);
	const cancelRef = useRef(null);
	const updateIndicator = useCallback(() => {
		if (!enabled || !containerRef.current || selectedKey == null) {
			setStyle(null);
			return;
		}
		const selectedTab = containerRef.current.querySelector("[aria-selected=\"true\"]");
		if (!selectedTab) {
			setStyle(null);
			return;
		}
		const containerRect = containerRef.current.getBoundingClientRect();
		const tabRect = selectedTab.getBoundingClientRect();
		if (tabRect.width > 0) setStyle({
			left: tabRect.left - containerRect.left + containerRef.current.scrollLeft,
			width: tabRect.width
		});
	}, [
		containerRef,
		selectedKey,
		enabled,
		orderToken
	]);
	useLayoutEffect(() => {
		if (cancelRef.current) cancelRef.current();
		cancelRef.current = chainRaf(() => {
			updateIndicator();
		}, 2);
		return () => {
			if (cancelRef.current) cancelRef.current();
		};
	}, [updateIndicator]);
	useEffect(() => {
		if (!enabled) return;
		const handleResize = () => updateIndicator();
		window.addEventListener("resize", handleResize);
		return () => window.removeEventListener("resize", handleResize);
	}, [enabled, updateIndicator]);
	useEffect(() => {
		if (!enabled) return;
		const container = containerRef.current;
		if (!container) return;
		let prevWidth = container.getBoundingClientRect().width;
		const observer = new ResizeObserver((entries) => {
			const entry = entries[0];
			if (!entry) return;
			const newWidth = entry.contentRect.width;
			if (prevWidth === 0 && newWidth > 0) updateIndicator();
			prevWidth = newWidth;
		});
		observer.observe(container);
		return () => observer.disconnect();
	}, [enabled, updateIndicator]);
	return enabled ? style : null;
}

//#endregion
export { useTabIndicator };
//# sourceMappingURL=use-tab-indicator.js.map