import { useEffect, useState } from 'react'; import { Stack } from 'expo-router'; import { useAuthStore } from '@/store/auth'; import { useWebSocket } from '@/hooks/useWebSocket'; import { authClient } from '@/lib/auth-client'; import { getBackendUrl } from '@/lib/api'; /** * Root layout with auth guard * Routes to backend-setup if not configured, then to auth stack or app stack */ export default function RootLayout() { const { user, setUser, setIsLoading } = useAuthStore(); const [backendConfigured, setBackendConfigured] = useState(false); const [checked, setChecked] = useState(false); // Initialize WebSocket connection when authenticated useWebSocket(); useEffect(() => { // Check if user is already authenticated async function checkAuth() { try { setIsLoading(true); const response = await authClient.getSession(); const sessionData = (response as any)?.data; if (sessionData && (sessionData.user || sessionData.data?.user)) { const user = sessionData.user || sessionData.data?.user; setUser(user); } } catch (error) { console.error('Auth check failed:', error); } finally { setIsLoading(false); } } // Check if backend URL is configured async function checkBackend() { const url = await getBackendUrl(); setBackendConfigured(!!url); setChecked(true); } checkBackend(); checkAuth(); }, [setUser, setIsLoading]); if (!checked) { return null; // Or a loading screen } return ( {!backendConfigured ? ( // Backend not configured - show setup first ) : user ? ( // User is authenticated - show app stack ) : ( // User is not authenticated - show auth stack )} ); }