"use client";
import { jsx } from "react/jsx-runtime";
import * as React from "react";
import { apiCall } from "./utils/apiCall.js";
import { subscribeOrganizationScopeChanged, getCurrentOrganizationScopeVersion } from "@open-mercato/shared/lib/frontend/organizationEvents";
const chromeCache = /* @__PURE__ */ new Map();
const BackendChromeContext = React.createContext(null);
function buildCacheKey(api) {
  return `${api}::scope:${getCurrentOrganizationScopeVersion()}`;
}
function BackendChromeProvider({ adminNavApi, children }) {
  const cachedPayload = React.useMemo(() => {
    if (!adminNavApi) return null;
    return chromeCache.get(buildCacheKey(adminNavApi)) ?? null;
  }, [adminNavApi]);
  const [payload, setPayload] = React.useState(cachedPayload);
  const [isLoading, setIsLoading] = React.useState(Boolean(adminNavApi && !cachedPayload));
  const refresh = React.useCallback(async () => {
    if (!adminNavApi) return;
    setIsLoading(true);
    try {
      const call = await apiCall(adminNavApi, { credentials: "include" });
      if (!call.ok || !call.result) return;
      const nextPayload = call.result;
      chromeCache.set(buildCacheKey(adminNavApi), nextPayload);
      setPayload(nextPayload);
    } finally {
      setIsLoading(false);
    }
  }, [adminNavApi]);
  React.useEffect(() => {
    if (!adminNavApi) {
      setPayload(null);
      setIsLoading(false);
      return;
    }
    const cached = chromeCache.get(buildCacheKey(adminNavApi)) ?? null;
    setPayload(cached);
    if (!cached) {
      void refresh();
    }
  }, [adminNavApi, refresh]);
  React.useEffect(() => {
    if (!adminNavApi) return;
    const onFocus = () => {
      void refresh();
    };
    const onManualRefresh = () => {
      void refresh();
    };
    const unsubscribeScope = subscribeOrganizationScopeChanged(() => {
      void refresh();
    });
    window.addEventListener("focus", onFocus);
    window.addEventListener("om:refresh-sidebar", onManualRefresh);
    return () => {
      unsubscribeScope();
      window.removeEventListener("focus", onFocus);
      window.removeEventListener("om:refresh-sidebar", onManualRefresh);
    };
  }, [adminNavApi, refresh]);
  const value = React.useMemo(() => ({
    payload,
    isLoading,
    isReady: !adminNavApi || payload !== null,
    refresh
  }), [adminNavApi, isLoading, payload, refresh]);
  return /* @__PURE__ */ jsx(BackendChromeContext.Provider, { value, children });
}
function useBackendChrome() {
  return React.useContext(BackendChromeContext) ?? {
    payload: null,
    isLoading: false,
    isReady: true,
    refresh: async () => {
    }
  };
}
export {
  BackendChromeProvider,
  useBackendChrome
};
//# sourceMappingURL=BackendChromeProvider.js.map
