import { useEffect } from 'react'
import { Slot, useRouter, useSegments } from 'expo-router'
import { SafeAreaProvider } from 'react-native-safe-area-context'
import { StatusBar } from 'expo-status-bar'
import { View, ActivityIndicator, StyleSheet } from 'react-native'
import { useAuthStore } from '@/lib/store'
import { C } from '@/lib/theme'

// Ré-exporter C pour la compatibilité avec les anciens imports
export { C } from '@/lib/theme'

export default function RootLayout() {
  const { user, loading, restore } = useAuthStore()
  const router = useRouter()
  const segments = useSegments()

  useEffect(() => { restore() }, [])

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

  if (loading) {
    return (
      <View style={s.loader}>
        <ActivityIndicator size="large" color={C.brand} />
      </View>
    )
  }

  return (
    <SafeAreaProvider>
      <StatusBar style="auto" />
      <Slot />
    </SafeAreaProvider>
  )
}

const s = StyleSheet.create({
  loader: { flex: 1, alignItems: 'center', justifyContent: 'center', backgroundColor: C.paper },
})
