/** @license MIT | @cube-dev/ui-kit v0.147.0 | Cube Dev Team */
import { useEvent } from "../../../_internal/hooks/use-event.js";
import { cloneLayout } from "./grid-core/layout.js";
import { useCallback, useEffect, useRef, useState } from "react";

//#region src/components/layout/Board/use-board-layout.ts
/**
* Headless layout state for a single board.
*
* Supports both controlled (`layout`) and uncontrolled (`defaultLayout`) usage.
* Intermediate drag/resize previews always update local state; only committed
* changes call `onLayoutChange`.
*/
function useBoardLayout(options) {
	const { layout: controlledLayout, defaultLayout, onLayoutChange } = options;
	const isControlled = controlledLayout !== void 0;
	const [layout, setLayout] = useState(() => cloneLayout(controlledLayout ?? defaultLayout ?? []));
	const layoutRef = useRef(layout);
	layoutRef.current = layout;
	const [placeholder, setPlaceholderState] = useState(null);
	const placeholderRef = useRef(null);
	const setPlaceholder = useCallback((item) => {
		placeholderRef.current = item;
		setPlaceholderState(item);
	}, []);
	const onLayoutChangeEvent = useEvent((next) => onLayoutChange?.(next));
	const prevControlledRef = useRef(controlledLayout);
	useEffect(() => {
		if (isControlled && controlledLayout !== prevControlledRef.current) {
			prevControlledRef.current = controlledLayout;
			const next = cloneLayout(controlledLayout ?? []);
			layoutRef.current = next;
			setLayout(next);
		}
	}, [controlledLayout, isControlled]);
	return {
		layout,
		layoutRef,
		placeholder,
		placeholderRef,
		setPlaceholder,
		applyLayout: useCallback((next, commit) => {
			layoutRef.current = next;
			setLayout(next);
			if (commit) onLayoutChangeEvent(next);
		}, [onLayoutChangeEvent])
	};
}

//#endregion
export { useBoardLayout };
//# sourceMappingURL=use-board-layout.js.map