import React, { useState, useEffect } from 'react'; interface LearningData { // AI Learning API data totalAnalyses?: number; totalDecisions?: number; totalOutcomes?: number; daysActive?: number; avgAccuracy?: number; winRate?: number; confidenceLevel?: number; phase?: string; nextMilestone?: string; recommendation?: string; // Legacy learning system data 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; realTradingData?: { statistics?: { totalTrades?: number; wins?: number; losses?: number; winRate?: number; totalPnl?: number; winsPnl?: number; lossesPnl?: number; avgWin?: number; avgLoss?: number; profitFactor?: number; }; trades?: Array<{ symbol: string; side: string; size: number; entryPrice: number; exitPrice: number; pnl: number; status: string; timestamp: number; outcome: string; }>; totalAnalyses?: number; avgAccuracy?: number; confidenceLevel?: number; phase?: string; nextMilestone?: string; recommendation?: string; daysActive?: number; } | 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 real Drift trading data const [learningResponse, statusResponse, aiLearningResponse] = await Promise.all([ fetch('/api/automation/learning-status'), fetch('/api/automation/status'), fetch('/api/ai-learning-status') ]); const learningData = await learningResponse.json(); const statusData = await statusResponse.json(); const aiLearningData = await aiLearningResponse.json(); const aiData = aiLearningData.success ? aiLearningData.data : { // Fallback data when AI learning API is unavailable totalAnalyses: 0, totalDecisions: 0, totalOutcomes: 0, daysActive: 0, avgAccuracy: 0, winRate: 0, confidenceLevel: 0, phase: 'UNKNOWN', nextMilestone: '', recommendation: 'Learning API unavailable', statistics: { totalTrades: 0, wins: 0, losses: 0, winRate: 0, totalPnl: 0, winsPnl: 0, lossesPnl: 0, avgWin: 0, avgLoss: 0, profitFactor: 0 } }; // Merge current status with real AI learning data const safeData = { // Include AI learning data at the top level totalAnalyses: aiData.totalAnalyses || 0, totalDecisions: aiData.totalDecisions || 0, totalOutcomes: aiData.totalOutcomes || 0, daysActive: aiData.daysActive || 0, avgAccuracy: aiData.avgAccuracy || 0, winRate: aiData.winRate || 0, confidenceLevel: aiData.confidenceLevel || 0, phase: aiData.phase || 'UNKNOWN', nextMilestone: aiData.nextMilestone || '', recommendation: aiData.recommendation || '', learningSystem: { enabled: learningData.learningSystem?.enabled || (aiData.totalAnalyses > 0), message: (aiData.totalAnalyses > 0) ? `Learning system active with ${aiData.totalAnalyses} analyses` : (learningData.message || 'Learning system not available'), activeDecisions: learningData.learningSystem?.activeDecisions || aiData.totalDecisions || 0 }, visibility: learningData.visibility || { decisionTrackingActive: aiData.totalDecisions > 0, learningDatabaseConnected: aiData.totalAnalyses > 0, aiEnhancementsActive: aiData.totalDecisions > 0, lastUpdateTime: new Date().toISOString() }, automationStatus: statusData, realTradingData: aiData }; 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({ totalAnalyses: 0, totalDecisions: 0, totalOutcomes: 0, daysActive: 0, avgAccuracy: 0, winRate: 0, confidenceLevel: 0, phase: 'UNKNOWN', nextMilestone: '', recommendation: '', learningSystem: { enabled: false, message: 'Failed to fetch learning status', activeDecisions: 0 }, visibility: { decisionTrackingActive: false, learningDatabaseConnected: false, aiEnhancementsActive: false, lastUpdateTime: new Date().toISOString() }, automationStatus: null, realTradingData: { // Error fallback - show empty data statistics: { totalTrades: 0, wins: 0, losses: 0, winRate: 0, totalPnl: 0, winsPnl: 0, lossesPnl: 0, avgWin: 0, avgLoss: 0, profitFactor: 0 }, totalAnalyses: 0, avgAccuracy: 0, confidenceLevel: 0, phase: 'ERROR', nextMilestone: 'Fix API connection', recommendation: 'Learning system API unavailable', daysActive: 0 } }); } 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 = () => { // Show as active if we have real AI learning data from the new API const hasLearningData = (learningData?.totalAnalyses || 0) > 0; const hasDecisions = (learningData?.totalDecisions || 0) > 0; const hasTradeData = (learningData?.realTradingData?.statistics?.totalTrades || 0) > 0; const isSystemActive = hasLearningData || hasDecisions || hasTradeData; if (!isSystemActive) { 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?.realTradingData?.statistics; const isAutomationActive = learningData?.automationStatus?.isRunning || learningData?.learningSystem?.enabled; if (!stats) { return (
📊 Trading Performance
No trading data available yet
); } return (
📊 Trading Performance {isAutomationActive && ( LIVE )}
{stats?.totalTrades || 0}
Total Trades
{stats?.winRate?.toFixed(1) || '0.0'}%
Win Rate
= 0 ? 'text-green-400' : 'text-red-400'}`}> ${(stats?.totalPnl || 0) >= 0 ? '+' : ''}{(stats?.totalPnl || 0).toFixed(2)}
Total PnL
{(learningData?.realTradingData?.confidenceLevel || 0).toFixed(1)}%
AI Confidence
{stats && (
Winning Trades: {stats.wins || 0}
Losing Trades: {stats.losses || 0}
Avg Win: ${(stats.avgWin || 0).toFixed(2)}
Avg Loss: ${(stats.avgLoss || 0).toFixed(2)}
Profit Factor: {(stats.profitFactor || 0).toFixed(2)}
Win PnL: ${(stats.winsPnl || 0).toFixed(2)}
)}
); }; return (

🧠 AI Learning System

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