import React, { useEffect, useState } from 'react';
import { View, ActivityIndicator } from 'react-native';
import { getAuth, onAuthStateChanged } from 'firebase/auth';
import { router } from 'expo-router';
import OpeningScreen from './screens/auth/OpeningScreen'; // ajuste le chemin si besoin

const Index = () => {
  const [checkingAuth, setCheckingAuth] = useState(true);
  const [isLoggedIn, setIsLoggedIn] = useState(false);

  useEffect(() => {
    const auth = getAuth();

    const unsubscribe = onAuthStateChanged(auth, (user) => {
      if (user) {
        setIsLoggedIn(true);
        router.replace('/screens/user/UserHomeScreen'); // redirige vers Home
      } else {
        setIsLoggedIn(false); // utilisateur non connecté
      }
      setCheckingAuth(false); // vérification terminée
    });

    return () => unsubscribe();
  }, []);

  if (checkingAuth) {
    return (
      <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#000' }}>
        <ActivityIndicator size="large" color="#fff" />
      </View>
    );
  }

  return !isLoggedIn ? <OpeningScreen /> : null;
};

export default Index;
