/**
* 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 && (
← Zur laufenden Übung ({timerOwnerLabelIndex + 1}/{timelineLength})
)}
← zurück
{runStartAt == null ? (
▶ Start{alive ? ` · ${clockStr}` : ''}
) : (
Pause · {clockStr}
)}
Ist ({istLabelMin} Min)
{alive && !branchGateMode && (
↺
)}
{doneLabel}
weiter →
)
}
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 (
)
}
if (loadError || !unit) {
return (
{loadError || 'Nicht gefunden.'}
navigate('/planning')}>
Zur Planung
)
}
return (
setCandidatePeekId(null)}
/>
navigate(`/planning/run/${unitId}`)}>
Zur Planansicht
navigate('/planning')}>
Planung
{streamFocusOptions.length > 0 ? (
Ansicht
{
setSplitRejoinPrompt(null)
setCoachDebriefPhase(false)
timerReset()
const v = e.target.value
if (!v) {
setBranchPicks({})
setStreamChoiceHint(null)
setSplitRejoinPrompt(null)
setSearchParams({}, { replace: true })
} else {
const [ppo, sso] = v.split('-').map((x) => parseInt(x, 10))
pickStreamForPhase(ppo, sso)
}
}}
>
Ablauf mit Split-Punkten (Standard)
{streamFocusOptions.map((o) => (
{o.label}
))}
) : null}
setOutlineOpen((o) => !o)}
style={{ marginLeft: 'auto' }}
>
{outlineOpen ? 'Rahmen schließen' : 'Trainingsrahmen'}
{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 ? (
{
setSplitRejoinPrompt(null)
setStep((s) => clampStep(s + 1, timeline.length))
}}
>
Gruppen zusammengeführt — weiter mit dem Plan
) : (
{
setSplitRejoinPrompt(null)
setCoachDebriefPhase(true)
try {
sessionStorage.setItem(storageDebriefKey(idNum), '1')
} catch {
/* ignore */
}
}}
>
Alle Gruppen fertig — zur Nachbereitung
)}
setSplitRejoinPrompt(null)}>
Zurück — andere Gruppe läuft noch
{
setSplitRejoinPrompt(null)
setCoachDebriefPhase(true)
try {
sessionStorage.setItem(storageDebriefKey(idNum), '1')
} catch {
/* ignore */
}
}}
>
{safeStep < timeline.length - 1
? 'Ausnahme: jetzt schon zur Nachbereitung'
: 'Ausnahme: trotzdem zur Nachbereitung'}
) : 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 (
{
setCoachDebriefPhase(false)
setStep(ix)
}}
>
{ctx ? (
{ctx.length > 42 ? `${ctx.slice(0, 40)}…` : ctx}
) : null}
{lbl}
)
})}
))}
)}
{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 (
{ent.coachContext ? {ent.coachContext} · : null}
{summarizeTimelineEntry(ent)}
{
const raw = e.target.value
if (raw === '') mergeDelta(setDeltas, k, { actual_duration_min: null })
else mergeDelta(setDeltas, k, { actual_duration_min: parseInt(raw, 10) })
}}
/>
)
})}
Ergänzung Trainer (wird angehängt · mit Zeitstempel)
setSaveMarkDone(e.target.checked)} />
Einheit als durchgeführt markieren
{saveOk && (
{saveOk}
)}
{saving ? 'Speichert…' : 'Speichern'}
{
setCoachDebriefPhase(false)
if (timeline.length > 0) setStep(Math.max(0, timeline.length - 1))
}}
>
Zurück zur letzten Übungsposition
{unit.trainer_notes ? (
Einheit · Trainernotizen
{unit.trainer_notes}
) : null}
) : (
<>
{!splitRejoinPrompt ? (
<>
Als Nächstes
{atBranchGate ? (
Wählen Sie unten eine Gruppe. Danach zeigt der Coach fortlaufend nur die Übungen dieses Streams in dieser
parallelen Phase.
) : nextEntry ? (
<>
Nächste: {summarizeTimelineEntry(nextEntry)}
{next2Entry && (
Daraufhin: {summarizeTimelineEntry(next2Entry)}
)}
>
) : (
Letzter Punkt — „Nachbereitung & Ist-Zeit“ öffnet die Abschlussseite zum Speichern.
)}
setStep(timerOwningStep ?? safeStep)}
timerOwnerLabelIndex={timerOwningStep ?? 0}
branchGateMode={atBranchGate}
/>
{atBranchGate && currentEntry?.branchMeta ? (
⑂ SPLIT — GRUPPE WÄHLEN
{currentEntry.branchMeta.phaseTitle != null && String(currentEntry.branchMeta.phaseTitle).trim()
? String(currentEntry.branchMeta.phaseTitle).trim()
: `Phase ${currentEntry.branchMeta.phaseOrderIndex}`}
Tippen Sie auf eine Kachel, um diese Gruppe zu coachen. Andere Trainer:innen wählen auf
ihrem Gerät parallel eine andere Kachel.
{(currentEntry.branchMeta.streams || []).map((st) => {
const hinted =
streamChoiceHint?.phaseOrder === currentEntry.branchMeta.phaseOrderIndex &&
streamChoiceHint?.streamOrder === st.streamOrder
const label = st.streamTitle?.trim() ? String(st.streamTitle).trim() : `Gruppe ${st.streamOrder + 1}`
const baseBg = hinted ? 'var(--accent)' : 'var(--surface2)'
const baseColor = hinted ? '#fff' : 'var(--text1)'
const borderCol = hinted ? 'var(--accent-dark)' : 'var(--border)'
return (
pickStreamForPhase(currentEntry.branchMeta.phaseOrderIndex, st.streamOrder)}
>
{hinted ? '◉' : '○'}
{label}
≈ {st.minutes} Min. Üb. · Jetzt aktivieren
{hinted ? (
Vorschlag aus Planansicht — trotzdem andere Kachel möglich
) : null}
)
})}
) : currentEntry?.item?.item_type === 'note' ? (
{currentEntry?.coachContext || currentEntry?.sec?.title || 'Abschnitt'} · Coach-Notiz · Teil{' '}
{safeStep + 1}
Coach-Notiz
{currentEntry.item.note_body || ''}
) : (
<>
In diesem Training · {currentEntry?.coachContext || currentEntry?.sec?.title || 'Abschnitt'} · Teil{' '}
{safeStep + 1}
{currentEntry?.item && (
<>
{currentEntry.item.exercise_title ||
(currentEntry.item.exercise_id ? `Übung #${currentEntry.item.exercise_id}` : 'Übung')}
{currentEntry.item.exercise_variant_name ? (
({currentEntry.item.exercise_variant_name})
) : null}
geplant {currentEntry.item.planned_duration_min ?? '—'} Min · Ist (Plan):{' '}
{durationOverridesForApi[String(currentEntry.item.id)] != null
? durationOverridesForApi[String(currentEntry.item.id)].actual_duration_min
: currentEntry.item.actual_duration_min ?? '—'}{' '}
Min
{' '}
{durationOverridesForApi[String(currentEntry.item.id)] != null ? '(Entwurf)' : ''}
{currentEntry.item.exercise_focus_area ? (
{currentEntry.item.exercise_focus_area}
) : null}
{currentEntry.item.notes ? (
Zu dieser Platzierung
{currentEntry.item.notes}
) : null}
{currentEntry.item.modifications ? (
Anpassung
{currentEntry.item.modifications}
) : null}
>
)}
Übung aus dem Katalog (vollständig)
setCandidatePeekId(id)}
/>
>
)}
{unit.trainer_notes ? (
Einheit · Trainernotizen
{unit.trainer_notes}
) : null}
setDebriefOpen(!debriefOpen)}
>
Nachbereitung & speichern
{debriefOpen ? '▼' : '▶'}
{debriefOpen && (
<>
Ist‑Minuten anpassen und Einheit speichern (inkl. Trainer-Ergänzung).
{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 (
{ent.coachContext ? {ent.coachContext} · : null}
{summarizeTimelineEntry(ent)}
{
const raw = e.target.value
if (raw === '') mergeDelta(setDeltas, k, { actual_duration_min: null })
else mergeDelta(setDeltas, k, { actual_duration_min: parseInt(raw, 10) })
}}
/>
)
})}
Ergänzung Trainer (wird angehängt · mit Zeitstempel)
setSaveMarkDone(e.target.checked)} />
Einheit als durchgeführt markieren
{saveOk && (
{saveOk}
)}
{saving ? 'Speichert…' : 'Speichern'}
>
)}
setStep(timerOwningStep ?? safeStep)}
timerOwnerLabelIndex={timerOwningStep ?? 0}
branchGateMode={atBranchGate}
/>
>
) : null}
>
)}
)
}