Searching in Bayonne, NJ
import React, { useState, useEffect, useRef } from 'react';
import { initializeApp } from 'firebase/app';
import { getAuth, signInAnonymously, signInWithCustomToken, onAuthStateChanged } from 'firebase/auth';
import { getFirestore, doc, getDoc, addDoc, setDoc, updateDoc, deleteDoc, onSnapshot, collection, query, where, getDocs } from 'firebase/firestore';
// Ensure global variables are defined or provide fallbacks for local development
const appId = typeof __app_id !== 'undefined' ? __app_id : 'default-app-id';
const firebaseConfig = typeof __firebase_config !== 'undefined' ? JSON.parse(__firebase_config) : {};
const initialAuthToken = typeof __initial_auth_token !== 'undefined' ? __initial_auth_token : null;
// Main App component
const App = () => {
// State to hold Firebase instances and user ID
const [db, setDb] = useState(null);
const [auth, setAuth] = useState(null);
const [userId, setUserId] = useState(null);
const [isAuthReady, setIsAuthReady] = useState(false);
// State for application data
const [pins, setPins] = useState([]);
const [selectedPinType, setSelectedPinType] = useState('sonar'); // 'sonar' or 'submarine'
const [message, setMessage] = useState(''); // For user messages/feedback
// Ref for the map container to calculate relative coordinates
const mapRef = useRef(null);
// 1. Initialize Firebase and handle authentication
useEffect(() => {
try {
const app = initializeApp(firebaseConfig);
const firestore = getFirestore(app);
const firebaseAuth = getAuth(app);
setDb(firestore);
setAuth(firebaseAuth);
// Sign in with custom token if available, otherwise anonymously
const authenticate = async () => {
try {
if (initialAuthToken) {
await signInWithCustomToken(firebaseAuth, initialAuthToken);
} else {
await signInAnonymously(firebaseAuth);
}
} catch (error) {
console.error("Firebase authentication failed:", error);
setMessage("Authentication failed. Please try again.");
}
};
authenticate();
// Listen for auth state changes to get the user ID
const unsubscribeAuth = onAuthStateChanged(firebaseAuth, (user) => {
if (user) {
setUserId(user.uid);