import React, { useState, useEffect } from 'react'; interface LearningData { learningSystem: { enabled: boolean; learningActive?: boolean; activeDecisions?: number; message?: string; recommendation?: string; report?: { summary?: { totalDecisions?: number; successRate?: number; systemConfidence?: number; }; insights?: { thresholds?: any; confidenceLevel?: number; }; recommendations?: Array<{ type: string; message: string; priority: string; } | string>; }; }; visibility?: { decisionTrackingActive?: boolean; learningDatabaseConnected?: boolean; aiEnhancementsActive?: boolean; lastUpdateTime?: string; }; automationStatus?: any; persistentData?: { tradingStats?: { totalTrades?: number; winningTrades?: number; losingTrades?: number; winRate?: number; totalPnL?: number; avgWinAmount?: number; avgLossAmount?: number; bestTrade?: number; worstTrade?: number; }; enhancedSummary?: { totalDecisions?: number; successRate?: number; systemConfidence?: number; isActive?: boolean; totalTrades?: number; totalPnL?: number; }; learningMetrics?: { totalDecisions?: number; aiEnhancements?: number; riskThresholds?: any; dataQuality?: string; }; isLive?: boolean; currentRunTime?: string; } | null; } const EnhancedAILearningPanel = () => { const [learningData, setLearningData] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const fetchLearningStatus = async () => { try { setLoading(true); // Get learning status, automation status, and persistent data const [learningResponse, statusResponse, persistentResponse] = await Promise.all([ fetch('/api/automation/learning-status'), fetch('/api/automation/status'), fetch('/api/learning/persistent-status') ]); const learningData = await learningResponse.json(); const statusData = await statusResponse.json(); const persistentData = await persistentResponse.json(); // Merge current status with persistent data const safeData = { learningSystem: learningData.learningSystem || { enabled: false, message: learningData.message || 'Learning system not available', activeDecisions: 0 }, visibility: learningData.visibility || { decisionTrackingActive: false, learningDatabaseConnected: false, aiEnhancementsActive: false, lastUpdateTime: new Date().toISOString() }, automationStatus: statusData, persistentData: persistentData.success ? persistentData.persistentData : null }; setLearningData(safeData); setError(null); } catch (err) { console.error('Error fetching learning status:', err); setError(err instanceof Error ? err.message : 'Unknown error'); // Set default data structure on error setLearningData({ learningSystem: { enabled: false, message: 'Failed to fetch learning status', activeDecisions: 0 }, visibility: { decisionTrackingActive: false, learningDatabaseConnected: false, aiEnhancementsActive: false, lastUpdateTime: new Date().toISOString() }, automationStatus: null, persistentData: null }); } finally { setLoading(false); } }; useEffect(() => { fetchLearningStatus(); // Refresh every 30 seconds const interval = setInterval(fetchLearningStatus, 30000); return () => clearInterval(interval); }, []); if (loading) { return (

🧠 AI Learning System

Loading learning status...
); } if (error) { return (

🧠 AI Learning System

Error: {error}
); } if (!learningData) { return null; } const { learningSystem, visibility } = learningData; // Safety check for learningSystem if (!learningSystem) { return (

🧠 AI Learning System

Loading learning system data...
); } const renderLearningStatus = () => { if (!learningSystem || !learningSystem.enabled) { return (
Learning System Not Active
{learningSystem?.message || 'The AI learning system is not currently integrated with the automation.'}
{learningSystem?.recommendation && (
💡 {learningSystem.recommendation}
)}
• Decision recording: Not active
• Learning database: Not connected
• AI enhancements: Not applied
); } return (
AI Learning Active
{learningSystem?.report && (
Total Decisions
{learningSystem.report.summary?.totalDecisions || 0}
Success Rate
{learningSystem.report.summary?.successRate || 0}%
Confidence
{learningSystem.report.summary?.systemConfidence || 0}%
)}
🔍 Learning Visibility
Decision Tracking
Database Connected
AI Enhancements
0 ? 'bg-blue-500' : 'bg-gray-500'}`}>
0 ? 'text-blue-400' : 'text-gray-400'}> Active Decisions ({learningSystem?.activeDecisions || 0})
{learningSystem?.report?.insights && (
🎯 Learning Insights
{learningSystem.report.insights.thresholds && (
Current Thresholds: {JSON.stringify(learningSystem.report.insights.thresholds)}
)} {learningSystem.report.insights.confidenceLevel && (
Confidence Level: {learningSystem.report.insights.confidenceLevel}%
)}
)} {learningSystem?.report?.recommendations && learningSystem.report.recommendations.length > 0 && (
💡 AI Recommendations
{learningSystem.report.recommendations.map((rec: any, index: number) => (
• {typeof rec === 'string' ? rec : rec.message || rec.type || 'No message'}
))}
)}
); }; const renderTradingStats = () => { const stats = learningData?.persistentData?.tradingStats; const enhanced = learningData?.persistentData?.enhancedSummary; if (!stats && !enhanced) { return (
📊 Trading Performance
No trading data available yet
); } return (
📊 Trading Performance {learningData?.persistentData?.isLive && ( LIVE )}
{stats?.totalTrades || enhanced?.totalTrades || 0}
Total Trades
{stats?.winRate?.toFixed(1) || enhanced?.successRate?.toFixed(1) || '0.0'}%
Win Rate
= 0 ? 'text-green-400' : 'text-red-400'}`}> ${(stats?.totalPnL || enhanced?.totalPnL || 0) >= 0 ? '+' : ''}{(stats?.totalPnL || enhanced?.totalPnL || 0).toFixed(2)}
Total PnL
{(enhanced?.systemConfidence || 0) * 100 || stats?.winRate || 0}%
AI Confidence
{stats && (
Winning Trades: {stats.winningTrades || 0}
Losing Trades: {stats.losingTrades || 0}
Avg Win: ${(stats.avgWinAmount || 0).toFixed(2)}
Avg Loss: ${(stats.avgLossAmount || 0).toFixed(2)}
Best Trade: ${(stats.bestTrade || 0).toFixed(2)}
Worst Trade: ${(stats.worstTrade || 0).toFixed(2)}
)}
); }; return (

🧠 AI Learning System

{renderTradingStats()} {renderLearningStatus()} {visibility?.lastUpdateTime && (
Last updated: {new Date(visibility.lastUpdateTime).toLocaleTimeString()}
)}
); }; export default EnhancedAILearningPanel;