import React, { useEffect } from "react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { GestureHandlerRootView } from "react-native-gesture-handler";
import { StatusBar } from "expo-status-bar";
import * as Notifications from "expo-notifications";
import { AuthProvider } from "@/auth/AuthProvider";
import RootNavigator from "@/navigation/RootNavigator";
import { colors } from "@/theme";
import "@/lib/backgroundAlerts"; // side-effect: defines the task
import { registerBackgroundAlerts } from "@/lib/backgroundAlerts";
import { readPushEnabled } from "@/lib/alerts";

// Foreground notification behavior — show banner + play sound even when the
// app is in the foreground, so the user gets visible feedback while a
// screen is open too.
Notifications.setNotificationHandler({
  handleNotification: async () => ({
    shouldShowAlert: true,
    shouldPlaySound: true,
    shouldSetBadge: false,
    shouldShowBanner: true,
    shouldShowList: true,
  }),
});

const queryClient = new QueryClient({
  defaultOptions: { queries: { retry: 1, refetchOnWindowFocus: false, staleTime: 15_000 } },
});

export default function App() {
  useEffect(() => {
    // Re-register the background fetch task on cold start if the user had
    // opted in previously. This is idempotent (isTaskRegisteredAsync).
    readPushEnabled().then((on) => {
      if (on) registerBackgroundAlerts().catch(() => {});
    });
  }, []);

  return (
    <GestureHandlerRootView style={{ flex: 1, backgroundColor: colors.bg }}>
      <QueryClientProvider client={queryClient}>
        <AuthProvider>
          <StatusBar style="light" />
          <RootNavigator />
        </AuthProvider>
      </QueryClientProvider>
    </GestureHandlerRootView>
  );
}
