const require_runtime = require("../../../_virtual/_rolldown/runtime.js");
const require_objectSpread2 = require("../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js");
const require_useVariables = require("../hooks/useVariables.js");
const require_utils = require("../provider/variables/utils.js");
let react = require("react");
react = require_runtime.__toESM(react);
let _pisell_utils = require("@pisell/utils");
let ahooks = require("ahooks");
//#region src/components/dataSourceComponents/dataSourceShow/utils.tsx
const parseValueToVariableKey = (value) => {
	if ((0, _pisell_utils.isArr)(value) && value.length === 1 && (0, _pisell_utils.isString)(value[0])) {
		const key = require_utils.getVariableKey(value[0]);
		return key ? key.split(".")[0] : null;
	}
	if ((0, _pisell_utils.isString)(value)) {
		const key = require_utils.getVariableKey(value);
		return key ? key.split(".")[0] : null;
	}
	return null;
};
const withParseVariables = (Component, keys) => {
	return (props) => {
		const [variables, setVariables] = (0, react.useState)({});
		const { parseVariable, subscribeVariables } = require_useVariables.default();
		const valuesRef = (0, react.useRef)(/* @__PURE__ */ new Set());
		const handleVariableChange = (0, ahooks.useMemoizedFn)((allVariables, updateVariables) => {
			const changedKey = Object.keys(updateVariables)[0];
			if (valuesRef.current.has(changedKey)) setVariables((prev) => require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, prev), allVariables));
		});
		(0, react.useEffect)(() => {
			const values = /* @__PURE__ */ new Set();
			keys.forEach((key) => {
				const variableKey = parseValueToVariableKey(props[key]);
				if (variableKey) values.add(variableKey);
			});
			valuesRef.current = values;
		}, [props, keys]);
		(0, react.useEffect)(() => {
			const unsubscribe = subscribeVariables === null || subscribeVariables === void 0 ? void 0 : subscribeVariables(handleVariableChange);
			return () => {
				unsubscribe === null || unsubscribe === void 0 || unsubscribe();
			};
		}, []);
		const parsedProps = (0, react.useMemo)(() => {
			const result = require_objectSpread2._objectSpread2({}, props);
			keys.forEach((key) => {
				const value = props[key];
				if ((0, _pisell_utils.isArr)(value) && value.length === 1 && (0, _pisell_utils.isString)(value[0])) result[key] = parseVariable === null || parseVariable === void 0 ? void 0 : parseVariable(value[0], variables);
				else if ((0, _pisell_utils.isString)(value)) result[key] = parseVariable === null || parseVariable === void 0 ? void 0 : parseVariable(value, variables);
			});
			return result;
		}, [
			props,
			variables,
			keys
		]);
		return /* @__PURE__ */ react.default.createElement(Component, parsedProps);
	};
};
//#endregion
exports.default = withParseVariables;
