import { useEffect } from 'react'
import { Stack, useRouter, useSegments } from 'expo-router'
import { StatusBar } from 'expo-status-bar'
import * as SplashScreen from 'expo-splash-screen'
import { AuthContext, useAuthState } from '../hooks/useAuth'

SplashScreen.preventAutoHideAsync()

export default function RootLayout() {
  const auth = useAuthState()
  const router = useRouter()
  const segments = useSegments()

  useEffect(() => {
    if (auth.loading) return
    SplashScreen.hideAsync()
    const inAuth = segments[0] === '(auth)'
    if (!auth.token && !inAuth) {
      router.replace('/(auth)/login')
    } else if (auth.token && inAuth) {
      router.replace('/(tabs)')
    }
  }, [auth.loading, auth.token])

  return (
    <AuthContext.Provider value={auth}>
      <StatusBar style="light" />
      <Stack screenOptions={{ headerShown: false }} />
    </AuthContext.Provider>
  )
}
