import { Redirect, Stack } from 'expo-router';
import { ActivityIndicator, StyleSheet, View } from 'react-native';

import { useAuth } from '../../lib/authContext';
import { colors } from '../../theme/colors';

export default function AppLayout() {
  const { ready, session, userKeyState } = useAuth();

  if (!ready) {
    return (
      <View style={styles.center}>
        <ActivityIndicator color={colors.accent} />
      </View>
    );
  }
  if (!session) return <Redirect href="/" />;
  if (userKeyState.status === 'loading') {
    return (
      <View style={styles.center}>
        <ActivityIndicator color={colors.accent} />
      </View>
    );
  }
  if (userKeyState.status === 'needs-setup') return <Redirect href="/(app)/setup" />;
  if (userKeyState.status === 'needs-unlock') return <Redirect href="/(app)/unlock" />;

  return (
    <Stack screenOptions={{ headerStyle: { backgroundColor: colors.bg } }}>
      <Stack.Screen name="chats" />
      <Stack.Screen name="conversations/[id]" />
      <Stack.Screen name="call" options={{ presentation: 'fullScreenModal' }} />
      <Stack.Screen name="settings" options={{ presentation: 'card' }} />
      <Stack.Screen name="setup" options={{ headerShown: false }} />
      <Stack.Screen name="unlock" options={{ headerShown: false }} />
    </Stack>
  );
}

const styles = StyleSheet.create({
  center: { flex: 1, alignItems: 'center', justifyContent: 'center', backgroundColor: colors.bg },
});
