import React, { useState, useEffect } from 'react';
// Firebase imports - MUST use the global variables provided by the environment
import { initializeApp } from 'firebase/app';
import { getAuth, signInAnonymously, signInWithCustomToken, onAuthStateChanged } from 'firebase/auth';
import { getFirestore, collection, addDoc, onSnapshot, query, serverTimestamp } from 'firebase/firestore';
// Main App component
const App = () => {
// State to manage Firebase instances and user info
const [db, setDb] = useState(null);
const [auth, setAuth] = useState(null);
const [userId, setUserId] = useState(null);
const [isAuthReady, setIsAuthReady] = useState(false); // To ensure Firestore operations run after auth
const [view, setView] = useState('user'); // 'user' or 'admin'
// Initialize Firebase and set up auth listener
useEffect(() => {
try {
// Check if global Firebase config is available
const firebaseConfig = typeof __firebase_config !== 'undefined'
? JSON.parse(__firebase_config)
: {};
if (Object.keys(firebaseConfig).length === 0) {
console.error("Firebase config is missing or empty.");
// Provide a dummy config if not available, for local development/testing without Canvas environment
// In a real scenario, this should be handled more robustly
// firebaseConfig = {
// apiKey: "YOUR_API_KEY",
// authDomain: "YOUR_AUTH_DOMAIN",
// projectId: "YOUR_PROJECT_ID",
// storageBucket: "YOUR_STORAGE_BUCKET",
// messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
// appId: "YOUR_APP_ID"
// };
}
const app = initializeApp(firebaseConfig);
const firestore = getFirestore(app);
const firebaseAuth = getAuth(app);
setDb(firestore);
setAuth(firebaseAuth);
// Sign in anonymously if no initial token, or use the provided token
const initialAuthToken = typeof __initial_auth_token !== 'undefined'
? __initial_auth_token
: null;
if (initialAuthToken) {
signInWithCustomToken(firebaseAuth, initialAuthToken)
.then(() => console.log("Signed in with custom token"))
.catch((error) => console.error("Error signing in with custom token:", error));
} else {
signInAnonymously(firebaseAuth)
.then(() => console.log("Signed in anonymously"))
.catch((error) => console.error("Error signing in anonymously:", error));
}
// Listen for auth state changes
const unsubscribe = onAuthStateChanged(firebaseAuth, (user) => {
if (user) {
setUserId(user.uid);
console.log("User ID:", user.uid);
} else {
setUserId(null);
console.log("No user signed in.");
}
setIsAuthReady(true); // Auth state has been checked
});
// Cleanup subscription on unmount
return () => unsubscribe();
} catch (error) {
console.error("Failed to initialize Firebase:", error);
}
}, []); // Empty dependency array means this runs once on mount
// Loading state for Firebase
if (!isAuthReady) {
return (
جاري تحميل التطبيق...
);
}
// Determine the base path for collections based on environment
const appId = typeof __app_id !== 'undefined' ? __app_id : 'default-app-id';
const getCollectionPath = (collectionName) => `/artifacts/${appId}/public/data/${collectionName}`;
return (