import React, { useState, useEffect } from 'react';
import { initializeApp } from 'firebase/app';
import {
getFirestore,
collection,
addDoc,
query,
onSnapshot,
orderBy,
doc,
setDoc,
getDoc
} from 'firebase/firestore';
import {
getAuth,
signInAnonymously,
onAuthStateChanged
} from 'firebase/auth';
import {
FileText,
Users,
HelpCircle,
Download,
PlusCircle,
LogOut,
LayoutDashboard,
ShieldCheck,
ChevronRight,
MapPin,
Navigation
} from 'lucide-react';
// --- CONFIGURATION ---
const firebaseConfig = JSON.parse(__firebase_config);
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
const auth = getAuth(app);
const appId = typeof __app_id !== 'undefined' ? __app_id : 'rever-bridge-portal';
const ADMIN_ID = "RB-ADMIN-99"; // Set your admin ID here
export default function App() {
const [user, setUser] = useState(null);
const [agentId, setAgentId] = useState('');
const [isLoggedIn, setIsLoggedIn] = useState(false);
const [activeTab, setActiveTab] = useState('dashboard');
const [leads, setLeads] = useState([]);
const [locationLogs, setLocationLogs] = useState([]);
const [loading, setLoading] = useState(false);
const [locLoading, setLocLoading] = useState(false);
const [toast, setToast] = useState({ show: false, message: '', type: 'info' });
// Form States
const [leadForm, setLeadForm] = useState({
clientName: '',
clientPhone: '',
loanAmount: '',
loanType: 'GRZ Loan',
notes: ''
});
// 1. Auth & Initial Load
useEffect(() => {
const initAuth = async () => {
if (typeof __initial_auth_token !== 'undefined' && __initial_auth_token) {
try {
// Note: In some environments this might be required
// await signInWithCustomToken(auth, __initial_auth_token);
await signInAnonymously(auth);
} catch (e) {
await signInAnonymously(auth);
}
} else {
await signInAnonymously(auth);
}
};
initAuth();
const unsubscribe = onAuthStateChanged(auth, (currUser) => {
setUser(currUser);
});
return () => unsubscribe();
}, []);
// 2. Fetch Data (Leads & Location Logs)
useEffect(() => {
if (!user || !isLoggedIn) return;
// Fetch Leads
const leadsRef = collection(db, 'artifacts', appId, 'public', 'data', 'leads');
const unsubLeads = onSnapshot(leadsRef, (snapshot) => {
const data = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
if (agentId !== ADMIN_ID) {
setLeads(data.filter(l => l.agentId === agentId));
} else {
setLeads(data);
}
});
// Fetch Location Logs
const logsRef = collection(db, 'artifacts', appId, 'public', 'data', 'location_logs');
const unsubLogs = onSnapshot(logsRef, (snapshot) => {
const data = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
// Sort in JS because simple collection query is safer
const sortedData = data.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
if (agentId !== ADMIN_ID) {
setLocationLogs(sortedData.filter(l => l.agentId === agentId));
} else {
setLocationLogs(sortedData);
}
});
return () => {
unsubLeads();
unsubLogs();
};
}, [user, isLoggedIn, agentId]);
const showToast = (message, type = 'info') => {
setToast({ show: true, message, type });
setTimeout(() => setToast({ show: false, message: '', type: 'info' }), 4000);
};
const handleLogin = (e) => {
e.preventDefault();
if (agentId.trim().length < 4) {
showToast("Please enter a valid Agent ID", "error");
return;
}
setIsLoggedIn(true);
showToast(`Welcome back, Agent ${agentId}`, "success");
};
const submitLead = async (e) => {
e.preventDefault();
if (!user) return;
setLoading(true);
try {
const leadsRef = collection(db, 'artifacts', appId, 'public', 'data', 'leads');
await addDoc(leadsRef, {
...leadForm,
agentId: agentId,
status: 'Pending',
timestamp: new Date().toISOString(),
});
showToast("Loan Lead submitted successfully!", "success");
setLeadForm({ clientName: '', clientPhone: '', loanAmount: '', loanType: 'GRZ Loan', notes: '' });
setActiveTab('dashboard');
} catch (err) {
showToast("Error submitting lead. Try again.", "error");
} finally {
setLoading(false);
}
};
const handleCheckIn = () => {
if (!navigator.geolocation) {
showToast("Geolocation is not supported by your browser.", "error");
return;
}
setLocLoading(true);
navigator.geolocation.getCurrentPosition(async (position) => {
try {
const { latitude, longitude } = position.coords;
const logsRef = collection(db, 'artifacts', appId, 'public', 'data', 'location_logs');
await addDoc(logsRef, {
agentId,
lat: latitude,
lng: longitude,
timestamp: new Date().toISOString(),
mapLink: `https://www.google.com/maps?q=${latitude},${longitude}`
});
showToast("Location check-in successful!", "success");
} catch (err) {
showToast("Failed to save location data.", "error");
} finally {
setLocLoading(false);
}
}, (error) => {
showToast("Permission denied. Enable GPS to check in.", "error");
setLocLoading(false);
});
};
if (!isLoggedIn) {
return (
Agent Portal
Rever-Bridge Financial Services Ltd
);
}
return (
{/* Sidebar - Desktop */}
{/* Main Content */}
{/* Header */}
{/* Dashboard View */}
{activeTab === 'dashboard' && (
Recent Activity
{leads.length === 0 && locationLogs.length === 0 ? (
No recent activity recorded.
) : (
{locationLogs.slice(0, 3).map(log => (
Field Check-in
{new Date(log.timestamp).toLocaleString()}
View Map
))}
)}
)}
{/* Field Logs View */}
{activeTab === 'field-logs' && (
Field Work Check-in
Click below to log your current location. This helps us verify field coverage and process commissions.
Your Location History
| Date & Time |
Coordinates |
Map Link |
{locationLogs.length === 0 ? (
| No check-ins recorded yet. |
) : (
locationLogs.map(log => (
| {new Date(log.timestamp).toLocaleString()} |
{log.lat.toFixed(5)}, {log.lng.toFixed(5)} |
Open in Google Maps
|
))
)}
)}
{/* Submit Lead View */}
{activeTab === 'new-lead' && (
)}
{/* Admin Monitoring View */}
{activeTab === 'admin' && agentId === ADMIN_ID && (
Master Field Compilation
Admin oversight of all registered activity
{/* Admin Table - Location Logs */}
All Agent Field Check-ins
| Agent ID |
Timestamp |
Coordinates |
Map View |
{locationLogs.map((log) => (
| {log.agentId} |
{new Date(log.timestamp).toLocaleString()} |
{log.lat.toFixed(5)}, {log.lng.toFixed(5)} |
|
))}
{/* Master Lead Table */}
All Registered Loan Leads
| Agent ID |
Client Name |
Amount |
Product |
Status |
Action |
{leads.map((lead) => (
| {lead.agentId} |
{lead.clientName} |
K{parseFloat(lead.loanAmount).toLocaleString()} |
{lead.loanType} |
{lead.status}
|
|
))}
)}
{/* Resources View */}
{activeTab === 'resources' && (
)}
{/* FAQ View */}
{activeTab === 'faq' && (
)}
{/* Toast Notification */}
{toast.show && (
{toast.message}
)}
);
}
// Sub-components
function NavItem({ icon, label, onClick, active }) {
return (
);
}
function StatCard({ label, value, color, textColor = "text-slate-800" }) {
return (
);
}
function ResourceItem({ title, type }) {
return (
);
}
function FaqItem({ question, answer }) {
const [open, setOpen] = useState(false);
return (
{open &&
{answer}
}
);
}