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'; 

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'); 
      } else {
        setIsLoggedIn(false); 
      }
      setCheckingAuth(false); 
    });

    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;
