// components/auth.jsx — Firebase Auth configuration and context

const firebaseConfig = {
  apiKey: "AIzaSyCeq-2K736Y21ipzZJyIcNk-QF0BIlYWgM",
  authDomain: "lineagelens-40833.firebaseapp.com",
  projectId: "lineagelens-40833",
  storageBucket: "lineagelens-40833.firebasestorage.app",
  messagingSenderId: "1055704899209",
  appId: "1:1055704899209:web:25a5347cb04f2e61c2b058",
  measurementId: "G-EZXWS1S5QY"
};

// Initialize Firebase if not already initialized
if (!firebase.apps.length) {
  firebase.initializeApp(firebaseConfig);
}

const auth = firebase.auth();
const googleProvider = new firebase.auth.GoogleAuthProvider();

const AuthContext = React.createContext();

function AuthProvider({ children }) {
  const [user, setUser] = React.useState(null);
  const [loading, setLoading] = React.useState(true);

  React.useEffect(() => {
    // Listen for auth state changes
    const unsubscribe = auth.onAuthStateChanged((currentUser) => {
      setUser(currentUser);
      setLoading(false);
    });
    return unsubscribe;
  }, []);

  const signIn = async () => {
    try {
      await auth.signInWithPopup(googleProvider);
    } catch (error) {
      console.error("Error signing in with Google", error);
    }
  };

  const signOut = async () => {
    try {
      await auth.signOut();
    } catch (error) {
      console.error("Error signing out", error);
    }
  };

  return (
    <AuthContext.Provider value={{ user, signIn, signOut, loading }}>
      {children}
    </AuthContext.Provider>
  );
}

function useAuth() {
  const context = React.useContext(AuthContext);
  if (context === undefined) {
    throw new Error('useAuth must be used within an AuthProvider');
  }
  return context;
}

Object.assign(window, { AuthProvider, useAuth });
