/*! © 2026 Yahoo, Inc. UDS v0.0.0-development */
//#region src/tokens/utils/spectrum.ts
/**
* Validates and coerces a value to a 0-255 integer.
* Accepts both string ("128") and numeric (128) inputs.
* Returns null for invalid values.
*
* Used by toSpectrumValueEntry below, and directly
* by spectrumColorUtils (configurator) for hex-to-rgb conversion.
*/
function toRgbChannel(value) {
	if (typeof value === "string" && /^\d+$/.test(value)) {
		const num = Number(value);
		return num >= 0 && num <= 255 ? num : null;
	}
	if (typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= 255) return value;
	return null;
}
/**
* Normalizes a spectrum value (unknown shape) into a SpectrumValueEntry.
*
* Returns undefined for null/undefined input.
* Returns the original reference when already normalized to avoid
* unnecessary object churn in memo comparators.
*
* Used by parseTokens (CSS variable injection), spectrumColorUtils
* (configurator previews/comparators), elevationUtils (shadow color
* resolution), and figma-data (Figma variable sync).
*/
function toSpectrumValueEntry(value) {
	if (value == null) return;
	if (typeof value === "object" && "rgb" in value) {
		const raw = value;
		const normalizedRef = typeof raw.$ref === "string" ? raw.$ref : null;
		if (typeof raw.rgb === "object" && raw.rgb !== null && "type" in raw.rgb && raw.rgb.type === "rgb") {
			const rgbLike = raw.rgb;
			const r = toRgbChannel(rgbLike.r);
			const g = toRgbChannel(rgbLike.g);
			const b = toRgbChannel(rgbLike.b);
			if (r == null || g == null || b == null) return;
			if ((raw.$ref ?? null) === normalizedRef && rgbLike.r === r && rgbLike.g === g && rgbLike.b === b) return value;
			return {
				rgb: {
					type: "rgb",
					r,
					g,
					b
				},
				$ref: normalizedRef
			};
		}
	}
}
/**
* Converts a SpectrumRGB to a space-separated string.
* Returns null for invalid input instead of throwing.
*
* Used by parseTokens (CSS variable values), spectrumColorUtils (equality
* comparators and hex/css conversion), elevationUtils (Color library input),
* and figma-data (Figma 0-1 RGB conversion).
*/
function spectrumRgbToString(rgb) {
	if (typeof rgb === "object" && rgb !== null && "r" in rgb && "g" in rgb && "b" in rgb) return `${rgb.r} ${rgb.g} ${rgb.b}`;
	return null;
}

//#endregion
export { spectrumRgbToString, toRgbChannel, toSpectrumValueEntry };