// src/navigation/RootNavigator.tsx
import React from 'react';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import { Platform } from 'react-native';

import { useAuth, AuthLoadingScreen } from '../contexts/AuthContext';
import AuthNavigator from './AuthNavigator'; // Unauthenticated flow
import AppNavigator from './AppNavigator'; // Import the new App stack navigator
import WebAppLayout from './WebAppLayout'; // Authenticated Web flow

import { RootStackParamList } from '../types/navigation';

const Stack = createNativeStackNavigator<RootStackParamList>();

const RootNavigator = () => {
  const { isAuthenticated, isLoading } = useAuth();

  // Show loading screen while checking auth state
  if (isLoading) {
    return <AuthLoadingScreen />;
  }

  return (
    <Stack.Navigator screenOptions={{ headerShown: false }}>
      {isAuthenticated ? (
        // User is logged in: Choose main app layout based on platform
        <Stack.Screen name="AppFlow">
           {/* Use AppNavigator for mobile, WebAppLayout for web */}
           {() => Platform.OS === 'web' ? <WebAppLayout /> : <AppNavigator />}
        </Stack.Screen>
      ) : (
        // User is not logged in: Show authentication flow
        <Stack.Screen name="AuthFlow" component={AuthNavigator} />
      )}
    </Stack.Navigator>
  );
};

export default RootNavigator;