import { jsx, jsxs } from "react/jsx-runtime";
import { useState, useEffect } from "react";
import Center from "@arcblock/ux/lib/Center";
import { CircularProgress } from "@mui/material";
export function createLazyComponent(loader, options = {}) {
  let loadPromise = null;
  const {
    LoadingComponent = () => /* @__PURE__ */ jsx(Center, { children: /* @__PURE__ */ jsx(CircularProgress, {}) }),
    ErrorComponent = ({ error }) => /* @__PURE__ */ jsxs("div", { children: [
      "Error: ",
      error.message
    ] })
  } = options;
  const loadComponent = async () => {
    if (loadPromise) return loadPromise;
    try {
      loadPromise = loader().then((result) => "default" in result ? result.default : result);
      return await loadPromise;
    } catch (error) {
      loadPromise = null;
      throw error;
    }
  };
  return function WrappedComponent(props) {
    const [Component, setComponent] = useState(null);
    const [error, setError] = useState(null);
    useEffect(() => {
      loadComponent().then((comp) => {
        setComponent(() => comp);
      }).catch((err) => {
        setError(err);
        console.error("Failed to load component:", err);
      });
    }, []);
    if (error) {
      return /* @__PURE__ */ jsx(ErrorComponent, { error });
    }
    if (!Component) {
      return /* @__PURE__ */ jsx(LoadingComponent, {});
    }
    return /* @__PURE__ */ jsx(Component, { ...props });
  };
}
