'use strict';

const React = require('react');
const types = require('../../../components/ui-builder/types.cjs');

function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }

const React__default = /*#__PURE__*/_interopDefaultCompat(React);

function resolveChildrenVariableReference(children, variables, variableValues) {
  if (types.isVariableReference(children)) {
    const variable = variables.find((v) => v.id === children.__variableRef);
    if (variable) {
      const resolvedValue = variableValues?.[variable.id] ?? variable.defaultValue;
      return String(resolvedValue);
    }
    return "";
  }
  return children;
}
function resolveVariableReferences(props, variables, variableValues, functionRegistry) {
  const resolved = {};
  const functionMetadata = {};
  for (const [key, value] of Object.entries(props)) {
    if (key.startsWith("__function_") && typeof value === "string") {
      const propName = key.replace("__function_", "");
      functionMetadata[propName] = value;
    }
  }
  for (const [propName, functionId] of Object.entries(functionMetadata)) {
    if (functionRegistry) {
      const funcDef = functionRegistry[functionId];
      if (funcDef) {
        resolved[propName] = funcDef.fn;
      } else {
        console.warn(`Function "${functionId}" not found in function registry for prop "${propName}"`);
        resolved[propName] = void 0;
      }
    }
  }
  for (const [key, value] of Object.entries(props)) {
    if (key.startsWith("__function_")) {
      continue;
    }
    if (functionMetadata[key] && functionRegistry) {
      continue;
    }
    if (types.isVariableReference(value)) {
      const variable = variables.find((v) => v.id === value.__variableRef);
      if (variable) {
        if (variable.type === "function") {
          const varFunctionId = String(variable.defaultValue);
          if (functionRegistry) {
            const funcDef = functionRegistry[varFunctionId];
            if (funcDef) {
              resolved[key] = funcDef.fn;
            } else {
              console.warn(`Function "${varFunctionId}" not found in function registry`);
              resolved[key] = void 0;
            }
          } else {
            resolved[key] = void 0;
          }
        } else {
          resolved[key] = variableValues?.[variable.id] ?? variable.defaultValue;
        }
      } else {
        resolved[key] = void 0;
      }
    } else if (typeof value === "object" && value !== null && !Array.isArray(value) && !React__default.isValidElement(value)) {
      resolved[key] = resolveVariableReferences(value, variables, variableValues, functionRegistry);
    } else {
      resolved[key] = value;
    }
  }
  return resolved;
}

exports.isVariableReference = types.isVariableReference;
exports.resolveChildrenVariableReference = resolveChildrenVariableReference;
exports.resolveVariableReferences = resolveVariableReferences;
