import React, { useState, useEffect, useRef } from 'react';
import { initializeApp } from 'firebase/app';
import {
getAuth,
onAuthStateChanged,
createUserWithEmailAndPassword,
signInWithEmailAndPassword,
signOut
} from 'firebase/auth';
import {
getFirestore,
collection,
addDoc,
query,
onSnapshot,
serverTimestamp
} from 'firebase/firestore';
// --- Firebase Configuration ---
// NOTE: This should be replaced with your actual Firebase config object
const firebaseConfig = {
apiKey: "AIzaSyDB9JWxknIUdoH2-BN7wjnprljjEjiJnX0",
authDomain: "mispeld-bb947.firebaseapp.com",
projectId: "mispeld-bb947",
storageBucket: "mispeld-bb947.appspot.com",
messagingSenderId: "183875526340",
appId: "1:183875526340:web:62c8c83cc3ca0bfd73b391",
measurementId: "G-KVQNM4FDSG"
};
// --- Firebase Initialization ---
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const db = getFirestore(app);
// --- Helper Functions ---
const getInitials = (email) => {
if (!email) return '?';
const parts = email.split('@')[0].replace(/[^a-zA-Z]/g, ' ').split(' ');
if (parts.length > 1) {
return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();
}
return email.substring(0, 2).toUpperCase();
};
// --- React Components ---
const Message = ({ msg, currentUser, onReply }) => {
const isOwn = msg.sender.uid === currentUser.uid;
return (
{getInitials(msg.sender.email)}
{msg.replyTo && (
{msg.replyTo.senderEmail === currentUser.email ? 'You' : msg.replyTo.senderEmail}
{msg.replyTo.text}
)}
{msg.text}
{isOwn ? 'You' : msg.sender.email} • {msg.timestamp ? new Date(msg.timestamp.toMillis()).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) : '...'}
{!isOwn && (
)}
);
};
const ChatInterface = ({ user, onLogout }) => {
const [messages, setMessages] = useState([]);
const [newMessage, setNewMessage] = useState('');
const [replyingTo, setReplyingTo] = useState(null);
const messagesEndRef = useRef(null);
useEffect(() => {
const messagesRef = collection(db, `public_chats/${firebaseConfig.appId}/messages`);
const q = query(messagesRef);
const unsubscribe = onSnapshot(q, (snapshot) => {
const fetchedMessages = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
fetchedMessages.sort((a, b) => (a.timestamp?.toMillis() || 0) - (b.timestamp?.toMillis() || 0));
setMessages(fetchedMessages);
});
return () => unsubscribe();
}, []);
useEffect(() => {
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
}, [messages]);
const handleSendMessage = async (e) => {
e.preventDefault();
const text = newMessage.trim();
if (!text) return;
const messagesRef = collection(db, `public_chats/${firebaseConfig.appId}/messages`);
const messageData = {
text,
timestamp: serverTimestamp(),
sender: { uid: user.uid, email: user.email },
...(replyingTo && {
replyTo: {
id: replyingTo.id,
text: replyingTo.text,
senderEmail: replyingTo.sender.email
}
})
};
try {
await addDoc(messagesRef, messageData);
setNewMessage('');
setReplyingTo(null);
} catch (error) {
console.error("Error sending message:", error);
}
};
return (
{messages.map(msg => (
))}
);
};
const LoginScreen = () => {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const handleLogin = async (e) => {
e.preventDefault();
setError('');
try {
await signInWithEmailAndPassword(auth, email, password);
} catch (err) {
setError(err.message);
}
};
const handleSignUp = async () => {
setError('');
try {
await createUserWithEmailAndPassword(auth, email, password);
} catch (err) {
setError(err.message);
}
};
return (
Chat Login
{error &&
{error}
}
);
};
export default function App() {
const [user, setUser] = useState(null);
useEffect(() => {
const unsubscribe = onAuthStateChanged(auth, (currentUser) => {
setUser(currentUser);
});
return () => unsubscribe();
}, []);
const handleLogout = () => {
signOut(auth);
};
return user ? : ;
}