import { Redirect, Stack } from "expo-router";

import CallWatcher from "@/components/call-watcher";
import { useSession } from "@/lib/session";

const RootLayout = () => {
  const { isLoaded, isSignedIn } = useSession();

  // Everything under (root) is behind the session, so the check belongs here
  // rather than in each screen. app/index.tsx only guards the way in, which
  // left a session that ended *while* a screen was open with nowhere to go:
  // the screen stayed mounted and kept polling with a token the server had
  // already rejected.
  //
  // Sign-in, not welcome: someone who reaches this point had an account a
  // moment ago, and the onboarding carousel is not what they need.
  if (!isLoaded) return null;
  if (!isSignedIn) return <Redirect href="/(auth)/sign-in" />;

  return (
    <>
      {/* Watches for incoming WebRTC calls on the active ride and routes the
          user to the call screen regardless of which tab is open. No UI. */}
      <CallWatcher />
      <Stack>
        <Stack.Screen name="(tabs)" options={{ headerShown: false }} />
        <Stack.Screen name="find-ride" options={{ headerShown: false }} />
        <Stack.Screen name="adjust-pin" options={{ headerShown: false }} />
        <Stack.Screen name="book-ride" options={{ headerShown: false }} />
        <Stack.Screen name="role" options={{ headerShown: false }} />
        <Stack.Screen
          name="driver-home"
          options={{ headerShown: false, gestureEnabled: false }}
        />
        <Stack.Screen name="driver-chat" options={{ headerShown: false }} />
        <Stack.Screen
          name="call"
          options={{
            headerShown: false,
            presentation: "fullScreenModal",
            gestureEnabled: false,
          }}
        />
      </Stack>
    </>
  );
};

export default RootLayout;
