'use client' import React, { useState, useEffect, useCallback, useMemo } from 'react' import { useSDK } from '@/lib/sdk' import { StepHeader, STEP_EXPLANATIONS } from '@/components/sdk/StepHeader/StepHeader' import { ScopeOverviewTab, ScopeWizardTab, ScopeDecisionTab, ScopeExportTab } from '@/components/sdk/compliance-scope' import type { ComplianceScopeState, ScopeProfilingAnswer, ScopeDecision } from '@/lib/sdk/compliance-scope-types' import { createEmptyScopeState, STORAGE_KEY } from '@/lib/sdk/compliance-scope-types' import { complianceScopeEngine } from '@/lib/sdk/compliance-scope-engine' import { getAllQuestions } from '@/lib/sdk/compliance-scope-profiling' type TabId = 'overview' | 'wizard' | 'decision' | 'export' const TABS: { id: TabId; label: string; icon: string }[] = [ { id: 'overview', label: 'Uebersicht', icon: '📊' }, { id: 'wizard', label: 'Scope-Profiling', icon: '📋' }, { id: 'decision', label: 'Scope-Entscheidung', icon: '⚖️' }, { id: 'export', label: 'Export', icon: '📤' }, ] export default function ComplianceScopePage() { const { state: sdkState, dispatch } = useSDK() // Active tab state const [activeTab, setActiveTab] = useState('overview') // Local scope state const [scopeState, setScopeState] = useState(() => { // Try to load from SDK context first if (sdkState.complianceScope) { return sdkState.complianceScope } return createEmptyScopeState() }) // Loading state const [isLoading, setIsLoading] = useState(true) const [isEvaluating, setIsEvaluating] = useState(false) // Load from localStorage on mount useEffect(() => { try { const stored = localStorage.getItem(STORAGE_KEY) if (stored) { const parsed = JSON.parse(stored) as ComplianceScopeState setScopeState(parsed) // Also sync to SDK context dispatch({ type: 'SET_COMPLIANCE_SCOPE', payload: parsed }) } } catch (error) { console.error('Failed to load compliance scope state from localStorage:', error) } finally { setIsLoading(false) } }, [dispatch]) // Save to localStorage and SDK context whenever state changes useEffect(() => { if (!isLoading) { try { localStorage.setItem(STORAGE_KEY, JSON.stringify(scopeState)) dispatch({ type: 'SET_COMPLIANCE_SCOPE', payload: scopeState }) } catch (error) { console.error('Failed to save compliance scope state:', error) } } }, [scopeState, isLoading, dispatch]) // Handle answers change from wizard const handleAnswersChange = useCallback((answers: ScopeProfilingAnswer[]) => { setScopeState(prev => ({ ...prev, answers, lastModified: new Date().toISOString(), })) }, []) // Handle evaluate button click const handleEvaluate = useCallback(async () => { setIsEvaluating(true) try { // Run the compliance scope engine const decision = complianceScopeEngine.evaluate(scopeState.answers) // Update state with decision setScopeState(prev => ({ ...prev, decision, lastModified: new Date().toISOString(), })) // Switch to decision tab to show results setActiveTab('decision') } catch (error) { console.error('Failed to evaluate compliance scope:', error) // Optionally show error toast/notification } finally { setIsEvaluating(false) } }, [scopeState.answers]) // Handle start profiling from overview const handleStartProfiling = useCallback(() => { setActiveTab('wizard') }, []) // Handle reset const handleReset = useCallback(() => { const emptyState = createEmptyScopeState() setScopeState(emptyState) setActiveTab('overview') localStorage.removeItem(STORAGE_KEY) }, []) // Calculate completion statistics const completionStats = useMemo(() => { const allQuestions = getAllQuestions() const requiredQuestions = allQuestions.filter(q => q.required) const totalQuestions = requiredQuestions.length const answeredIds = new Set(scopeState.answers.map(a => a.questionId)) const answeredQuestions = requiredQuestions.filter(q => answeredIds.has(q.id)).length const completionPercentage = totalQuestions > 0 ? Math.round((answeredQuestions / totalQuestions) * 100) : 0 const isComplete = answeredQuestions === totalQuestions return { total: totalQuestions, answered: answeredQuestions, percentage: completionPercentage, isComplete, } }, [scopeState.answers]) // Auto-enable evaluation when all questions are answered const canEvaluate = useMemo(() => { return completionStats.isComplete }, [completionStats.isComplete]) if (isLoading) { return (
Loading...
) } return (
{/* Step Header */} {/* Progress Indicator */} {completionStats.answered > 0 && (
Fortschritt: {completionStats.answered} von {completionStats.total} Fragen beantwortet
{completionStats.percentage}%
)} {/* Main Content Card */}
{/* Tab Navigation */}
{/* Tab Content */}
{activeTab === 'overview' && ( setActiveTab('wizard')} onGoToDecision={() => setActiveTab('decision')} onGoToExport={() => setActiveTab('export')} /> )} {activeTab === 'wizard' && ( )} {activeTab === 'decision' && ( setActiveTab('wizard')} onGoToExport={() => setActiveTab('export')} canEvaluate={canEvaluate} onEvaluate={handleEvaluate} isEvaluating={isEvaluating} /> )} {activeTab === 'export' && ( setActiveTab('decision')} /> )}
{/* Quick Action Buttons (Fixed at bottom on mobile) */}
{completionStats.isComplete ? ( Profiling abgeschlossen ) : ( 📋 {completionStats.answered === 0 ? 'Starten Sie mit dem Profiling' : `Noch ${completionStats.total - completionStats.answered} Fragen offen` } )}
{activeTab !== 'wizard' && completionStats.answered > 0 && ( )} {canEvaluate && activeTab !== 'decision' && ( )} {scopeState.decision && activeTab !== 'export' && ( )}
{/* Debug Info (only in development) */} {process.env.NODE_ENV === 'development' && (
Debug Information
Active Tab: {activeTab}
Total Answers: {scopeState.answers.length}
Answered: {completionStats.answered} ({completionStats.percentage}%)
Has Decision: {scopeState.decision ? 'Yes' : 'No'}
{scopeState.decision && ( <>
Level: {scopeState.decision.level}
Score: {scopeState.decision.score}
Hard Triggers: {scopeState.decision.hardTriggers.length}
)}
Last Modified: {scopeState.lastModified || 'Never'}
Can Evaluate: {canEvaluate ? 'Yes' : 'No'}
)}
) }