/**
 * Fogbreak Mobile — App Entry Point
 *
 * React Native/Expo app for iOS + Android.
 * Replaces: FUB, ShowingTime, Sisu, Paperless Pipeline, DocuSign, RealScout.
 *
 * Auth flow → Tab navigator → Full platform.
 * Push notifications, offline-first, GPS routing, camera, eSign.
 * White-label theming from tenant config.
 */

import React, { useEffect, useState, useCallback } from 'react';
import { StatusBar } from 'expo-status-bar';
import { NavigationContainer } from '@react-navigation/native';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import * as SplashScreen from 'expo-splash-screen';

import ThemeProvider from './src/themes/ThemeProvider';
import TabNavigator from './src/navigation/TabNavigator';
import LoginScreen from './src/screens/Auth/LoginScreen';
import { configureAPI } from './src/services/api';
import {
  isAuthenticated,
  getStoredAPIUrl,
  getStoredTenantId,
} from './src/services/auth';
import {
  registerForPushNotifications,
  setupNotificationCategories,
  addNotificationResponseListener,
  parseNotificationData,
  getNavigationRoute,
} from './src/services/notifications';
import { initNetworkMonitor, preCacheEssentials } from './src/services/offline';

// Prevent splash from hiding until we're ready
SplashScreen.preventAutoHideAsync();

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 5 * 60 * 1000, // 5 minutes
      retry: 2,
    },
  },
});

// Default API URL — overridden per tenant on login
const DEFAULT_API_URL = 'https://fogbreak.io';

export default function App() {
  const [isReady, setIsReady] = useState(false);
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const navigationRef = React.useRef<any>(null);

  const initialize = useCallback(async () => {
    try {
      // Restore API config
      const storedUrl = await getStoredAPIUrl();
      const storedTenant = await getStoredTenantId();
      configureAPI(storedUrl ?? DEFAULT_API_URL, storedTenant);

      // Check auth state
      const authed = await isAuthenticated();
      setIsLoggedIn(authed);

      if (authed) {
        // Initialize background services
        await Promise.allSettled([
          registerForPushNotifications(),
          setupNotificationCategories(),
          preCacheEssentials(),
        ]);
      }
    } catch {
      // Silent fail on init — user can still log in
    } finally {
      setIsReady(true);
      await SplashScreen.hideAsync();
    }
  }, []);

  useEffect(() => {
    initialize();
  }, [initialize]);

  // Network monitoring
  useEffect(() => {
    const unsubscribe = initNetworkMonitor();
    return unsubscribe;
  }, []);

  // Push notification deep linking
  useEffect(() => {
    const subscription = addNotificationResponseListener((response) => {
      const notification = parseNotificationData(response.notification);
      if (notification && navigationRef.current) {
        const { screen, params } = getNavigationRoute(notification.type, notification.data);
        navigationRef.current.navigate(screen, params);
      }
    });
    return () => subscription.remove();
  }, []);

  const handleLogin = useCallback(async () => {
    setIsLoggedIn(true);
    await Promise.allSettled([
      registerForPushNotifications(),
      setupNotificationCategories(),
      preCacheEssentials(),
    ]);
  }, []);

  if (!isReady) {
    return null; // Splash screen still showing
  }

  return (
    <QueryClientProvider client={queryClient}>
      <SafeAreaProvider>
        <ThemeProvider>
          <StatusBar style="light" />
          {isLoggedIn ? (
            <NavigationContainer ref={navigationRef}>
              <TabNavigator />
            </NavigationContainer>
          ) : (
            <LoginScreen onLogin={handleLogin} />
          )}
        </ThemeProvider>
      </SafeAreaProvider>
    </QueryClientProvider>
  );
}
