import { useState, useCallback, useEffect } from 'react'; import api from '../utils/api'; import { useAuth } from './useAuth'; export interface Workspace { id: string; name: string; slug: string; branding?: any; } // --- SINGULAR: Current Workspace Cache --- const WS_CACHE_KEY = 'nexus_active_ws_v1'; let globalActiveWorkspace: Workspace | null = (() => { try { const cached = sessionStorage.getItem(WS_CACHE_KEY); return cached ? JSON.parse(cached) : null; } catch { return null; } })(); let globalActiveWorkspaceLoading = false; const activeWorkspaceListeners = new Set<(w: Workspace | null, l: boolean) => void>(); const notifyActiveWorkspace = () => activeWorkspaceListeners.forEach(l => l(globalActiveWorkspace, globalActiveWorkspaceLoading)); export const useWorkspace = (workspaceId?: string) => { const [workspace, setWorkspace] = useState(globalActiveWorkspace); const [loading, setLoading] = useState(globalActiveWorkspaceLoading); useEffect(() => { const listener = (w: Workspace | null, l: boolean) => { setWorkspace(w); setLoading(l); }; activeWorkspaceListeners.add(listener); return () => { activeWorkspaceListeners.delete(listener); }; }, []); const fetchWorkspace = useCallback(async (force: boolean = false, targetId?: string) => { // If we have a targetId, we only use the global singleton cache logic if it matches current if (!force && globalActiveWorkspace && !targetId) return; globalActiveWorkspaceLoading = true; notifyActiveWorkspace(); try { const url = targetId ? `workspace/?workspace_id=${targetId}` : 'workspace/'; const response = await api.get(url); // Update global active workspace if: // 1. No specific targetId was requested (default flow) // 2. The targetId matches the currently active singleton // 3. The targetId matches the workspaceId this hook instance is tracking if (!targetId || targetId === globalActiveWorkspace?.id || targetId === workspaceId) { globalActiveWorkspace = response.data; sessionStorage.setItem(WS_CACHE_KEY, JSON.stringify(globalActiveWorkspace)); } notifyActiveWorkspace(); return response.data; } catch (err) { console.error("Failed to fetch current workspace", err); } finally { globalActiveWorkspaceLoading = false; notifyActiveWorkspace(); } }, [workspaceId]); const { token } = useAuth(); useEffect(() => { if (token && !globalActiveWorkspace && !globalActiveWorkspaceLoading) { fetchWorkspace(); } }, [fetchWorkspace, token]); // Sync with targeted workspaceId if provided useEffect(() => { if (token && workspaceId && workspaceId !== workspace?.id) { fetchWorkspace(true, workspaceId); } }, [workspaceId, token, workspace?.id, fetchWorkspace]); return { workspace, loading, refresh: (targetId?: string) => fetchWorkspace(true, targetId || workspaceId) }; }; // --- PLURAL: Workspace Selection Cache --- let globalWorkspaces: Workspace[] = []; let globalWorkspacesLoading = false; let globalWorkspacesError: string | null = null; const workspacesListeners = new Set<(w: Workspace[], l: boolean, e: string | null) => void>(); const notifyWorkspaces = () => workspacesListeners.forEach(l => l(globalWorkspaces, globalWorkspacesLoading, globalWorkspacesError)); export const useWorkspaces = () => { const [localWorkspaces, setLocalWorkspaces] = useState(globalWorkspaces); const [loading, setLoading] = useState(globalWorkspacesLoading); const [error, setError] = useState(globalWorkspacesError); useEffect(() => { const listener = (w: Workspace[], l: boolean, e: string | null) => { setLocalWorkspaces(w); setLoading(l); setError(e); }; workspacesListeners.add(listener); return () => { workspacesListeners.delete(listener); }; }, []); const fetchWorkspaces = useCallback(async (force: boolean = false) => { if (!force && globalWorkspaces.length > 0) return; globalWorkspacesLoading = true; notifyWorkspaces(); try { const response = await api.get('workspace/list/'); globalWorkspaces = response.data; globalWorkspacesError = null; } catch (err: any) { globalWorkspacesError = err.response?.data?.detail || 'Failed to fetch workspaces'; } finally { globalWorkspacesLoading = false; notifyWorkspaces(); } }, []); const { token } = useAuth(); useEffect(() => { if (token && globalWorkspaces.length === 0) { fetchWorkspaces(); } }, [fetchWorkspaces, token]); return { workspaces: localWorkspaces, loading, error, refresh: () => fetchWorkspaces(true) }; };