'use client' import { useEffect, useState } from 'react' import { getModules, getMatrix, getAssignments, getStats, getDeadlines, getModuleMedia, getAuditLog, generateContent, generateQuiz, publishContent, checkEscalation, getContent, generateAllContent, generateAllQuizzes, createModule, updateModule, deleteModule, deleteMatrixEntry, setMatrixEntry, startAssignment, completeAssignment, updateAssignment, listBlockConfigs, createBlockConfig, deleteBlockConfig, previewBlock, generateBlock, getCanonicalMeta, generateInteractiveVideo, } from '@/lib/sdk/training/api' import type { TrainingModule, TrainingAssignment, MatrixResponse, TrainingStats, DeadlineInfo, AuditLogEntry, ModuleContent, TrainingMedia, TrainingBlockConfig, CanonicalControlMeta, BlockPreview, BlockGenerateResult, } from '@/lib/sdk/training/types' import { REGULATION_LABELS, REGULATION_COLORS, FREQUENCY_LABELS, STATUS_LABELS, STATUS_COLORS, ROLE_LABELS, ALL_ROLES, TARGET_AUDIENCE_LABELS, } from '@/lib/sdk/training/types' import AudioPlayer from '@/components/training/AudioPlayer' import VideoPlayer from '@/components/training/VideoPlayer' import ScriptPreview from '@/components/training/ScriptPreview' type Tab = 'overview' | 'modules' | 'matrix' | 'assignments' | 'content' | 'audit' export default function TrainingPage() { const [activeTab, setActiveTab] = useState('overview') const [loading, setLoading] = useState(true) const [error, setError] = useState(null) const [stats, setStats] = useState(null) const [modules, setModules] = useState([]) const [matrix, setMatrix] = useState(null) const [assignments, setAssignments] = useState([]) const [deadlines, setDeadlines] = useState([]) const [auditLog, setAuditLog] = useState([]) const [selectedModuleId, setSelectedModuleId] = useState('') const [generatedContent, setGeneratedContent] = useState(null) const [generating, setGenerating] = useState(false) const [bulkGenerating, setBulkGenerating] = useState(false) const [bulkResult, setBulkResult] = useState<{ generated: number; skipped: number; errors: string[] } | null>(null) const [moduleMedia, setModuleMedia] = useState([]) const [interactiveGenerating, setInteractiveGenerating] = useState(false) const [statusFilter, setStatusFilter] = useState('') const [regulationFilter, setRegulationFilter] = useState('') // Modal/Drawer states const [showModuleCreate, setShowModuleCreate] = useState(false) const [selectedModule, setSelectedModule] = useState(null) const [matrixAddRole, setMatrixAddRole] = useState(null) const [selectedAssignment, setSelectedAssignment] = useState(null) const [escalationResult, setEscalationResult] = useState<{ total_checked: number; escalated: number } | null>(null) // Block (Controls → Module) state const [blocks, setBlocks] = useState([]) const [canonicalMeta, setCanonicalMeta] = useState(null) const [showBlockCreate, setShowBlockCreate] = useState(false) const [blockPreview, setBlockPreview] = useState(null) const [blockPreviewId, setBlockPreviewId] = useState('') const [blockGenerating, setBlockGenerating] = useState(false) const [blockResult, setBlockResult] = useState(null) useEffect(() => { loadData() }, []) useEffect(() => { if (selectedModuleId) { loadModuleMedia(selectedModuleId) } }, [selectedModuleId]) async function loadData() { setLoading(true) setError(null) try { const [statsRes, modulesRes, matrixRes, assignmentsRes, deadlinesRes, auditRes, blocksRes, metaRes] = await Promise.allSettled([ getStats(), getModules(), getMatrix(), getAssignments({ limit: 50 }), getDeadlines(10), getAuditLog({ limit: 30 }), listBlockConfigs(), getCanonicalMeta(), ]) if (statsRes.status === 'fulfilled') setStats(statsRes.value) if (modulesRes.status === 'fulfilled') setModules(modulesRes.value.modules) if (matrixRes.status === 'fulfilled') setMatrix(matrixRes.value) if (assignmentsRes.status === 'fulfilled') setAssignments(assignmentsRes.value.assignments) if (deadlinesRes.status === 'fulfilled') setDeadlines(deadlinesRes.value.deadlines) if (auditRes.status === 'fulfilled') setAuditLog(auditRes.value.entries) if (blocksRes.status === 'fulfilled') setBlocks(blocksRes.value.blocks) if (metaRes.status === 'fulfilled') setCanonicalMeta(metaRes.value) } catch (e) { setError(e instanceof Error ? e.message : 'Fehler beim Laden') } finally { setLoading(false) } } async function handleGenerateContent() { if (!selectedModuleId) return setGenerating(true) try { const content = await generateContent(selectedModuleId) setGeneratedContent(content) } catch (e) { setError(e instanceof Error ? e.message : 'Fehler bei der Content-Generierung') } finally { setGenerating(false) } } async function handleGenerateQuiz() { if (!selectedModuleId) return setGenerating(true) try { await generateQuiz(selectedModuleId, 5) await loadData() } catch (e) { setError(e instanceof Error ? e.message : 'Fehler bei der Quiz-Generierung') } finally { setGenerating(false) } } async function handleGenerateInteractiveVideo() { if (!selectedModuleId) return setInteractiveGenerating(true) try { await generateInteractiveVideo(selectedModuleId) await loadModuleMedia(selectedModuleId) } catch (e) { setError(e instanceof Error ? e.message : 'Fehler bei der interaktiven Video-Generierung') } finally { setInteractiveGenerating(false) } } async function handlePublishContent(contentId: string) { try { await publishContent(contentId) setGeneratedContent(null) await loadData() } catch (e) { setError(e instanceof Error ? e.message : 'Fehler beim Veroeffentlichen') } } async function handleCheckEscalation() { try { const result = await checkEscalation() setEscalationResult({ total_checked: result.total_checked, escalated: result.escalated }) await loadData() } catch (e) { setError(e instanceof Error ? e.message : 'Fehler bei der Eskalationspruefung') } } async function handleDeleteMatrixEntry(roleCode: string, moduleId: string) { if (!window.confirm('Modulzuordnung entfernen?')) return try { await deleteMatrixEntry(roleCode, moduleId) await loadData() } catch (e) { setError(e instanceof Error ? e.message : 'Fehler beim Entfernen') } } async function handleLoadContent(moduleId: string) { try { const content = await getContent(moduleId) setGeneratedContent(content) } catch { setGeneratedContent(null) } } async function handleBulkContent() { setBulkGenerating(true) setBulkResult(null) try { const result = await generateAllContent('de') setBulkResult({ generated: result.generated ?? 0, skipped: result.skipped ?? 0, errors: result.errors ?? [] }) await loadData() } catch (e) { setError(e instanceof Error ? e.message : 'Fehler bei der Bulk-Generierung') } finally { setBulkGenerating(false) } } async function loadModuleMedia(moduleId: string) { try { const result = await getModuleMedia(moduleId) setModuleMedia(result.media) } catch { setModuleMedia([]) } } async function handleBulkQuiz() { setBulkGenerating(true) setBulkResult(null) try { const result = await generateAllQuizzes() setBulkResult({ generated: result.generated ?? 0, skipped: result.skipped ?? 0, errors: result.errors ?? [] }) await loadData() } catch (e) { setError(e instanceof Error ? e.message : 'Fehler bei der Bulk-Quiz-Generierung') } finally { setBulkGenerating(false) } } // Block handlers async function handleCreateBlock(data: { name: string; description?: string; domain_filter?: string; category_filter?: string; severity_filter?: string; target_audience_filter?: string; regulation_area: string; module_code_prefix: string; max_controls_per_module?: number; }) { try { await createBlockConfig(data) setShowBlockCreate(false) const res = await listBlockConfigs() setBlocks(res.blocks) } catch (e) { setError(e instanceof Error ? e.message : 'Fehler beim Erstellen') } } async function handleDeleteBlock(id: string) { if (!confirm('Block-Konfiguration wirklich loeschen?')) return try { await deleteBlockConfig(id) const res = await listBlockConfigs() setBlocks(res.blocks) } catch (e) { setError(e instanceof Error ? e.message : 'Fehler beim Loeschen') } } async function handlePreviewBlock(id: string) { setBlockPreviewId(id) setBlockPreview(null) setBlockResult(null) try { const preview = await previewBlock(id) setBlockPreview(preview) } catch (e) { setError(e instanceof Error ? e.message : 'Fehler beim Preview') } } async function handleGenerateBlock(id: string) { setBlockGenerating(true) setBlockResult(null) try { const result = await generateBlock(id, { language: 'de', auto_matrix: true }) setBlockResult(result) await loadData() } catch (e) { setError(e instanceof Error ? e.message : 'Fehler bei der Block-Generierung') } finally { setBlockGenerating(false) } } const tabs: { id: Tab; label: string }[] = [ { id: 'overview', label: 'Uebersicht' }, { id: 'modules', label: 'Modulkatalog' }, { id: 'matrix', label: 'Training Matrix' }, { id: 'assignments', label: 'Zuweisungen' }, { id: 'content', label: 'Content-Generator' }, { id: 'audit', label: 'Audit Trail' }, ] const filteredModules = modules.filter(m => (!regulationFilter || m.regulation_area === regulationFilter) ) const filteredAssignments = assignments.filter(a => (!statusFilter || a.status === statusFilter) ) if (loading) { return (
{[1,2,3,4].map(i =>
)}
) } return (
{/* Header */}

Compliance Training Engine

Training-Module, Zuweisungen und Compliance-Schulungen verwalten

{error && (
{error}
)} {/* Tabs */}
{/* Tab Content */} {activeTab === 'overview' && stats && (
{escalationResult && (
Eskalation abgeschlossen: {escalationResult.total_checked} Zuweisungen geprueft, {escalationResult.escalated} eskaliert
)}
= 80 ? 'green' : stats.completion_rate >= 50 ? 'yellow' : 'red'} /> 0 ? 'red' : 'green'} />
5 ? 'yellow' : 'green'} />
{/* Status Bar */}

