import React, { useEffect } from 'react';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import { RootNavigation } from './src/navigation';
import { authService } from './src/modules/auth/services/authService';
import { useAuthStore } from './src/store';

function App(): React.JSX.Element {
  const { setLoading } = useAuthStore();

  useEffect(() => {
    // Session wiederherstellen beim App-Start
    const initAuth = async () => {
      setLoading(true);
      await authService.restoreSession();
      setLoading(false);
    };

    initAuth();

    // Auth State Listener
    const { data: subscription } = authService.onAuthStateChange((session) => {
      if (session) {
        // Session aktiv
        console.log('User authenticated');
      } else {
        // Keine Session
        console.log('User logged out');
      }
    });

    // Cleanup
    return () => {
      subscription?.subscription?.unsubscribe();
    };
  }, [setLoading]);

  return (
    <SafeAreaProvider>
      <RootNavigation />
    </SafeAreaProvider>
  );
}

export default App;
