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'

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>
  )
}

export const C = {
  brand: '#A47148',
  ink: '#1A1A18',
  paper: '#FAFAF8',
  concrete: '#8A8A82',
  border: '#E8E6E0',
  white: '#FFFFFF',
  rose: '#e11d48',
  roseBg: '#fff1f2',
  roseBorder: '#fecdd3',
}

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