import { useEffect, useRef, 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
/* ============================ 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')
}
/* ============================ body weight ============================ */
function BwSheet({ required, onDone, close }) {
const st = useStore(s => s.S)
const unit = st.unit
const bw = lastBW(st)
const start = bw ? bw.w : 70
const [v, setV] = useState(start)
const clamp = x => Math.max(20, Math.min(300, Math.round((x || 0) * 10) / 10))
const set = x => setV(clamp(x)) // absolute (slider)
const step = d => setV(p => clamp(p + d)) // relative (buttons/chips) β safe for rapid taps
// fixed slider window around the starting value (buttons/quick chips can go beyond)
const lo = Math.max(30, Math.round(start - 20))
const hi = Math.min(250, Math.round(start + 20))
const save = () => {
const n = clamp(v)
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, 6)
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)}
step(-0.1)} aria-label="minus">β
{fmtNum(v)} {unit}
step(0.1)} aria-label="plus">+
set(parseFloat(e.target.value))}
style={{ '--track': `linear-gradient(90deg, var(--acc) ${((Math.max(lo, Math.min(hi, v)) - lo) / (hi - lo)) * 100}%, var(--bg2) ${((Math.max(lo, Math.min(hi, v)) - lo) / (hi - lo)) * 100}%)` }} />
{required ? 'Save & start workout' : 'Save'}
{required && <>
{ close(); onDone && onDone(null) }}>Skip today
{ close(); nav('/workout') }}>βΊ Choose a different workout
>}
{!required && recent.length > 0 && <>
Recent weigh-ins
{recent.map(b =>
{fmtDate(b.d, true)}
{fmtNum(b.w)} {unit}
delEntry(b.d)} aria-label="delete">π
)}
>}
>
}
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 ? String(bw.w) : ''))
const ref = useRef(null)
useEffect(() => { setTimeout(() => { ref.current?.focus(); ref.current?.select() }, 250) }, [])
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.
setV(e.target.value)} placeholder="0.0" />{st.unit}
{
const n = parseFloat(v)
if (!n || n <= 0 || n > 400) { toast('Enter a valid weight'); return }
update(s => { s.targetW = n }); close()
const b = lastBW(S()); toast('Goal set: ' + fmtNum(n) + ' ' + st.unit + (b ? ' (' + fmtNum(Math.abs(n - b.w)) + ' to go)' : ''))
}}>Save goal
{st.targetW && <>
{ update(s => { s.targetW = null }); close(); toast('Goal removed') }}>Remove goal >}
>
}
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(', ')}` : ''}
}
addToRoutineSheet(ex)}>οΌ Add to my plan
{ex.st && ex.st.length > 0 && <>How to {ex.st.map((s, i) => {s} )} >}
>
}
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
{chosenCount > 0 && { setBp('β
'); setShown(50) }}>β Chosen ({chosenCount}) }
{ setBp(''); setShown(50) }}>All
{BODYPARTS.map(b => { setBp(b); setShown(50) }}>{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 && <>
setShown(s => s + 50)}>Show more >}
>
}
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 }))} />
>}
{existing ? 'Save' : 'Add to routine'}
{onDelete && <>
{ close(); onDelete() }}>Remove exercise >}
>
}
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 => { close(); onPick(e) }}>{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 &&
}
>
}
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('')}>
{!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'}
})}
{ if (confirm('Delete this workout from history?')) { update(s => { s.workouts = s.workouts.filter(x => x.id !== w.id) }); close(); toast('Workout deleted') } }}>Delete workout
>
}
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( {
if (!ws) { close(); dayOverrideSheet(iso); return }
if (ws.length === 1) { close(); workoutDetailSheet(ws[0]); return }
close(); ui().openSheet(c2 => <>{fmtDate(iso, true)} {ws.map(w => { c2(); workoutDetailSheet(w) }} />)}
>)
}}>{d} )
}
return <>
setCur(new Date(y, mo - 1, 1))}>βΉ
{MONTHS_LONG[mo]} {y}
setCur(new Date(y, mo + 1, 1))}>βΊ
{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(String(Math.max(maxSet, prevBest) || entry.target.weight || 0))
const ref = useRef(null)
useEffect(() => { setTimeout(() => { ref.current?.focus(); ref.current?.select() }, 250) }, [])
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 = parseFloat(v)
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.' : ''}
setV(e.target.value)} />{st.unit}
{prevBest > 0 ? Previous best: {fmtNum(prevBest)} {st.unit}{maxSet > prevBest && β new record! π }
:
}
{unitDone ? <>
commit(true)}>{isLastUnit ? 'Save β' : 'Save & next exercise βΊ'}
commit(false)}>Just close
> : commit(false)}>Save weight }
>
}
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.
{ close(); finishWorkout() }}>Finish workout π
{ close(); useUI.getState().toast('Keep going πͺ β tap β+ Add exerciseβ below') }}>Continue workout
}
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)}
PRs
{prs.length ? 'π ' + prs.length : 'β'}
{prs.length > 0 &&
{prs.map(id =>
π New PR: {(EXIDX[id] || {}).n || id}
)}
}
{ close(); nav('/home') }}>Nice! πͺ
}
export function finishWorkout() {
const st = S()
const A = st.active
if (!A) return
const done = setsDoneActive(A)
const total = A.entries.reduce((n, e) => n + e.sets.length, 0)
if (!done && !confirm('No sets logged β finish anyway?')) return
if (done < total && done > 0 && !confirm('Some sets are unchecked. Finish workout?')) 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 })
}