import { ElevasisServiceContext } from './chunk-2FTX4WO2.js';
import { useAuthContext } from './chunk-BRJ3QZ4E.js';
import { createContext, useContext, useState, useEffect, createElement } from 'react';

// src/profile/services/UserProfileService.ts
var UserProfileService = class {
  constructor(apiRequest) {
    this.apiRequest = apiRequest;
  }
  /**
   * Sync WorkOS user data to Supabase users table
   * This creates or updates the user profile with latest WorkOS data
   */
  async syncUserProfile() {
    try {
      const profile = await this.apiRequest("/users/me/sync", {
        method: "POST"
      });
      return profile;
    } catch (error) {
      console.error("User profile sync error:", error);
      return null;
    }
  }
  /**
   * Get user profile from API
   * Server identifies user from JWT (no user ID needed)
   */
  async getUserProfile() {
    try {
      const profile = await this.apiRequest("/users/me");
      return profile;
    } catch (error) {
      console.error("Get user profile error:", error);
      return null;
    }
  }
  /**
   * Update last visited organization for the user
   * @param organizationId - The Supabase organization ID
   */
  async updateLastVisitedOrg(organizationId) {
    try {
      await this.apiRequest("/users/me", {
        method: "PATCH",
        body: JSON.stringify({ lastVisitedOrg: organizationId })
      });
    } catch (error) {
      console.error("Update last visited org error:", error);
    }
  }
  /**
   * Update user profile data
   */
  async updateUserProfile(updates) {
    try {
      const profile = await this.apiRequest("/users/me", {
        method: "PATCH",
        body: JSON.stringify(updates)
      });
      return profile;
    } catch (error) {
      console.error("Update user profile error:", error);
      return null;
    }
  }
};
var useUserProfile = (options) => {
  const { user, isLoading: authLoading } = useAuthContext();
  const serviceCtx = useContext(ElevasisServiceContext);
  const apiRequest = options?.apiRequest ?? serviceCtx?.apiRequest;
  if (!apiRequest) {
    throw new Error(
      "useUserProfile: no apiRequest available. Either pass it via options or use within ElevasisServiceProvider."
    );
  }
  const [profile, setProfile] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const syncAndFetchProfile = async () => {
    if (!user || authLoading) {
      return;
    }
    try {
      setLoading(true);
      setError(null);
      const profileService = new UserProfileService(apiRequest);
      const syncedProfile = await profileService.syncUserProfile();
      if (syncedProfile) {
        setProfile(syncedProfile);
      } else {
        console.warn("Failed to sync user profile");
      }
    } catch (err) {
      const error2 = err instanceof Error ? err : new Error("Unknown error occurred");
      if (options?.onError) {
        options.onError(
          {
            phase: "profile-sync",
            userId: user?.id
          },
          error2
        );
      }
      setError(error2);
      console.error("User profile sync failed:", error2);
    } finally {
      setLoading(false);
    }
  };
  useEffect(() => {
    if (!authLoading) {
      if (user) {
        syncAndFetchProfile();
      } else {
        setProfile(null);
        setLoading(false);
        setError(null);
      }
    }
  }, [user, authLoading]);
  const refetch = async () => {
    await syncAndFetchProfile();
  };
  return {
    profile,
    // Treat as loading whenever a user is present but profile hasn't synced yet.
    // Prevents a render window after re-login where `loading` is still false
    // (from a prior logout) while `user` has just become defined and the sync
    // effect has not yet fired. Without this, ProtectedRoute briefly sees
    // !isInitializing && !userReady, marks the user unauthenticated, and
    // bounces back to /auth-redirect in a loop.
    loading: loading || authLoading || !!user && !profile && !error,
    error,
    refetch
  };
};
var ProfileContext = createContext(null);
function useProfile() {
  const ctx = useContext(ProfileContext);
  if (!ctx) {
    throw new Error(
      "useProfile must be used within a ProfileProvider. Wrap your app (or the relevant subtree) with <ProfileProvider>."
    );
  }
  return ctx;
}
function ProfileProvider({ apiRequest, children }) {
  const value = useUserProfile({ apiRequest });
  return createElement(ProfileContext.Provider, { value }, children);
}

export { ProfileProvider, UserProfileService, useProfile, useUserProfile };
