Self-hosted fitness tracker. Log workouts, track nutrition, and monitor progress. Docker deployment, mobile-friendly.
import { useState, useEffect, useMemo } from 'react'
import { format, startOfWeek, isSameDay, eachDayOfInterval, endOfWeek, subWeeks } from 'date-fns'
import {
Dumbbell, Flame, ArrowRight, Beef, BookOpen,
Play, Timer, TrendingUp, Scale, Activity, Plus,
} from 'lucide-react'
import {
BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer, Cell,
LineChart, Line, PieChart, Pie,
} from 'recharts'
import Loading from '../components/Loading'
import SectionHeader from '../components/ui/SectionHeader'
import { ErrorState, StatFailure } from '../components/ui'
import PeriodSelector from '../components/PeriodSelector'
import QuickWeighInSheet from '../components/QuickWeighInSheet'
import { workoutAPI, foodAPI, weightAPI, programAPI } from '../services/api'
import { useWorkoutSession } from '../stores/workoutSession'
import { useAuthStore } from '../stores/auth'
import { useSettingsStore, weightShort, displayWeight, displayVolume } from '../stores/settings'
import { useDisplayName } from '../lib/lyftr'
import { isDailyStats, workoutDay, entryDay, types, activeSessionExercisesForDay, dayLabel, sessionNameForDay, nextStartableDay, muscleRoast, muscleHex, calcVolume, greeting, formatDay, lifterQuip, formatDate, uiMessage, useTranslation, type UiMessage } from '@lyftr/shared'
import { useNavigate, Link } from 'react-router-dom'
import { muscleColor, muscleLabel } from '../utils/exerciseUtils'
const DEFAULT_FOOD: types.DailyStats = {
date: '',
total_calories: 0, total_protein: 0, total_carbs: 0, total_fat: 0, total_fiber: 0, workout_count: 0,
}
function MuscleSparkline({ values, color, isTop }: { values: number[], color: string, isTop: boolean }) {
if (values.length < 2) return <div className="w-14 h-6 flex-shrink-0" />
const max = Math.max(...values)
const min = Math.min(...values)
const range = max - min || 1
const W = 56, H = 24
const pts = values.map((v, i) => [
(i / (values.length - 1)) * W,
H - 4 - ((v - min) / range) * (H - 8),
])
const d = pts.map((p, i) => `${i === 0 ? 'M' : 'L'}${p[0].toFixed(1)},${p[1].toFixed(1)}`).join(' ')
// Filled area path
const area = `${d} L${W},${H} L0,${H} Z`
return (
<svg width={W} height={H} className="flex-shrink-0 overflow-visible">
{isTop && (
<path d={area} fill={color} fillOpacity={0.12} />
)}
<path d={d} fill="none" stroke={color} strokeWidth={isTop ? 2 : 1.5}
strokeLinecap="round" strokeLinejoin="round"
strokeOpacity={isTop ? 1 : 0.6}
/>
{/* End dot */}
<circle
cx={pts[pts.length - 1][0]}
cy={pts[pts.length - 1][1]}
r={isTop ? 2.5 : 1.5}
fill={color}
fillOpacity={isTop ? 1 : 0.7}
/>
</svg>
)
}
// The seven weekday rows of the heatmap; every other one carries a letter.
const WEEKDAY_ROWS = [0, 1, 2, 3, 4, 5, 6] as const
const TOOLTIP_STYLE = {
background: 'var(--color-surface-raised, #1e1e2e)',
border: '1px solid var(--color-surface-border, #2d2d3a)',
borderRadius: 8,
fontSize: 11,
color: 'var(--color-tx-primary, #f1f5f9)',
}
export default function Dashboard() {
const { t } = useTranslation()
// Sampled per mount, not at module load. As a module constant this went stale the
// moment the tab outlived the day it was opened on — a tab left open across midnight
// kept yesterday's date header, week boundary and heatmap "today" until a reload.
const TODAY = useMemo(() => new Date(), [])
const navigate = useNavigate()
const { session, startSession } = useWorkoutSession()
const { user } = useAuthStore()
// Settings come from the store, not a page-local fetch. This page used to make
// its OWN /settings request with its OWN defaults literal — a third copy of the
// fallback the store already owns, and one the store's loadFailed flag could
// never see. The store fetch no-ops when already loaded and retries when the
// last read fell back, so this costs nothing on the happy path.
const { settings, fetch: fetchSettings } = useSettingsStore()
const [workouts, setWorkouts] = useState<types.Workout[]>([])
const [programs, setPrograms] = useState<types.Program[]>([])
const [food, setFood] = useState<types.DailyStats>(DEFAULT_FOOD)
const [weightLogs, setWeightLogs] = useState<types.WeightLog[]>([])
const [weightStats, setWeightStats] = useState<types.WeightStats | null>(null)
const [loading, setLoading] = useState(true)
// Failures are kept as a UiMessage (a key and the failure that caused it), not as a sentence,
// so a banner already on screen follows a language switch.
const [error, setError] = useState<UiMessage | null>(null)
// Bumping this re-runs the load effect. A lifted useCallback would be the tidier
// shape, but it would mean restructuring a working effect to gain a retry button;
// this does the same job in three lines.
const [retryKey, setRetryKey] = useState(0)
const [sheetOpen, setSheetOpen] = useState(false)
// The four secondary reads are caught so one dead endpoint cannot blank a working
// dashboard — that part is deliberate. What was missing is that they then said nothing:
// a 500 from /food/stats substituted DEFAULT_FOOD and rendered today as 0 kcal, which
// is what "hasn't eaten yet" looks like. The page stays up; the numbers it never
// received read "—", and one marker names what is missing.
// Name -> what the server actually said. Keeping the message matters for the two
// areas big enough to show one: a card that never loaded can say why, and a generic
// sentence there would be us inventing a cause we were handed.
const [missing, setMissing] = useState<Record<string, UiMessage>>({})
const foodMissing = "today's food" in missing
const weightMissing = 'your weight' in missing
const [volumePeriod, setVolumePeriod] = useState<'7' | '14' | '30'>('7')
const retry = () => { setLoading(true); setRetryKey(k => k + 1) }
const wUnit = weightShort(settings.weight_unit)
useEffect(() => {
void fetchSettings()
const absent: Record<string, UiMessage> = {}
Promise.all([
workoutAPI.list({ limit: 84 }), // 12 weeks × 7 days max
// backend's max — Up Next must see every program
programAPI.list({ limit: 100 })
.catch(err => { absent['your programs'] = { key: 'errors.unknown', cause: err }; return [] }),
foodAPI.stats(format(TODAY, 'yyyy-MM-dd'))
// A 200 carrying the wrong shape never reaches the catch. Unchecked, the missing
// field went through Math.round and the ring read "NaN".
.then(fs => isDailyStats(fs) ? fs : Promise.reject(new Error('unreadable')))
.catch(err => { absent["today's food"] = { key: 'errors.unknown', cause: err }; return DEFAULT_FOOD }),
weightAPI.list({ limit: 14 })
.catch(err => { absent['your weight'] = { key: 'errors.unknown', cause: err }; return [] }),
weightAPI.stats()
.catch(err => { absent['your weight'] = { key: 'errors.unknown', cause: err }; return null }),
])
.then(([ws, ps, fs, wl, wst]) => {
setWorkouts(ws || [])
setPrograms(ps || [])
setFood(fs || DEFAULT_FOOD)
setWeightLogs(wl || [])
setWeightStats(wst)
setMissing(absent)
})
.catch(err => setError({ key: 'errors.unknown', cause: err }))
.finally(() => setLoading(false))
}, [TODAY, retryKey, fetchSettings])
// Above the early returns: it is a hook now, so it has to run on every render or the
// hook order changes between the loading branch and the loaded one.
const username = useDisplayName()
if (loading) return <Loading />
// The dashboard is nothing but other requests' answers, so when the load fails there
// is no honest partial view to show — every tile would read 0, which states "you did
// nothing this week" rather than "we could not ask".
if (error) {
return (
<ErrorState
size="page"
title={t('home.loadFailed')}
message={uiMessage(error)}
onRetry={() => { setError(null); setLoading(true); setRetryKey(k => k + 1) }}
/>
)
}
// ── Derived data ────────────────────────────────
const weekStart = startOfWeek(TODAY, { weekStartsOn: 1 })
// Compared as days, not instants: the dot strip below buckets by workoutDay, so a
// count taken from the raw timestamp can disagree with the dots it sits above for a
// workout logged near the week boundary in another zone.
const weekStartDay = format(weekStart, 'yyyy-MM-dd')
const weekWorkouts = workouts.filter(w => workoutDay(w) >= weekStartDay)
const lastWorkout = workouts[0] ?? null
// "Up next": the first (most recently created) program whose due day is a
// startable workout day. Surfaces today's routine workout without opening the
// Programs page — a routine that never shows on the dashboard never gets started.
const upNext = nextStartableDay(programs)
const startUpNext = () => {
if (!upNext) return
const { program, day } = upNext
startSession(sessionNameForDay(program, day), activeSessionExercisesForDay(day), program.id, day.id)
navigate('/workout/active')
}
// Volume chart: slice by selected period, oldest→newest
const chartData = workouts.slice(0, Number(volumePeriod)).reverse().map(w => ({
date: formatDay(workoutDay(w), 'numericMonthDay'),
volume: displayVolume(calcVolume(w), settings.weight_unit),
name: w.name,
}))
// Current week dots
const weekDays = eachDayOfInterval({ start: weekStart, end: endOfWeek(TODAY, { weekStartsOn: 1 }) })
// Heatmap: 12 weeks, Mon–Sun columns
const heatmapStart = startOfWeek(subWeeks(TODAY, 11), { weekStartsOn: 1 })
const heatmapEnd = endOfWeek(TODAY, { weekStartsOn: 1 })
const heatmapDays = eachDayOfInterval({ start: heatmapStart, end: heatmapEnd })
// map dateString → count
const workoutDayMap = new Map<string, number>()
workouts.forEach(w => {
// The workout's own day, so the heatmap counts it under the day it happened
// rather than the day the viewing device would place that instant on.
const k = workoutDay(w)
workoutDayMap.set(k, (workoutDayMap.get(k) || 0) + 1)
})
// chunk into weeks
const heatmapWeeks: Date[][] = []
for (let i = 0; i < heatmapDays.length; i += 7) {
heatmapWeeks.push(heatmapDays.slice(i, i + 7))
}
// month labels: show month name on first week that starts in that month
const monthLabels: (string | null)[] = heatmapWeeks.map((week, i) => {
const m = formatDate(week[0], 'monthShort')
if (i === 0) return m
const prev = formatDate(heatmapWeeks[i - 1][0], 'monthShort')
return m !== prev ? m : null
})
// Muscle group donut: sets per muscle across all fetched workouts
const muscleMap = new Map<string, number>()
workouts.forEach(w => {
(w.exercises ?? []).forEach(ex => {
const mg = ex.exercise?.muscle_group || 'other'
muscleMap.set(mg, (muscleMap.get(mg) || 0) + (ex.sets ?? []).length)
})
})
const muscleData = Array.from(muscleMap.entries())
.sort((a, b) => b[1] - a[1])
.slice(0, 8) // top 8 groups
.map(([name, value]) => ({ name, value }))
const totalMuscSets = muscleData.reduce((s, d) => s + d.value, 0)
// Sparklines: sets per muscle per workout (last 10, oldest→newest)
const sparklineWorkouts = workouts.slice(0, 10).reverse()
const muscleSparklines = new Map<string, number[]>()
muscleData.forEach(({ name }) => {
muscleSparklines.set(name, sparklineWorkouts.map(w =>
(w.exercises ?? [])
.filter(ex => ex.exercise?.muscle_group === name)
.reduce((s, ex) => s + (ex.sets ?? []).length, 0)
))
})
const topMuscle = muscleData[0]?.name ?? null
// Nutrition %
const calPct = Math.min(100, (food.total_calories / settings.calorie_target) * 100) || 0
const protPct = Math.min(100, (food.total_protein / settings.protein_target) * 100) || 0
const carbsPct = Math.min(100, (food.total_carbs / settings.carb_target) * 100) || 0
const fatPct = Math.min(100, (food.total_fat / settings.fat_target) * 100) || 0
// Weight sparkline
const sparkData = [...weightLogs].reverse().map(l => ({
date: formatDay(entryDay(l), 'numericMonthDay'),
weight: displayWeight(l.weight, settings.weight_unit),
}))
return (
<div className="space-y-4 animate-slide-up">
{/* ── Header ─────────────────────────────────── */}
<div className="flex justify-between items-start gap-3">
<div className="min-w-0">
<p className="text-[11px] text-tx-muted uppercase tracking-wider font-medium">
{formatDate(TODAY, 'weekdayMonthDayLong')}
</p>
{/* Never clipped: a name is the one string here that is the user's own, and
its length is bounded at the input instead (MaxDisplayNameLen). text-balance
breaks it at the comma rather than mid-surname; browsers without it just
wrap. Mobile wraps too, but gets no text-balance and deliberately no
leading-tight — an imposed lineHeight clips descenders on iOS (ui/Field.tsx). */}
<h1 className="font-display font-bold text-2xl text-tx-primary mt-0.5 leading-tight text-balance">
{greeting(TODAY, username)}
</h1>
<p className="text-xs text-tx-muted mt-1">{lifterQuip(user?.id ?? '')}</p>
</div>
<button
onClick={() => navigate('/workout/start')}
className="btn-primary btn-sm flex-shrink-0"
>
<Play className="w-3.5 h-3.5" />
{t(session ? 'home.header.resume' : 'home.header.start')}
</button>
</div>
{/* ── Active session banner ──────────────────── */}
{session && (
<Link
to="/workout/active"
className="flex items-center justify-between p-3 bg-amber-500/10 border border-amber-500/30 rounded-xl hover:bg-amber-500/15 transition-colors"
>
<div className="flex items-center gap-3">
<div className="w-8 h-8 rounded-lg bg-amber-500/20 border border-amber-500/30 flex items-center justify-center flex-shrink-0">
<Timer className="w-4 h-4 text-amber-400 animate-pulse" />
</div>
<div>
<p className="text-sm font-semibold text-amber-300">{t('home.activeSession.title')}</p>
<p className="text-xs text-amber-400/70">{t('home.activeSession.tapToResume', { name: session.name })}</p>
</div>
</div>
<ArrowRight className="w-4 h-4 text-amber-400 flex-shrink-0" />
</Link>
)}
{/* ── Up next — today's due day on the current routine. Hidden while a
session is live: the banner above already owns that slot. Thumbnail is
the due day's own first exercise (same pattern as Programs.tsx's card
and the Last-workout list below), not a generic program glyph — makes
the card read as "this is what you're about to do." Start is icon-only,
not a labeled pill: the header above already has a text "Start"/"Resume"
button, and two buttons both saying "Start" stacked this close reads as
noise, not choice. The Start button stays a SIBLING of the link, not a
child: an <a> may not contain interactive descendants (invalid HTML, and
screen readers fold the button into the link's accessible name). ── */}
{!session && upNext && (
<div className="flex items-center gap-3 card p-3 hover:bg-surface-muted/40 transition-colors">
<Link
to={`/programs/${upNext.program.id}`}
aria-label={t('home.upNext.viewRoutine', { name: upNext.program.name })}
className="flex items-center gap-3 flex-1 min-w-0"
>
{upNext.day.exercises?.[0]?.exercise?.image_url ? (
<img
src={upNext.day.exercises[0].exercise.image_url}
alt=""
className="w-10 h-10 rounded-xl object-cover flex-shrink-0 bg-surface-muted"
onError={e => { (e.target as HTMLImageElement).style.display = 'none' }}
/>
) : (
<div className="w-10 h-10 rounded-xl bg-brand-500/10 border border-brand-500/20 flex items-center justify-center flex-shrink-0">
<BookOpen className="w-5 h-5 text-brand-500" />
</div>
)}
<div className="flex-1 min-w-0">
<p className="text-[10px] text-tx-muted uppercase tracking-wide font-medium truncate">{t('home.upNext.label', { name: upNext.program.name })}</p>
<p className="text-sm font-semibold text-tx-primary truncate mt-0.5">{dayLabel(upNext.day, upNext.day.order_index)}</p>
<p className="text-xs text-tx-muted mt-0.5">{t('common.count.exercises', { count: (upNext.day.exercises ?? []).length })}</p>
</div>
</Link>
<button
onClick={startUpNext}
aria-label={t('home.upNext.start', { name: dayLabel(upNext.day, upNext.day.order_index) })}
className="flex items-center justify-center w-9 h-9 bg-brand-500 hover:bg-brand-600 text-white rounded-xl transition-colors flex-shrink-0"
>
<Play className="w-4 h-4" />
</button>
</div>
)}
{/* ── KPI strip ──────────────────────────────── */}
<div className="grid grid-cols-3 gap-2">
<div className="card p-3 flex flex-col gap-1.5">
<div className="flex items-center justify-between">
<span className="text-[10px] text-tx-muted uppercase tracking-wide font-medium">{t('home.kpi.week')}</span>
<Dumbbell className="w-3 h-3 text-tx-muted" />
</div>
<p className="text-xl font-bold text-tx-primary leading-none">{weekWorkouts.length}</p>
<p className="text-[10px] text-tx-muted">{t('home.kpi.sessions')}</p>
</div>
<div className="card p-3 flex flex-col gap-1.5">
<div className="flex items-center justify-between">
<span className="text-[10px] text-tx-muted uppercase tracking-wide font-medium">{t('home.kpi.cals')}</span>
<Flame className="w-3 h-3 text-tx-muted" />
</div>
{foodMissing ? (
<StatFailure label={t('home.kpi.caloriesFailed')} />
) : (
<>
<p className="text-xl font-bold text-tx-primary leading-none">{Math.round(food.total_calories)}</p>
<div className="progress-track">
<div className="progress-bar" style={{ width: `${calPct}%`, background: '#00b8d9' }} />
</div>
</>
)}
</div>
<div className="card p-3 flex flex-col gap-1.5">
<div className="flex items-center justify-between">
<span className="text-[10px] text-tx-muted uppercase tracking-wide font-medium">{t('food.macro.protein')}</span>
<Beef className="w-3 h-3 text-tx-muted" />
</div>
{foodMissing ? (
<StatFailure label={t('home.kpi.proteinFailed')} />
) : (
<>
<p className="text-xl font-bold text-tx-primary leading-none">
{Math.round(food.total_protein)}<span className="text-xs text-tx-muted font-normal">g</span>
</p>
<div className="progress-track">
<div className="progress-bar" style={{ width: `${protPct}%`, background: '#f59e0b' }} />
</div>
</>
)}
</div>
</div>
{/* ── Volume trend chart ─────────────────────── */}
<div className="card p-4">
<SectionHeader
icon={TrendingUp}
title={t('home.volume.title')}
right={<PeriodSelector options={['7', '14', '30'] as const} value={volumePeriod} onChange={setVolumePeriod} />}
className="mb-3"
/>
{chartData.length === 0 ? (
<div className="flex flex-col items-center justify-center py-8 gap-2">
<Dumbbell className="w-6 h-6 text-tx-muted opacity-40" />
<p className="text-xs text-tx-muted">{t('home.volume.empty')}</p>
</div>
) : (
<>
<div className="w-full min-w-0">
<ResponsiveContainer width="100%" height={110}>
<BarChart data={chartData} barSize={18} barCategoryGap="30%">
<XAxis
dataKey="date"
tick={{ fontSize: 10, fill: 'var(--color-tx-muted, #9ca3af)' }}
axisLine={false}
tickLine={false}
/>
<YAxis hide />
<Tooltip
contentStyle={TOOLTIP_STYLE}
formatter={(v: number) => [`${v.toLocaleString()} ${wUnit}`, t('home.volume.tooltip')]}
labelFormatter={(label: string) => chartData.find(d => d.date === label)?.name || label}
cursor={{ fill: 'rgba(99,102,241,0.08)', radius: 4 }}
/>
<Bar dataKey="volume" radius={[4, 4, 0, 0]}>
{chartData.map((_, i) => (
<Cell key={i} fill="#6366f1" fillOpacity={i === chartData.length - 1 ? 1 : 0.25} />
))}
</Bar>
</BarChart>
</ResponsiveContainer>
</div>
{/* Current week day dots */}
<div className="flex items-center justify-between mt-4 px-1">
{weekDays.map((day, i) => {
const hasWorkout = workouts.some(w => workoutDay(w) === format(day, 'yyyy-MM-dd'))
const isToday = isSameDay(day, TODAY)
const isFuture = day > TODAY
return (
<div key={i} className="flex flex-col items-center gap-1.5">
<span className={`text-[10px] font-semibold ${isToday ? 'text-brand-400' : 'text-tx-muted'}`}>
{formatDate(day, 'weekdayNarrow')}
</span>
<div className={`w-3 h-3 rounded-full transition-all ${
hasWorkout ? 'bg-brand-500 shadow-sm shadow-brand-500/50' :
isToday ? 'bg-transparent ring-2 ring-brand-500/60' :
isFuture ? 'bg-surface-border/20' :
'bg-surface-border/60'
}`} />
</div>
)
})}
</div>
</>
)}
</div>
{/* ── Frequency heatmap ──────────────────────── */}
<div className="card p-4">
<SectionHeader
icon={Activity}
title={t('home.consistency.title')}
right={<span className="text-xs text-tx-muted">{t('home.consistency.range')}</span>}
className="mb-3"
/>
{workouts.length === 0 ? (
<div className="flex flex-col items-center justify-center py-6 gap-2">
<p className="text-xs text-tx-muted">{t('home.consistency.empty')}</p>
</div>
) : (
<>
{/* CSS grid: 1 auto col (day labels) + N 1fr cols (weeks) */}
<div
className="w-full"
style={{ display: 'grid', gridTemplateColumns: `1.25rem repeat(${heatmapWeeks.length}, 1fr)`, gap: '2px' }}
>
{/* Row 0: spacer + month labels */}
<div />
{heatmapWeeks.map((_, i) => (
<div key={i} className="text-[9px] text-tx-muted font-medium overflow-visible whitespace-nowrap leading-none pb-0.5">
{monthLabels[i] ?? ''}
</div>
))}
{/* Rows 1–7: day label + cells */}
{WEEKDAY_ROWS.map((dayIdx) => (
[
<div key={`lbl-${dayIdx}`} className="text-[9px] text-tx-muted/60 font-medium flex items-center leading-none">
{dayIdx % 2 === 0 ? formatDate(heatmapWeeks[0][dayIdx], 'weekdayNarrow') : ''}
</div>,
...heatmapWeeks.map((week, wi) => {
const day = week[dayIdx]
const k = format(day, 'yyyy-MM-dd')
const count = workoutDayMap.get(k) || 0
const future = day > TODAY
return (
<div
key={`${wi}-${dayIdx}`}
title={count > 0 ? t('home.heatmap.workouts', { date: formatDate(day, 'monthDay'), count }) : formatDate(day, 'monthDay')}
className={`h-3 rounded-[2px] transition-colors ${
future ? 'bg-surface-muted/20' :
count === 0 ? 'bg-surface-muted/50' :
count === 1 ? 'bg-brand-500/50' :
'bg-brand-500'
}`}
/>
)
}),
]
))}
</div>
{/* Legend */}
<div className="flex items-center gap-1.5 mt-2 justify-end">
<span className="text-[9px] text-tx-muted">{t('home.heatmap.less')}</span>
{['bg-surface-muted/50', 'bg-brand-500/30', 'bg-brand-500/60', 'bg-brand-500'].map((cls, i) => (
<div key={i} className={`w-3 h-3 rounded-[3px] ${cls}`} />
))}
<span className="text-[9px] text-tx-muted">{t('home.heatmap.more')}</span>
</div>
</>
)}
</div>
{/* ── Last workout + Nutrition ───────────────── */}
<div className="grid lg:grid-cols-2 gap-4 min-w-0">
{lastWorkout ? (() => {
const exs = lastWorkout.exercises ?? []
const totalSets = exs.reduce((s, ex) => s + (ex.sets ?? []).length, 0)
const totalVolume = displayVolume(calcVolume(lastWorkout), settings.weight_unit)
const mins = Math.round(lastWorkout.duration / 60)
return (
<div className="card p-4 overflow-hidden min-w-0 cursor-pointer active:scale-[0.99] transition-transform"
onClick={() => navigate(`/workouts/${lastWorkout.id}`)}>
<div className="flex items-start justify-between gap-2 mb-3">
<div className="min-w-0">
<p className="text-sm font-semibold text-tx-primary truncate">{lastWorkout.name}</p>
<p className="text-xs text-tx-muted mt-0.5">
{[
formatDay(workoutDay(lastWorkout), 'monthDay'),
mins > 0 && t('home.lastWorkout.minutes', { mins }),
totalSets > 0 && t('common.count.sets', { count: totalSets }),
totalVolume > 0 && `${totalVolume.toLocaleString()} ${wUnit}`,
].filter(Boolean).join(' · ')}
</p>
</div>
<Link to="/workouts" className="flex items-center gap-0.5 text-xs text-brand-400 hover:text-brand-300 flex-shrink-0 transition-colors">
{t('home.lastWorkout.all')} <ArrowRight className="w-3 h-3" />
</Link>
</div>
<div className="divide-y divide-surface-border/60">
{exs.slice(0, 4).map((ex) => {
const sets = ex.sets ?? []
const best = sets.length > 0
? sets.reduce((b, s) => s.weight > b.weight ? s : b, sets[0])
: null
return (
<div key={ex.id} className="flex items-center gap-2.5 py-2.5">
{ex.exercise.image_url ? (
<img
src={ex.exercise.image_url}
alt=""
loading="lazy"
className="w-8 h-8 rounded-lg object-cover flex-shrink-0 bg-surface-muted"
onError={e => { (e.target as HTMLImageElement).style.display = 'none' }}
/>
) : (
<div className="w-8 h-8 rounded-lg bg-brand-500/10 border border-brand-500/20 flex items-center justify-center flex-shrink-0">
<Dumbbell className="w-3.5 h-3.5 text-brand-500" />
</div>
)}
<div className="flex-1 min-w-0">
<p className="text-sm text-tx-secondary truncate">{ex.exercise.name}</p>
<span className={`text-[10px] px-1 py-0.5 rounded ${muscleColor(ex.exercise.muscle_group)}`}>
{muscleLabel(ex.exercise.muscle_group)}
</span>
</div>
{best && (
<span className="text-xs text-tx-muted tabular-nums flex-shrink-0">
{sets.length}×{best.weight > 0 ? ` ${displayWeight(best.weight, settings.weight_unit)}${wUnit}` : ` ${t('weight.bodyweightShort')}`}
</span>
)}
</div>
)
})}
</div>
{exs.length > 4 && (
<p className="text-xs text-tx-muted text-center pt-2">
{t('home.lastWorkout.moreExercises', { count: exs.length - 4 })}
</p>
)}
</div>
)
})() : (
<div className="card p-4 flex flex-col items-center justify-center min-h-36 gap-2">
<Dumbbell className="w-7 h-7 text-tx-muted opacity-40" />
<p className="text-sm text-tx-muted">{t('home.lastWorkout.empty')}</p>
{/* Suppressed when the Up Next card is already showing above — that
card is its own "start something" CTA; a second "start your first
workout" link right under it is the redundant-buttons clutter this
card exists to avoid. */}
{!upNext && (
<button
onClick={() => navigate('/workout/start')}
className="text-xs text-brand-400 hover:text-brand-300 font-medium transition-colors mt-1"
>
{t('home.lastWorkout.startFirst')}
</button>
)}
</div>
)}
{/* Nutrition */}
<div className="card p-4 overflow-hidden min-w-0">
<div className="flex items-center justify-between mb-3">
<h2 className="section-title">{t('home.nutrition.title')}</h2>
<Link to="/food" className="text-xs text-brand-400 hover:text-brand-300 transition-colors flex-shrink-0">
{t('home.nutrition.log')}
</Link>
</div>
{foodMissing ? (
// The KPI tiles above mirror these numbers with the bare failure mark; the
// sentence and the retry belong here, in the section that owns them.
<ErrorState
size="section"
title={t('home.nutrition.loadFailed')}
message={uiMessage(missing["today's food"])}
onRetry={retry}
/>
) : (
<>
{/* Calorie total */}
<div className="flex items-baseline gap-1.5 mb-3">
<span className="text-3xl font-bold text-tx-primary tabular-nums leading-none">
{Math.round(food.total_calories)}
</span>
<span className="text-xs text-tx-muted">/ {settings.calorie_target} kcal</span>
<div className="flex-1" />
<span className="text-xs text-tx-muted tabular-nums">{Math.round(calPct)}%</span>
</div>
<div className="progress-track mb-4">
<div className="progress-bar" style={{ width: `${calPct}%`, background: '#00b8d9' }} />
</div>
{/* Macros */}
<div className="space-y-2.5">
{[
{ id: 'protein', label: t('food.macro.protein'), val: food.total_protein, target: settings.protein_target, pct: protPct, color: '#3b82f6' },
{ id: 'carbs', label: t('home.macro.carbs'), val: food.total_carbs, target: settings.carb_target, pct: carbsPct, color: '#f59e0b' },
{ id: 'fat', label: t('food.macro.fat'), val: food.total_fat, target: settings.fat_target, pct: fatPct, color: '#8b5cf6' },
].map(m => (
<div key={m.id}>
<div className="flex justify-between items-center mb-1">
<span className="text-xs text-tx-muted">{m.label}</span>
<span className="text-xs font-semibold text-tx-primary tabular-nums">
{Math.round(m.val)}g
<span className="text-tx-muted font-normal"> / {m.target}g</span>
</span>
</div>
<div className="progress-track">
<div className="progress-bar" style={{ width: `${m.pct}%`, background: m.color }} />
</div>
</div>
))}
</div>
</>
)}
</div>
</div>
{/* ── Muscle group balance ────────────────────── */}
<div className="card p-4">
<SectionHeader
icon={Dumbbell}
title={t('home.muscle.title')}
right={<span className="text-xs text-tx-muted">{t('home.muscle.workouts', { count: workouts.length })}</span>}
className="mb-1"
/>
{topMuscle ? (
<p className="text-xs text-tx-muted mb-3 italic">
{muscleRoast(topMuscle)}
</p>
) : (
<p className="text-xs text-tx-muted mb-3">{t('home.muscle.empty')}</p>
)}
{muscleData.length === 0 ? (
<div className="flex flex-col items-center justify-center py-6 gap-2">
<Dumbbell className="w-6 h-6 text-tx-muted opacity-30" />
<p className="text-xs text-tx-muted">{t('home.muscle.noData')}</p>
</div>
) : (
<div className="flex flex-col sm:flex-row items-center gap-4">
{/* Donut */}
<div className="flex-shrink-0 flex items-center justify-center">
<ResponsiveContainer width={160} height={160}>
<PieChart>
<Pie
data={muscleData}
cx="50%"
cy="50%"
innerRadius={44}
outerRadius={68}
dataKey="value"
strokeWidth={0}
paddingAngle={2}
>
{muscleData.map((entry, i) => (
<Cell key={i} fill={muscleHex(entry.name)} fillOpacity={0.85} />
))}
</Pie>
<Tooltip
contentStyle={TOOLTIP_STYLE}
formatter={(v: number, _: string, props: { payload?: { name: string } }) => [
t('home.muscle.tooltip', { count: v, percent: Math.round((v / totalMuscSets) * 100) }),
muscleLabel(props.payload?.name),
]}
/>
</PieChart>
</ResponsiveContainer>
</div>
{/* Legend — muscle name + sparkline + set count */}
<div className="flex-1 w-full min-w-0 space-y-2">
{muscleData.map((d) => {
const pct = Math.round((d.value / totalMuscSets) * 100)
const isTop = d.name === topMuscle
const values = muscleSparklines.get(d.name) ?? []
const color = muscleHex(d.name)
return (
<div key={d.name}>
<div className="flex items-center gap-2 mb-0.5">
<div className="w-2 h-2 rounded-full flex-shrink-0" style={{ background: color }} />
<span className={`text-xs capitalize flex-1 min-w-0 truncate ${isTop ? 'font-semibold text-tx-primary' : 'text-tx-secondary'}`}>
{muscleLabel(d.name)}
{isTop && <span className="ml-1 text-[9px] font-normal text-tx-muted uppercase tracking-wide">{t('home.muscle.top')}</span>}
</span>
<MuscleSparkline values={values} color={color} isTop={isTop} />
<span className="text-xs text-tx-muted tabular-nums w-16 text-right flex-shrink-0">
{d.value} · {pct}%
</span>
</div>
<div className="progress-track">
<div className="progress-bar transition-all" style={{ width: `${pct}%`, background: color, opacity: isTop ? 1 : 0.6 }} />
</div>
</div>
)
})}
</div>
</div>
)}
</div>
{/* ── Weight quick-log card ──────────────────── */}
<div className="card p-4">
<SectionHeader
icon={Scale}
title={t('home.weight.title')}
right={
<Link to="/weight" className="text-xs text-brand-400 hover:text-brand-300 transition-colors flex items-center gap-0.5">
{t('home.weight.view')} <ArrowRight className="w-3 h-3" />
</Link>
}
className="mb-2"
/>
{weightLogs.length === 0 && weightMissing ? (
// Not the "log your first weight" prompt: this reader may have years of them.
// Card-sized, so it gets the section treatment — mark, sentence and a button —
// rather than the bare mark a stat tile has room for.
<ErrorState
size="section"
title={t('home.weight.loadFailed')}
message={uiMessage(missing['your weight'])}
onRetry={retry}
/>
) : weightLogs.length === 0 ? (
<button
type="button"
onClick={() => setSheetOpen(true)}
className="w-full flex items-center gap-3 p-3 bg-brand-500/5 border border-dashed border-brand-500/30 rounded-xl hover:bg-brand-500/10 transition-colors text-left"
>
<div className="w-9 h-9 rounded-lg bg-brand-500/10 border border-brand-500/20 flex items-center justify-center flex-shrink-0">
<Plus className="w-4 h-4 text-brand-500" />
</div>
<div className="min-w-0">
<p className="text-sm font-semibold text-tx-primary">{t('home.weight.logFirst')}</p>
<p className="text-xs text-tx-muted">{t('home.weight.logFirstHint')}</p>
</div>
</button>
) : (
<button
type="button"
onClick={() => setSheetOpen(true)}
className="w-full text-left active:scale-[0.99] transition-transform"
aria-label={t('home.weight.logAria')}
>
<div className="flex items-center justify-between mb-2">
<div className="flex items-baseline gap-1.5">
<span className="text-2xl font-bold text-tx-primary tabular-nums leading-none">
{displayWeight(weightLogs[0].weight, settings.weight_unit)}
</span>
<span className="text-sm text-tx-muted">{wUnit}</span>
</div>
<div className="flex items-center gap-2">
{(() => {
const delta = weightStats?.change_7d ?? 0
if (delta === 0) {
return <span className="text-xs text-tx-muted">{t('home.weight.noChange7d')}</span>
}
return (
<span className={`text-xs tabular-nums ${delta < 0 ? 'text-success-400' : 'text-error-400'}`}>
{t(delta < 0 ? 'home.weight.trendDown' : 'home.weight.trendUp', { amount: Math.abs(displayWeight(delta, settings.weight_unit)), unit: wUnit })}
</span>
)
})()}
<div className="w-8 h-8 rounded-lg bg-brand-500 flex items-center justify-center text-white shadow-sm flex-shrink-0">
<Plus className="w-3.5 h-3.5" />
</div>
</div>
</div>
{weightLogs.length >= 2 && (
<div className="w-full min-w-0">
<ResponsiveContainer width="100%" height={48}>
<LineChart data={sparkData}>
<Line dataKey="weight" dot={false} stroke="#6366f1" strokeWidth={2} type="monotone" />
<Tooltip
contentStyle={TOOLTIP_STYLE}
formatter={(v: number) => [`${v} ${wUnit}`, t('home.weight.title')]}
/>
</LineChart>
</ResponsiveContainer>
</div>
)}
</button>
)}
</div>
<QuickWeighInSheet
isOpen={sheetOpen}
lastValue={weightLogs[0] ? displayWeight(weightLogs[0].weight, settings.weight_unit) : null}
lastLog={weightLogs[0] ?? null}
onClose={() => setSheetOpen(false)}
onSuccess={(log) => {
// Same order the server returns (logged_on DESC, logged_at DESC), so the
// optimistic row sits where the next refetch will put it. Sorting by the
// instant alone can place a cross-zone entry above or below its own label.
setWeightLogs(prev =>
[log, ...prev].sort(
(a, b) =>
entryDay(b).localeCompare(entryDay(a)) ||
new Date(b.logged_at).getTime() - new Date(a.logged_at).getTime()
)
)
weightAPI.stats().then(setWeightStats).catch(() => {})
}}
/>
</div>
)
}