Self-hosted fitness tracker. Log workouts, track nutrition, and monitor progress. Docker deployment, mobile-friendly.
import { useState, useEffect, useRef } from 'react'
import { useNavigate } from 'react-router-dom'
import {
CheckCircle2, Plus, X, Dumbbell, Flag, ChevronRight, ChevronLeft, Play,
Minimize2, Trash2, Repeat, Check, Layers, Timer,
} from 'lucide-react'
import Model, { IExerciseData } from 'react-body-highlighter'
import { useAsyncAction, types, PLATE_STEP, REP_STEP, clampStep, clampValue, nextIncompleteSet, numericRange, useTranslation } from '@lyftr/shared'
import { muscleColor, muscleColorBordered, categoryLabel, equipmentLabel, muscleLabel, muscleToBodySlugs } from '../utils/exerciseUtils'
import { useTheme } from '../hooks/useTheme'
import { useWorkoutSession } from '../stores/workoutSession'
import { useSettingsStore } from '../stores/settings'
import RestPicker from '../components/RestPicker'
import RestTimerBanner from '../components/RestTimerBanner'
import { workoutAPI } from '../services/api'
import StepperTile from '../components/ui/StepperTile'
import NumberField from '../components/ui/NumberField'
import { ConfirmSheet } from '../components/ui'
import { displayWeight, displayToLbs } from '../stores/settings'
function buildBodyData(exercise: types.Exercise): IExerciseData[] {
const primarySlugs = muscleToBodySlugs(exercise.muscle_group)
const secondarySlugs = (exercise.secondary_muscles || [])
.flatMap(m => muscleToBodySlugs(m))
.filter(s => !primarySlugs.includes(s))
const data: IExerciseData[] = []
if (primarySlugs.length > 0) data.push({ name: 'Primary', muscles: primarySlugs as any, frequency: 2 })
if (secondarySlugs.length > 0) data.push({ name: 'Secondary', muscles: secondarySlugs as any, frequency: 1 })
return data
}
function ExerciseNotes({ exIdx, notes, onSave }: { exIdx: number; notes: string; onSave: (i: number, v: string) => void }) {
const { t } = useTranslation()
const [editing, setEditing] = useState(false)
const [val, setVal] = useState(notes)
const commit = () => { onSave(exIdx, val); setEditing(false) }
if (editing) {
return (
<input
autoFocus type="text" value={val}
onChange={e => setVal(e.target.value)}
onBlur={commit}
onKeyDown={e => { if (e.key === 'Enter') commit(); if (e.key === 'Escape') { setVal(notes); setEditing(false) } }}
placeholder={t('workouts.active.notes.placeholder')}
className="input text-sm w-full"
/>
)
}
return (
<button
onClick={() => { setVal(notes); setEditing(true) }}
className="text-xs text-tx-muted hover:text-tx-secondary transition-colors text-left w-full"
>
{notes ? <span className="italic">{notes}</span> : <span className="opacity-50">{t('workouts.active.notes.add')}</span>}
</button>
)
}
interface GymModeWorkoutProps {
wUnit: string
}
export default function GymModeWorkout({ wUnit }: GymModeWorkoutProps) {
// Also re-renders on a language switch for the labels read from the catalog.
const { t } = useTranslation()
const navigate = useNavigate()
const { isDark } = useTheme()
const {
session, minimizeGym,
gymPhase: phase, gymExIdx: activeIdx, gymSetIdx: activeSetIdx, setGymState,
updateSet, completeSet, addSet, removeSet, removeExercise, updateExerciseNotes,
buildPayload, cancelSession,
startRest, clearRest, restExIdx, restSetIdx, setExerciseRest,
} = useWorkoutSession()
const { settings } = useSettingsStore()
const [imgFailed, setImgFailed] = useState(false)
const [confirmFinish, setConfirmFinish] = useState(false)
const [confirmCancel, setConfirmCancel] = useState(false)
const setPhase = (p: typeof phase) => setGymState(p, activeIdx, activeSetIdx)
const onSetActiveIdx = (i: number) => setGymState(phase, i, 0)
const setActiveSetIdx = (i: number) => setGymState(phase, activeIdx, i)
useEffect(() => { setImgFailed(false) }, [activeIdx])
// Jump to a newly added exercise. Must sit above the `!session` early return with
// every other hook: when a session ends, `session` goes null and React would see
// fewer hooks than the previous render — the "rendered fewer hooks than expected"
// crash. Reads through `?.` because it now also runs on the session-less render.
const exerciseCount = session?.exercises.length ?? 0
const prevLenRef = useRef(exerciseCount)
useEffect(() => {
if (exerciseCount > prevLenRef.current) onSetActiveIdx(exerciseCount - 1)
prevLenRef.current = exerciseCount
}, [exerciseCount])
// This used to set the message and then dismiss the sheet that displays it, so the
// explanation was rendered nowhere and a failed finish looked like a dead button.
// The sheet stays open now; the session is intact and the retry is one tap away.
const finish = useAsyncAction(async () => {
const saved = await workoutAPI.create(buildPayload())
cancelSession()
minimizeGym()
// Surface the routine auto-progression as a toast on the workouts list (#40).
navigate('/workouts', saved?.progression ? { state: { progression: saved.progression } } : undefined)
}, t('workouts.active.saveFailed'))
if (!session) return null
const handleMinimize = () => {
minimizeGym()
// Navigate away from /workout/active so list mode doesn't show underneath
if (window.location.pathname === '/workout/active') navigate('/')
}
const totalSets = session.exercises.reduce((s, ex) => s + ex.sets.length, 0)
const completedSets = session.exercises.reduce((s, ex) => s + ex.sets.filter(st => st.completed).length, 0)
const bodyColor = isDark ? '#162240' : '#e2e8f0'
const highlightColors = ['#0e7490', '#22d3ee']
// ── Shared top bar (exercise-info + exercise phases) ──────────────────
function TopBar({ onBack, s }: { onBack: () => void; s: types.ActiveSession }) {
const allDone = completedSets === totalSets && totalSets > 0
return (
<div className="flex items-center gap-3 px-4 pt-4 pb-3 border-b border-surface-border flex-shrink-0">
<button
onClick={onBack}
className="p-2 hover:bg-surface-muted rounded-xl transition-colors text-tx-muted"
>
<ChevronLeft className="w-5 h-5" />
</button>
<div className="flex-1 min-w-0 flex items-center gap-2">
<div className="flex items-center gap-1.5 overflow-x-auto min-w-0">
{s.exercises.map((_, i) => (
<button
key={i}
onClick={() => setGymState('exercise-info', i, 0)}
aria-label={t('gym.goToExercise', { number: i + 1 })}
className={`h-1.5 rounded-full flex-shrink-0 transition-all duration-200 ${
i === activeIdx ? 'w-6 bg-brand-500' :
s.exercises[i].sets.every(st => st.completed) && s.exercises[i].sets.length > 0
? 'w-2 bg-brand-500/40' : 'w-2 bg-surface-border'
}`}
/>
))}
</div>
<span className="text-xs text-tx-muted tabular-nums flex-shrink-0">{activeIdx + 1}/{s.exercises.length}</span>
</div>
<div className="flex items-center gap-1 flex-shrink-0">
<button
onClick={() => setConfirmFinish(true)}
className={`flex items-center gap-1.5 px-3 py-2 rounded-xl text-xs font-semibold transition-all ${
allDone
? 'bg-brand-500 hover:bg-brand-600 text-white shadow-sm shadow-brand-500/30'
: 'bg-surface-muted text-tx-muted border border-surface-border'
}`}
>
<Flag className="w-3.5 h-3.5" />
{t('workouts.active.finish')}
</button>
<button
onClick={handleMinimize}
className="p-2 hover:bg-surface-muted rounded-xl transition-colors text-tx-muted"
aria-label={t('gym.minimizeWorkout')}
title={t('gym.minimize')}
>
<Minimize2 className="w-4 h-4" />
</button>
<button
onClick={() => setConfirmCancel(true)}
className="p-2 hover:bg-error-500/10 rounded-xl transition-colors text-tx-muted hover:text-error-400"
aria-label={t('gym.discardWorkout')}
title={t('gym.discardWorkout')}
>
<X className="w-5 h-5" />
</button>
</div>
</div>
)
}
// Closes every phase: the docked rest panel (in-flow, below the phase's bottom
// actions, null when no rest is active) plus the two portalled confirms. Each phase
// below returns its own tree, and nothing here varies by phase.
const trailing = (
<>
<RestTimerBanner />
<ConfirmSheet
open={confirmFinish}
icon={Flag}
title={t('workouts.active.finishConfirm.title')}
message={t('workouts.active.finishConfirm.message', { done: completedSets, count: totalSets })}
confirmLabel={t('workouts.active.finish')}
busyLabel={t('common.saving')}
cancelLabel={t('workouts.active.keepGoing')}
busy={finish.busy}
error={finish.error}
onConfirm={() => { void finish.run() }}
onCancel={() => { setConfirmFinish(false); finish.reset() }}
/>
<ConfirmSheet
open={confirmCancel}
icon={Trash2}
destructive
title={t('gym.discard.title')}
message={t('gym.discard.message')}
confirmLabel={t('gym.discard.confirm')}
cancelLabel={t('workouts.active.keepGoing')}
onConfirm={() => { cancelSession(); handleMinimize() }}
onCancel={() => setConfirmCancel(false)}
/>
</>
)
// ── Overview ──────────────────────────────────────────────────────────
if (phase === 'overview') {
return (
<div role="dialog" aria-modal="true" aria-label={t('gym.workout')} className="fixed inset-0 z-[60] bg-surface-base overflow-y-auto flex flex-col">
<div className="flex items-center justify-between px-5 pt-5 pb-4 border-b border-surface-border flex-shrink-0">
<div>
<p className="text-xs font-semibold text-tx-muted uppercase tracking-wider mb-0.5">{t('gym.workout')}</p>
<h1 className="font-display font-bold text-xl text-tx-primary leading-tight">{session.name}</h1>
</div>
<div className="flex items-center gap-1">
<button onClick={handleMinimize} className="p-2 hover:bg-surface-muted rounded-xl transition-colors text-tx-muted" aria-label={t('gym.minimize')}>
<Minimize2 className="w-4 h-4" />
</button>
<button onClick={() => setConfirmCancel(true)} aria-label={t('gym.discardWorkout')} title={t('gym.discardWorkout')} className="p-2 hover:bg-surface-muted rounded-xl transition-colors text-tx-muted hover:text-error-400">
<X className="w-5 h-5" />
</button>
</div>
</div>
{/* Stats strip */}
<div className="grid grid-cols-3 gap-3 px-5 py-4 border-b border-surface-border flex-shrink-0">
<div className="text-center">
<p className="text-xl font-bold text-tx-primary tabular-nums">{session.exercises.length}</p>
<p className="text-[10px] text-tx-muted uppercase tracking-wide mt-0.5">{t('gym.overview.exercises')}</p>
</div>
<div className="text-center">
<p className="text-xl font-bold text-tx-primary tabular-nums">{totalSets}</p>
<p className="text-[10px] text-tx-muted uppercase tracking-wide mt-0.5">{t('gym.overview.totalSets')}</p>
</div>
<div className="text-center">
<p className="text-xl font-bold text-tx-primary tabular-nums">
{[...new Set(session.exercises.map(e => e.exercise.muscle_group))].length}
</p>
<p className="text-[10px] text-tx-muted uppercase tracking-wide mt-0.5">{t('gym.overview.muscles')}</p>
</div>
</div>
{/* Exercise list */}
<div className="flex-1 overflow-y-auto px-5 py-3">
{session.exercises.length === 0 ? (
<div className="flex flex-col items-center justify-center py-16 gap-3">
<Dumbbell className="w-10 h-10 text-tx-muted/30" />
<p className="text-sm text-tx-muted">{t('gym.overview.empty')}</p>
</div>
) : (
<div className="space-y-2">
{session.exercises.map((ex, i) => {
const done = ex.sets.length > 0 && ex.sets.every(s => s.completed)
return (
<div key={i} className={`flex items-center gap-3 p-3 rounded-2xl border transition-all ${
done ? 'border-brand-500/30 bg-brand-500/[0.04]' : 'border-surface-border bg-surface-base'
}`}>
<div className="flex-shrink-0 w-8 h-8 rounded-full bg-surface-muted border border-surface-border flex items-center justify-center">
<span className={`text-sm font-bold ${done ? 'text-brand-400' : 'text-tx-muted'}`}>{i + 1}</span>
</div>
{ex.exercise.image_url ? (
<img src={ex.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">
<Dumbbell className="w-4 h-4 text-brand-500" />
</div>
)}
<div className="flex-1 min-w-0">
<p className="text-sm font-semibold text-tx-primary truncate">{ex.exercise.name}</p>
<div className="flex items-center gap-2 mt-0.5">
<span className={`inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-medium ${muscleColor(ex.exercise.muscle_group)}`}>
{muscleLabel(ex.exercise.muscle_group)}
</span>
<span className="text-[10px] text-tx-muted">{t('common.count.sets', { count: ex.sets.length })}</span>
</div>
</div>
{done && <CheckCircle2 className="w-4 h-4 text-brand-400 flex-shrink-0" />}
</div>
)
})}
</div>
)}
</div>
{/* Bottom actions */}
<div className="px-5 pb-6 pt-4 border-t border-surface-border flex-shrink-0 space-y-2">
<button
onClick={() => navigate('/workout/active/add-exercise')}
className="w-full py-3 bg-surface-muted/60 hover:bg-surface-muted border border-surface-border hover:border-brand-500/40 rounded-2xl text-sm font-medium text-tx-secondary hover:text-brand-400 transition-colors flex items-center justify-center gap-2"
>
<Plus className="w-4 h-4" />
{t('workouts.active.addExercise')}
</button>
{session.exercises.length > 0 && (
<button
onClick={() => setGymState('exercise-info', 0, 0)}
className="w-full py-4 bg-brand-500 hover:bg-brand-600 text-white rounded-2xl text-base font-bold flex items-center justify-center gap-2 shadow-lg shadow-brand-500/30 transition-colors"
>
<Play className="w-5 h-5 fill-current" />
{t('gym.overview.startWorkout')}
</button>
)}
</div>
{trailing}
</div>
)
}
const ex = session.exercises[activeIdx]
if (!ex) { onSetActiveIdx(0); return null }
const isFirst = activeIdx === 0
const isLast = activeIdx === session.exercises.length - 1
// ── Exercise info ─────────────────────────────────────────────────────
if (phase === 'exercise-info') {
const exercise = ex.exercise
const equipLabel = equipmentLabel(exercise.equipment)
const descLines = exercise.description
? exercise.description.split('\n').filter(l => l.trim())
: []
const bodyData = buildBodyData(exercise)
// Plan summary: one value if every set matches, else a min–max range.
const repsVals = ex.sets.map(s => s.target_reps).filter(r => r > 0)
const wtVals = ex.sets.map(s => displayWeight(s.target_weight, wUnit)).filter(w => w > 0)
const planStats = [
{ icon: Layers, label: t('gym.labels.sets'), value: <>{ex.sets.length}</> },
{ icon: Repeat, label: t('gym.labels.reps'), value: <>{numericRange(repsVals)}</> },
{ icon: Dumbbell, label: t('gym.labels.weight'), value: <>{numericRange(wtVals)}<span className="text-xs font-semibold text-tx-muted ml-0.5">{wUnit}</span></> },
]
return (
<div role="dialog" aria-modal="true" aria-label={t('gym.workout')} className="fixed inset-0 z-[60] bg-surface-base overflow-y-auto flex flex-col">
<TopBar s={session} onBack={() => isFirst ? setPhase('overview') : setGymState('exercise', activeIdx - 1, 0)} />
<div className="flex-1 overflow-y-auto">
{/* Hero image */}
{exercise.image_url && !imgFailed && (
<img
src={exercise.image_url}
alt={exercise.name}
onError={() => setImgFailed(true)}
className="w-full h-52 object-cover bg-surface-muted"
/>
)}
<div className="px-5 pt-5 pb-4 space-y-5">
{/* Name + muscle */}
<div>
<h2 className="font-display font-bold text-2xl text-tx-primary leading-tight">{exercise.name}</h2>
<div className="flex flex-wrap items-center gap-2 mt-2">
<span className={`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium border ${muscleColorBordered(exercise.muscle_group)}`}>
{muscleLabel(exercise.muscle_group)}
</span>
{equipLabel && exercise.equipment !== 'other' && (
<span className="inline-flex items-center px-3 py-1 rounded-full bg-surface-muted border border-surface-border text-xs font-medium text-tx-secondary">
{equipLabel}
</span>
)}
{exercise.category && (
<span className="inline-flex items-center px-3 py-1 rounded-full bg-surface-muted border border-surface-border text-xs font-medium text-tx-secondary capitalize">
{categoryLabel(exercise.category)}
</span>
)}
</div>
</div>
{/* Plan — what you're about to do, as an icon stat strip */}
<div className="card p-4 grid grid-cols-3 divide-x divide-surface-border">
{planStats.map(({ icon: Ico, label, value }) => (
<div key={label} className="flex flex-col items-center gap-1.5 px-2">
<Ico className="w-4 h-4 text-brand-400" />
<span className="font-display font-bold text-xl text-tx-primary tabular-nums leading-none whitespace-nowrap">{value}</span>
<span className="text-[10px] font-medium text-tx-muted uppercase tracking-wider">{label}</span>
</div>
))}
</div>
{/* Rest timer for this exercise */}
<div className="card p-4">
<div className="flex items-center gap-2">
<Timer className="w-4 h-4 text-brand-500" />
<p className="text-xs font-semibold text-tx-muted uppercase tracking-wider">{t('gym.info.restTitle')}</p>
</div>
<p className="text-[11px] text-tx-muted mt-1 mb-3">{t('gym.info.restHint')}</p>
<RestPicker value={ex.rest_seconds ?? (settings.rest_seconds_default ?? 90)} onChange={secs => setExerciseRest(activeIdx, secs)} />
</div>
{/* Secondary muscles */}
{exercise.secondary_muscles?.length > 0 && (
<div>
<p className="text-xs font-semibold text-tx-muted uppercase tracking-wider mb-2">{t('exercises.detail.alsoWorks')}</p>
<div className="flex flex-wrap gap-1.5">
{exercise.secondary_muscles.map(m => (
<span key={m} className={`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${muscleColor(m)}`}>{muscleLabel(m)}</span>
))}
</div>
</div>
)}
{/* Muscle diagram */}
{bodyData.length > 0 && (
<div className="card p-4">
<p className="text-xs font-semibold text-tx-muted uppercase tracking-wider mb-3">{t('exercises.detail.musclesWorked')}</p>
<div className="flex items-start justify-center gap-6">
<div className="flex flex-col items-center gap-1">
<Model data={bodyData} type="anterior" bodyColor={bodyColor} highlightedColors={highlightColors} style={{ width: '120px' }} />
<span className="text-xs text-tx-muted">{t('exercises.detail.bodyFront')}</span>
</div>
<div className="flex flex-col items-center gap-1">
<Model data={bodyData} type="posterior" bodyColor={bodyColor} highlightedColors={highlightColors} style={{ width: '120px' }} />
<span className="text-xs text-tx-muted">{t('exercises.detail.bodyBack')}</span>
</div>
</div>
<div className="flex items-center gap-4 mt-3 justify-center">
<div className="flex items-center gap-1.5">
<div className="w-3 h-3 rounded-full" style={{ backgroundColor: '#22d3ee' }} />
<span className="text-xs text-tx-muted">{t('exercises.detail.primary')}</span>
</div>
<div className="flex items-center gap-1.5">
<div className="w-3 h-3 rounded-full" style={{ backgroundColor: '#0e7490' }} />
<span className="text-xs text-tx-muted">{t('exercises.detail.secondary')}</span>
</div>
</div>
</div>
)}
{/* Instructions */}
{descLines.length > 0 && (
<div className="card p-4">
<p className="text-xs font-semibold text-tx-muted uppercase tracking-wider mb-3">{t('exercises.detail.instructions')}</p>
<div className="space-y-2.5">
{descLines.map((line, i) => {
const stepMatch = line.match(/^(\d+\.)\s*(.*)/)
if (stepMatch) {
return (
<p key={i} className="text-sm text-tx-secondary leading-relaxed">
<span className="font-semibold text-tx-primary">{stepMatch[1]}</span>{' '}{stepMatch[2]}
</p>
)
}
return <p key={i} className="text-sm text-tx-secondary leading-relaxed">{line}</p>
})}
</div>
</div>
)}
</div>
</div>
{/* CTA */}
<div className="px-5 pb-6 pt-4 border-t border-surface-border flex-shrink-0">
<button
onClick={() => setPhase('exercise')}
className="w-full py-4 bg-brand-500 hover:bg-brand-600 text-white rounded-2xl text-base font-bold flex items-center justify-center gap-2 shadow-lg shadow-brand-500/30 transition-colors"
>
<Play className="w-5 h-5 fill-current" />
{t('gym.info.begin')}
</button>
</div>
{trailing}
</div>
)
}
// ── Exercise sets ─────────────────────────────────────────────────────
const allSetsComplete = ex.sets.length > 0 && ex.sets.every(s => s.completed)
const completedHere = ex.sets.filter(s => s.completed).length
const clampedSetIdx = Math.min(activeSetIdx, ex.sets.length - 1)
const set = ex.sets[clampedSetIdx]
const handleCompleteSetGym = (setIdx: number) => {
const wasCompleted = ex.sets[setIdx].completed
completeSet(activeIdx, setIdx)
if (wasCompleted) {
// Un-completing: cancel the running rest only if it belongs to this set.
if (restExIdx === activeIdx && restSetIdx === setIdx) clearRest()
return
}
// Completing: start rest (per-exercise value, else the global default; 0 = off).
if (settings.rest_enabled) {
const r = ex.rest_seconds ?? settings.rest_seconds_default ?? 90
if (r > 0) startRest(r, activeIdx, setIdx)
}
// Auto-advance to next incomplete set
const next = nextIncompleteSet(ex.sets, setIdx)
if (next !== -1) setActiveSetIdx(next)
}
const handleRemoveSet = (setIdx: number) => {
removeSet(activeIdx, setIdx)
setActiveSetIdx(Math.max(0, Math.min(setIdx, ex.sets.length - 2)))
}
const handleRemoveExercise = () => {
removeExercise(activeIdx)
const newLen = session.exercises.length - 1
if (newLen === 0) { setPhase('overview'); return }
onSetActiveIdx(Math.min(activeIdx, newLen - 1))
}
if (!set) return null
// Rest-timer view state for this exercise (restExIdx/restSetIdx are cleared or
// remapped by the store on structural edits, so they're safe to key on here).
const restingHere = restExIdx === activeIdx
return (
<div role="dialog" aria-modal="true" aria-label={t('gym.workout')} className="fixed inset-0 z-[60] bg-surface-base flex flex-col">
<TopBar s={session} onBack={() => setPhase('exercise-info')} />
{/* Exercise name + muscle (compact) */}
<div className="px-5 pt-4 pb-3 border-b border-surface-border flex-shrink-0">
<div className="flex items-center justify-between gap-2">
<div className="min-w-0">
<h2 className="font-display font-bold text-lg text-tx-primary leading-tight truncate">{ex.exercise.name}</h2>
<div className="flex items-center gap-2 mt-1">
<span className={`inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium ${muscleColor(ex.exercise.muscle_group)}`}>
{muscleLabel(ex.exercise.muscle_group)}
</span>
<span className="text-xs text-tx-muted tabular-nums">{t('workouts.active.setsDone', { done: completedHere, count: ex.sets.length })}</span>
</div>
</div>
{!allSetsComplete && (
<button onClick={handleRemoveExercise} aria-label={t('gym.removeExercise')} title={t('workouts.active.removeExercise')} className="p-1.5 hover:bg-error-500/10 rounded-lg transition-colors flex-shrink-0">
<Trash2 className="w-4 h-4 text-tx-muted hover:text-error-400 transition-colors" />
</button>
)}
</div>
<div className="mt-2">
<ExerciseNotes exIdx={activeIdx} notes={ex.notes} onSave={updateExerciseNotes} />
</div>
</div>
{/* The whole logging group (set chips, target, inputs, action). Scrollable +
min-h-0 so when the rest timer docks below and compresses this area the
content scrolls instead of clipping; m-auto keeps it centred when it fits. */}
<div className="flex-1 min-h-0 overflow-y-auto flex flex-col">
{/* m-auto (not justify-center): centres the group when it fits, and when the
docked rest panel leaves too little room (short phones) the auto margins
collapse and the group scrolls with EVERYTHING reachable — margin-auto is
scroll-stable where flex justify-center fights the scroll. No hardcoded
heights. Spacing tightens while resting; roomy otherwise. */}
<div className={`m-auto w-full flex flex-col items-center px-5 ${restingHere ? 'gap-4 py-2' : 'gap-6 py-4'}`}>
{/* Set selector — one chip per set: active filled, done shows a check.
Progress + navigation in one place (replaced the old dots + big number). */}
<div className="flex items-center justify-center flex-wrap gap-2">
{ex.sets.map((s, i) => {
// Set ↔ timer linkage: while resting, the chip of the set that started
// the timer keeps a subtle brand ring so it reads as "resting after
// this one" even though focus auto-advanced to the next set.
const resting = restingHere && restSetIdx === i
return (
<button
key={i}
onClick={() => setActiveSetIdx(i)}
aria-label={t(
s.completed
? (resting ? 'gym.set.chipDoneResting' : 'gym.set.chipDone')
: (resting ? 'gym.set.chipResting' : 'gym.set.chip'),
{ number: i + 1 },
)}
aria-current={i === clampedSetIdx}
className={`flex items-center justify-center gap-1 min-w-[2.75rem] h-10 px-3 rounded-full text-sm font-bold tabular-nums transition-all active:scale-95 ${
i === clampedSetIdx ? 'bg-brand-500 text-white shadow-sm shadow-brand-500/30' :
s.completed ? `bg-brand-500/15 text-brand-400${resting ? ' ring-1 ring-brand-500/60' : ''}` :
'bg-surface-muted text-tx-muted hover:text-tx-secondary'
}`}
>
{s.completed && <Check className="w-3.5 h-3.5" />}
{i + 1}
</button>
)
})}
</div>
{/* Target reference for this set (the goal to hit) */}
{(set.target_reps > 0 || set.target_weight > 0) && (
<p className="text-sm text-tx-muted text-center">
{t('gym.target.label')}{' '}
<span className="font-semibold text-tx-secondary tabular-nums">{set.target_reps > 0 ? t('common.count.reps', { count: set.target_reps }) : t('gym.target.repsUnknown')}</span>
{set.target_weight > 0 && (
<> · <span className="font-semibold text-tx-secondary tabular-nums">{displayWeight(set.target_weight, wUnit)} {wUnit}</span></>
)}
</p>
)}
{/* Reps + Weight — a tile per metric: icon header, big value, split ⊖/⊕ footer.
Value spans the full tile (buttons are below, not flanking) so long
weights never clip. */}
<div className="w-full grid grid-cols-2 gap-3">
{/* Reps — key by set so a half-typed value can't bleed to the next set */}
<StepperTile
icon={Repeat} label={t('gym.labels.reps')} name={t('gym.labels.repsName')} step={REP_STEP} disabled={set.completed}
onStep={d => updateSet(activeIdx, clampedSetIdx, 'actual_reps', clampStep(set.actual_reps || 0, d, { min: 0 }))}
>
<NumberField
key={`reps-${activeIdx}-${clampedSetIdx}`}
inputMode="numeric"
value={set.actual_reps ? String(set.actual_reps) : ''}
onChange={v => updateSet(activeIdx, clampedSetIdx, 'actual_reps', Math.round(clampValue(v)))}
placeholder={set.target_reps > 0 ? String(set.target_reps) : '0'}
disabled={set.completed}
aria-label={t('gym.labels.reps')}
/>
</StepperTile>
{/* Weight */}
<StepperTile
icon={Dumbbell} label={t('common.weightWithUnit', { unit: wUnit })} name={t('common.weightName')} step={PLATE_STEP} disabled={set.completed}
onStep={d => updateSet(activeIdx, clampedSetIdx, 'actual_weight', displayToLbs(clampStep(displayWeight(set.actual_weight, wUnit), d, { min: 0 }), wUnit))}
>
<NumberField
key={`wt-${activeIdx}-${clampedSetIdx}`}
inputMode="decimal"
value={set.actual_weight ? String(displayWeight(set.actual_weight, wUnit)) : ''}
onChange={v => updateSet(activeIdx, clampedSetIdx, 'actual_weight', displayToLbs(clampValue(v), wUnit))}
placeholder={set.target_weight > 0 ? String(displayWeight(set.target_weight, wUnit)) : '0'}
disabled={set.completed}
aria-label={t('gym.labels.weight')}
/>
</StepperTile>
</div>
<div className="w-full flex flex-col items-center gap-6">
{/* Complete button */}
<button
onClick={() => handleCompleteSetGym(clampedSetIdx)}
className={`w-full py-5 rounded-2xl text-base font-bold flex items-center justify-center gap-3 transition-all ${
set.completed
? 'bg-brand-500/15 border-2 border-brand-500/40 text-brand-400'
: 'bg-brand-500 hover:bg-brand-600 text-white shadow-lg shadow-brand-500/30'
}`}
>
<CheckCircle2 className="w-6 h-6" />
{set.completed ? t('gym.completed') : t('gym.completeSet')}
</button>
{/* Remove set — hidden on the last set (removing it would empty the exercise
and drop to a blank screen; use the header trash to remove the exercise) */}
{ex.sets.length > 1 && (
<button
onClick={() => handleRemoveSet(clampedSetIdx)}
className="text-xs text-tx-muted/50 hover:text-error-400 transition-colors"
>
{t('gym.removeSet')}
</button>
)}
</div>
</div>
</div>
{/* Bottom nav */}
<div className="px-5 pb-6 pt-3 border-t border-surface-border flex-shrink-0 space-y-2">
{/* Set prev/next + add */}
<div className="flex gap-2">
<button
onClick={() => setActiveSetIdx(clampedSetIdx - 1)}
disabled={clampedSetIdx === 0}
className="p-3 rounded-xl bg-surface-muted hover:bg-surface-muted/80 border border-surface-border text-tx-secondary transition-colors disabled:opacity-30 disabled:pointer-events-none"
>
<ChevronLeft className="w-4 h-4" />
</button>
<button
onClick={() => { addSet(activeIdx); setActiveSetIdx(ex.sets.length) }}
className="flex-1 py-3 flex items-center justify-center gap-1.5 rounded-xl border border-dashed border-surface-border hover:border-brand-500/40 hover:bg-brand-500/5 text-xs font-medium text-tx-muted hover:text-brand-400 transition-colors"
>
<Plus className="w-3.5 h-3.5" />
{t('workouts.active.addSet')}
</button>
<button
onClick={() => setActiveSetIdx(clampedSetIdx + 1)}
disabled={clampedSetIdx >= ex.sets.length - 1}
className="p-3 rounded-xl bg-surface-muted hover:bg-surface-muted/80 border border-surface-border text-tx-secondary transition-colors disabled:opacity-30 disabled:pointer-events-none"
>
<ChevronRight className="w-4 h-4" />
</button>
</div>
{/* Exercise prev/next */}
<div className="flex gap-2">
<button
onClick={() => setPhase('exercise-info')}
className="flex items-center gap-1.5 px-4 py-3 rounded-xl bg-surface-muted hover:bg-surface-muted/80 border border-surface-border text-tx-secondary text-sm font-medium transition-colors"
>
<ChevronLeft className="w-4 h-4" />
{t('gym.nav.info')}
</button>
{isLast ? (
<button
onClick={() => setConfirmFinish(true)}
className={`flex-1 py-3 rounded-xl text-sm font-bold flex items-center justify-center gap-2 transition-all ${
allSetsComplete
? 'bg-brand-500 hover:bg-brand-600 text-white shadow-lg shadow-brand-500/30'
: 'bg-brand-500/10 hover:bg-brand-500/20 text-brand-400 border border-brand-500/30'
}`}
>
<Flag className="w-4 h-4" />
{t('gym.nav.finishWorkout')}
</button>
) : (
<button
onClick={() => setGymState('exercise-info', activeIdx + 1, 0)}
className={`flex-1 py-3 rounded-xl text-sm font-bold flex items-center justify-center gap-2 transition-all ${
allSetsComplete
? 'bg-brand-500 hover:bg-brand-600 text-white shadow-lg shadow-brand-500/30'
: 'bg-surface-muted hover:bg-surface-muted/80 text-tx-secondary border border-surface-border'
}`}
>
{t('gym.nav.nextExercise')}
<ChevronRight className="w-4 h-4" />
</button>
)}
</div>
</div>
{trailing}
</div>
)
}