import { BirthdaysProvider } from "@/context/birthdays-context";
import { useAuth } from "@/context/auth-context";
import { Stack, router, useRootNavigationState, useSegments } from "expo-router";
import React, { useEffect } from "react";
import LoadingScreen from "./loading-screen";

export default function RootLayout() {
  const { user, isHydrated } = useAuth();
  const navigationState = useRootNavigationState();
  const segments = useSegments();
  const [loaded, setLoaded] = React.useState(false);

  useEffect(() => {
  if (!isHydrated || !navigationState?.key) return;

  const inAuthGroup = segments.length === 0;

  if (!user) {
    router.replace("/(auth)/login");
  } else if (inAuthGroup) {
    router.replace("/(tabs)");
  }

  setLoaded(true); // 👈 ALWAYS run this
}, [isHydrated, navigationState?.key, segments, user]);

  if(!loaded) {
    return (<LoadingScreen />); // or a loading spinner
  }

  return (
    <BirthdaysProvider>
      <Stack screenOptions={{ headerShown: false }} />
    </BirthdaysProvider>
  );
}
