import { useEffect } from "react";
import { StatusBar } from "expo-status-bar";
import { QueryClientProvider } from "@tanstack/react-query";
import { GestureHandlerRootView } from "react-native-gesture-handler";
import { NavigationContainer } from "@react-navigation/native";
import {
  initialWindowMetrics,
  SafeAreaProvider,
} from "react-native-safe-area-context";
import { Toaster } from "sonner-native";
import { createQueryClient } from "@/lib/query-client";
import {
  flushPendingNavigation,
  navigationRef,
} from "@/lib/notification-routing";
import { configureNotifications } from "@/lib/push-notifications";
import { PusherProvider } from "@/lib/pusher-provider";
import { RootNavigator } from "@/navigation/RootNavigator";
import { useAuthStore } from "@/stores/auth-store";

const queryClient = createQueryClient();

// One-time setup: foreground handler + tap routing. Idempotent. Note that
// push-token rotation sync is NOT set up here — that's owned by the auth
// store and only runs while a session is active.
configureNotifications();

export default function App() {
  const restoreSession = useAuthStore((s) => s.restoreSession);

  useEffect(() => {
    void restoreSession();
  }, [restoreSession]);

  return (
    <GestureHandlerRootView style={{ flex: 1 }}>
      <QueryClientProvider client={queryClient}>
        <PusherProvider>
          <SafeAreaProvider initialMetrics={initialWindowMetrics}>
            <NavigationContainer
              ref={navigationRef}
              onReady={flushPendingNavigation}
            >
              <RootNavigator />
            </NavigationContainer>
            <Toaster />
            <StatusBar style="light" />
          </SafeAreaProvider>
        </PusherProvider>
      </QueryClientProvider>
    </GestureHandlerRootView>
  );
}
