'use client' import { useEffect, useRef } from 'react' import { createLogger } from '@sim/logger' import { useRouter } from 'next/navigation' import { requestJson } from '@/lib/api/client/request' import { getWorkflowStateContract } from '@/lib/api/contracts/workflows' import { createWorkspaceContract } from '@/lib/api/contracts/workspaces' import { useSession } from '@/lib/auth/auth-client' import { WorkspaceRecencyStorage } from '@/lib/core/utils/browser-storage' import { useWorkspacesWithMetadata, type WorkspaceCreationPolicy } from '@/hooks/queries/workspace' const logger = createLogger('WorkspacePage') export default function WorkspacePage() { const router = useRouter() const { data: session, isPending: isSessionPending } = useSession() const isAuthenticated = !isSessionPending && !!session?.user const hasRedirectedRef = useRef(false) const { data, isLoading: isWorkspacesLoading } = useWorkspacesWithMetadata(isAuthenticated) useEffect(() => { if (isSessionPending || hasRedirectedRef.current) return if (!session?.user) { logger.info('User not authenticated, redirecting to login') router.replace('/login') return } if (isWorkspacesLoading || !data) return hasRedirectedRef.current = true const urlParams = new URLSearchParams(window.location.search) const redirectWorkflowId = urlParams.get('redirect_workflow') const { workspaces, lastActiveWorkspaceId, creationPolicy } = data if (workspaces.length === 0) { handleNoWorkspaces(router, creationPolicy) return } const localRecentId = WorkspaceRecencyStorage.getMostRecent() const findWorkspace = (id: string | null) => id ? workspaces.find((w) => w.id === id) : undefined const targetWorkspace = findWorkspace(localRecentId) ?? findWorkspace(lastActiveWorkspaceId) ?? workspaces[0] if (redirectWorkflowId) { handleWorkflowRedirect(redirectWorkflowId, targetWorkspace.id, router) return } logger.info(`Redirecting to workspace: ${targetWorkspace.id}`) router.replace(`/workspace/${targetWorkspace.id}/home`) }, [session, isSessionPending, isWorkspacesLoading, data, router]) if (isSessionPending || isWorkspacesLoading) { return (