'use client'; import React, { useState, useEffect, useTransition } from 'react'; import { Sparkles, Bot, AlertTriangle, Play, RotateCcw, CheckCircle2, XCircle, Clock, TrendingUp, Percent, MessageSquare, Wrench, Building2, HelpCircle, ChevronRight, ShieldAlert, Send, UserCheck, Cpu, BarChart2, FileText, DollarSign, Activity, Layers, StopCircle, Users, } from 'lucide-react'; import { toast } from 'sonner'; import { simulationService, SimulationJobDetail, SimulationJobSummary, ScenariosResponse, } from '@/services/api/simulation'; import { ResponsiveContainer, BarChart, Bar, XAxis, YAxis, Tooltip, CartesianGrid, Legend, LineChart, Line, } from 'recharts'; export default function SimulationDashboardPage() { const [scenariosMeta, setScenariosMeta] = useState(null); const [selectedScenario, setSelectedScenario] = useState('pricing_elasticity'); const [inputParams, setInputParams] = useState>({ discount_pct: 15.0, current_price: 3500.0, cost_price: 2100.0, target_category: 'Display & Touch Screens', }); const [activeJobId, setActiveJobId] = useState(null); const [activeJob, setActiveJob] = useState(null); const [jobHistory, setJobHistory] = useState([]); const [isSubmitting, setIsSubmitting] = useState(false); const [selectedAgentId, setSelectedAgentId] = useState(''); const [interviewQuestion, setInterviewQuestion] = useState(''); const [interviewAnswers, setInterviewAnswers] = useState< Array<{ agent_id: string; question: string; answer: string; latency_ms: number }> >([]); const [isInterviewing, setIsInterviewing] = useState(false); const [activeTab, setActiveTab] = useState<'metrics' | 'report' | 'agents' | 'interview'>('metrics'); // Load scenarios & recent history on mount useEffect(() => { fetchMetadataAndHistory(); }, []); // Poll active job until final state useEffect(() => { if (!activeJobId) return; let isMounted = true; const interval = setInterval(async () => { try { const job = await simulationService.getJobDetail(activeJobId); if (!isMounted) return; setActiveJob(job); // Pre-select first agent for interview when logs arrive if (job.agent_logs && job.agent_logs.length > 0 && !selectedAgentId) { setSelectedAgentId(job.agent_logs[0].agent_id); } if (['COMPLETED', 'FAILED', 'FAILED_INTERRUPTED', 'TIMED_OUT', 'CANCELLED'].includes(job.status)) { clearInterval(interval); if (job.status === 'COMPLETED') { toast.success(`Simulation completed in ${job.execution_time_ms}ms!`); fetchHistory(); } else if (job.status === 'CANCELLED') { toast.info('Simulation job cancelled.'); fetchHistory(); } else { toast.error(`Simulation ended with status: ${job.status}`); fetchHistory(); } } } catch (err: any) { console.error('Error polling simulation job:', err); } }, 1200); return () => { isMounted = false; clearInterval(interval); }; }, [activeJobId]); const fetchMetadataAndHistory = async () => { try { const [meta, history] = await Promise.all([ simulationService.getScenarios(), simulationService.listJobs(10), ]); setScenariosMeta(meta); setJobHistory(history); // Auto-load most recent completed job if present const latestCompleted = history.find((h) => h.status === 'COMPLETED'); if (latestCompleted && !activeJobId) { loadJobDetail(latestCompleted.job_id); } } catch (err: any) { toast.error('Failed to connect to simulation engine.'); } }; const fetchHistory = async () => { try { const history = await simulationService.listJobs(10); setJobHistory(history); } catch { // ignore } }; const handleScenarioChange = (scenarioKey: string) => { setSelectedScenario(scenarioKey); if (scenariosMeta?.scenarios[scenarioKey]?.default_params) { setInputParams({ ...scenariosMeta.scenarios[scenarioKey].default_params }); } }; const handleLaunchSimulation = async () => { setIsSubmitting(true); try { const res = await simulationService.runSimulation(selectedScenario, inputParams, 1); toast.success('Simulation job dispatched to queue.'); setActiveJobId(res.job_id); setActiveJob(null); setInterviewAnswers([]); } catch (err: any) { toast.error(err.message || 'Failed to dispatch simulation job.'); } finally { setIsSubmitting(false); } }; const handleCancelJob = async () => { if (!activeJobId) return; try { await simulationService.cancelJob(activeJobId); toast.info('Cancellation request sent.'); } catch (err: any) { toast.error(err.message || 'Failed to cancel job.'); } }; const loadJobDetail = async (jobId: string) => { try { const job = await simulationService.getJobDetail(jobId); setActiveJob(job); setActiveJobId(job.id); setSelectedScenario(job.scenario_type); setInputParams(job.input_params || {}); if (job.agent_logs && job.agent_logs.length > 0) { setSelectedAgentId(job.agent_logs[0].agent_id); } setInterviewAnswers([]); } catch (err: any) { toast.error('Could not load simulation run details.'); } }; const handleAskInterview = async () => { if (!activeJob?.id || !selectedAgentId || !interviewQuestion.trim()) return; setIsInterviewing(true); try { const res = await simulationService.interviewPersona( activeJob.id, selectedAgentId, interviewQuestion.trim() ); setInterviewAnswers((prev) => [ { agent_id: res.agent_id, question: res.question, answer: res.response, latency_ms: res.latency_ms, }, ...prev, ]); setInterviewQuestion(''); toast.success('Agent persona responded.'); } catch (err: any) { toast.error(err.message || 'Persona interview failed.'); } finally { setIsInterviewing(false); } }; // Prepare chart data based on scenario interface ChartDataPoint { metric: string; Baseline: number; Projected: number; } const getChartData = (): ChartDataPoint[] => { if (!activeJob || !activeJob.summary_metrics) return []; if (activeJob.scenario_type === 'pricing_elasticity') { const sm = activeJob.summary_metrics; return [ { metric: 'Conversion Rate (%)', Baseline: sm.baseline_conversion_pct || 0, Projected: sm.projected_conversion_pct || 0, }, { metric: 'Price Elasticity Coeff', Baseline: 1.0, Projected: sm.price_elasticity_coefficient || 0, }, ]; } if (activeJob.scenario_type === 'whatsapp_preflight') { const sm = activeJob.summary_metrics; return [ { metric: 'Read / Open Rate (%)', Baseline: sm.baseline_open_rate_pct || 0, Projected: sm.projected_open_rate_pct || 0, }, { metric: 'Spam Risk Score (0-100)', Baseline: 5.0, Projected: sm.spam_block_risk_score || 0, }, ]; } if (activeJob.scenario_type === 'workshop_surge') { const sm = activeJob.summary_metrics; return [ { metric: 'Backlog Queue (Tickets)', Baseline: sm.baseline_daily_intake || 0, Projected: sm.projected_queue_tickets || 0, }, { metric: 'TAT Hours (SLA)', Baseline: sm.sla_threshold_hours || 48, Projected: sm.projected_turnaround_hours || 0, }, ]; } if (activeJob.scenario_type === 'fleet_quote') { const sm = activeJob.summary_metrics; return [ { metric: 'CFO Vote (0-100)', Baseline: 50, Projected: sm.committee_votes?.cfo?.score || 0, }, { metric: 'IT Admin Vote (0-100)', Baseline: 50, Projected: sm.committee_votes?.it_admin?.score || 0, }, { metric: 'Procurement Vote (0-100)', Baseline: 50, Projected: sm.committee_votes?.legal_procurement?.score || 0, }, ]; } return []; }; return (
{/* 1. Header & Title */}

Swarm Intelligence & Predictive Digital Twin 50-Agent Engine

Multi-agent behavioral sandbox simulating customer elasticity, campaign pre-flights, workshop SLA surges, and B2B procurement.

{/* 2. Prominent Epistemic Notice Alert Banner */}
EPISTEMIC NOTICE & CALIBRATION METHODOLOGY: {' '} Multi-agent behavioral dispersion represents an exploratory hypothesis space of heterogeneous AI personas. Agent disagreement reflects persona divergence, not statistical sampling error. All projections are mathematically calibrated against verified historical store baselines (products & orders) with an empirical 95% confidence interval.
{/* 3. Scenario Selection Cards */}

1. Select Simulation Scenario

{/* Card 1: Pricing */}
handleScenarioChange('pricing_elasticity')} className={`cursor-pointer rounded-xl p-4 border transition-all ${ selectedScenario === 'pricing_elasticity' ? 'bg-indigo-50/60 dark:bg-indigo-950/30 border-indigo-500 shadow-sm ring-2 ring-indigo-500/20' : 'bg-white dark:bg-slate-900 border-slate-200 dark:border-slate-800 hover:border-slate-300 dark:hover:border-slate-700' }`} >
Commerce

