// app/_layout.tsx
import { Stack } from 'expo-router';
import { GestureHandlerRootView } from 'react-native-gesture-handler';
import { useEffect, useState } from 'react';
import { View, ActivityIndicator } from 'react-native';
import { useUserStore } from '@/store/useUserStore';
import { getDatabase } from '@/lib/database';
import '../global.css';

export default function RootLayout() {
  const [loading, setLoading] = useState(true);
  const setUser = useUserStore((s) => s.setUser);

  useEffect(() => {
    async function bootstrap() {
      try {
        const db = await getDatabase();
        const user = await db.getFirstAsync<{ id: string; display_name: string; share_id: string }>(
          'SELECT id, display_name, share_id FROM users WHERE is_self = 1 LIMIT 1'
        );
        if (user) {
          setUser({ id: user.id, displayName: user.display_name, shareId: user.share_id });
        }
      } catch (e) {
        console.error('Bootstrap error:', e);
      } finally {
        setLoading(false);
      }
    }
    bootstrap();
  }, []);

  if (loading) {
    return (
      <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F8F4EF' }}>
        <ActivityIndicator size="large" color="#1A6B72" />
      </View>
    );
  }

  return (
    <GestureHandlerRootView style={{ flex: 1 }}>
      <Stack screenOptions={{ headerShown: false }}>
        <Stack.Screen name="onboarding" />
        <Stack.Screen name="(tabs)" />
      </Stack>
    </GestureHandlerRootView>
  );
}
