import { useState, useCallback, useEffect } from 'react'; import api from '../utils/api'; import { useAuth } from './useAuth'; export interface User { id: string; email: string; full_name: string; role: string; team?: string; is_active: boolean; avatar_url?: string; } // Global singleton for user list with hydration const USERS_CACHE_KEY = 'nexus_users_v1'; let globalUsers: User[] = (() => { try { const cached = sessionStorage.getItem(USERS_CACHE_KEY); return cached ? JSON.parse(cached) : []; } catch { return []; } })(); let globalUsersLoading = false; let globalUsersError: string | null = null; let globalUsersLoaded = globalUsers.length > 0; const usersListeners = new Set<(u: User[], l: boolean, e: string | null, d: boolean) => void>(); const notifyUsers = () => usersListeners.forEach(l => l(globalUsers, globalUsersLoading, globalUsersError, globalUsersLoaded)); export const useUsers = (workspaceId?: string) => { const [localUsers, setLocalUsers] = useState(globalUsers); const [loading, setLoading] = useState(globalUsersLoading); const [error, setError] = useState(globalUsersError); const [loaded, setLoaded] = useState(globalUsersLoaded); useEffect(() => { const listener = (u: User[], l: boolean, e: string | null, d: boolean) => { setLocalUsers(u); setLoading(l); setError(e); setLoaded(d); }; usersListeners.add(listener); return () => { usersListeners.delete(listener); }; }, []); const fetchUsers = useCallback(async (force: boolean = false) => { if (!force && globalUsers.length > 0) return; globalUsersLoading = true; notifyUsers(); try { const url = workspaceId ? `users/?workspace_id=${workspaceId}` : 'users/'; const response = await api.get(url); globalUsers = response.data; sessionStorage.setItem(USERS_CACHE_KEY, JSON.stringify(globalUsers)); globalUsersError = null; globalUsersLoaded = true; } catch (err: any) { globalUsersError = err.response?.data?.detail || 'Failed to fetch users'; } finally { globalUsersLoading = false; notifyUsers(); } }, [workspaceId]); const addUser = async (payload: any) => { try { const response = await api.post('users/', payload); await fetchUsers(true); return response.data; } catch (err: any) { const detail = err.response?.data?.detail; const msg = Array.isArray(detail) ? detail.map((d: any) => d.msg).join(', ') : detail; throw new Error(msg || 'Failed to add user'); } }; const { token } = useAuth(); useEffect(() => { if (token && !globalUsersLoaded && !globalUsersLoading) { fetchUsers(); } }, [fetchUsers, token]); return { users: localUsers, loading, error, loaded, refresh: () => fetchUsers(true), addUser }; };