import { useOrganization } from './chunk-DD3CCMCZ.js';
import { useProfile } from './chunk-W2SFTXMT.js';
import { useAuthContext } from './chunk-BRJ3QZ4E.js';
import { createContext, useContext, useMemo, useCallback, createElement } from 'react';

var InitializationContext = createContext(null);
function useInitialization() {
  const ctx = useContext(InitializationContext);
  if (!ctx) {
    throw new Error(
      "useInitialization must be used within an InitializationProvider. Wrap your app (or the relevant subtree) with <InitializationProvider>."
    );
  }
  return ctx;
}
function InitializationProvider({ children }) {
  const { user, isLoading: authLoading } = useAuthContext();
  const { profile, loading: profileLoading, error: profileError, refetch } = useProfile();
  const {
    isInitializing: orgInitializing,
    isOrgRefreshing: orgLoading,
    error: orgErrorMsg,
    currentWorkOSOrganizationId,
    memberships,
    retry: orgRetry
  } = useOrganization();
  const isInitializing = authLoading || profileLoading || orgInitializing || orgLoading;
  const userReady = !authLoading && !profileLoading && !!user && !!profile && !profileError;
  const organizationReady = userReady && !orgInitializing && !orgLoading && !!currentWorkOSOrganizationId && !orgErrorMsg;
  const allReady = organizationReady;
  const error = useMemo(() => {
    if (profileError) {
      return {
        layer: "profile",
        message: "Failed to load user profile",
        originalError: profileError
      };
    }
    if (orgErrorMsg) {
      return {
        layer: "organization",
        message: orgErrorMsg,
        originalError: new Error(orgErrorMsg)
      };
    }
    if (userReady && !orgInitializing && !orgLoading && !currentWorkOSOrganizationId && memberships.length > 0) {
      return {
        layer: "organization",
        message: "No organization membership found. Please contact your administrator for an invitation."
      };
    }
    return null;
  }, [profileError, orgErrorMsg, userReady, orgInitializing, orgLoading, currentWorkOSOrganizationId, memberships]);
  const retry = useCallback(async () => {
    if (profileError && refetch) {
      await refetch();
    }
    await orgRetry();
  }, [profileError, refetch, orgRetry]);
  const value = useMemo(
    () => ({
      userReady,
      organizationReady,
      allReady,
      isInitializing,
      error,
      retry,
      profile
    }),
    [userReady, organizationReady, allReady, isInitializing, error, retry, profile]
  );
  return createElement(InitializationContext.Provider, { value }, children);
}

export { InitializationContext, InitializationProvider, useInitialization };
