// App.tsx
import React, { useCallback, useEffect } from 'react'; // Add useEffect
import { Platform, View } from 'react-native';
import { Provider as PaperProvider } from 'react-native-paper';
import { NavigationContainer, DarkTheme as NavigationDarkTheme } from '@react-navigation/native'; // Import NavigationDarkTheme
import { SafeAreaProvider } from 'react-native-safe-area-context';
import { StatusBar } from 'expo-status-bar';
import * as SplashScreen from 'expo-splash-screen';
import { useFonts } from 'expo-font';

import { AuthProvider, useAuth } from './src/contexts/AuthContext'; // Import useAuth
import RootNavigator from './src/navigation/RootNavigator';
import theme from './src/constants/theme';
import {
    registerForPushNotificationsAsync,
    sendPushTokenToBackend,
    setupNotificationHandlers
} from './src/services/notificationService'; // Import notification functions

// Keep the splash screen visible while we fetch resourcesDone, please go ahead with the changes.
SplashScreen.preventAutoHideAsync();

// Create a navigation theme based on the Paper theme colors but without the incompatible fonts object
const navigationTheme = {
  ...NavigationDarkTheme, // Use React Navigation's dark theme as a base
  colors: {
    ...NavigationDarkTheme.colors,
    primary: theme.colors.primary,
    background: theme.colors.background,
    card: theme.colors.surface, // Map Paper surface to Navigation card
    text: theme.colors.text,
    border: theme.colors.surface, // Use surface for border or another appropriate color
    notification: theme.colors.primary, // Example mapping
  },
};

// Wrapper component to handle notification logic after auth state is known
function AppContent() {
  const { user } = useAuth(); // Get user state

  useEffect(() => {
    // Setup notification handlers (listeners)
    const cleanupNotificationHandlers = setupNotificationHandlers();

    // Register for push notifications only if user is logged in
    const registerAndSendToken = async () => {
      if (user) { // Only register if logged in
        console.log('[App] User logged in, attempting to register for push notifications...');
        const token = await registerForPushNotificationsAsync();
        if (token) {
          console.log('[App] Push token obtained, sending to backend...');
          await sendPushTokenToBackend(token);
        } else {
          console.log('[App] Could not get push token.');
        }
      } else {
        console.log('[App] User not logged in, skipping push notification registration.');
        // Optionally: If you need to clear the token on the backend when logged out,
        // you might need a separate API call here or handle it server-side based on user activity.
      }
    };

    registerAndSendToken();

    // Cleanup listeners on component unmount
    return () => {
      cleanupNotificationHandlers();
    };
  }, [user]); // Re-run when user logs in or out

  return <RootNavigator />;
}

export default function App() {
  const [fontsLoaded, fontError] = useFonts({
    'Inter-Regular': require('./src/assets/fonts/Inter-Regular.ttf'),
    'Inter-Bold': require('./src/assets/fonts/Inter-Bold.ttf'),
    'Inter-Medium': require('./src/assets/fonts/Inter-Medium.ttf'),
    'Inter-Light': require('./src/assets/fonts/Inter-Light.ttf'),
    'Inter-Thin': require('./src/assets/fonts/Inter-Thin.ttf'),
    // Add other weights/styles if you have them
  });

  const onLayoutRootView = useCallback(async () => {
    if (fontsLoaded || fontError) {
      // Log font loading status
      if (fontError) {
        console.error("Font loading error:", fontError);
      }
      await SplashScreen.hideAsync();
    }
  }, [fontsLoaded, fontError]);

  if (!fontsLoaded && !fontError) {
    return null; // Return null or a loading indicator while fonts are loading
  }

  // If fonts are loaded (or there was an error), render the app
  return (
    <View style={{ flex: 1 }} onLayout={onLayoutRootView}>
      <SafeAreaProvider>
        <AuthProvider>
          {/* PaperProvider uses the full theme with custom fonts */}
          <PaperProvider theme={theme}>
            {/* NavigationContainer uses the simplified navigationTheme */}
            <NavigationContainer theme={navigationTheme}>
              {/* Use AppContent which contains RootNavigator and notification logic */}
              <AppContent />
            </NavigationContainer>
            <StatusBar
              style="light" // Assuming dark theme
              backgroundColor={Platform.OS === 'web' ? theme.colors.background : theme.colors.surface}
            />
          </PaperProvider>
        </AuthProvider>
      </SafeAreaProvider>
    </View>
  );
}