import React, { useRef, useEffect } from 'react';
import {
  NavigationContainer,
  DefaultTheme,
  DarkTheme,
  NavigationContainerRef,
} from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import { useColorScheme } from 'react-native';
import { RootStackParamList } from '@navigation/navigationTypes';
import AuthStack from './authStack';
import AppStack from './appStack';
import onBoardingStack from './onBoardingStack';
import { useAppSelector } from '@store';
import { socketService } from '@services';

const Stack = createNativeStackNavigator<RootStackParamList>();

const RootNavigator: React.FC = () => {
  const scheme = useColorScheme();
  const theme = scheme === 'dark' ? DarkTheme : DefaultTheme;

  const accessToken = useAppSelector(state => state.auth.accessToken);
  const isOnboarding = useAppSelector(
    state => state.auth.user?.status === 'ONBOARDING',
  );

  const navigationRef = useRef<NavigationContainerRef<RootStackParamList>>(null);

  // Inject the navigation ref into the socket service so it can navigate
  // to NewJobRequest from anywhere when a delivery_offer event arrives.
  useEffect(() => {
    if (navigationRef.current) {
      socketService.bootstrap(
        // store is already injected in App.tsx — pass null so it's not overwritten
        null as any,
        navigationRef.current,
      );
    }
  }, []);

  return (
    <NavigationContainer ref={navigationRef} theme={theme}>
      <Stack.Navigator screenOptions={{ headerShown: false }}>
        {!accessToken ? (
          <Stack.Screen name="Auth" component={AuthStack} />
        ) : isOnboarding ? (
          <Stack.Screen name="OnBoarding" component={onBoardingStack} />
        ) : (
          <Stack.Screen name="App" component={AppStack} />
        )}
      </Stack.Navigator>
    </NavigationContainer>
  );
};

export default RootNavigator;
