import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { useNavigate, useParams } from 'react-router-dom' import api from '../utils/api' import TrainingUnitSectionsEditor from '../components/TrainingUnitSectionsEditor' import FormActionBar from '../components/FormActionBar' import UnsavedChangesPrompt from '../components/UnsavedChangesPrompt' import { useBeforeUnloadWhen, useUnsavedChangesBlocker } from '../hooks/useUnsavedChangesBlocker' import { useAuth } from '../context/AuthContext' import { useToast } from '../context/ToastContext' import { useNavReturn } from '../hooks/useNavReturn' import { buildPlanTemplatesListReturnContext, } from '../utils/navReturnContext' import { defaultSection, formSectionsFromPlanTemplateRows, templateSectionsPayloadFromFormSections, } from '../utils/trainingUnitSectionsForm' import { activeClubMemberships, getDefaultClubIdForGovernanceForms, getTenantClubDependencyKey, } from '../utils/activeClub' function templateFormSnapshot({ name, description, visibility, clubIdField, sections }) { return JSON.stringify({ name: (name || '').trim(), description: (description || '').trim(), visibility: visibility || '', clubIdField: (clubIdField || '').trim(), sections: templateSectionsPayloadFromFormSections(sections), }) } export default function TrainingPlanTemplateEditPage() { const { id: routeId } = useParams() const navigate = useNavigate() const templatesListReturn = useMemo(() => buildPlanTemplatesListReturnContext(), []) const { goBack } = useNavReturn(templatesListReturn) const templateId = parseInt(routeId, 10) const toast = useToast() const { user } = useAuth() const isPlatformAdmin = user?.role === 'admin' || user?.role === 'superadmin' const tenantClubDepKey = useMemo(() => getTenantClubDependencyKey(user), [user]) const [loading, setLoading] = useState(true) const [saving, setSaving] = useState(false) const [error, setError] = useState('') const [name, setName] = useState('') const [description, setDescription] = useState('') const [visibility, setVisibility] = useState('club') const [clubIdField, setClubIdField] = useState('') const [sections, setSections] = useState([defaultSection()]) const [clubsForGovernanceForms, setClubsForGovernanceForms] = useState([]) const baselineRef = useRef(null) const latestFormRef = useRef({}) const [baselineReady, setBaselineReady] = useState(false) const [bypassDirty, setBypassDirty] = useState(false) latestFormRef.current = { name, description, visibility, clubIdField, sections } const dirtySignature = templateFormSnapshot(latestFormRef.current) const formDirtyEffective = baselineReady && baselineRef.current != null && !bypassDirty && !loading && dirtySignature !== baselineRef.current const blocker = useUnsavedChangesBlocker(Boolean(formDirtyEffective && !saving)) useBeforeUnloadWhen(Boolean(formDirtyEffective && !saving)) const membershipClubRows = useMemo(() => activeClubMemberships(user?.clubs ?? []), [user?.clubs]) const visibilityClubChoices = useMemo(() => { if (isPlatformAdmin && clubsForGovernanceForms.length > 0) { return [...clubsForGovernanceForms].sort((a, b) => String(a.name || '').localeCompare(String(b.name || ''), 'de') ) } return [...membershipClubRows].sort((a, b) => String(a.name || '').localeCompare(String(b.name || ''), 'de') ) }, [isPlatformAdmin, clubsForGovernanceForms, membershipClubRows]) useEffect(() => { if (!isPlatformAdmin) { setClubsForGovernanceForms([]) return undefined } let cancelled = false ;(async () => { try { const list = await api.listClubs() if (!cancelled) setClubsForGovernanceForms(Array.isArray(list) ? list : []) } catch { if (!cancelled) setClubsForGovernanceForms([]) } })() return () => { cancelled = true } }, [isPlatformAdmin, tenantClubDepKey]) useEffect(() => { baselineRef.current = null setBaselineReady(false) setBypassDirty(false) }, [templateId]) useEffect(() => { if (loading) return const handle = window.setTimeout(() => { baselineRef.current = templateFormSnapshot(latestFormRef.current) setBaselineReady(true) }, 120) return () => clearTimeout(handle) }, [loading, templateId]) useEffect(() => { if (!Number.isFinite(templateId) || templateId < 1) { setError('Ungültige Vorlagen-ID') setLoading(false) return undefined } let cancelled = false async function load() { setLoading(true) setError('') try { const tpl = await api.getTrainingPlanTemplate(templateId) if (cancelled) return setName((tpl.name || '').trim()) setDescription((tpl.description || '').trim()) setVisibility((tpl.visibility || 'club').trim()) setClubIdField(tpl.club_id != null ? String(tpl.club_id) : '') const nextSections = formSectionsFromPlanTemplateRows(tpl.sections) setSections(nextSections.length ? nextSections : [defaultSection()]) } catch (e) { if (!cancelled) setError(e.message || 'Laden fehlgeschlagen') } finally { if (!cancelled) setLoading(false) } } load() return () => { cancelled = true } }, [templateId]) const buildBody = useCallback(() => { let cid = null if (visibility === 'club') { const raw = (clubIdField || '').trim() if (raw !== '') { const p = parseInt(raw, 10) if (Number.isFinite(p) && p >= 1) cid = p } else if (visibilityClubChoices.length === 1) { cid = visibilityClubChoices[0].id } } return { name: name.trim(), description: description.trim() || null, visibility, club_id: cid != null && Number.isFinite(cid) && cid >= 1 ? cid : visibility === 'club' ? undefined : null, sections: templateSectionsPayloadFromFormSections(sections), } }, [name, description, visibility, clubIdField, visibilityClubChoices, sections]) const performSave = async ({ fromUnsavedDialog = false, closeAfter = false } = {}) => { if (!name.trim()) { toast.error('Name ist Pflicht.') return false } if (visibility === 'club') { const bodyPreview = buildBody() if (bodyPreview.club_id === undefined) { toast.error('Bitte einen Verein wählen (Sichtbarkeit „Verein“).') return false } } setSaving(true) setError('') try { await api.updateTrainingPlanTemplate(templateId, buildBody()) baselineRef.current = templateFormSnapshot(latestFormRef.current) setBypassDirty(false) toast.success('Vorlage gespeichert.') if (closeAfter) goBack() return true } catch (err) { const msg = err.message || 'Speichern fehlgeschlagen' setError(msg) toast.error(msg) return false } finally { setSaving(false) } } const handleSave = async (e) => { e?.preventDefault?.() await performSave({ closeAfter: false }) } const handleSaveAndClose = async () => { await performSave({ closeAfter: true }) } const handleUnsavedDialogSave = async () => { const ok = await performSave({ fromUnsavedDialog: true }) if (ok) blocker.proceed() } if (loading) { return (
Laden …
Nur die Abschnitts-Gliederung (inkl. Split-Sessions / parallele Gruppen) — ohne Übungen. Beim Anwenden auf eine Einheit wird der Ablauf als Struktur übernommen.
{error ?{error}
: null}