import AuthProvider from '@/providers/AuthProvider';
import ThemeProvider, { useTheme } from '@/providers/ThemeProvider';
import QueryProvider from '@/providers/QueryProvider';
import ErrorBoundary from '@/components/ErrorBoundary';
import { flushErrorQueue } from '@/lib/errorLogger';
import { useFonts } from 'expo-font';
import { Stack } from 'expo-router';
import * as SplashScreen from 'expo-splash-screen';
import { StatusBar } from 'expo-status-bar';
import { useEffect } from 'react';
import { AppState } from 'react-native';
import { GestureHandlerRootView } from 'react-native-gesture-handler';
import { NotifierWrapper } from 'react-native-notifier';
import 'react-native-reanimated';
import Styles from '@/constants/Styles';

// Prevent the splash screen from auto-hiding before asset loading is complete.
SplashScreen.preventAutoHideAsync();

// Inner component - berada di dalam ThemeProvider, bisa pakai useTheme()
function AppStack() {
  const { colors } = useTheme();

  return (
    <>
      <Stack screenOptions={{ contentStyle: { backgroundColor: colors.header } }}>
        <Stack.Screen name="index" options={{ headerShown: false }} />
        <Stack.Screen name="(application)" options={{ headerShown: false }} />
      </Stack>
      <StatusBar style="auto" />
    </>
  );
}

export default function RootLayout() {
  const [loaded] = useFonts({
    SpaceMono: require('../assets/fonts/SpaceMono-Regular.ttf'),
  });

  useEffect(() => {
    if (loaded) {
      SplashScreen.hideAsync();
      flushErrorQueue();
    }
  }, [loaded]);

  useEffect(() => {
    const sub = AppState.addEventListener('change', (state) => {
      if (state === 'active') flushErrorQueue();
    });
    return () => sub.remove();
  }, []);

  if (!loaded) {
    return null;
  }

  return (
    <GestureHandlerRootView style={Styles.flex1}>
      <ErrorBoundary>
        <NotifierWrapper>
          <ThemeProvider>
            <QueryProvider>
              <AuthProvider>
                <AppStack />
              </AuthProvider>
            </QueryProvider>
          </ThemeProvider>
        </NotifierWrapper>
      </ErrorBoundary>
    </GestureHandlerRootView>
  );
}
