import React, { useState, useEffect, useRef } from ‘react’;
import { initializeApp } from ‘firebase/app’;
import { getAuth, signInAnonymously, signInWithCustomToken, onAuthStateChanged } from ‘firebase/auth’;
import { getFirestore, doc, setDoc, collection, query, onSnapshot, addDoc } from ‘firebase/firestore’;
import Chart from ‘chart.js/auto’;
import { createRoot } from ‘react-dom/client’;
import * as d3 from ‘d3’;
import * as topojson from ‘topojson-client’;
// Define Firebase configuration and globals
const firebaseConfig = JSON.parse(typeof __firebase_config !== ‘undefined’ ? __firebase_config : ‘{}’);
const appId = typeof __app_id !== ‘undefined’ ? __app_id : ‘default-app-id’;
const initialAuthToken = typeof __initial_auth_token !== ‘undefined’ ? __initial_auth_token : ”;
// Function to initialize Firebase
const initFirebase = async () => {
try {
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const db = getFirestore(app);
if (initialAuthToken) {
await signInWithCustomToken(auth, initialAuthToken);
} else {
await signInAnonymously(auth);
}
return { auth, db };
} catch (error) {
console.error(“Firebase initialization error:”, error);
return null;
}
};
// Main App Component
export default function App() {
const [db, setDb] = useState(null);
const [auth, setAuth] = useState(null);
const [userId, setUserId] = useState(null);
const [isAuthReady, setIsAuthReady] = useState(false);
const [isMember, setIsMember] = useState(false); // New state for membership status
const [activeSection, setActiveSection] = useState(‘dashboard’);
const [showDestinationModal, setShowDestinationModal] = useState(false);
const [showGoalModal, setShowGoalModal] = useState(false);
const [destinations, setDestinations] = useState([]);
const [goals, setGoals] = useState([]);
const [message, setMessage] = useState(”);
const [messageType, setMessageType] = useState(‘success’);
const [isLoading, setIsLoading] = useState(true);
// Hardcoded mapping for the map feature
const locationToCountry = {
‘Paris, France’: ‘France’,
‘Arizona, USA’: ‘United States of America’,
‘Beijing, China’: ‘China’,
‘Cusco, Peru’: ‘Peru’,
‘Rome, Italy’: ‘Italy’
};
// Effect to initialize Firebase and set up auth state listener
useEffect(() => {
initFirebase().then(services => {
if (services) {
setAuth(services.auth);
setDb(services.db);
const unsubscribe = onAuthStateChanged(services.auth, (user) => {
if (user) {
setUserId(user.uid);
} else {
setUserId(crypto.randomUUID());
}
setIsAuthReady(true);
unsubscribe();
});
}
});
}, []);
// Effect to listen for data changes from Firestore
useEffect(() => {
if (isAuthReady && db && userId) {
// Listen for destinations
const destinationsRef = collection(db, `artifacts/${appId}/users/${userId}/destinations`);
const unsubscribeDestinations = onSnapshot(destinationsRef, (snapshot) => {
setDestinations(snapshot.docs.map(doc => ({ id: doc.id, …doc.data() })));
setIsLoading(false);
}, (error) => {
showMessage(‘Error fetching destinations: ‘ + error.message, ‘error’);
setIsLoading(false);
});
// Listen for goals
const goalsRef = collection(db, `artifacts/${appId}/users/${userId}/goals`);
const unsubscribeGoals = onSnapshot(goalsRef, (snapshot) => {
setGoals(snapshot.docs.map(doc => ({ id: doc.id, …doc.data() })));
setIsLoading(false);
}, (error) => {
showMessage(‘Error fetching goals: ‘ + error.message, ‘error’);
setIsLoading(false);
});
// Clean up listeners on component unmount
return () => {
unsubscribeDestinations();
unsubscribeGoals();
};
}
}, [isAuthReady, db, userId]);
// Handle messages
const showMessage = (msg, type = ‘success’) => {
setMessage(msg);
setMessageType(type);
setTimeout(() => setMessage(”), 3000);
};
// Calculate dashboard KPIs
const totalMiles = destinations.reduce((sum, d) => sum + (d.milesTraveled || 0), 0).toLocaleString();
const destinationsVisited = destinations.length;
const goalsCompleted = goals.filter(g => g.status === ‘Complete’).length;
// Render Charts
useEffect(() => {
if (activeSection === ‘dashboard’) {
const milesCanvas = document.getElementById(‘milesChart’);
if (milesCanvas) {
const milesCtx = milesCanvas.getContext(‘2d’);
if (Chart.getChart(milesCtx)) Chart.getChart(milesCtx).destroy();
new Chart(milesCtx, {
type: ‘bar’,
data: {
labels: destinations.map(d => d.destinationName),
datasets: [{
label: ‘Miles Traveled’,
data: destinations.map(d => d.milesTraveled),
backgroundColor: ‘#A8B8A5’,
}]
},
options: { responsive: true, maintainAspectRatio: false }
});
}
const goalsCanvas = document.getElementById(‘goalsChart’);
if (goalsCanvas) {
const goalsCtx = goalsCanvas.getContext(‘2d’);
if (Chart.getChart(goalsCtx)) Chart.getChart(goalsCtx).destroy();
const statusCounts = goals.reduce((acc, goal) => {
acc[goal.status] = (acc[goal.status] || 0) + 1;
return acc;
}, {});
new Chart(goalsCtx, {
type: ‘doughnut’,
data: {
labels: [‘Complete’, ‘In Progress’, ‘Not Started’],
datasets: [{
data: [‘Complete’, ‘In Progress’, ‘Not Started’].map(label => statusCounts[label] || 0),
backgroundColor: [‘#6A7B66’, ‘#A8B8A5’, ‘#EAE8E1’],
}]
},
options: { responsive: true, maintainAspectRatio: false }
});
}
}
}, [destinations, goals, activeSection]);
// Handle form submissions
const handleAddDestination = async (event) => {
event.preventDefault();
const form = event.target;
const newDestination = {
destinationName: form.destinationName.value,
location: form.location.value,
dateVisited: form.dateVisited.value,
imageUrl: form.imageUrl.value || ‘https://placehold.co/600×400/EAE8E1/334155?text=Image+Not+Found’,
notes: form.notes.value,
milesTraveled: parseInt(form.milesTraveled.value, 10),
};
try {
if (db && userId) {
await addDoc(collection(db, `artifacts/${appId}/users/${userId}/destinations`), newDestination);
showMessage(‘Destination added successfully!’);
}
setShowDestinationModal(false);
} catch (e) {
showMessage(‘Error adding destination: ‘ + e.message, ‘error’);
}
};
const handleAddGoal = async (event) => {
event.preventDefault();
const form = event.target;
const newGoal = {
goalName: form.goalName.value,
description: form.description.value,
status: form.status.value,
completionDate: form.completionDate.value || ”,
};
try {
if (db && userId) {
await addDoc(collection(db, `artifacts/${appId}/users/${userId}/goals`), newGoal);
showMessage(‘Goal added successfully!’);
}
setShowGoalModal(false);
} catch (e) {
showMessage(‘Error adding goal: ‘ + e.message, ‘error’);
}
};
// Render content based on membership status
const renderPremiumContent = (content) => {
if (isMember) {
return content;
}
return (
👑
Unlock Pro Features
Become a member to access this premium content!
(In a real app, this would redirect to a payment page.)
);
};
return (
{/* Message Box */}
{message && (
{message}
)}
{/* Sidebar Navigation */}
{/* Main Content Area */}
User ID:
{userId || ‘Loading…’}
{activeSection === ‘dashboard’ && (
Welcome, Traveler!
Here’s a summary of your amazing journeys.
{isLoading ? (
) : (
<>
Total Miles Traveled
{totalMiles}
Destinations Visited
{destinationsVisited}
Goals Completed
{goalsCompleted}
>
)}
)}
{activeSection === ‘destinations’ && (
My Destinations
A log of all the places you’ve explored.
{renderPremiumContent(
<>
{destinations.length > 0 ? (
destinations.map(d => (

{ e.target.onerror = null; e.target.src = ‘https://placehold.co/600×400/EAE8E1/334155?text=Image+Not+Found’; }} />
{d.dateVisited}
{d.destinationName}
{d.location}
{d.notes}
))
) : (
No destinations logged yet. Time for an adventure!
)}
>
)}
)}
{activeSection === ‘map’ && (
My Travel Map
Explore all your visited locations on the globe.
{renderPremiumContent(
{/* The Map component will render here */}
locationToCountry[d.location]).filter(Boolean))}
/>
)}
)}
{activeSection === ‘goals’ && (
My Travel Goals
Your aspirations and achievements, all in one place.
{renderPremiumContent(
<>
{goals.length > 0 ? (
[‘In Progress’, ‘Not Started’, ‘Complete’].map(status => {
const goalsInStatus = goals.filter(g => g.status === status);
if (goalsInStatus.length > 0) {
let statusColor = ‘bg-amber-100 text-amber-800’;
if (status === ‘Complete’) statusColor = ‘bg-emerald-100 text-emerald-800’;
if (status === ‘Not Started’) statusColor = ‘bg-slate-100 text-slate-800’;
return (
{status}
{goalsInStatus.length}
{goalsInStatus.map(goal => (
{status === ‘Complete’ ? ‘✅’ : (status === ‘In Progress’ ? ‘⏳’ : ‘⚪️’)}
{goal.goalName}
{goal.description}
{goal.completionDate &&
Completed: {goal.completionDate}
}
))}
);
}
return null;
})
) : (
No goals set yet. What’s your next dream trip?
)}
>
)}
)}
{/* Modals */}
{showDestinationModal && (
setShowDestinationModal(false)}>
e.stopPropagation()}>
setShowDestinationModal(false)}>×
Add New Destination
)}
{showGoalModal && (
)}
);
}
// Separate Map component to handle D3 logic
function TravelMap({ width, height, visitedCountries }) {
const mapRef = React.useRef(null);
let projection, path, svg, drag;
React.useEffect(() => {
if (!mapRef.current) return;
// Clear previous SVG
d3.select(mapRef.current).select(‘svg’).remove();
const size = Math.min(width, height);
const margin = 20;
svg = d3.select(mapRef.current).append(‘svg’)
.attr(‘width’, ‘100%’)
.attr(‘height’, ‘100%’)
.attr(‘viewBox’, `0 0 ${size} ${size}`)
.style(‘overflow’, ‘visible’);
projection = d3.geoOrthographic()
.scale(size / 2 – margin)
.translate([size / 2, size / 2])
.clipAngle(90);
path = d3.geoPath().projection(projection);
d3.json(‘https://cdn.jsdelivr.net/npm/world-atlas@2/countries-110m.json’).then(worldData => {
const countries = topojson.feature(worldData, worldData.objects.countries);
svg.append(‘path’)
.datum({ type: ‘Sphere’ })
.attr(‘fill’, ‘#A8B8A5’)
.attr(‘stroke’, ‘#6A7B66’)
.attr(‘d’, path);
svg.append(‘g’)
.selectAll(‘path’)
.data(countries.features)
.join(‘path’)
.attr(‘fill’, d => visitedCountries.has(d.properties.name) ? ‘#6A7B66’ : ‘#EAE8E1’)
.attr(‘stroke’, ‘#FDFBF7’)
.attr(‘d’, path)
.attr(‘cursor’, ‘pointer’);
});
let rotation = [0, 0, 0];
drag = d3.drag()
.on(‘start’, function(event) { rotation = projection.rotate(); })
.on(‘drag’, function(event) {
const rotate = [rotation[0] + event.dx, rotation[1] – event.dy];
projection.rotate(rotate);
svg.selectAll(‘path’).attr(‘d’, path);
});
svg.call(drag);
}, [width, height, visitedCountries]);
return
;
}