import {
  __spreadValues
} from "./chunk-Z67LV52D.js";

// ../toolpad-core/dist/constants.js
var RUNTIME_PROP_NODE_ID = "__toolpadNodeId";
var RUNTIME_PROP_SLOTS = "__toolpadSlots";
var TOOLPAD_COMPONENT = Symbol.for("ToolpadComponent");

// ../toolpad-core/dist/jsRuntime.js
import { getQuickJS } from "quickjs-emscripten";
import * as React from "react";
var JsRuntimeContext = React.createContext(null);
var JsRuntimeProvider = React.lazy(async () => {
  const quickJs = await getQuickJS();
  const Context = (props) => {
    const [runtime, setRuntime] = React.useState(() => quickJs.newRuntime(props.options));
    React.useEffect(() => {
      return () => {
        if (runtime.alive) {
          runtime.dispose();
        }
      };
    }, [runtime]);
    React.useEffect(() => setRuntime(quickJs.newRuntime(props.options)), [props.options]);
    return React.createElement(JsRuntimeContext.Provider, __spreadValues({ value: runtime }, props));
  };
  Context.displayName = "JsRuntimeProvider";
  return { default: Context };
});
function useJsRuntime() {
  const runtime = React.useContext(JsRuntimeContext);
  if (!runtime) {
    throw new Error(`No JsRuntime contetx found`);
  }
  return runtime;
}

// ../toolpad-core/dist/runtime.js
import * as React3 from "react";
import ErrorIcon from "@mui/icons-material/Error";
import { Tooltip } from "@mui/material";

// ../../node_modules/@babel/runtime/helpers/esm/setPrototypeOf.js
function _setPrototypeOf(o, p) {
  _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf2(o2, p2) {
    o2.__proto__ = p2;
    return o2;
  };
  return _setPrototypeOf(o, p);
}

// ../../node_modules/@babel/runtime/helpers/esm/inheritsLoose.js
function _inheritsLoose(subClass, superClass) {
  subClass.prototype = Object.create(superClass.prototype);
  subClass.prototype.constructor = subClass;
  _setPrototypeOf(subClass, superClass);
}

// ../../node_modules/react-error-boundary/dist/react-error-boundary.esm.js
import * as React2 from "react";
var changedArray = function changedArray2(a, b) {
  if (a === void 0) {
    a = [];
  }
  if (b === void 0) {
    b = [];
  }
  return a.length !== b.length || a.some(function(item, index) {
    return !Object.is(item, b[index]);
  });
};
var initialState = {
  error: null
};
var ErrorBoundary = /* @__PURE__ */ function(_React$Component) {
  _inheritsLoose(ErrorBoundary2, _React$Component);
  function ErrorBoundary2() {
    var _this;
    for (var _len = arguments.length, _args = new Array(_len), _key = 0; _key < _len; _key++) {
      _args[_key] = arguments[_key];
    }
    _this = _React$Component.call.apply(_React$Component, [this].concat(_args)) || this;
    _this.state = initialState;
    _this.resetErrorBoundary = function() {
      var _this$props;
      for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
        args[_key2] = arguments[_key2];
      }
      _this.props.onReset == null ? void 0 : (_this$props = _this.props).onReset.apply(_this$props, args);
      _this.reset();
    };
    return _this;
  }
  ErrorBoundary2.getDerivedStateFromError = function getDerivedStateFromError(error) {
    return {
      error
    };
  };
  var _proto = ErrorBoundary2.prototype;
  _proto.reset = function reset() {
    this.setState(initialState);
  };
  _proto.componentDidCatch = function componentDidCatch(error, info) {
    var _this$props$onError, _this$props2;
    (_this$props$onError = (_this$props2 = this.props).onError) == null ? void 0 : _this$props$onError.call(_this$props2, error, info);
  };
  _proto.componentDidUpdate = function componentDidUpdate(prevProps, prevState) {
    var error = this.state.error;
    var resetKeys = this.props.resetKeys;
    if (error !== null && prevState.error !== null && changedArray(prevProps.resetKeys, resetKeys)) {
      var _this$props$onResetKe, _this$props3;
      (_this$props$onResetKe = (_this$props3 = this.props).onResetKeysChange) == null ? void 0 : _this$props$onResetKe.call(_this$props3, prevProps.resetKeys, resetKeys);
      this.reset();
    }
  };
  _proto.render = function render() {
    var error = this.state.error;
    var _this$props4 = this.props, fallbackRender = _this$props4.fallbackRender, FallbackComponent = _this$props4.FallbackComponent, fallback = _this$props4.fallback;
    if (error !== null) {
      var _props = {
        error,
        resetErrorBoundary: this.resetErrorBoundary
      };
      if (/* @__PURE__ */ React2.isValidElement(fallback)) {
        return fallback;
      } else if (typeof fallbackRender === "function") {
        return fallbackRender(_props);
      } else if (FallbackComponent) {
        return /* @__PURE__ */ React2.createElement(FallbackComponent, _props);
      } else {
        throw new Error("react-error-boundary requires either a fallback, fallbackRender, or FallbackComponent prop");
      }
    }
    return this.props.children;
  };
  return ErrorBoundary2;
}(React2.Component);

