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

export default function RootLayout() {
  const { user, isHydrated } = useAuth();
  const navigationState = useRootNavigationState();
  const segments = useSegments();

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

    const inAuthGroup = segments[0] === "(auth)";

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

    if (user && inAuthGroup) {
      router.replace("/(tabs)");
    }
  }, [isHydrated, navigationState?.key, segments, user]);

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