import React from 'react';
import { NavigationContainer, NavigatorScreenParams } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import { AuthStack } from './authStack';
import { DrawerStack, DrawerStackParamList } from './drawerStack';
import { useAppSelector } from '../store/store';
import { RootState } from '../store/rootReducer';
import { navigationRef, flushPendingNavigation } from '@utils';

export type RootStackParamList = {
  AuthStack: undefined;
  DrawerStack: NavigatorScreenParams<DrawerStackParamList> | undefined;
};

// Augment the global ReactNavigation type so navigationRef.current.navigate()
// is fully typed everywhere in the app (React Navigation v6 pattern).
declare global {
  namespace ReactNavigation {
    interface RootParamList extends RootStackParamList {}
  }
}

const RootStack = createNativeStackNavigator<RootStackParamList>();

export const RootNavigator = () => {
  const { token } = useAppSelector((state: RootState) => state.auth);
  const initialRouteName = token ? 'DrawerStack' : 'AuthStack';

  return (
    <NavigationContainer ref={navigationRef} onReady={flushPendingNavigation}>
      <RootStack.Navigator
        screenOptions={{ headerShown: false }}
        initialRouteName={initialRouteName}
      >
        <RootStack.Screen name="AuthStack" component={AuthStack} />
        <RootStack.Screen name="DrawerStack" component={DrawerStack} />
      </RootStack.Navigator>
    </NavigationContainer>
  );
};