Status-Verteilung

{stats.total_assignments > 0 && (
{stats.completed_count > 0 &&
} {stats.in_progress_count > 0 &&
} {stats.pending_count > 0 &&
} {stats.overdue_count > 0 &&
}
)}
Abgeschlossen In Bearbeitung Ausstehend Ueberfaellig
{/* Deadlines */} {deadlines.length > 0 && (

Naechste Deadlines

{deadlines.slice(0, 5).map(d => (
{d.module_title} ({d.user_name})
{d.days_left <= 0 ? `${Math.abs(d.days_left)} Tage ueberfaellig` : `${d.days_left} Tage`}
))}
)}
)} {activeTab === 'modules' && (
{filteredModules.map(m => (
setSelectedModule(m)} className="bg-white border rounded-lg p-4 hover:shadow-md cursor-pointer transition-shadow" >
{REGULATION_LABELS[m.regulation_area] || m.regulation_area}

{m.title}

{m.module_code}

{m.nis2_relevant && ( NIS2 )} {!m.is_active && ( Inaktiv )}
{m.description &&

{m.description}

}
{m.duration_minutes} Min. {FREQUENCY_LABELS[m.frequency_type]} Quiz: {m.pass_threshold}%
))}
{filteredModules.length === 0 &&

Keine Module gefunden

}
)} {activeTab === 'matrix' && matrix && (

Compliance Training Matrix (CTM): Welche Rollen benoetigen welche Schulungsmodule

{ALL_ROLES.map(role => { const entries = matrix.entries[role] || [] return ( ) })}
Rolle Module Anzahl
{role} {ROLE_LABELS[role]}
{entries.map(e => ( {e.is_mandatory ? '🔴' : '🔵'} {e.module_code} ))} {entries.length === 0 && Keine Module}
{entries.length}
)} {activeTab === 'assignments' && (
{filteredAssignments.map(a => ( setSelectedAssignment(a)} className="border-b hover:bg-gray-50 cursor-pointer" > ))}
Modul Mitarbeiter Rolle Fortschritt Status Quiz Deadline Eskalation
{a.module_title || a.module_code}
{a.module_code}
{a.user_name}
{a.user_email}
{a.role_code || '-'}
{a.progress_percent}%
{STATUS_LABELS[a.status] || a.status} {a.quiz_score != null ? ( {a.quiz_score.toFixed(0)}% ) : '-'} {new Date(a.deadline).toLocaleDateString('de-DE')} {a.escalation_level > 0 ? L{a.escalation_level} : '-'}
{filteredAssignments.length === 0 &&

Keine Zuweisungen

}
)} {activeTab === 'content' && (
{/* Training Blocks — Controls → Schulungsmodule */}

Schulungsbloecke aus Controls

Canonical Controls nach Kriterien filtern und automatisch Schulungsmodule generieren {canonicalMeta && ({canonicalMeta.total} Controls verfuegbar)}

{/* Block list */} {blocks.length > 0 ? (
{blocks.map(block => ( ))}
Name Domain Zielgruppe Severity Prefix Letzte Generierung Aktionen
{block.name}
{block.description &&
{block.description}
}
{block.domain_filter || 'Alle'} {block.target_audience_filter ? (TARGET_AUDIENCE_LABELS[block.target_audience_filter] || block.target_audience_filter) : 'Alle'} {block.severity_filter || 'Alle'} {block.module_code_prefix} {block.last_generated_at ? new Date(block.last_generated_at).toLocaleString('de-DE') : 'Noch nie'}
) : (
Noch keine Schulungsbloecke konfiguriert. Erstelle einen Block, um Controls automatisch in Module umzuwandeln.
)} {/* Preview result */} {blockPreview && blockPreviewId && (

Preview: {blocks.find(b => b.id === blockPreviewId)?.name}

Controls: {blockPreview.control_count} Module: {blockPreview.module_count} Rollen: {blockPreview.proposed_roles.map(r => ROLE_LABELS[r] || r).join(', ')}
{blockPreview.controls.length > 0 && (
Passende Controls anzeigen ({blockPreview.control_count})
{blockPreview.controls.slice(0, 50).map(ctrl => (
{ctrl.control_id} {ctrl.title} {ctrl.severity}
))} {blockPreview.control_count > 50 &&
... und {blockPreview.control_count - 50} weitere
}
)}
)} {/* Generate result */} {blockResult && (

Generierung abgeschlossen

Module erstellt: {blockResult.modules_created} Controls verknuepft: {blockResult.controls_linked} Matrix-Eintraege: {blockResult.matrix_entries_created} Content generiert: {blockResult.content_generated}
{blockResult.errors && blockResult.errors.length > 0 && (
{blockResult.errors.map((err, i) =>
{err}
)}
)}
)}
{/* Block Create Modal */} {showBlockCreate && (

Neuen Schulungsblock erstellen

{ e.preventDefault() const fd = new FormData(e.currentTarget) handleCreateBlock({ name: fd.get('name') as string, description: fd.get('description') as string || undefined, domain_filter: fd.get('domain_filter') as string || undefined, category_filter: fd.get('category_filter') as string || undefined, severity_filter: fd.get('severity_filter') as string || undefined, target_audience_filter: fd.get('target_audience_filter') as string || undefined, regulation_area: fd.get('regulation_area') as string, module_code_prefix: fd.get('module_code_prefix') as string, max_controls_per_module: parseInt(fd.get('max_controls_per_module') as string) || 20, }) }} className="space-y-3">