Dynamic Pricing Elasticity

Predict customer price sensitivity, sales conversion lift, and margin cannibalization risk.

{/* Card 2: WhatsApp */}
handleScenarioChange('whatsapp_preflight')} className={`cursor-pointer rounded-xl p-4 border transition-all ${ selectedScenario === 'whatsapp_preflight' ? 'bg-indigo-50/60 dark:bg-indigo-950/30 border-indigo-500 shadow-sm ring-2 ring-indigo-500/20' : 'bg-white dark:bg-slate-900 border-slate-200 dark:border-slate-800 hover:border-slate-300 dark:hover:border-slate-700' }`} >
Marketing

WhatsApp Campaign Pre-Flight

Pre-flight blast copy to evaluate customer reception, click-through, and spam report hazard.

{/* Card 3: Workshop */}
handleScenarioChange('workshop_surge')} className={`cursor-pointer rounded-xl p-4 border transition-all ${ selectedScenario === 'workshop_surge' ? 'bg-indigo-50/60 dark:bg-indigo-950/30 border-indigo-500 shadow-sm ring-2 ring-indigo-500/20' : 'bg-white dark:bg-slate-900 border-slate-200 dark:border-slate-800 hover:border-slate-300 dark:hover:border-slate-700' }`} >
Operations

Workshop SLA & Surge Delay

