import "../global.css";
import { GestureHandlerRootView } from "react-native-gesture-handler";
import { SafeAreaProvider, initialWindowMetrics } from "react-native-safe-area-context";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { Stack } from "expo-router";
import { useEffect } from "react";
import { ThemeProvider } from "@/lib/theme-provider";
import { StoreProvider } from "@/lib/store";
import { initManusRuntime } from "@/lib/_core/manus-runtime";

const queryClient = new QueryClient();

const providerInitialMetrics =
  initialWindowMetrics
    ? {
        ...initialWindowMetrics,
        insets: {
          ...initialWindowMetrics.insets,
          top: Math.max(initialWindowMetrics.insets.top, 0),
          bottom: Math.max(initialWindowMetrics.insets.bottom, 0),
        },
      }
    : undefined;

export default function RootLayout() {
  useEffect(() => {
    initManusRuntime();
  }, []);

  return (
    <GestureHandlerRootView style={{ flex: 1 }}>
      <QueryClientProvider client={queryClient}>
        <SafeAreaProvider initialMetrics={providerInitialMetrics}>
          <ThemeProvider>
            <StoreProvider>
              <Stack screenOptions={{ headerShown: false }}>
                <Stack.Screen name="index" />
                <Stack.Screen name="(tabs)" />
                <Stack.Screen name="entry/[category]" options={{ presentation: "card" }} />
                <Stack.Screen name="oauth/callback" />
              </Stack>
            </StoreProvider>
          </ThemeProvider>
        </SafeAreaProvider>
      </QueryClientProvider>
    </GestureHandlerRootView>
  );
}
