import FontAwesome from '@expo/vector-icons/FontAwesome';
import { ThemeProvider } from '@emotion/react';
import { useThemeColors } from '@/app/shared/theme/index';
import { useFonts } from 'expo-font';
import { Stack } from 'expo-router';
import * as SplashScreen from 'expo-splash-screen';
import { useEffect } from 'react';
import 'react-native-reanimated';
import { i18n } from './i18n/i18n';
import { LanguageProvider } from '@/app/shared/providers/LanguageProvider';
import { TimerProvider } from '@/app/store/TimerContext';

export {
  // Catch any errors thrown by the Layout component.
  ErrorBoundary,
} from 'expo-router';

export const unstable_settings = {
  // Ensure that reloading on `/modal` keeps a back button present.
  initialRouteName: '(tabs)',
};

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

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

  // Expo Router uses Error Boundaries to catch errors in the navigation tree.
  useEffect(() => {
    if (error) throw error;
  }, [error]);

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

  if (!loaded) {
    return null;
  }

  return <RootLayoutNav />;
}

function RootLayoutNav() {
  const dynamicTheme = useThemeColors();

  return (
    <LanguageProvider>
      <ThemeProvider theme={dynamicTheme}>
        <TimerProvider>
          <Stack>
            <Stack.Screen name="(tabs)" options={{ headerShown: false }} />
            <Stack.Screen name="Timer" options={{ headerShown: false }} />
            <Stack.Screen name="Settings" options={{ headerShown: true, title: i18n.t('settings.title') }} />
          </Stack>
        </TimerProvider>
      </ThemeProvider>
    </LanguageProvider>
  );
}