Model repair ticket intake surges and supplier parts delays to forecast SLA breaches.

{/* Card 4: Fleet Quote */}
handleScenarioChange('fleet_quote')} className={`cursor-pointer rounded-xl p-4 border transition-all ${ selectedScenario === 'fleet_quote' ? 'bg-indigo-50/60 dark:bg-indigo-950/30 border-indigo-500 shadow-sm ring-2 ring-indigo-500/20' : 'bg-white dark:bg-slate-900 border-slate-200 dark:border-slate-800 hover:border-slate-300 dark:hover:border-slate-700' }`} >
B2B Fleet

Corporate Fleet Negotiation

Simulate 3-party corporate committee (CFO, IT Admin, Legal) deliberation on bulk repair quotes.

{/* 4. Scenario Parameter Configuration & Execution */}

Configure Simulation Parameters

Tune inputs for the 50 simulated agent personas before dispatching the job.

{activeJob && ['QUEUED', 'CLAIMED', 'RUNNING'].includes(activeJob.status) ? ( ) : ( )}
{/* Dynamic Parameter Fields */}
{selectedScenario === 'pricing_elasticity' && ( <>
setInputParams({ ...inputParams, discount_pct: parseFloat(e.target.value) || 0 }) } className="w-full px-3 py-2 text-sm rounded-lg border border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-950 text-slate-900 dark:text-white" />
setInputParams({ ...inputParams, current_price: parseFloat(e.target.value) || 0 }) } className="w-full px-3 py-2 text-sm rounded-lg border border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-950 text-slate-900 dark:text-white" />
setInputParams({ ...inputParams, cost_price: parseFloat(e.target.value) || 0 }) } className="w-full px-3 py-2 text-sm rounded-lg border border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-950 text-slate-900 dark:text-white" />
)} {selectedScenario === 'whatsapp_preflight' && ( <>