import i18next, { getLanguage } from "../services/i18n/index";
import { Stack, useRouter } from "expo-router";
import * as SplashScreen from "expo-splash-screen";
import { useEffect, useState } from "react";
import "react-native-reanimated";
import { I18nextProvider } from "react-i18next";
import { Provider } from "react-redux";
import { store } from "@/store";

export { ErrorBoundary } from "expo-router";

export const unstable_settings = {
  initialRouteName: "(tabs)",
};

SplashScreen.preventAutoHideAsync();

export default function RootLayout() {
  const [appIsReady, setAppIsReady] = useState(false);
  const [shouldRedirect, setShouldRedirect] = useState(false);
  const router = useRouter();

  useEffect(() => {
    const initLang = async () => {
      const lang = await getLanguage();
      if (!lang) {
        setShouldRedirect(true);
      }
      setAppIsReady(true);
    };

    initLang();
  }, []);

  useEffect(() => {
    if (appIsReady) {
      SplashScreen.hideAsync();
      router.replace("/init/language");
    }
  }, [appIsReady]);

  // useEffect(() => {
  //   if (appIsReady && shouldRedirect) {
  //     router.replace("/init/language");
  //     setShouldRedirect(false);
  //   }
  // }, [appIsReady, shouldRedirect]);

  if (!appIsReady) {
    return null;
  }

  return <RootLayoutNav />;
}

function RootLayoutNav() {
  return (
    <Provider store={store}>
      <I18nextProvider i18n={i18next}>
        <Stack
          screenOptions={{
            headerShown: false,
            animation: "fade",
          }}
        >
          <Stack.Screen name="(tabs)" options={{ headerShown: false }} />
        </Stack>
      </I18nextProvider>
    </Provider>
  );
}
