import { useEffect, useRef, useState } from 'react' import { useStore } from './store/useStore.js' import { useUI } from './store/useUI.js' import { EXDB, EXIDX, BODYPARTS, isCardio, isBodyweightEq, allExercises, equipmentOf } from './lib/exercises.js' import { fmtDate, fmtNum, fmtVol, fmtDur, durPart, todayISO, uid, exCount, DAYN, MONTHS_LONG, ACCENTS } from './lib/format.js' import { lastEntryFor, bestWeightFor, buildSets, effectiveRoutineId, workoutVolume, setsDone, setsDoneActive, lastBW, supersetUnits, unitOf, setLabel, defaultConfig, cleanupSg, modeOf, effortOf, isBw, isPerSide, sideReps, workSetsDone } from './lib/history.js' import { beep, vibrate } from './lib/sound.js' import { t, instrFor, getLang, INSTR_LANGS } from './lib/i18n.js' import { nav } from './lib/nav.js' import { starterRoutines } from './lib/starter.js' import Media, { Thumb } from './components/Media.jsx' import Stepper from './components/Stepper.jsx' import Icon from './components/Icon.jsx' import { Button, Slider, Switch, Segmented, SelectRow, Row } from './components/ui.jsx' import { glyphOf, GLYPH_GROUPS, DEFAULT_GLYPH } from './lib/glyphs.js' import BodyMap from './components/BodyMap.jsx' import { loadOfWorkouts } from './lib/muscles.js' import { parseImport, mergeImport } from './lib/import-csv.js' import { buildPlanBundle, parsePlan, mergePlan, printPlan } from './lib/plan-share.js' import { estimate1RM, best1RM, is1RMRecord, REP_CAP } from './lib/onerm.js' import { nextPrescription, applyPrescription, policyFor, defaultIncrement, POLICIES_FOR, POLICY_NAME, POLICY_DESC, MAX_BW_SETS } from './lib/progression.js' import { MOBILE, shareExport } from './lib/mobile.js' 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 [push, pull, legs] = starterRoutines() update(st => { st.routines.push(push, pull, legs) st.week[1] = push.id; st.week[3] = pull.id; st.week[5] = legs.id }) toast(t('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. // The ceiling follows the profile's unit: 300 covers a body weight or a working weight in // kg, but as pounds it cut off at 136 kg — below plenty of people's body weight, and well // below an everyday squat. const W_LO = 1 const wHi = unit => (unit === 'lb' ? 660 : 300) function WeightInput({ value, setValue, unit }) { const W_HI = wHi(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 onSlide = v => setValue(clamp(v)) return <>
{fmtNum(value)} {unit}
} /* ============================ 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(t('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(t('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 ? t('Quick check-in') : t('Log body weight')}

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

{t('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 } /* ============================ import from another app ============================ */ // Shows what a parsed export would actually do before anything is written. An import is // the one action where "just try it" is expensive — it's someone's entire training // history — so the numbers, the unit conversion and the exercises we couldn't recognise // are all on screen before the confirm button. function ImportSummary({ parsed, close }) { const st = useStore(s => s.S) const isBW = parsed.kind === 'bodyweight' const have = isBW ? parsed.bodyweight.filter(b => st.bodyweight.some(x => x.d === b.d)).length : parsed.workouts.filter(w => st.workouts.some(x => x.d === w.d)).length const fresh = (isBW ? parsed.bodyweight.length : parsed.workouts.length) - have const doImport = () => { let res update(s => { res = mergeImport(s, parsed) }) close() toast(isBW ? t('{0} weigh-ins imported', res.added) : t('{0} workouts imported', res.added)) } return <>

{parsed.source ? t('Import from {0}', parsed.source) : t('Import history')}

{parsed.from === parsed.to ? fmtDate(parsed.from, true) : fmtDate(parsed.from, true) + ' – ' + fmtDate(parsed.to, true)}
{isBW ? <>
{t('Weigh-ins')}
{parsed.bodyweight.length}
{t('New')}
{fresh}
: <>
{t('Workouts')}
{parsed.workouts.length}
{t('Sets')}
{parsed.sets}
{t('Exercises matched')}
{parsed.matched}
{t('Added as your own')}
{parsed.created}
}
{parsed.mixedUnits ?
{t('The file mixes kg and lb — each set is converted to {0}.', st.unit)}
: parsed.converted ?
{t('The file is in {0} and your profile is in {1} — weights will be converted.', parsed.fileUnit, st.unit)}
: null} {!isBW && !parsed.fileUnit && !parsed.mixedUnits &&
{t('The file does not say which unit it uses — numbers are imported as they are.')}
} {have > 0 &&
{t('{0} days already have data here and will be left alone.', have)}
} {/* The file rated its sets. Say so: the column is off by default, so the ratings would otherwise arrive invisibly and look like they had been dropped. */} {!isBW && (parsed.rirSets + parsed.rpeSets) > 0 &&
{t(effortOf(st) === 'none' ? '{0} sets bring an {1} with them — switch on Effort per set in Settings to see it.' : '{0} sets bring an {1} with them.', parsed.rirSets || parsed.rpeSets, parsed.rirSets ? 'RIR' : 'RPE')}
} {!isBW && parsed.unmatchedNames.length > 0 && <>

{t('Not in the library — added as your own exercises')}

{parsed.unmatchedNames.slice(0, 12).map(n => {n})} {parsed.unmatchedNames.length > 12 && +{parsed.unmatchedNames.length - 12}}
}
} /** Read a CSV/XML export, then show what it would do. */ export function importFromApp(file, onDone) { const rd = new FileReader() rd.onload = () => { let parsed try { parsed = parseImport(String(rd.result), { unit: S().unit }) } catch (e) { toast(t('Could not read that file')); return } if (parsed.error === 'empty') { toast(t('That file is empty')); return } if (parsed.error) { toast(t("That file's columns aren't recognised — see the docs for supported apps.")); return } if (parsed.kind === 'bodyweight' ? !parsed.bodyweight.length : !parsed.workouts.length) { toast(t('Nothing to import from that file')); return } ui().openSheet(close => ) onDone && onDone() } rd.onerror = () => toast(t('Could not read that file')) rd.readAsText(file) } /* ============================ target weight ============================ */ export function bwDeltaColor(delta, currentW) { if (!delta) return 'var(--label-2)' if (!S().targetW) return 'var(--label)' 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 <>

{t('Target weight')}

{t('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 ============================ */ // Estimated 1RM for one exercise (issue #18): what the log already implies, plus a calculator // for a set you have not done — so the number is reachable before there is any history. function OneRM({ ex }) { const st = useStore(s => s.S) const best = best1RM(st, ex.id) const [w, setW] = useState(best ? best.w : (st.exWeights[ex.id] || {}).w || 20) const [r, setR] = useState(best ? best.r : 5) const est = estimate1RM(w, r) return <>

{t('Estimated 1RM')}

{best &&
{t('From your log:')} {fmtNum(best.est)} {st.unit} · {t('{0} × {1} on {2}', fmtNum(best.w) + ' ' + st.unit, best.r, fmtDate(best.d, true))}
}
{t('Estimate')} {est === null ? '—' : fmtNum(est) + ' ' + st.unit}
{est === null ? t('Enter a weight and 1–{0} reps — beyond that an estimate is guesswork.', REP_CAP) : t('Epley formula — a calculation from one set, not a tested max.')}
} function ExerciseDetail({ ex, close }) { const st = useStore(s => s.S) const last = lastEntryFor(st, ex.id) const best = bestWeightFor(st, ex.id) return <>

{ex.n}

{t(ex.bp)} {ex.tg && {t(ex.tg)}} {t(ex.eq)} {(ex.sm || []).slice(0, 3).map((s, i) => {t(s)})}
{ex.desc &&
{ex.desc}
} {best > 0 &&
{t('Best:')} {fmtNum(best)} {st.unit}{last ? ` · ${t('last')} ${fmtDate(last.d)}: ${last.sets.map(s => setLabel(ex.id, s, last.target)).join(', ')}` : ''}
} {ex.custom &&
} {!isCardio(ex) && } {instrFor(ex).length > 0 &&<>

{t('How to')}{!INSTR_LANGS.includes(getLang()) && · {t('instructions in English')}}

    {instrFor(ex).map((s, i) =>
  1. {s}
  2. )}
} } export const exerciseDetailSheet = ex => ui().openSheet(close => ) /* ============================ 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: t('New routine'), emoji: DEFAULT_GLYPH, 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(t('“{0}” added to {1}', ex.n, r ? r.name : t('routine'))) if (isNew && r) nav('/plan/r/' + r.id) }, null, isNew ? null : st.routines.find(x => x.id === rid)) } return <>

{t('Add “{0}”', ex.n)}

{t('Pick a routine — sets, reps & weight come next.')}
{st.routines.map(r =>
pick(r.id)}>
{r.name}
{exCount(r.ex.length)}
{r.ex.some(e => e.id === ex.id) && {t('already in')}}
)}
pick('_new')}>
{t('New routine')}
{t('Create one and start with this exercise')}
} export const addToRoutineSheet = ex => ui().openSheet(close => ) /* ============================ custom exercises (issue #11) ============================ */ // Name + body part is all it takes — the exercise then behaves like any built-in one // (planning, logging, PRs, stats), just without an animation. function CustomExForm({ existing, prefill, onDone, close }) { const [n, setN] = useState(existing ? existing.n : (prefill || '')) const [bp, setBp] = useState(existing ? existing.bp : '') const [desc, setDesc] = useState(existing ? (existing.desc || '') : '') const save = () => { const name = n.trim() if (!name) { toast(t('Give it a name')); return } if (!bp) { toast(t('Pick a body part')); return } const dup = allExercises(S()).find(e => e.n.toLowerCase() === name.toLowerCase() && e.id !== (existing || {}).id) if (dup) { toast(t('“{0}” already exists', dup.n)); return } const d = desc.trim().slice(0, 1000) let id = existing && existing.id if (existing) update(s => { const c = (s.customEx || []).find(x => x.id === id); if (c) { c.n = name; c.bp = bp; c.desc = d } }) else { id = 'c' + uid() update(s => { (s.customEx = s.customEx || []).push({ id, n: name, bp, desc: d, tg: '', eq: 'custom', custom: true }) }) } close() toast(existing ? t('Saved') : t('“{0}” created', name)) onDone && onDone(EXIDX[id]) } return <>

{existing ? t('Edit custom exercise') : t('Create your own exercise')}

{t('Name it and pick a body part — it behaves like any other exercise, just without an animation.')}
setN(e.target.value)} />
{BODYPARTS.map(b => )}
{bp === 'cardio' &&
{t('Cardio exercises log time + speed instead of weight × reps.')}
}