/*! © 2026 Yahoo, Inc. UDS v0.0.0-development */
import { composeRefs } from "./composeRefs.js";
import { Children, cloneElement, forwardRef, isValidElement } from "react";
import { jsx } from "react/jsx-runtime";
//#region src/utils/createSlot.tsx
/**
* Essentially @radix-ui/react-slot typed as a generic we can use with asChild
* @link: https://www.radix-ui.com/primitives/docs/utilities/slot
**/
function createSlot() {
	const Slot = forwardRef((props, forwardedRef) => {
		const { children, ...slotProps } = props;
		const childrenArray = Children.toArray(children);
		const slottable = childrenArray.find(isSlottable);
		if (slottable) {
			const newElement = slottable.props.children;
			const newChildren = childrenArray.map((child) => {
				if (child === slottable) {
					if (Children.count(newElement) > 1) return Children.only(null);
					return isValidElement(newElement) ? newElement.props.children : null;
				} else return child;
			});
			return /* @__PURE__ */ jsx(SlotClone, {
				...slotProps,
				ref: forwardedRef,
				children: isValidElement(newElement) ? cloneElement(newElement, void 0, newChildren) : null
			});
		}
		return /* @__PURE__ */ jsx(SlotClone, {
			...slotProps,
			ref: forwardedRef,
			children
		});
	});
	Slot.displayName = "Slot";
	const SlotClone = forwardRef((props, forwardedRef) => {
		const { children, ...slotProps } = props;
		if (isValidElement(children)) {
			const childProps = children.props;
			return cloneElement(children, {
				...mergeProps(slotProps, childProps),
				ref: forwardedRef ? composeRefs(forwardedRef, children.props.ref ?? children.ref) : children.props.ref ?? children.ref
			});
		}
		return Children.count(children) > 1 ? Children.only(null) : null;
	});
	SlotClone.displayName = "SlotClone";
	const Slottable = ({ children }) => {
		return children;
	};
	function isSlottable(child) {
		return isValidElement(child) && child.type === Slottable;
	}
	function mergeProps(slotProps, childProps) {
		const overrideProps = { ...childProps };
		for (const propName in childProps) {
			const slotPropValue = slotProps[propName];
			const childPropValue = childProps[propName];
			if (/^on[A-Z]/.test(propName)) {
				if (slotPropValue && childPropValue) overrideProps[propName] = (...args) => {
					childPropValue(...args);
					slotPropValue(...args);
				};
				else if (slotPropValue) overrideProps[propName] = slotPropValue;
			} else if (propName === "style") overrideProps[propName] = {
				...slotPropValue,
				...childPropValue
			};
		}
		return {
			...slotProps,
			...overrideProps
		};
	}
	return Slot;
}
//#endregion
export { createSlot };
