import { useEffect, useState } from 'react';
import { Stack } from 'expo-router';
import * as SplashScreen from 'expo-splash-screen';
import { getDBConnection } from '@/database/sqlite';
import '@/global.css';

// Keep splash screen visible while loading resources
SplashScreen.preventAutoHideAsync();

export default function RootLayout() {
  const [dbInitialized, setDbInitialized] = useState(false);

  useEffect(() => {
    async function prepare() {
      try {
        // Initialize SQLite DB schema
        await getDBConnection();
        setDbInitialized(true);
      } catch (e) {
        console.warn('Lỗi khởi tạo cơ sở dữ liệu SQLite:', e);
      } finally {
        // Hide splash screen
        await SplashScreen.hideAsync();
      }
    }

    prepare();
  }, []);

  if (!dbInitialized) {
    return null;
  }

  return (
    <Stack screenOptions={{ headerShown: false }}>
      <Stack.Screen name="(tabs)" />
      <Stack.Screen name="replay/[id]" options={{ presentation: 'card' }} />
    </Stack>
  );
}
