import { useEffect, useState } from 'react' import { useStore } from './store/useStore.js' import { useUI } from './store/useUI.js' import { EXDB, EXIDX, BODYPARTS, isCardio } from './lib/exercises.js' import { fmtDate, fmtNum, fmtVol, fmtDur, todayISO, uid, DAYN, MONTHS_LONG, ACCENTS } from './lib/format.js' import { lastEntryFor, bestWeightFor, buildSets, effectiveRoutineId, workoutVolume, setsDone, setsDoneActive, lastBW, supersetUnits, unitOf, setLabel, defaultConfig } from './lib/history.js' import { beep, vibrate } from './lib/sound.js' import { nav } from './lib/nav.js' import Media, { Thumb } from './components/Media.jsx' import Stepper from './components/Stepper.jsx' const S = () => useStore.getState().S const update = (...a) => useStore.getState().update(...a) const ui = () => useUI.getState() const toast = m => ui().toast(m) const snd = () => S().sound /* ============================ custom confirm dialog ============================ */ function ConfirmDialog({ title, message, confirmText, cancelText, danger, onConfirm, close }) { return
{title &&

{title}

}
{message}
} // Themed replacement for window.confirm β€” callback-based (no blocking). export function confirmSheet(opts) { ui().openSheet(close => , { kind: 'center' }) } /* ============================ starter plan ============================ */ export function loadStarterPlan() { const mk = (name, emoji, list) => ({ id: uid(), name, emoji, ex: list.map(([id, sets, reps]) => ({ id, sets, reps, weight: 0 })) }) update(st => { const push = mk('Push Day', '🫸', [['0025', 4, 8], ['0047', 3, 10], ['0426', 3, 10], ['0334', 3, 12], ['0241', 3, 12], ['0251', 3, 10]]) const pull = mk('Pull Day', '🫷', [['2330', 4, 10], ['0027', 4, 8], ['1323', 3, 10], ['0031', 3, 10], ['0313', 3, 12]]) const legs = mk('Leg Day', '🦡', [['0043', 4, 8], ['0085', 3, 10], ['0739', 3, 12], ['0585', 3, 12], ['0586', 3, 12], ['0605', 4, 15]]) st.routines.push(push, pull, legs) st.week[1] = push.id; st.week[3] = pull.id; st.week[5] = legs.id }) toast('Starter plan loaded β€” Mon Push Β· Wed Pull Β· Fri Legs') } /* ============================ weight picker (shared: body weight + goal) ============================ */ // Fixed range, not a moving window β€” a window that resizes itself mid-drag (the previous // attempt) makes the thumb's position unpredictable: every time it grows, everything already // placed on it shifts toward one side. A static range never has that problem, at the cost of // coarser precision per pixel β€” the +/- buttons cover exact values. const W_LO = 1, W_HI = 300 function WeightInput({ value, setValue, unit }) { const clamp = x => Math.max(W_LO, Math.min(W_HI, Math.round((x || 0) * 10) / 10)) const sv = Math.max(W_LO, Math.min(W_HI, value)) const pct = ((sv - W_LO) / (W_HI - W_LO)) * 100 const onSlide = v => setValue(clamp(v)) return <>
{fmtNum(value)} {unit}
onSlide(parseFloat(e.target.value))} style={{ '--track': `linear-gradient(90deg, var(--acc) ${pct}%, var(--bg2) ${pct}%)` }} /> } /* ============================ body weight ============================ */ function BwSheet({ required, onDone, close }) { const st = useStore(s => s.S) const unit = st.unit const bw = lastBW(st) const [v, setV] = useState(bw ? bw.w : 70) const save = () => { const n = Math.round((v || 0) * 10) / 10 if (!n || n <= 0) { toast('Enter a valid weight'); return } update(s => { const iso = todayISO() const ex = s.bodyweight.find(b => b.d === iso) if (ex) { ex.w = n; ex.t = Date.now() } else s.bodyweight.push({ d: iso, w: n, t: Date.now() }) s.bodyweight.sort((a, b) => (a.d < b.d ? -1 : 1)) }) close() if (onDone) onDone(n); else toast('Weight saved βœ“') } const recent = [...st.bodyweight].reverse().slice(0, 3) const delEntry = d => update(s => { s.bodyweight = s.bodyweight.filter(b => b.d !== d) }) return <>

{required ? 'Quick check-in βš–οΈ' : 'Log body weight'}

{required ? 'Slide or tap to set your weight β€” tracked before every workout so your curve stays honest.' : 'Today, ' + fmtDate(todayISO(), true)}
{required && <>
} {!required && recent.length > 0 && <>

Recent weigh-ins

{recent.map(b =>
{fmtDate(b.d, true)} {fmtNum(b.w)} {unit}
)}
} } export function bwSheet(opts = {}) { const h = ui().openSheet(close => , { locked: !!opts.required }) return h } /* ============================ target weight ============================ */ export function bwDeltaColor(delta, currentW) { if (!delta) return 'var(--mut)' if (!S().targetW) return 'var(--txt)' const up = S().targetW > currentW return (delta > 0) === up ? 'var(--acc)' : 'var(--red)' } function GoalSheet({ close }) { const st = S() const bw = lastBW(st) const [v, setV] = useState(st.targetW || (bw ? bw.w : 70)) return <>

Target weight 🎯

Your goal is drawn as a line through the weight charts, and gains/losses are colored by whether they move toward it.
{st.targetW && <>
} } export const goalSheet = () => ui().openSheet(close => ) /* ============================ exercise detail ============================ */ function ExerciseDetail({ ex }) { const st = useStore(s => s.S) const last = lastEntryFor(st, ex.id) const best = bestWeightFor(st, ex.id) return <>

{ex.n}

{ex.bp} {ex.tg && 🎯 {ex.tg}} πŸ›  {ex.eq} {(ex.sm || []).slice(0, 3).map((s, i) => {s})}
{best > 0 &&
πŸ† Best: {fmtNum(best)} {st.unit}{last ? ` Β· last ${fmtDate(last.d)}: ${last.sets.map(s => setLabel(ex.id, s)).join(', ')}` : ''}
} {ex.st && ex.st.length > 0 && <>

How to

    {ex.st.map((s, i) =>
  1. {s}
  2. )}
} } export const exerciseDetailSheet = ex => ui().openSheet(() => ) /* ============================ add to routine ============================ */ function AddToRoutine({ ex, close }) { const st = useStore(s => s.S) const pick = rid => { close() const isNew = rid === '_new' exConfigSheet(ex, null, cfg => { update(s => { let r = isNew ? { id: uid(), name: 'New routine', emoji: 'πŸ’ͺ', ex: [] } : s.routines.find(x => x.id === rid) if (isNew) s.routines.push(r) if (r) r.ex.push({ id: ex.id, ...cfg }) }) const r = isNew ? S().routines[S().routines.length - 1] : st.routines.find(x => x.id === rid) toast('β€œ' + ex.n + '” added to ' + (r ? r.name : 'routine') + ' βœ“') if (isNew && r) nav('/plan/r/' + r.id) }) } return <>

Add β€œ{ex.n}”

Pick a routine β€” sets, reps & weight come next.
{st.routines.map(r =>
pick(r.id)}>
{r.emoji || 'πŸ’ͺ'}
{r.name}
{r.ex.length} exercises
{r.ex.some(e => e.id === ex.id) && already in}οΌ‹
)}
pick('_new')}>
✨
New routine
Create one and start with this exercise
οΌ‹
} export const addToRoutineSheet = ex => ui().openSheet(close => ) /* ============================ exercise picker ============================ */ // Exercises already used in your routines or past workouts (for the "Chosen" filter + a marker). function usageMap(st) { const u = {} st.routines.forEach(r => r.ex.forEach(e => { u[e.id] = (u[e.id] || 0) + 1 })) st.workouts.forEach(w => w.entries.forEach(e => { u[e.id] = (u[e.id] || 0) + 1 })) return u } function ExercisePicker({ onPick, close }) { const st = useStore(s => s.S) const usage = usageMap(st) const [q, setQ] = useState('') const [bp, setBp] = useState('') // '' = all, 'β˜…' = chosen, else a body part const [shown, setShown] = useState(50) const ql = q.toLowerCase().trim() let f = EXDB.filter(e => (bp === 'β˜…' ? usage[e.id] : (!bp || e.bp === bp)) && (!ql || e.n.includes(ql) || e.tg.includes(ql) || e.eq.includes(ql))) if (bp === 'β˜…') f = [...f].sort((a, b) => (usage[b.id] - usage[a.id]) || (a.n < b.n ? -1 : 1)) const chosenCount = Object.keys(usage).length return <>

