"use client"; import { useEffect } from "react"; import { useQuery } from "@tanstack/react-query"; import { useTenantId } from "@/hooks/useTenantId"; import { workspaceApi } from "@/modules/workspace/services/workspace-api"; const STORAGE_KEY = "workspace.currentHubId"; export function readStoredHubId() { if (typeof window === "undefined") return null; return window.localStorage.getItem(STORAGE_KEY); } export function storeHubId(id: string) { if (typeof window === "undefined") return; window.localStorage.setItem(STORAGE_KEY, id); } export function useCurrentHub() { const { tenantId } = useTenantId(); const hubs = useQuery({ queryKey: ["workspace", tenantId, "hubs"], queryFn: () => workspaceApi.hubs.list(tenantId!), enabled: !!tenantId, }); const stored = readStoredHubId(); const current = hubs.data?.find((hub) => hub.id === stored) ?? hubs.data?.[0] ?? null; useEffect(() => { if (current?.id && current.id !== stored) storeHubId(String(current.id)); }, [current?.id, stored]); return { tenantId, hubs: hubs.data ?? [], hub: current, hubId: current?.id ? String(current.id) : null, loading: hubs.isLoading, error: hubs.error, refetch: hubs.refetch, selectHub: storeHubId, }; }