Files
shinkan-jinkendo/frontend/src/pages/TrainingCoachPage.jsx
T
Lars a4f11a8225
Deploy Development / deploy (push) Successful in 39s
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m11s
Test Suite / pytest-backend (pull_request) Successful in 34s
Test Suite / lint-backend (pull_request) Successful in 0s
Test Suite / build-frontend (pull_request) Successful in 12s
Test Suite / k6 /health Baseline (pull_request) Successful in 34s
Test Suite / playwright-tests (pull_request) Successful in 1m20s
Enhance TrainingCoachPage and trainingPlanUtils with split rejoin transition logic
- Introduced a new utility function to determine when to prompt for a split rejoin transition between phases, improving user guidance during training sessions.
- Updated TrainingCoachPage to incorporate this logic, enhancing the flow of navigation through training timelines.
- Refactored button actions to provide clearer options for users when managing group transitions, optimizing the user experience during training.
2026-05-15 18:52:27 +02:00

1371 lines
56 KiB
React
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 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 (
<div className="training-coach-stepbar" style={{ marginBottom: '10px' }}>
{showJumpToTimerOwner && showJumpToTimerOwnerRow && (
<div style={{ textAlign: 'center', marginBottom: '8px' }}>
<button
type="button"
className="btn btn-secondary"
style={{ fontSize: '0.82rem', fontWeight: 600, padding: '8px 12px', lineHeight: 1.3 }}
onClick={onJumpToTimerOwner}
>
← Zur laufenden Übung ({timerOwnerLabelIndex + 1}/{timelineLength})
</button>
</div>
)}
<div
style={{
display: 'grid',
gridTemplateColumns: 'minmax(92px,1fr) minmax(0,2fr) minmax(92px,1fr)',
gap: '8px',
alignItems: 'stretch',
}}
>
<button
type="button"
className="btn btn-secondary"
style={{ minHeight: '46px', fontWeight: 700, padding: '6px 8px' }}
disabled={disPrev}
onClick={onPrev}
>
← zurück
</button>
<div style={{ display: 'flex', flexDirection: 'column', gap: '6px', justifyContent: 'center' }}>
<div style={{ display: 'flex', flexWrap: 'wrap', gap: '6px', justifyContent: 'center', alignItems: 'center' }}>
{runStartAt == null ? (
<button
type="button"
className="btn btn-primary"
style={{ minHeight: '44px', flex: '1 1 auto', fontWeight: 700 }}
disabled={branchGateMode}
onClick={onTimerStart}
>
▶ Start{alive ? ` · ${clockStr}` : ''}
</button>
) : (
<button type="button" className="btn btn-secondary" style={{ minHeight: '44px', flex: '1 1 auto', fontWeight: 700 }} onClick={onTimerPause}>
Pause · {clockStr}
</button>
)}
<button type="button" className="btn btn-secondary" style={{ minHeight: '44px', flex: '0 1 auto', fontWeight: 600 }} disabled={!canApplyForOwner} onClick={onApplyActual}>
Ist ({istLabelMin}&nbsp;Min)
</button>
{alive && !branchGateMode && (
<button
type="button"
className="btn btn-secondary"
title="Zeit löschen"
style={{ minHeight: '44px', flex: '0 0 auto', padding: '0 10px' }}
onClick={onTimerReset}
>
↺
</button>
)}
</div>
<button
type="button"
className="btn btn-primary"
style={{ width: '100%', minHeight: '44px', fontWeight: 700, lineHeight: 1.2, padding: '6px 10px', whiteSpace: 'normal', textAlign: 'center' }}
disabled={branchGateMode}
onClick={onDone}
>
{doneLabel}
</button>
</div>
<button
type="button"
className="btn btn-secondary"
style={{ minHeight: '46px', fontWeight: 700, padding: '6px 8px' }}
disabled={disNext}
onClick={onNext}
>
weiter →
</button>
</div>
</div>
)
}
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 (
<div style={{ padding: '2rem', textAlign: 'center' }}>
<div className="spinner" />
<p>Coach laden…</p>
</div>
)
}
if (loadError || !unit) {
return (
<div className="card" style={{ margin: '1rem', padding: '1.5rem' }}>
<p style={{ marginBottom: '1rem' }}>{loadError || 'Nicht gefunden.'}</p>
<button type="button" className="btn btn-secondary" onClick={() => navigate('/planning')}>
Zur Planung
</button>
</div>
)
}
return (
<div className="training-coach-page training-coach-layout">
<ExercisePeekModal
key={candidatePeekId != null ? String(candidatePeekId) : 'coach-peek-closed'}
open={candidatePeekId != null}
exerciseId={candidatePeekId}
onClose={() => setCandidatePeekId(null)}
/>
<nav
className="no-print training-coach-meta-nav"
style={{
flexShrink: 0,
display: 'flex',
flexWrap: 'wrap',
gap: '8px',
alignItems: 'center',
marginBottom: '8px',
paddingBottom: '4px'
}}
>
<button type="button" className="btn btn-secondary" onClick={() => navigate(`/planning/run/${unitId}`)}>
Zur Planansicht
</button>
<button type="button" className="btn btn-secondary" onClick={() => navigate('/planning')}>
Planung
</button>
{streamFocusOptions.length > 0 ? (
<label
className="no-print"
style={{ display: 'inline-flex', alignItems: 'center', gap: '6px', fontSize: '0.82rem', color: 'var(--text2)' }}
>
<span style={{ color: 'var(--text3)', whiteSpace: 'nowrap' }}>Ansicht</span>
<select
className="form-input"
style={{ minWidth: 'min(220px, 72vw)', margin: 0, padding: '6px 8px', fontSize: '0.82rem' }}
value={streamQuickSelectValue}
onChange={(e) => {
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)
}
}}
>
<option value="">Ablauf mit Split-Punkten (Standard)</option>
{streamFocusOptions.map((o) => (
<option key={o.valueKey} value={o.valueKey}>
{o.label}
</option>
))}
</select>
</label>
) : null}
<button
type="button"
className="btn btn-primary"
onClick={() => setOutlineOpen((o) => !o)}
style={{ marginLeft: 'auto' }}
>
{outlineOpen ? 'Rahmen schließen' : 'Trainingsrahmen'}
</button>
</nav>
{streamParamsInvalid ? (
<p
className="no-print card"
style={{
padding: '10px 12px',
fontSize: '0.82rem',
color: 'var(--danger)',
marginBottom: '8px',
flexShrink: 0,
}}
>
Ungültige Stream-Parameter in der Adresszeile — es wird der Gesamtplan angezeigt.
</p>
) : null}
{splitRejoinPrompt && !coachDebriefPhase ? (
<div
className="card no-print"
style={{
flexShrink: 0,
marginBottom: '10px',
padding: '16px 14px',
borderRadius: '12px',
border: '2px solid var(--accent)',
background: 'linear-gradient(135deg, var(--accent-light), var(--surface))',
}}
>
<div style={{ fontSize: '0.72rem', fontWeight: 700, color: 'var(--accent-dark)', marginBottom: '6px' }}>
Parallelphase · Abschluss
</div>
<p style={{ fontSize: '0.95rem', fontWeight: 700, margin: '0 0 8px', color: 'var(--text1)' }}>
{splitRejoinPrompt.phaseTitle != null && String(splitRejoinPrompt.phaseTitle).trim()
? String(splitRejoinPrompt.phaseTitle).trim()
: `Phase ${splitRejoinPrompt.phaseOrderIndex}`}
{' — '}
alle Gruppen zusammen?
</p>
<p style={{ fontSize: '0.84rem', color: 'var(--text2)', margin: '0 0 12px', lineHeight: 1.45 }}>
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.
</p>
<ul style={{ margin: '0 0 14px', paddingLeft: '1.2rem', fontSize: '0.82rem', color: 'var(--text2)' }}>
{splitRejoinPrompt.streams.map((st) => (
<li key={st.printStreamId || `s-${st.streamOrder}`}>
{st.streamTitle?.trim() ? String(st.streamTitle).trim() : `Gruppe ${st.streamOrder + 1}`}{' '}
<span style={{ color: 'var(--text3)' }}>(ca. {st.minutes} Min. Üb.)</span>
</li>
))}
</ul>
<div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
{safeStep < timeline.length - 1 ? (
<button
type="button"
className="btn btn-primary"
style={{ minHeight: '48px', fontWeight: 700 }}
onClick={() => {
setSplitRejoinPrompt(null)
setStep((s) => clampStep(s + 1, timeline.length))
}}
>
Gruppen zusammengeführt — weiter mit dem Plan
</button>
) : (
<button
type="button"
className="btn btn-primary"
style={{ minHeight: '48px', fontWeight: 700 }}
onClick={() => {
setSplitRejoinPrompt(null)
setCoachDebriefPhase(true)
try {
sessionStorage.setItem(storageDebriefKey(idNum), '1')
} catch {
/* ignore */
}
}}
>
Alle Gruppen fertig — zur Nachbereitung
</button>
)}
<button type="button" className="btn btn-secondary" style={{ minHeight: '44px' }} onClick={() => setSplitRejoinPrompt(null)}>
Zurück — andere Gruppe läuft noch
</button>
<button
type="button"
className="btn btn-secondary"
style={{ minHeight: '44px', fontSize: '0.82rem' }}
onClick={() => {
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'}
</button>
</div>
</div>
) : null}
<header
className="card training-coach-hero training-coach-hero--compact"
style={{
flexShrink: 0,
padding: '12px 14px',
marginBottom: '8px',
background: 'var(--surface)',
borderRadius: '12px',
borderLeft: `4px solid var(--accent)`
}}
>
<div style={{ fontSize: '0.7rem', color: 'var(--text3)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>
Coach ·{' '}
{coachDebriefPhase ? 'Nachbereitung · abschließend speichern' : `Schritt ${(safeStep || 0) + 1} / ${Math.max(timeline.length, 1)}`}
</div>
<h1 style={{ fontSize: '1.1rem', margin: '4px 0 0', lineHeight: 1.28 }}>
{unit.planned_date}
{unit.planned_time_start && ` · ${String(unit.planned_time_start).slice(0, 5)}`}
{unit.planned_focus ? ` · ${unit.planned_focus}` : ''}
</h1>
{streamFocusOptions.length > 0 ? (
<p style={{ fontSize: '0.8rem', color: 'var(--text2)', margin: '8px 0 0', lineHeight: 1.4 }}>
Parallele Phasen erscheinen als Schritt <strong>Gruppe wählen</strong> — 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 ? (
<span style={{ display: 'block', marginTop: '6px', color: 'var(--text3)', fontSize: '0.78rem' }}>
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(' · ')}
</span>
) : null}
</p>
) : null}
</header>
{outlineOpen && (
<div className="card training-coach-outline" style={{ flexShrink: 0, marginBottom: '8px', padding: '10px 12px', maxHeight: 'min(28vh, 260px)', display: 'flex', flexDirection: 'column', minHeight: 0 }}>
<div style={{ fontSize: '0.75rem', color: 'var(--text3)', marginBottom: '6px', flexShrink: 0 }}>
Trainingsrahmen · nach Blöcken und Streams
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: '10px', overflowY: 'auto', minHeight: 0 }}>
{outlineGroups.map((grp) => (
<div key={grp.mergeKey} style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>
<div
style={{
fontSize: '0.72rem',
fontWeight: 700,
color: 'var(--accent-dark)',
textTransform: 'uppercase',
letterSpacing: '0.04em',
}}
>
{grp.heading}
{grp.sub ? <span style={{ fontWeight: 600, color: 'var(--text3)', textTransform: 'none' }}> · {grp.sub}</span> : null}
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>
{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 (
<button
key={rowKey}
type="button"
className={`btn ${active ? 'btn-primary' : 'btn-secondary'}`}
style={{
textAlign: 'left',
justifyContent: 'flex-start',
opacity: active ? 1 : 0.92,
fontWeight: active ? 700 : 500,
}}
onClick={() => {
setCoachDebriefPhase(false)
setStep(ix)
}}
>
{ctx ? (
<span style={{ opacity: 0.8, display: 'block', fontSize: '0.72rem', marginBottom: '2px' }}>
{ctx.length > 42 ? `${ctx.slice(0, 40)}…` : ctx}
</span>
) : null}
<span>{lbl}</span>
</button>
)
})}
</div>
</div>
))}
</div>
</div>
)}
{timeline.length === 0 ? (
<p className="card" style={{ padding: '1rem', flexShrink: 0 }}>
Dieser Plan ist leer. <Link to="/planning">Unter Planung ergänzen</Link>.
</p>
) : coachDebriefPhase ? (
<div className="training-coach-scroll" style={{ flex: 1, minHeight: 0 }}>
<div className="card" style={{ padding: '14px', marginBottom: '12px', borderRadius: '12px', borderLeft: `4px solid var(--accent)` }}>
<div style={{ fontSize: '0.88rem', fontWeight: 700, marginBottom: '8px', color: 'var(--accent-dark)' }}>
Nachbereitung
</div>
<p style={{ fontSize: '0.82rem', color: 'var(--text2)', margin: '0 0 14px', lineHeight: 1.5 }}>
<strong>Ist‑Minuten</strong> prüfen, Trainer‑Ergänzung anlegen und Einheit sichern (zeigt bestehende Notizen weiter unten an).
</p>
<div style={{ display: 'flex', flexDirection: 'column', gap: '10px', marginBottom: '12px' }}>
{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 (
<label key={`db-${k}`} style={{ display: 'grid', gridTemplateColumns: '1fr 88px', gap: '10px', alignItems: 'center', fontSize: '0.88rem' }}>
<span style={{ wordBreak: 'break-word' }}>
{ent.coachContext ? <span style={{ color: 'var(--text3)' }}>{ent.coachContext} · </span> : null}
{summarizeTimelineEntry(ent)}
</span>
<input
type="number"
min="0"
className="form-input"
style={{ margin: 0 }}
value={val === '' || val == null ? '' : String(val)}
placeholder="Min"
onChange={(e) => {
const raw = e.target.value
if (raw === '') mergeDelta(setDeltas, k, { actual_duration_min: null })
else mergeDelta(setDeltas, k, { actual_duration_min: parseInt(raw, 10) })
}}
/>
</label>
)
})}
</div>
<label style={{ display: 'block', marginBottom: '10px', fontSize: '0.88rem', color: 'var(--text2)' }}>
Ergänzung Trainer (wird angehängt · mit Zeitstempel)
<textarea className="form-input" rows={3} value={trainerAppend} onChange={(e) => setTrainerAppend(e.target.value)} style={{ marginTop: '6px' }} />
</label>
<label style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '12px', fontSize: '0.88rem' }}>
<input type="checkbox" checked={saveMarkDone} onChange={(e) => setSaveMarkDone(e.target.checked)} />
Einheit als <strong>durchgeführt</strong> markieren
</label>
{saveOk && (
<p
style={{
fontSize: '0.88rem',
marginBottom: '8px',
color: saveOk.startsWith('Fehler') ? 'var(--danger)' : 'var(--accent-dark)'
}}
>
{saveOk}
</p>
)}
<div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
<button type="button" className="btn btn-primary" style={{ width: '100%', minHeight: '48px' }} disabled={saving} onClick={handleSaveDebrief}>
{saving ? 'Speichert…' : 'Speichern'}
</button>
<button
type="button"
className="btn btn-secondary"
style={{ width: '100%', minHeight: '44px' }}
onClick={() => {
setCoachDebriefPhase(false)
if (timeline.length > 0) setStep(Math.max(0, timeline.length - 1))
}}
>
Zurück zur letzten Übungsposition
</button>
</div>
</div>
{unit.trainer_notes ? (
<div className="card" style={{ marginBottom: '12px', padding: '12px 14px', borderLeft: `4px solid var(--accent)` }}>
<div style={{ fontSize: '0.7rem', fontWeight: 700, color: 'var(--text3)', textTransform: 'uppercase' }}>Einheit · Trainernotizen</div>
<p style={{ fontSize: '0.88rem', marginTop: '6px', whiteSpace: 'pre-wrap', color: 'var(--text2)' }}>{unit.trainer_notes}</p>
</div>
) : null}
</div>
) : (
<>
{!splitRejoinPrompt ? (
<>
<div
className="training-coach-assist training-coach-assist--compact"
style={{
flexShrink: 0,
marginBottom: '8px',
padding: '12px 14px',
background: 'var(--accent-light)',
borderRadius: '12px'
}}
>
<div style={{ fontSize: '0.72rem', fontWeight: 700, color: 'var(--accent-dark)', marginBottom: '6px' }}>
Als Nächstes
</div>
{atBranchGate ? (
<p style={{ margin: 0, fontSize: '0.88rem', color: 'var(--text2)', lineHeight: 1.45 }}>
Wählen Sie unten eine Gruppe. Danach zeigt der Coach fortlaufend nur die Übungen dieses Streams in dieser
parallelen Phase.
</p>
) : nextEntry ? (
<>
<p style={{ margin: '0', fontSize: '0.9rem', color: 'var(--text1)', lineHeight: 1.4 }}>
<strong>Nächste:</strong> {summarizeTimelineEntry(nextEntry)}
</p>
{next2Entry && (
<p style={{ margin: '6px 0 0', fontSize: '0.82rem', color: 'var(--text2)' }}>
<strong>Daraufhin:</strong> {summarizeTimelineEntry(next2Entry)}
</p>
)}
</>
) : (
<p style={{ margin: 0, fontSize: '0.88rem', color: 'var(--text2)' }}>
Letzter Punkt — „Nachbereitung &amp; Ist-Zeit“ öffnet die Abschlussseite zum Speichern.
</p>
)}
</div>
<CoachControlsBand
step={safeStep}
timelineLength={timeline.length}
onPrev={goPrev}
onNext={goNext}
onDone={markCurrentDoneAdvance}
clockStr={clockStr}
runStartAt={runStartAt}
pausedAccumMs={pausedAccumMs}
onTimerStart={timerStart}
onTimerPause={timerPause}
onTimerReset={timerReset}
onApplyActual={applySuggestedDuration}
roundedMinForApply={roundedMinApply}
isLastCoachStep={isLastCoachStep}
showJumpToTimerOwner={showJumpToTimerOwner}
showJumpToTimerOwnerRow
onJumpToTimerOwner={() => setStep(timerOwningStep ?? safeStep)}
timerOwnerLabelIndex={timerOwningStep ?? 0}
branchGateMode={atBranchGate}
/>
<div className="training-coach-scroll">
{atBranchGate && currentEntry?.branchMeta ? (
<div
className="card"
style={{
padding: '18px 16px',
marginBottom: '12px',
borderRadius: '14px',
border: '2px solid var(--accent)',
background: 'linear-gradient(180deg, var(--accent-light) 0%, var(--surface) 38%)',
boxShadow: '0 2px 12px rgba(0,0,0,0.06)',
}}
>
<div style={{ fontSize: '0.74rem', fontWeight: 800, color: 'var(--accent-dark)', marginBottom: '6px', letterSpacing: '0.04em' }}>
⑂ SPLIT — GRUPPE WÄHLEN
</div>
<p style={{ fontSize: '1.05rem', fontWeight: 800, margin: '0 0 8px', color: 'var(--text1)' }}>
{currentEntry.branchMeta.phaseTitle != null && String(currentEntry.branchMeta.phaseTitle).trim()
? String(currentEntry.branchMeta.phaseTitle).trim()
: `Phase ${currentEntry.branchMeta.phaseOrderIndex}`}
</p>
<p style={{ fontSize: '0.88rem', color: 'var(--text2)', margin: '0 0 16px', lineHeight: 1.45 }}>
Tippen Sie auf eine Kachel, um <strong>diese Gruppe</strong> zu coachen. Andere Trainer:innen wählen auf
ihrem Gerät parallel eine andere Kachel.
</p>
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(240px, 1fr))', gap: '12px' }}>
{(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 (
<button
key={st.printStreamId || `s-${st.streamOrder}`}
type="button"
className="btn"
style={{
textAlign: 'left',
justifyContent: 'flex-start',
flexDirection: 'column',
alignItems: 'stretch',
padding: '14px 16px',
minHeight: '96px',
fontWeight: 700,
background: baseBg,
color: baseColor,
border: `2px solid ${borderCol}`,
borderRadius: '12px',
boxShadow: hinted ? '0 4px 0 var(--accent-dark)' : '0 3px 0 hsl(200 20% 78%)',
transition: 'transform 0.08s ease, box-shadow 0.08s ease',
}}
onClick={() => pickStreamForPhase(currentEntry.branchMeta.phaseOrderIndex, st.streamOrder)}
>
<span style={{ display: 'flex', alignItems: 'center', gap: '8px', fontSize: '1rem' }}>
<span style={{ fontSize: '1.35rem', lineHeight: 1 }} aria-hidden="true">
{hinted ? '◉' : '○'}
</span>
<span>{label}</span>
</span>
<span
style={{
display: 'block',
fontSize: '0.82rem',
fontWeight: 600,
opacity: hinted ? 0.95 : 0.88,
marginTop: '8px',
}}
>
≈ {st.minutes} Min. Üb. · Jetzt aktivieren
</span>
{hinted ? (
<span style={{ display: 'block', fontSize: '0.74rem', fontWeight: 600, marginTop: '8px', opacity: 0.92 }}>
Vorschlag aus Planansicht — trotzdem andere Kachel möglich
</span>
) : null}
</button>
)
})}
</div>
</div>
) : currentEntry?.item?.item_type === 'note' ? (
<div className="card" style={{ padding: '16px 14px' }}>
<div style={{ fontSize: '0.74rem', color: 'var(--text3)', marginBottom: '8px' }}>
{currentEntry?.coachContext || currentEntry?.sec?.title || 'Abschnitt'} · Coach-Notiz · Teil{' '}
{safeStep + 1}
</div>
<div style={{ fontSize: '0.78rem', color: 'var(--text3)', marginBottom: '6px' }}>Coach-Notiz</div>
<p style={{ fontSize: '1.05rem', lineHeight: 1.52, whiteSpace: 'pre-wrap', margin: 0 }}>{currentEntry.item.note_body || ''}</p>
</div>
) : (
<>
<div className="card training-coach-plan-strip" style={{ padding: '12px 14px', marginBottom: '12px', borderRadius: '12px', borderLeft: `3px solid var(--accent)` }}>
<div style={{ fontSize: '0.74rem', color: 'var(--text3)', marginBottom: '6px' }}>
In diesem Training · {currentEntry?.coachContext || currentEntry?.sec?.title || 'Abschnitt'} · Teil{' '}
{safeStep + 1}
</div>
{currentEntry?.item && (
<>
<p style={{ margin: '0 0 6px', fontSize: '0.95rem', fontWeight: 700 }}>
{currentEntry.item.exercise_title ||
(currentEntry.item.exercise_id ? `Übung #${currentEntry.item.exercise_id}` : 'Übung')}
{currentEntry.item.exercise_variant_name ? (
<span style={{ fontWeight: 600, color: 'var(--text2)' }}> ({currentEntry.item.exercise_variant_name})</span>
) : null}
</p>
<p style={{ fontSize: '0.83rem', color: 'var(--text3)', marginBottom: '8px' }}>
geplant <strong>{currentEntry.item.planned_duration_min ?? '—'}</strong> Min · Ist (Plan):{' '}
<strong>
{durationOverridesForApi[String(currentEntry.item.id)] != null
? durationOverridesForApi[String(currentEntry.item.id)].actual_duration_min
: currentEntry.item.actual_duration_min ?? '—'}{' '}
Min
</strong>{' '}
{durationOverridesForApi[String(currentEntry.item.id)] != null ? '(Entwurf)' : ''}
</p>
{currentEntry.item.exercise_focus_area ? (
<p style={{ fontSize: '0.82rem', color: 'var(--text2)', marginBottom: '10px' }}>{currentEntry.item.exercise_focus_area}</p>
) : null}
{currentEntry.item.notes ? (
<div style={{ marginBottom: '10px', padding: '10px', background: 'var(--surface2)', borderRadius: '8px' }}>
<div style={{ fontSize: '0.72rem', textTransform: 'uppercase', color: 'var(--text3)' }}>Zu dieser Platzierung</div>
<p style={{ marginTop: '4px', whiteSpace: 'pre-wrap', fontSize: '0.93rem' }}>{currentEntry.item.notes}</p>
</div>
) : null}
{currentEntry.item.modifications ? (
<div style={{ padding: '10px', borderRadius: '8px', border: `1px solid var(--accent)` }}>
<div style={{ fontSize: '0.72rem', textTransform: 'uppercase', color: 'var(--accent-dark)' }}>Anpassung</div>
<p style={{ marginTop: '4px', whiteSpace: 'pre-wrap', fontSize: '0.93rem' }}>{currentEntry.item.modifications}</p>
</div>
) : null}
</>
)}
<hr style={{ border: 'none', borderTop: '1px solid var(--border)', margin: '14px 0 12px' }} />
<div style={{ fontSize: '0.72rem', textTransform: 'uppercase', letterSpacing: '0.04em', color: 'var(--text3)', marginBottom: '6px' }}>
Übung aus dem Katalog (vollständig)
</div>
<ExerciseFullContent
loading={catalogLoading}
error={catalogError}
exercise={catalogExercise}
exerciseId={currentEntry?.item?.exercise_id ?? null}
variantId={currentEntry?.item?.exercise_variant_id ?? null}
catalogMethodProfileSnapshot={
String(currentEntry?.item?.exercise_kind || 'simple').toLowerCase().trim() === 'combination'
? currentEntry?.item?.catalog_method_profile ?? null
: null
}
planningComboMethodProfile={
String(currentEntry?.item?.exercise_kind || 'simple').toLowerCase().trim() === 'combination'
? currentEntry?.item?.planning_method_profile ?? null
: null
}
onCandidateExercisePeek={(id) => setCandidatePeekId(id)}
/>
</div>
</>
)}
{unit.trainer_notes ? (
<div className="card" style={{ marginBottom: '12px', padding: '12px 14px', borderLeft: `4px solid var(--accent)` }}>
<div style={{ fontSize: '0.7rem', fontWeight: 700, color: 'var(--text3)', textTransform: 'uppercase' }}>Einheit · Trainernotizen</div>
<p style={{ fontSize: '0.88rem', marginTop: '6px', whiteSpace: 'pre-wrap', color: 'var(--text2)' }}>{unit.trainer_notes}</p>
</div>
) : null}
<div className="card training-coach-debrief" style={{ padding: '14px', marginBottom: '8px', borderRadius: '10px' }}>
<button
type="button"
className="btn btn-secondary"
style={{ width: '100%', textAlign: 'left', justifyContent: 'space-between', display: 'flex', alignItems: 'center' }}
onClick={() => setDebriefOpen(!debriefOpen)}
>
<span style={{ fontWeight: 700 }}>Nachbereitung &amp; speichern</span>
<span>{debriefOpen ? '▼' : '▶'}</span>
</button>
{debriefOpen && (
<>
<p style={{ fontSize: '0.82rem', color: 'var(--text2)', margin: '14px 0 10px', lineHeight: 1.5 }}>
<strong>Ist‑Minuten</strong> anpassen und Einheit speichern (inkl. Trainer-Ergänzung).
</p>
<div style={{ display: 'flex', flexDirection: 'column', gap: '10px', marginBottom: '12px' }}>
{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 (
<label key={k} style={{ display: 'grid', gridTemplateColumns: '1fr 88px', gap: '10px', alignItems: 'center', fontSize: '0.88rem' }}>
<span style={{ wordBreak: 'break-word' }}>
{ent.coachContext ? <span style={{ color: 'var(--text3)' }}>{ent.coachContext} · </span> : null}
{summarizeTimelineEntry(ent)}
</span>
<input
type="number"
min="0"
className="form-input"
style={{ margin: 0 }}
value={val === '' || val == null ? '' : String(val)}
placeholder="Min"
onChange={(e) => {
const raw = e.target.value
if (raw === '') mergeDelta(setDeltas, k, { actual_duration_min: null })
else mergeDelta(setDeltas, k, { actual_duration_min: parseInt(raw, 10) })
}}
/>
</label>
)
})}
</div>
<label style={{ display: 'block', marginBottom: '10px', fontSize: '0.88rem', color: 'var(--text2)' }}>
Ergänzung Trainer (wird angehängt · mit Zeitstempel)
<textarea className="form-input" rows={3} value={trainerAppend} onChange={(e) => setTrainerAppend(e.target.value)} style={{ marginTop: '6px' }} />
</label>
<label style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '12px', fontSize: '0.88rem' }}>
<input type="checkbox" checked={saveMarkDone} onChange={(e) => setSaveMarkDone(e.target.checked)} />
Einheit als <strong>durchgeführt</strong> markieren
</label>
{saveOk && (
<p
style={{
fontSize: '0.88rem',
marginBottom: '8px',
color: saveOk.startsWith('Fehler') ? 'var(--danger)' : 'var(--accent-dark)'
}}
>
{saveOk}
</p>
)}
<button type="button" className="btn btn-primary" style={{ width: '100%', minHeight: '48px' }} disabled={saving} onClick={handleSaveDebrief}>
{saving ? 'Speichert…' : 'Speichern'}
</button>
</>
)}
</div>
</div>
<CoachControlsBand
step={safeStep}
timelineLength={timeline.length}
onPrev={goPrev}
onNext={goNext}
onDone={markCurrentDoneAdvance}
clockStr={clockStr}
runStartAt={runStartAt}
pausedAccumMs={pausedAccumMs}
onTimerStart={timerStart}
onTimerPause={timerPause}
onTimerReset={timerReset}
onApplyActual={applySuggestedDuration}
roundedMinForApply={roundedMinApply}
isLastCoachStep={isLastCoachStep}
showJumpToTimerOwner={showJumpToTimerOwner}
showJumpToTimerOwnerRow={false}
onJumpToTimerOwner={() => setStep(timerOwningStep ?? safeStep)}
timerOwnerLabelIndex={timerOwningStep ?? 0}
branchGateMode={atBranchGate}
/>
</>
) : null}
</>
)}
</div>
)
}