Add exercise

{ setQ(e.target.value); setShown(50) }} />
{chosenCount > 0 && } {BODYPARTS.map(b => )}
{f.slice(0, shown).map(e =>
onPick(e)}>
{e.n}
{(e.tg || e.bp)} Β· {e.eq}
{usage[e.id] && ⭐}+
)} {f.length === 0 &&
{bp === 'β˜…' ? 'Nothing chosen yet β€” add exercises and they’ll show up here.' : 'No match 🀷'}
}
{f.length > shown && <>
} } export const exercisePicker = onPick => ui().openSheet(close => ) /* ============================ exercise config ============================ */ function ExConfig({ ex, existing, onSave, onDelete, close }) { const st = useStore(s => s.S) const cardio = isCardio(ex.id) const [c, setC] = useState(existing || defaultConfig(ex.id)) const save = () => { close() if (cardio) onSave({ sets: Math.max(1, Math.round(c.sets) || 1), min: Math.max(1, Math.round(c.min) || 20), speed: Math.max(0, c.speed || 8) }) else onSave({ sets: Math.max(1, Math.round(c.sets) || 3), reps: Math.max(1, Math.round(c.reps) || 10), weight: Math.max(0, c.weight || 0) }) } return <>

{ex.n}

{cardio && πŸƒ Cardio} {ex.tg || ex.bp}{ex.eq}
{cardio ? <> setC(x => ({ ...x, sets: v }))} /> setC(x => ({ ...x, min: v }))} /> setC(x => ({ ...x, speed: v }))} /> : <> setC(x => ({ ...x, sets: v }))} /> setC(x => ({ ...x, reps: v }))} /> setC(x => ({ ...x, weight: v }))} /> }
{onDelete && <>
} } export const exConfigSheet = (ex, existing, onSave, onDelete) => ui().openSheet(close => ) /* ============================ emoji picker ============================ */ const ROUTINE_EMOJIS = ['πŸ’ͺ', 'πŸ‹οΈ', 'πŸ‹οΈβ€β™€οΈ', '🦡', '🦾', '🫸', '🫷', 'πŸ”₯', '⚑', 'πŸ’₯', 'πŸƒ', 'πŸƒβ€β™€οΈ', '🚴', '🏊', '🀸', 'πŸ₯Š', 'πŸ§—', '⛰️', 'πŸ”οΈ', 'πŸš€', '🧘', 'πŸ§˜β€β™€οΈ', '🎯', 'πŸ†', 'πŸ₯‡', '⭐', '🌟', 'πŸ‘‘', 'πŸ›‘οΈ', 'βš”οΈ', '🦍', 'πŸ‚', '🐻', '🦁', '🐺', '🦈', '😀', 'πŸ€–', '🧨', '❀️‍πŸ”₯'] export const emojiPicker = (current, onPick) => ui().openSheet(close => <>

Pick an emoji

{ROUTINE_EMOJIS.map(e => )}
) /* ============================ day override / assign ============================ */ function DayOverride({ iso, close }) { const st = useStore(s => s.S) const wd = new Date(iso + 'T12:00:00').getDay() const weeklyR = st.routines.find(r => r.id === st.week[wd]) const hasOvr = st.dayPlan[iso] !== undefined const effId = effectiveRoutineId(st, iso) const set = v => { update(s => { if (!v) delete s.dayPlan[iso]; else s.dayPlan[iso] = v }) close() toast(v === '' ? 'Back to weekly plan' : v === 'rest' ? fmtDate(iso) + ' set to rest' : (st.routines.find(r => r.id === v) || {}).name + ' planned for ' + fmtDate(iso) + ' βœ“') } return <>

{fmtDate(iso, true)}

Weekly plan: {weeklyR ? weeklyR.name : 'Rest'}{hasOvr && Β· changed for this day}
Sick, missed a day or want a different session? Pick what to train instead.
{st.routines.map(r =>
set(r.id)}>
{r.emoji || 'πŸ’ͺ'}
{r.name}
{r.ex.length} exercises
{effId === r.id && βœ“}
)}
set('rest')}>
😌 Rest / skip this day
{effId === null && βœ“}
{hasOvr &&
set('')}>
β†Ί Back to weekly plan
}
} export const dayOverrideSheet = iso => ui().openSheet(close => ) function DayAssign({ day, close }) { const st = useStore(s => s.S) const set = v => { update(s => { if (v) s.week[day] = v; else delete s.week[day] }); close() } return <>

{DAYN[day]}

set('')}>
😌 Rest day
{!st.week[day] && βœ“}
{st.routines.map(r =>
set(r.id)}>
{r.emoji || 'πŸ’ͺ'}
{r.name}
{r.ex.length} exercises
{st.week[day] === r.id && βœ“}
)}
} export const dayAssignSheet = day => ui().openSheet(close => ) /* ============================ workout detail ============================ */ function WorkoutDetail({ w, close }) { const st = useStore(s => s.S) return <>

{w.name}

{fmtDate(w.d, true)} Β· {fmtDur(w.end - w.start)} Β· {fmtVol(w.vol, st.unit)}{w.bw ? ' Β· βš–οΈ ' + fmtNum(w.bw) + ' ' + st.unit : ''}
{w.entries.map((e, i) => { const ex = EXIDX[e.id] return
{ex && }
{ex ? ex.n : e.id} {w.prs && w.prs.includes(e.id) && πŸ† PR}
{e.sets.filter(s => s.done).map(s => setLabel(e.id, s)).join(' Β· ') || 'no sets'}
})} } export const workoutDetailSheet = w => ui().openSheet(close => ) /* ============================ calendar ============================ */ function Calendar({ start, close }) { const st = useStore(s => s.S) const [cur, setCur] = useState(() => { const d = start ? new Date(start) : new Date(); d.setDate(1); return d }) const y = cur.getFullYear(), mo = cur.getMonth() const byDay = {} st.workouts.forEach(w => (byDay[w.d] = byDay[w.d] || []).push(w)) const startOffset = (new Date(y, mo, 1).getDay() + 6) % 7 const daysIn = new Date(y, mo + 1, 0).getDate() const monthWs = st.workouts.filter(w => w.d.startsWith(y + '-' + String(mo + 1).padStart(2, '0'))) const monthVol = monthWs.reduce((a, w) => a + (w.vol || 0), 0) const monthMs = monthWs.reduce((a, w) => a + Math.max(0, (w.end || w.start) - w.start), 0) const cells = [] for (let i = 0; i < startOffset; i++) cells.push(
) for (let d = 1; d <= daysIn; d++) { const iso = y + '-' + String(mo + 1).padStart(2, '0') + '-' + String(d).padStart(2, '0') const ws = byDay[iso], effId = effectiveRoutineId(st, iso), ovr = st.dayPlan[iso] !== undefined const dotCls = ws ? 'done' : ovr && effId ? 'ovr' : effId ? 'plan' : '' cells.push() } return <>

{MONTHS_LONG[mo]} {y}

{monthWs.length ? `${monthWs.length} workout${monthWs.length > 1 ? 's' : ''} Β· ${fmtDur(monthMs)} Β· ${fmtVol(monthVol, st.unit)}` : 'No workouts this month'}
{['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'].map(l =>
{l}
)}{cells}
Trained Planned Rescheduled
Tap a trained day for details Β· tap any other day to plan a session
} export const calendarSheet = start => ui().openSheet(close => ) /* shared small workout row (used in lists) */ export function WorkoutRow({ w, onClick }) { const st = useStore(s => s.S) const emoji = (st.routines.find(r => r.id === w.routineId) || {}).emoji || 'πŸ’ͺ' return
{emoji}
{w.name}
{fmtDate(w.d, true)} Β· {fmtDur(w.end - w.start)} Β· {setsDone(w)} sets Β· {fmtVol(w.vol, st.unit)}
{w.prs && w.prs.length > 0 && πŸ† {w.prs.length} PR} β€Ί
} /* ============================ workout lifecycle ============================ */ export function startFlow(routineId) { bwSheet({ required: true, onDone: bw => beginWorkout(routineId, bw) }) } export function beginWorkout(routineId, bw) { const st = S() const r = routineId ? st.routines.find(x => x.id === routineId) : null const entries = (r ? r.ex : []).map(cfg => ({ id: cfg.id, sg: cfg.sg, target: { ...cfg }, sets: buildSets(st, cfg) })) update(s => { s.active = { id: uid(), d: todayISO(), start: Date.now(), routineId, name: r ? r.name : 'Freestyle', bw: bw || null, cur: 0, entries } }) useUI.getState().stopRest() nav('/workout') } function TopWeight({ entryIdx, close }) { const st = useStore(s => s.S) const A = st.active const entry = A.entries[entryIdx] const ex = EXIDX[entry.id] const maxSet = Math.max(0, ...entry.sets.filter(s => s.done).map(s => s.w || 0)) const prevBest = Math.max((st.exWeights[entry.id] || {}).w || 0, bestWeightFor(st, entry.id)) const [v, setV] = useState(Math.max(maxSet, prevBest) || entry.target.weight || 0) const units = supersetUnits(A.entries) const unit = unitOf(units, entryIdx) const unitDone = unit.every(i => A.entries[i].sets.every(s => s.done)) const unitIdx = units.findIndex(u => u === unit) const isLastUnit = unitIdx === units.length - 1 const commit = advance => { const n = Math.round((v || 0) * 10) / 10 if (!isFinite(n) || n < 0) { toast('Enter a valid weight'); return } update(s => { s.active.entries[entryIdx].topW = n const cur = s.exWeights[entry.id] s.exWeights[entry.id] = { w: Math.max(n, cur ? cur.w : 0), d: todayISO() } }) close() if (advance && unitDone) { if (isLastUnit) workoutCompleteSheet() // whole workout done β†’ finish/continue prompt else update(s => { s.active.cur = units[unitIdx + 1][0] }) } else toast('Tracked β€” next time starts at ' + fmtNum(S().exWeights[entry.id].w) + ' ' + st.unit + ' πŸ“ˆ') } return <>

βœ… {ex.n} done

Confirm the weight you worked with β€” your highest becomes the default next time.{!unitDone && unit.length > 1 ? ' Then finish the superset partner.' : ''}
{prevBest > 0 ?
Previous best: {fmtNum(prevBest)} {st.unit}{maxSet > prevBest && β€” new record! πŸ†}
:
} {unitDone ? <>
: } } export const topWeightSheet = entryIdx => ui().openSheet(close => ) // Shown when the last exercise's last set is checked β€” finish, or keep going. function WorkoutComplete({ close }) { return
πŸŽ‰

That's the whole workout!

Every exercise done β€” great work. Finish up, or keep going and add another exercise.
} export const workoutCompleteSheet = () => ui().openSheet(close => , { kind: 'center' }) function FinishSummary({ w, prs, close }) { const st = useStore(s => s.S) return
πŸŽ‰

Workout complete!

Duration
{fmtDur(w.end - w.start)}
Volume
{fmtVol(w.vol, st.unit)}
Sets
{setsDone(w)}
PRs
{prs.length ? 'πŸ† ' + prs.length : 'β€”'}
{prs.length > 0 &&
{prs.map(id =>
πŸ† New PR: {(EXIDX[id] || {}).n || id}
)}
}
} export function finishWorkout() { const A = S().active if (!A) return const done = setsDoneActive(A) const total = A.entries.reduce((n, e) => n + e.sets.length, 0) if (!done) { confirmSheet({ title: 'Nothing logged yet', message: 'You haven’t checked off any sets. Finish the workout anyway?', confirmText: 'Finish anyway', onConfirm: doFinishWorkout }); return } if (done < total) { confirmSheet({ title: 'Finish early?', message: `${total - done} set${total - done === 1 ? '' : 's'} still unchecked. Finish the workout now?`, confirmText: 'Finish workout', onConfirm: doFinishWorkout }); return } doFinishWorkout() } function doFinishWorkout() { const st = S() const A = st.active if (!A) return const prs = [] A.entries.forEach(e => { const mx = Math.max(0, ...e.sets.filter(s => s.done).map(s => s.w)) if (mx > 0 && mx > bestWeightFor(st, e.id)) prs.push(e.id) }) const w = { id: A.id, d: A.d, start: A.start, end: Date.now(), routineId: A.routineId, name: A.name, bw: A.bw, entries: A.entries.map(e => ({ id: e.id, sets: e.sets, topW: e.topW || null })).filter(e => e.sets.some(s => s.done)), prs } w.vol = workoutVolume(w) update(s => { w.entries.forEach(e => { const mx = Math.max(0, ...e.sets.filter(x => x.done).map(x => x.w || 0), e.topW || 0) if (mx > 0) { const cur = s.exWeights[e.id]; if (!cur || mx > cur.w) s.exWeights[e.id] = { w: mx, d: w.d } } }) s.workouts.push(w) s.active = null }) useUI.getState().stopRest() beep(snd(), 880, 0.15); beep(snd(), 1100, 0.15, 0.18); beep(snd(), 1320, 0.3, 0.36) ui().openSheet(close => , { kind: 'center', locked: true }) }