import { DarkTheme, DefaultTheme, ThemeProvider } from '@react-navigation/native';
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 { useColorScheme } from '@/components/useColorScheme';
import { AuthProvider } from '@/context/AuthContext';
import { BindProvider } from '@/context/BindContext';
import { PocketBaseAuthModal } from '@/components/PocketBaseAuthModal';

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

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

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

/** 避免部分真机/构建环境下字体加载挂起或失败时永远停在 Expo 默认靶心启动图 */
const SPLASH_FALLBACK_MS = 4000;

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

  useEffect(() => {
    if (error) {
      console.warn('[expo-font]', error);
    }
  }, [error]);

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

  useEffect(() => {
    const t = setTimeout(() => {
      void SplashScreen.hideAsync();
    }, SPLASH_FALLBACK_MS);
    return () => clearTimeout(t);
  }, []);

  // 不再在字体未就绪时 return null，否则 hideAsync 后会出现纯白屏且仍无界面
  return <RootLayoutNav />;
}

function RootLayoutNav() {
  const colorScheme = useColorScheme();

  return (
    <AuthProvider>
      <BindProvider>
        <ThemeProvider value={colorScheme === 'dark' ? DarkTheme : DefaultTheme}>
          <Stack>
            <Stack.Screen name="(tabs)" options={{ headerShown: false }} />
          </Stack>
          <PocketBaseAuthModal />
        </ThemeProvider>
      </BindProvider>
    </AuthProvider>
  );
}
