// app/_layout.tsx
import { Redirect, Stack, useRouter, useSegments } from "expo-router";
import { AuthProvider, useAuth } from "@/constants/AuthContext";
import { AnimatedSplashOverlay } from "@/components/animated-icon";
import { Appearance, Button, useColorScheme } from "react-native";
import { useTheme } from "@/hooks/use-theme";
import { useEffect, useState } from "react";
import * as SecureStore from "expo-secure-store";
import LoadingScreen from "./LoadingScreen";

function RootLayoutNav() {
  const { isLogin, isLoading } = useAuth();
  const segments = useSegments();
  const router = useRouter();
  const inAuthGroup = segments[0] === "(auth)";

  useEffect(() => {
    if (isLoading) return;

    if (!isLogin && !inAuthGroup) {
      router.replace("/(auth)/homeLogin");
    } else if (isLogin && inAuthGroup) {
      router.replace("/(tabs)");
    }
  }, [isLogin, isLoading, inAuthGroup]);

  if (isLoading) {
    return <LoadingScreen message="در حال آماده‌سازی..." />;
  }

  const initialRoute = isLogin ? "(tabs)" : "(auth)";

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


export default function RootLayout() {
  const systemColorScheme = useColorScheme();
  const [userSelectedTheme, setUserSelectedTheme] = useState<
    "light" | "dark" | null
  >(null);

  useEffect(() => {
    const loadTheme = async () => {
      try {
        const saved = await SecureStore.getItemAsync("userTheme");
        if (saved === "light" || saved === "dark") {
          setUserSelectedTheme(saved);
          Appearance.setColorScheme(saved);
        } else {
          setUserSelectedTheme(null);
          Appearance.setColorScheme("unspecified");
        }
      } catch (error) {
        console.warn(error);
      }
    };
    loadTheme();
  }, []);

  const toggleTheme = async () => {
    const currentEffective = userSelectedTheme ?? systemColorScheme ?? "light";
    const newTheme = currentEffective === "light" ? "dark" : "light";

    setUserSelectedTheme(newTheme);
    await SecureStore.setItemAsync("userTheme", newTheme);
    Appearance.setColorScheme(newTheme);
  };
  const activeColorScheme = userSelectedTheme ?? systemColorScheme ?? "light";
  return (
    <AuthProvider>
      <RootLayoutNav />
      {/* <Button title="تم" onPress={toggleTheme}/> */}
    </AuthProvider>
  );
}
