import React, { useEffect, useState } from 'react';
import { GestureHandlerRootView } from 'react-native-gesture-handler';
import { NavigationContainer } from '@react-navigation/native';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import { enableScreens } from 'react-native-screens';
import AppStack from './src/Navigators/Stack';
import { loadToken, cachedToken } from './src/api/api';

enableScreens();

const App = () => {
  // null = masih loading, string = initial route sudah ditentukan
  const [initialRoute, setInitialRoute] = useState<string | null>(null);

  useEffect(() => {
    const bootstrap = async () => {
      await loadToken();
      // Kalau token ada di storage → langsung ke Dashboard, tidak perlu login ulang
      setInitialRoute(cachedToken ? 'DashboardNavigation' : 'LoginNavigation');
    };
    bootstrap();
  }, []);

  // Tunggu cek token selesai sebelum render navigator
  if (initialRoute === null) return null;

  return (
    <GestureHandlerRootView style={{ flex: 1 }}>
      <SafeAreaProvider>
        <NavigationContainer>
          <AppStack initialRoute={initialRoute} />
        </NavigationContainer>
      </SafeAreaProvider>
    </GestureHandlerRootView>
  );
};

export default App;