/** * Coach-Modus: Schrittfolge mit Split-Punkten (branch_gate), Stream-Wahl pro paralleler Phase, Assistenz und Zeitnahme. */ import React, { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react' import { Link, useNavigate, useParams, useSearchParams } from 'react-router-dom' import api from '../utils/api' import ExerciseFullContent from '../components/ExerciseFullContent' import ExercisePeekModal from '../components/ExercisePeekModal' import { COACH_ENTRY_BRANCH_GATE, buildCoachSavePlanPayload, coachBranchPicksStepStorageSuffix, coachBranchPicksStorageKey, coachOutlineGroupsFromTimeline, coachShouldPromptSplitRejoin, coachShouldPromptSplitRejoinTransition, durationOverridesMapFromDeltas, findCoachTimelineJumpIndexForPhase, flattenPlanTimeline, itemStableKey, listCoachStreamFocusOptions, mergeCoachBranchPicksWithUrlFocus, normalizeCoachBranchPicks, summarizeTimelineEntry, } from '../utils/trainingPlanUtils' function storageStepKey(unitId, mergedPicks) { return `sj_coach_step_${unitId}_${coachBranchPicksStepStorageSuffix(mergedPicks)}` } function clearCoachStepStorageForUnit(unitId) { const pref = `sj_coach_step_${unitId}_` try { for (let i = sessionStorage.length - 1; i >= 0; i -= 1) { const k = sessionStorage.key(i) if (k && k.startsWith(pref)) sessionStorage.removeItem(k) } } catch { /* ignore */ } } function storageDeltasKey(unitId) { return `sj_coach_deltas_${unitId}` } function storageDebriefKey(unitId) { return `sj_coach_debrief_${unitId}` } function formatClock(totalSec) { const m = Math.floor(totalSec / 60) const s = totalSec % 60 return `${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}` } function mergeDelta(setDeltas, itemKey, patch) { setDeltas((prev) => ({ ...prev, [itemKey]: { ...prev[itemKey], ...patch } })) } function CoachControlsBand({ step, timelineLength, onPrev, onNext, onDone, clockStr, runStartAt, pausedAccumMs, onTimerStart, onTimerPause, onTimerReset, onApplyActual, roundedMinForApply, isLastCoachStep, showJumpToTimerOwner, showJumpToTimerOwnerRow = true, onJumpToTimerOwner, timerOwnerLabelIndex, branchGateMode = false, }) { const disPrev = step <= 0 const disNext = branchGateMode || step >= timelineLength - 1 const alive = runStartAt != null || pausedAccumMs > 0 const canApplyForOwner = !branchGateMode && roundedMinForApply != null && roundedMinForApply >= 1 const istLabelMin = roundedMinForApply == null ? '—' : String(roundedMinForApply) const doneLabel = branchGateMode ? 'Zuerst Gruppe wählen' : timelineLength <= 1 ? 'Nachbereitung öffnen' : isLastCoachStep ? 'Nachbereitung & Ist-Zeit' : 'Abgeschlossen & weiter' return (
{showJumpToTimerOwner && showJumpToTimerOwnerRow && (
)}
{runStartAt == null ? ( ) : ( )} {alive && !branchGateMode && ( )}
) } export default function TrainingCoachPage() { const { unitId } = useParams() const navigate = useNavigate() const [searchParams, setSearchParams] = useSearchParams() const idNum = unitId ? parseInt(unitId, 10) : NaN const coachFocusResetRef = useRef(null) const [unit, setUnit] = useState(null) const [loadError, setLoadError] = useState(null) const [loading, setLoading] = useState(true) const [outlineOpen, setOutlineOpen] = useState(false) const [catalogExercise, setCatalogExercise] = useState(null) const [catalogLoading, setCatalogLoading] = useState(false) const [catalogError, setCatalogError] = useState(null) const [debriefOpen, setDebriefOpen] = useState(false) const [coachDebriefPhase, setCoachDebriefPhase] = useState(false) const [step, setStep] = useState(0) const [branchPicks, setBranchPicks] = useState({}) const [streamChoiceHint, setStreamChoiceHint] = useState(null) const [deltas, setDeltas] = useState({}) const [runStartAt, setRunStartAt] = useState(null) const [pausedAccumMs, setPausedAccumMs] = useState(0) const [timerOwningStep, setTimerOwningStep] = useState(null) const [, setPulse] = useState(0) const [splitRejoinPrompt, setSplitRejoinPrompt] = useState(null) const [trainerAppend, setTrainerAppend] = useState('') const [saveMarkDone, setSaveMarkDone] = useState(true) const [saving, setSaving] = useState(false) const [candidatePeekId, setCandidatePeekId] = useState(null) const [saveOk, setSaveOk] = useState(null) const reloadUnit = useCallback(async () => { const u = await api.getTrainingUnit(idNum) setUnit(u) }, [idNum]) const coachFocus = useMemo(() => { const poRaw = searchParams.get('po') const soRaw = searchParams.get('so') if (poRaw == null || poRaw === '' || soRaw == null || soRaw === '') return null const po = parseInt(poRaw, 10) const so = parseInt(soRaw, 10) if (!Number.isFinite(po) || !Number.isFinite(so)) return null if (!unit) return null const opts = listCoachStreamFocusOptions(unit) if (!opts.some((o) => o.phaseOrder === po && o.streamOrder === so)) return null return { phaseOrder: po, streamOrder: so } }, [searchParams, unit]) const mergedPicks = useMemo( () => mergeCoachBranchPicksWithUrlFocus(branchPicks, coachFocus), [branchPicks, coachFocus] ) const streamFocusOptions = useMemo(() => (unit ? listCoachStreamFocusOptions(unit) : []), [unit]) const navigationKey = coachBranchPicksStepStorageSuffix(mergedPicks) const streamQuickSelectValue = useMemo(() => { for (let i = 0; i < streamFocusOptions.length; i++) { const o = streamFocusOptions[i] if (mergedPicks[o.phaseOrder] === o.streamOrder) return o.valueKey } return '' }, [streamFocusOptions, mergedPicks]) const hasStreamSelectParams = (searchParams.get('po') != null && searchParams.get('po') !== '') || (searchParams.get('so') != null && searchParams.get('so') !== '') const streamParamsInvalid = Boolean(unit && hasStreamSelectParams && !coachFocus) const timeline = useMemo(() => flattenPlanTimeline(unit, mergedPicks), [unit, mergedPicks]) const outlineGroups = useMemo(() => coachOutlineGroupsFromTimeline(timeline), [timeline]) useEffect(() => { if (!unitId || Number.isNaN(idNum)) { setLoadError('Ungültige Trainingseinheit') setLoading(false) return } coachFocusResetRef.current = null let cancelled = false ;(async () => { setLoading(true) setLoadError(null) try { await reloadUnit() if (cancelled) return let nextBranchPicks = {} try { const br = sessionStorage.getItem(coachBranchPicksStorageKey(idNum)) if (br) { const o = JSON.parse(br) if (o && typeof o === 'object') nextBranchPicks = normalizeCoachBranchPicks(o) } } catch { /* ignore */ } try { const raw = sessionStorage.getItem(storageDeltasKey(idNum)) if (raw) { const o = JSON.parse(raw) if (o && typeof o === 'object') setDeltas(o) } } catch { /* ignore */ } try { if (sessionStorage.getItem(storageDebriefKey(idNum)) === '1') setCoachDebriefPhase(true) } catch { /* ignore */ } if (!cancelled) { setBranchPicks(nextBranchPicks) setStreamChoiceHint(null) } } catch (e) { if (!cancelled) setLoadError(e.message || 'Laden fehlgeschlagen') } finally { if (!cancelled) setLoading(false) } })() return () => { cancelled = true } }, [unitId, idNum, reloadUnit]) useEffect(() => { if (!unit) return const po = searchParams.get('po') const so = searchParams.get('so') if ((po == null || po === '') && (so == null || so === '')) return const p = parseInt(po, 10) const s = parseInt(so, 10) if (!Number.isFinite(p) || !Number.isFinite(s)) { setSearchParams({}, { replace: true }) return } const opts = listCoachStreamFocusOptions(unit) if (opts.length === 0 || !opts.some((o) => o.phaseOrder === p && o.streamOrder === s)) { setSearchParams({}, { replace: true }) } }, [unit, searchParams, setSearchParams]) useEffect(() => { if (!unit) return const ab = searchParams.get('atBranch') if (ab == null || ab === '') return const po = parseInt(ab, 10) const phaseOrders = [...new Set(streamFocusOptions.map((o) => o.phaseOrder))] if (!Number.isFinite(po) || !phaseOrders.includes(po)) { const next = new URLSearchParams(searchParams) next.delete('atBranch') next.delete('preferSo') setSearchParams(next, { replace: true }) } }, [unit, searchParams, setSearchParams, streamFocusOptions]) useEffect(() => { if (!unit || timeline.length === 0) return const ab = searchParams.get('atBranch') if (ab == null || ab === '') return const po = parseInt(ab, 10) if (!Number.isFinite(po)) return const prefRaw = searchParams.get('preferSo') const pref = prefRaw != null && prefRaw !== '' ? parseInt(prefRaw, 10) : NaN const ix = findCoachTimelineJumpIndexForPhase(timeline, po, Number.isFinite(pref) ? pref : null) if (ix >= 0) { setStep(ix) if (Number.isFinite(pref)) setStreamChoiceHint({ phaseOrder: po, streamOrder: pref }) } const next = new URLSearchParams(searchParams) next.delete('atBranch') next.delete('preferSo') setSearchParams(next, { replace: true }) }, [unit, timeline, searchParams, setSearchParams]) useEffect(() => { if (Number.isNaN(idNum)) return try { sessionStorage.setItem(coachBranchPicksStorageKey(idNum), JSON.stringify(branchPicks)) } catch { /* quota */ } }, [idNum, branchPicks]) useEffect(() => { if (Number.isNaN(idNum)) return sessionStorage.setItem(storageStepKey(idNum, mergedPicks), String(step)) }, [idNum, mergedPicks, step]) useEffect(() => { try { sessionStorage.setItem(storageDeltasKey(idNum), JSON.stringify(deltas)) } catch { /* quota */ } }, [idNum, deltas]) useEffect(() => { try { sessionStorage.setItem(storageDebriefKey(idNum), coachDebriefPhase ? '1' : '0') } catch { /* quota */ } }, [idNum, coachDebriefPhase]) useEffect(() => { if (runStartAt == null) return undefined const iv = setInterval(() => setPulse((p) => p + 1), 380) return () => clearInterval(iv) }, [runStartAt]) const clampStep = (s, len = timeline.length) => Math.max(0, Math.min(s, Math.max(len - 1, 0))) const timerReset = useCallback(() => { setRunStartAt(null) setPausedAccumMs(0) setTimerOwningStep(null) }, []) useEffect(() => { if (!unit) return if (timeline.length === 0) { setStep(0) return } if (coachDebriefPhase) { setStep(timeline.length - 1) } else { setStep((prev) => clampStep(prev, timeline.length)) } }, [unit, timeline.length, coachDebriefPhase]) useEffect(() => { if (!unit || Number.isNaN(idNum)) return if (timeline.length === 0) { setStep(0) return } const prev = coachFocusResetRef.current if (prev === null) { coachFocusResetRef.current = navigationKey } else if (prev !== navigationKey) { coachFocusResetRef.current = navigationKey setCoachDebriefPhase(false) setSplitRejoinPrompt(null) timerReset() } else { return } try { const raw = sessionStorage.getItem(storageStepKey(idNum, mergedPicks)) const s = parseInt(raw, 10) const maxIdx = Math.max(0, timeline.length - 1) if (!Number.isNaN(s) && s >= 0) setStep(Math.min(s, maxIdx)) else setStep(0) } catch { setStep(0) } }, [unit, idNum, navigationKey, mergedPicks, timeline.length, timerReset]) const elapsedMs = pausedAccumMs + (runStartAt != null ? Date.now() - runStartAt : 0) const tickDisplaySec = Math.max(0, Math.floor(elapsedMs / 1000)) const safeStep = useMemo(() => { if (!timeline.length) return 0 return Math.min(Math.max(0, step), timeline.length - 1) }, [step, timeline.length]) useLayoutEffect(() => { if (!timeline.length) return const max = timeline.length - 1 const s = Math.min(Math.max(0, step), max) if (s !== step) setStep(s) }, [step, timeline.length]) const currentEntry = timeline[safeStep] ?? null const nextEntry = timeline[safeStep + 1] || null const next2Entry = timeline[safeStep + 2] || null const clockStr = formatClock(tickDisplaySec) const roundedMinApply = elapsedMs <= 650 ? null : Math.max(1, Math.round(elapsedMs / 60000)) const showJumpToTimerOwner = timerOwningStep != null && safeStep !== timerOwningStep && (runStartAt != null || pausedAccumMs > 0) const isLastCoachStep = timeline.length > 0 && safeStep >= timeline.length - 1 && currentEntry?.entryKind !== COACH_ENTRY_BRANCH_GATE const timerStart = () => { setRunStartAt(Date.now()) setTimerOwningStep(safeStep) } const timerPause = () => { if (runStartAt != null) { setPausedAccumMs((a) => a + (Date.now() - runStartAt)) setRunStartAt(null) } } const applySuggestedDuration = () => { const idx = timerOwningStep != null ? timerOwningStep : safeStep const ent = timeline[idx] const item = ent?.item if (!item || item.item_type !== 'exercise') return if (elapsedMs <= 650) return const min = Math.max(1, Math.round(elapsedMs / 60000)) const key = itemStableKey(item, ent.secOrder, ent.ii) mergeDelta(setDeltas, key, { actual_duration_min: min }) timerPause() } const pickStreamForPhase = useCallback( (phaseOrder, streamOrder) => { if (!Number.isFinite(phaseOrder) || !Number.isFinite(streamOrder)) return setStreamChoiceHint(null) setSplitRejoinPrompt(null) setBranchPicks((prev) => ({ ...normalizeCoachBranchPicks(prev), [phaseOrder]: streamOrder })) timerReset() setCoachDebriefPhase(false) setSearchParams({ po: String(phaseOrder), so: String(streamOrder) }, { replace: true }) }, [timerReset, setSearchParams] ) const atBranchGate = currentEntry?.entryKind === COACH_ENTRY_BRANCH_GATE const goPrev = () => setStep((s) => clampStep(s - 1)) const goNext = () => setStep((s) => clampStep(s + 1)) const markCurrentDoneAdvance = () => { const ownerIdx = timerOwningStep != null ? timerOwningStep : safeStep const ent = timeline[ownerIdx] if (ent?.entryKind === COACH_ENTRY_BRANCH_GATE) return const item = ent?.item if (item?.item_type === 'exercise' && elapsedMs > 650) { const key = itemStableKey(item, ent.secOrder, ent.ii) const min = Math.max(1, Math.round(elapsedMs / 60000)) mergeDelta(setDeltas, key, { actual_duration_min: min }) } timerReset() const lastIdx = timeline.length - 1 if (safeStep >= lastIdx && lastIdx >= 0) { const rejoin = coachShouldPromptSplitRejoin(unit, timeline[safeStep]) if (rejoin) { setSplitRejoinPrompt(rejoin) return } setCoachDebriefPhase(true) try { sessionStorage.setItem(storageDebriefKey(idNum), '1') } catch { /* ignore */ } return } const nextIdx = safeStep + 1 if (nextIdx < timeline.length) { const rejoinMid = coachShouldPromptSplitRejoinTransition(unit, timeline[safeStep], timeline[nextIdx]) if (rejoinMid) { setSplitRejoinPrompt(rejoinMid) return } } setStep((s) => clampStep(s + 1, timeline.length)) } useEffect(() => { if (!atBranchGate) return if (runStartAt != null || pausedAccumMs > 0) timerReset() }, [step, atBranchGate, runStartAt, pausedAccumMs, timerReset]) const durationOverridesForApi = useMemo(() => durationOverridesMapFromDeltas(unit, deltas), [unit, deltas]) useEffect(() => { if (currentEntry?.entryKind === COACH_ENTRY_BRANCH_GATE) { setCatalogExercise(null) setCatalogError(null) setCatalogLoading(false) return } const item = currentEntry?.item if (!item || item.item_type === 'note') { setCatalogExercise(null) setCatalogError(null) setCatalogLoading(false) return } const eid = item.exercise_id if (!eid) { setCatalogExercise(null) setCatalogError(null) setCatalogLoading(false) return } let cancelled = false setCatalogLoading(true) setCatalogError(null) setCatalogExercise(null) api.getExercise(eid) .then((ex) => { if (!cancelled) { setCatalogExercise(ex) setCatalogLoading(false) } }) .catch((err) => { if (!cancelled) { setCatalogError(err.message || String(err)) setCatalogExercise(null) setCatalogLoading(false) } }) return () => { cancelled = true } }, [step, currentEntry?.entryKind, currentEntry?.item?.exercise_id, currentEntry?.item?.exercise_variant_id, currentEntry?.item?.item_type]) const handleSaveDebrief = async () => { setSaveOk(null) setSaving(true) try { const sectionsPayloadPart = buildCoachSavePlanPayload(unit, durationOverridesForApi) const tn = trainerAppend.trim() const payload = { ...sectionsPayloadPart, ...(saveMarkDone ? { status: 'completed' } : {}), } if (tn) { payload.trainer_notes = [unit.trainer_notes || '', `--- (${new Date().toLocaleString('de-DE')}) ---`, tn] .filter(Boolean) .join('\n') .trim() } await api.updateTrainingUnit(idNum, payload) setTrainerAppend('') try { sessionStorage.removeItem(storageDeltasKey(idNum)) sessionStorage.removeItem(storageDebriefKey(idNum)) sessionStorage.removeItem(coachBranchPicksStorageKey(idNum)) clearCoachStepStorageForUnit(idNum) } catch { /* ignore */ } setDeltas({}) setBranchPicks({}) setStreamChoiceHint(null) setSplitRejoinPrompt(null) setCoachDebriefPhase(false) setDebriefOpen(false) setSaveOk('Gespeichert.') setSearchParams({}, { replace: true }) navigate(`/planning/run/${unitId}`, { replace: true }) } catch (e) { setSaveOk(`Fehler: ${e.message || e}`) } finally { setSaving(false) } } if (loading) { return (

Coach laden…

) } if (loadError || !unit) { return (

{loadError || 'Nicht gefunden.'}

) } return (
setCandidatePeekId(null)} /> {streamParamsInvalid ? (

Ungültige Stream-Parameter in der Adresszeile — es wird der Gesamtplan angezeigt.

) : null} {splitRejoinPrompt && !coachDebriefPhase ? (
Parallelphase · Abschluss

{splitRejoinPrompt.phaseTitle != null && String(splitRejoinPrompt.phaseTitle).trim() ? String(splitRejoinPrompt.phaseTitle).trim() : `Phase ${splitRejoinPrompt.phaseOrderIndex}`} {' — '} alle Gruppen zusammen?

Diese Phase hat mehrere Streams. Kurz mit dem anderen Trainer klären, dann gemeinsam weitermachen. Ist-Zeiten und Speichern erfolgen in der Nachbereitung am Ende der Einheit.

    {splitRejoinPrompt.streams.map((st) => (
  • {st.streamTitle?.trim() ? String(st.streamTitle).trim() : `Gruppe ${st.streamOrder + 1}`}{' '} (ca. {st.minutes} Min. Üb.)
  • ))}
{safeStep < timeline.length - 1 ? ( ) : ( )}
) : null}
Coach ·{' '} {coachDebriefPhase ? 'Nachbereitung · abschließend speichern' : `Schritt ${(safeStep || 0) + 1} / ${Math.max(timeline.length, 1)}`}

{unit.planned_date} {unit.planned_time_start && ` · ${String(unit.planned_time_start).slice(0, 5)}`} {unit.planned_focus ? ` · ${unit.planned_focus}` : ''}

{streamFocusOptions.length > 0 ? (

Parallele Phasen erscheinen als Schritt Gruppe wählen — kein Durcheinander mehr aus verschränkten Streams. Pro paralleler Phase entscheiden Sie (oder der Co-Trainer auf dem eigenen Gerät), welcher Stream coacht wird. Kurzwahl oben springt die betreffende Phase sofort auf einen Stream (z. B. zwischen Gruppen wechseln). {Object.keys(mergedPicks).length > 0 ? ( Aktuell festgelegt:{' '} {Object.keys(mergedPicks) .map((pk) => { const po = parseInt(pk, 10) const so = mergedPicks[pk] const o = streamFocusOptions.find((x) => x.phaseOrder === po && x.streamOrder === so) return o?.label ?? `Phase ${po} · Stream ${so}` }) .join(' · ')} ) : null}

) : null}
{outlineOpen && (
Trainingsrahmen · nach Blöcken und Streams
{outlineGroups.map((grp) => (
{grp.heading} {grp.sub ? · {grp.sub} : null}
{grp.entries.map(({ ix, ent }) => { const lbl = summarizeTimelineEntry(ent) const ctx = ent.coachContext || '' const active = coachDebriefPhase ? ix === timeline.length - 1 : ix === safeStep const rowKey = ent.entryKind === COACH_ENTRY_BRANCH_GATE ? `gate-${ix}` : `${itemStableKey(ent.item, ent.secOrder, ent.ii)}-${ix}` return ( ) })}
))}
)} {timeline.length === 0 ? (

Dieser Plan ist leer. Unter Planung ergänzen.

) : coachDebriefPhase ? (
Nachbereitung

Ist‑Minuten prüfen, Trainer‑Ergänzung anlegen und Einheit sichern (zeigt bestehende Notizen weiter unten an).

{timeline .filter((e) => e.item?.item_type === 'exercise') .map((ent) => { const k = itemStableKey(ent.item, ent.secOrder, ent.ii) const val = deltas[k]?.actual_duration_min ?? ent.item.actual_duration_min ?? '' return ( ) })}