'use client'; import React, { useState, useEffect } from 'react'; import { Bot, Play, RotateCcw, Send, BarChart2, FileText, Activity, StopCircle, Users, } from 'lucide-react'; import { toast } from 'sonner'; import { CustomSelect } from '@/components/ui/CustomSelect'; import { simulationService, SimulationJobDetail, SimulationJobSummary, ScenariosResponse, } from '@/services/api/simulation'; import { ResponsiveContainer, BarChart, Bar, XAxis, YAxis, Tooltip, CartesianGrid, Legend, } from 'recharts'; const fieldClass = 'w-full h-9 px-3 bg-card border border-border crm-radius-control text-[13px] text-foreground focus:outline-none focus:border-primary'; const areaClass = 'w-full px-3 py-2 bg-card border border-border crm-radius-control text-[13px] text-foreground focus:outline-none focus:border-primary'; const primaryButton = 'inline-flex items-center justify-center gap-1.5 h-9 px-3 crm-radius-control bg-primary hover:bg-primary/90 text-white text-[13px] font-semibold cursor-pointer disabled:opacity-50'; const secondaryButton = 'inline-flex items-center justify-center gap-1.5 h-9 px-3 crm-radius-control border border-border bg-card text-foreground text-[13px] font-medium hover:bg-muted cursor-pointer'; const shell = 'crm-radius-section border border-border bg-card shadow-[0_1px_3px_rgba(16,24,40,0.06)] min-w-0'; const labelClass = 'block text-[11px] font-semibold text-muted-foreground uppercase mb-1.5'; 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 (

Prediction lab

{jobHistory.length}

Parameters

({ value: id, label: scenariosMeta?.scenarios[id]?.title || id.replaceAll('_', ' '), }))} />
{activeJob && ['QUEUED', 'CLAIMED', 'RUNNING'].includes(activeJob.status) ? ( ) : ( )}
{/* Dynamic Parameter Fields */}
{selectedScenario === 'pricing_elasticity' && ( <>
setInputParams({ ...inputParams, discount_pct: parseFloat(e.target.value) || 0 }) } className={fieldClass} />
setInputParams({ ...inputParams, current_price: parseFloat(e.target.value) || 0 }) } className={fieldClass} />
setInputParams({ ...inputParams, cost_price: parseFloat(e.target.value) || 0 }) } className={fieldClass} />
setInputParams({ ...inputParams, target_category: value })} options={[ { value: 'Display & Touch Screens', label: 'Display & Touch Screens' }, { value: 'Battery Replacement', label: 'Battery Replacement' }, { value: 'Charging Ports & Flex', label: 'Charging Ports & Flex' }, { value: 'Back Glass & Housing', label: 'Back Glass & Housing' }, ]} />
)} {selectedScenario === 'whatsapp_preflight' && ( <>