// ../toolpad-core/dist/runtime.js
var ResetNodeErrorsKeyContext = React3.createContext(0);
var ResetNodeErrorsKeyProvider = ResetNodeErrorsKeyContext.Provider;
var NodeRuntimeContext = React3.createContext(null);
function SlotsWrapper({ children }) {
  return React3.createElement(React3.Fragment, null, children);
}
function PlaceholderWrapper(props) {
  return React3.createElement("div", { style: {
    display: "block",
    minHeight: 40,
    minWidth: 200
  } });
}
function NodeError({ error }) {
  return React3.createElement(Tooltip, { title: error.message }, React3.createElement("span", { style: {
    display: "inline-flex",
    flexDirection: "row",
    alignItems: "center",
    padding: 8,
    background: "red",
    color: "white"
  } }, React3.createElement(ErrorIcon, { color: "inherit", style: { marginRight: 8 } }), " Error"));
}
function NodeFiberHost({ children }) {
  return children;
}
function NodeRuntimeWrapper({ nodeId, componentConfig, children }) {
  const resetNodeErrorsKey = React3.useContext(ResetNodeErrorsKeyContext);
  return React3.createElement(ErrorBoundary, { resetKeys: [resetNodeErrorsKey], fallbackRender: ({ error }) => React3.createElement(NodeFiberHost, __spreadValues({}, {
    [RUNTIME_PROP_NODE_ID]: nodeId,
    nodeError: error,
    componentConfig
  }), React3.createElement(NodeError, { error })) }, React3.createElement(NodeRuntimeContext.Provider, { value: nodeId }, React3.createElement(NodeFiberHost, __spreadValues({}, {
    [RUNTIME_PROP_NODE_ID]: nodeId,
    componentConfig
  }), children)));
}
function fireEvent(event) {
  if (!window.__TOOLPAD_RUNTIME_EVENT__) {
    window.__TOOLPAD_RUNTIME_EVENT__ = [];
  }
  if (typeof window.__TOOLPAD_RUNTIME_EVENT__ === "function") {
    window.__TOOLPAD_RUNTIME_EVENT__(event);
  } else {
    window.__TOOLPAD_RUNTIME_EVENT__.push(event);
  }
}
function setEventHandler(window2, handleEvent) {
  if (typeof window2.__TOOLPAD_RUNTIME_EVENT__ === "function") {
    throw new Error(`Event handler already attached.`);
  }
  const queuedEvents = Array.isArray(window2.__TOOLPAD_RUNTIME_EVENT__) ? window2.__TOOLPAD_RUNTIME_EVENT__ : [];
  queuedEvents.forEach((event) => handleEvent(event));
  window2.__TOOLPAD_RUNTIME_EVENT__ = (event) => handleEvent(event);
  return () => {
    delete window2.__TOOLPAD_RUNTIME_EVENT__;
  };
}
function useNode() {
  const nodeId = React3.useContext(NodeRuntimeContext);
  return React3.useMemo(() => {
    if (!nodeId) {
      return null;
    }
    return {
      updateAppDomConstProp: (prop, value) => {
        fireEvent({
          type: "propUpdated",
          nodeId,
          prop,
          value
        });
      }
    };
  }, [nodeId]);
}
function Placeholder({ prop, children }) {
  const nodeId = React3.useContext(NodeRuntimeContext);
  if (!nodeId) {
    return React3.createElement(React3.Fragment, null, children);
  }
  const count = React3.Children.count(children);
  return count > 0 ? React3.createElement(React3.Fragment, null, children) : React3.createElement(PlaceholderWrapper, __spreadValues({ parentId: nodeId }, {
    [RUNTIME_PROP_SLOTS]: prop,
    slotType: "single"
  }));
}
function Slots({ prop, children }) {
  const nodeId = React3.useContext(NodeRuntimeContext);
  if (!nodeId) {
    return React3.createElement(React3.Fragment, null, children);
  }
  const count = React3.Children.count(children);
  return count > 0 ? React3.createElement(SlotsWrapper, __spreadValues({ parentId: nodeId }, {
    [RUNTIME_PROP_SLOTS]: prop,
    slotType: "multiple"
  }), children) : React3.createElement(Placeholder, { prop });
}
var iframe;
function evalCode(code, globalScope) {
  if (!iframe) {
    iframe = document.createElement("iframe");
    iframe.setAttribute("sandbox", "allow-same-origin allow-scripts");
    iframe.style.display = "none";
    document.documentElement.appendChild(iframe);
  }
  iframe.contentWindow.__SCOPE = globalScope;
  return iframe.contentWindow.eval(`with (window.__SCOPE) { ${code} }`);
}
function evaluateBindable(bindable, globalScope, argType) {
  const execExpression = () => {
    if ((bindable == null ? void 0 : bindable.type) === "jsExpression") {
      return evalCode(bindable == null ? void 0 : bindable.value, globalScope);
    }
    if ((bindable == null ? void 0 : bindable.type) === "const") {
      return bindable == null ? void 0 : bindable.value;
    }
    return void 0;
  };
  try {
    const value = execExpression();
    return { value };
  } catch (err) {
    return { error: err };
  }
}

export {
  RUNTIME_PROP_NODE_ID,
  RUNTIME_PROP_SLOTS,
  TOOLPAD_COMPONENT,
  ErrorBoundary,
  JsRuntimeProvider,
  useJsRuntime,
  ResetNodeErrorsKeyProvider,
  NodeRuntimeContext,
  NodeRuntimeWrapper,
  fireEvent,
  setEventHandler,
  useNode,
  Placeholder,
  Slots,
  evaluateBindable
};
