import { useUserProfile } from './chunk-W2SFTXMT.js';
import { useAuthContext } from './chunk-BRJ3QZ4E.js';
import { useMemo, useCallback } from 'react';

function createUseAppInitialization(useOrgInitialization) {
  return function useAppInitialization() {
    const { user, isLoading: authLoading } = useAuthContext();
    const { profile, loading: profileLoading, error: profileError, refetch } = useUserProfile();
    const {
      isInitializing: orgInitializing,
      isLoading: orgLoading,
      error: orgErrorMsg,
      currentOrganization,
      memberships,
      retry: orgRetry
    } = useOrgInitialization();
    const isInitializing = authLoading || profileLoading || orgInitializing || orgLoading;
    const userReady = !authLoading && !profileLoading && !!user && !!profile && !profileError;
    const organizationReady = userReady && !orgInitializing && !orgLoading && !!currentOrganization && !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 && !currentOrganization && 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, currentOrganization, memberships]);
    const retry = useCallback(() => {
      if (profileError && refetch) {
        refetch();
      }
      if (orgErrorMsg && orgRetry) {
        orgRetry();
      }
    }, [profileError, refetch, orgErrorMsg, orgRetry]);
    return { userReady, organizationReady, allReady, isInitializing, error, retry, profile };
  };
}

export { createUseAppInitialization };
