import React from "react";
import { DevContext } from "./../../ricos-context/index.js";
import { logInvariant } from "./../log-invariant.js";
import { createContext, useContext } from "./../use-context-selector.js";
import { parseInstance } from "./parse-instance.js";
import { useRequestService } from "./request-service-provider.js";
const WixInstanceContext = createContext({});
const WixInstanceContextProvider = ({ children, instance }) => {
  const { getWixClientPromise } = useRequestService();
  const [state, setState] = React.useState(() => ({
    ...instance ? parseInstance(instance) : {},
    getWixClientPromise
  }));
  const devContext = React.useContext(DevContext);
  React.useEffect(() => {
    if (devContext.decodedInstance) {
      setState((prev) => ({
        ...prev,
        ...devContext.decodedInstance
      }));
      return;
    }
    const decode = async () => {
      try {
        if (instance) {
          return;
        }
        const wixClient = await getWixClientPromise();
        const { headers } = await wixClient.auth.getAuthHeaders();
        const authorizationHeader = headers.Authorization;
        setState((prev) => ({
          ...prev,
          ...authorizationHeader ? parseInstance(authorizationHeader) : {}
        }));
      } catch (error) {
        logInvariant(new Error(`Failed to decode instance: ${error}`));
        setState((prev) => ({ ...prev, getWixClientPromise }));
      }
    };
    decode();
  }, [instance, getWixClientPromise, devContext.decodedInstance]);
  return /* @__PURE__ */ React.createElement(WixInstanceContext.Provider, { value: state }, children);
};
const useWixInstanceService = () => {
  const context = useContext(WixInstanceContext);
  if (!context) {
    throw new Error("useWixInstanceService must be used within a WixInstanceContextProvider");
  }
  const serviceRef = React.useRef(context);
  serviceRef.current = context;
  return React.useCallback(() => serviceRef.current, []);
};
export {
  WixInstanceContext,
  WixInstanceContextProvider,
  useWixInstanceService
};
//# sourceMappingURL=wix-instance-context.js.map
