import { useEffect, useState } from 'react'; import GarminSync from '../components/garmin/GarminSync'; import WorkoutChart from '../components/analysis/WorkoutCharts'; import PlanTimeline from '../components/plans/PlanTimeline'; import { useAuth } from '../context/AuthContext'; import LoadingSpinner from '../components/LoadingSpinner'; const Dashboard = () => { const { apiKey, loading: apiLoading } = useAuth(); const isBuildTime = typeof window === 'undefined'; const [recentWorkouts, setRecentWorkouts] = useState([]); const [currentPlan, setCurrentPlan] = useState(null); const [stats, setStats] = useState({ totalWorkouts: 0, totalDistance: 0 }); const [healthStatus, setHealthStatus] = useState(null); const [localLoading, setLocalLoading] = useState(true); const [error, setError] = useState(''); useEffect(() => { const fetchDashboardData = async () => { try { const [workoutsRes, planRes, statsRes, healthRes] = await Promise.all([ fetch(`${process.env.REACT_APP_API_URL}/api/workouts?limit=3`, { headers: { 'X-API-Key': apiKey } }), fetch(`${process.env.REACT_APP_API_URL}/api/plans/active`, { headers: { 'X-API-Key': apiKey } }), fetch(`${process.env.REACT_APP_API_URL}/api/stats`, { headers: { 'X-API-Key': apiKey } }), fetch(`${process.env.REACT_APP_API_URL}/api/health`, { headers: { 'X-API-Key': apiKey } }) ]); const errors = []; if (!workoutsRes.ok) errors.push('Failed to fetch workouts'); if (!planRes.ok) errors.push('Failed to fetch plan'); if (!statsRes.ok) errors.push('Failed to fetch stats'); if (!healthRes.ok) errors.push('Failed to fetch health status'); if (errors.length > 0) throw new Error(errors.join(', ')); const [workoutsData, planData, statsData, healthData] = await Promise.all([ workoutsRes.json(), planRes.json(), statsRes.json(), healthRes.json() ]); setRecentWorkouts(workoutsData.workouts || []); setCurrentPlan(planData); setStats(statsData.workouts || { totalWorkouts: 0, totalDistance: 0 }); setHealthStatus(healthData); } catch (err) { setError(err.message); } finally { setLocalLoading(false); } }; fetchDashboardData(); }, [apiKey]); if (isBuildTime) { return (

Training Dashboard

Loading dashboard data...

); } if (localLoading || apiLoading) return ; if (error) return
{error}
; // Calculate total distance in km const totalDistanceKm = (stats.totalDistance / 1000).toFixed(0); return (

Training Dashboard

{/* Stats Summary Cards */}

Total Workouts

{stats.totalWorkouts}

Total Distance

{totalDistanceKm} km

Current Plan

{currentPlan ? `v${currentPlan.version}` : 'None'}

System Status

{healthStatus?.status || 'unknown'}

Performance Metrics

Recent Activities

{recentWorkouts.length > 0 ? (
{recentWorkouts.map(workout => (

{new Date(workout.start_time).toLocaleDateString()}

{workout.activity_type}

{(workout.distance_m / 1000).toFixed(1)} km

{Math.round(workout.duration_seconds / 60)} mins

))}
) : (
No recent activities found
)}

Current Plan

{currentPlan ? ( ) : (
No active training plan
)}

Upcoming Workouts

{currentPlan?.jsonb_plan.weeks[0]?.workouts.map((workout, index) => (
{workout.day} {workout.type.replace('_', ' ')}

{workout.description}

))}
); }; export default Dashboard;