ifixkart-admin/app/(admin)/simulation/page.tsx

1246 lines
56 KiB
TypeScript

'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<ScenariosResponse | null>(null);
const [selectedScenario, setSelectedScenario] = useState<string>('pricing_elasticity');
const [inputParams, setInputParams] = useState<Record<string, any>>({
discount_pct: 15.0,
current_price: 3500.0,
cost_price: 2100.0,
target_category: 'Display & Touch Screens',
});
const [activeJobId, setActiveJobId] = useState<string | null>(null);
const [activeJob, setActiveJob] = useState<SimulationJobDetail | null>(null);
const [jobHistory, setJobHistory] = useState<SimulationJobSummary[]>([]);
const [isSubmitting, setIsSubmitting] = useState(false);
const [selectedAgentId, setSelectedAgentId] = useState<string>('');
const [interviewQuestion, setInterviewQuestion] = useState<string>('');
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 (
<div className="space-y-8 pb-16">
{/* 1. Header & Title */}
<div className="flex flex-col md:flex-row md:items-center justify-between gap-4 border-b border-slate-200 dark:border-slate-800 pb-6">
<div>
<div className="flex items-center gap-3">
<div className="p-2.5 bg-gradient-to-tr from-indigo-500 to-purple-600 rounded-xl text-white shadow-lg shadow-indigo-500/20">
<Sparkles className="w-6 h-6 animate-pulse" />
</div>
<div>
<h1 className="text-2xl font-bold tracking-tight text-slate-900 dark:text-white flex items-center gap-2">
Swarm Intelligence & Predictive Digital Twin
<span className="px-2.5 py-0.5 text-xs font-semibold rounded-full bg-indigo-100 text-indigo-700 dark:bg-indigo-900/40 dark:text-indigo-300 border border-indigo-200 dark:border-indigo-800">
50-Agent Engine
</span>
</h1>
<p className="text-sm text-slate-500 dark:text-slate-400 mt-0.5">
Multi-agent behavioral sandbox simulating customer elasticity, campaign pre-flights, workshop SLA surges, and B2B procurement.
</p>
</div>
</div>
</div>
<div className="flex items-center gap-3">
<button
onClick={fetchMetadataAndHistory}
className="px-3.5 py-2 text-sm font-medium rounded-lg border border-slate-200 dark:border-slate-800 hover:bg-slate-100 dark:hover:bg-slate-800 text-slate-700 dark:text-slate-300 transition-colors flex items-center gap-2"
>
<RotateCcw className="w-4 h-4" />
Refresh
</button>
</div>
</div>
{/* 2. Prominent Epistemic Notice Alert Banner */}
<div className="bg-amber-50 dark:bg-amber-950/30 border border-amber-200 dark:border-amber-800/50 rounded-xl p-4 flex items-start gap-3.5">
<AlertTriangle className="w-5 h-5 text-amber-600 dark:text-amber-400 shrink-0 mt-0.5" />
<div className="text-sm text-amber-900 dark:text-amber-200/90 leading-relaxed">
<span className="font-semibold text-amber-950 dark:text-amber-100">
EPISTEMIC NOTICE & CALIBRATION METHODOLOGY:
</span>{' '}
Multi-agent behavioral dispersion represents an exploratory hypothesis space of heterogeneous AI personas.
Agent disagreement reflects persona divergence, <em>not</em> statistical sampling error. All projections are mathematically calibrated
against verified historical store baselines (<code className="px-1 py-0.5 text-xs bg-amber-100 dark:bg-amber-900/60 rounded">products</code> & <code className="px-1 py-0.5 text-xs bg-amber-100 dark:bg-amber-900/60 rounded">orders</code>) with an empirical 95% confidence interval.
</div>
</div>
{/* 3. Scenario Selection Cards */}
<div>
<h2 className="text-xs font-semibold uppercase tracking-wider text-slate-500 dark:text-slate-400 mb-3">
1. Select Simulation Scenario
</h2>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
{/* Card 1: Pricing */}
<div
onClick={() => 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'
}`}
>
<div className="flex items-center justify-between mb-3">
<div className="p-2 bg-emerald-100 dark:bg-emerald-950/50 text-emerald-600 dark:text-emerald-400 rounded-lg">
<Percent className="w-5 h-5" />
</div>
<span className="text-[11px] font-semibold px-2 py-0.5 rounded-full bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-400">
Commerce
</span>
</div>
<h3 className="font-semibold text-sm text-slate-900 dark:text-white">Dynamic Pricing Elasticity</h3>
<p className="text-xs text-slate-500 dark:text-slate-400 mt-1 line-clamp-2">
Predict customer price sensitivity, sales conversion lift, and margin cannibalization risk.
</p>
</div>
{/* Card 2: WhatsApp */}
<div
onClick={() => 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'
}`}
>
<div className="flex items-center justify-between mb-3">
<div className="p-2 bg-green-100 dark:bg-green-950/50 text-green-600 dark:text-green-400 rounded-lg">
<MessageSquare className="w-5 h-5" />
</div>
<span className="text-[11px] font-semibold px-2 py-0.5 rounded-full bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-400">
Marketing
</span>
</div>
<h3 className="font-semibold text-sm text-slate-900 dark:text-white">WhatsApp Campaign Pre-Flight</h3>
<p className="text-xs text-slate-500 dark:text-slate-400 mt-1 line-clamp-2">
Pre-flight blast copy to evaluate customer reception, click-through, and spam report hazard.
</p>
</div>
{/* Card 3: Workshop */}
<div
onClick={() => 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'
}`}
>
<div className="flex items-center justify-between mb-3">
<div className="p-2 bg-amber-100 dark:bg-amber-950/50 text-amber-600 dark:text-amber-400 rounded-lg">
<Wrench className="w-5 h-5" />
</div>
<span className="text-[11px] font-semibold px-2 py-0.5 rounded-full bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-400">
Operations
</span>
</div>
<h3 className="font-semibold text-sm text-slate-900 dark:text-white">Workshop SLA & Surge Delay</h3>
<p className="text-xs text-slate-500 dark:text-slate-400 mt-1 line-clamp-2">
Model repair ticket intake surges and supplier parts delays to forecast SLA breaches.
</p>
</div>
{/* Card 4: Fleet Quote */}
<div
onClick={() => 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'
}`}
>
<div className="flex items-center justify-between mb-3">
<div className="p-2 bg-blue-100 dark:bg-blue-950/50 text-blue-600 dark:text-blue-400 rounded-lg">
<Building2 className="w-5 h-5" />
</div>
<span className="text-[11px] font-semibold px-2 py-0.5 rounded-full bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-400">
B2B Fleet
</span>
</div>
<h3 className="font-semibold text-sm text-slate-900 dark:text-white">Corporate Fleet Negotiation</h3>
<p className="text-xs text-slate-500 dark:text-slate-400 mt-1 line-clamp-2">
Simulate 3-party corporate committee (CFO, IT Admin, Legal) deliberation on bulk repair quotes.
</p>
</div>
</div>
</div>
{/* 4. Scenario Parameter Configuration & Execution */}
<div className="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-xl p-6 shadow-sm">
<div className="flex flex-col md:flex-row md:items-center justify-between gap-4 border-b border-slate-100 dark:border-slate-800 pb-4 mb-6">
<div>
<h2 className="text-base font-semibold text-slate-900 dark:text-white flex items-center gap-2">
<Cpu className="w-4 h-4 text-indigo-500" />
Configure Simulation Parameters
</h2>
<p className="text-xs text-slate-500 dark:text-slate-400 mt-0.5">
Tune inputs for the 50 simulated agent personas before dispatching the job.
</p>
</div>
<div className="flex items-center gap-3">
{activeJob && ['QUEUED', 'CLAIMED', 'RUNNING'].includes(activeJob.status) ? (
<button
onClick={handleCancelJob}
className="px-4 py-2 text-sm font-semibold rounded-lg bg-rose-600 hover:bg-rose-700 text-white transition-all flex items-center gap-2 shadow-sm"
>
<StopCircle className="w-4 h-4" />
Cancel Simulation
</button>
) : (
<button
disabled={isSubmitting}
onClick={handleLaunchSimulation}
className="px-5 py-2.5 text-sm font-semibold rounded-lg bg-gradient-to-r from-indigo-600 to-purple-600 hover:from-indigo-500 hover:to-purple-500 text-white transition-all shadow-md shadow-indigo-500/20 flex items-center gap-2 disabled:opacity-50"
>
{isSubmitting ? (
<>
<Activity className="w-4 h-4 animate-spin" />
Enqueuing...
</>
) : (
<>
<Play className="w-4 h-4 fill-current" />
Run 50-Agent Simulation
</>
)}
</button>
)}
</div>
</div>
{/* Dynamic Parameter Fields */}
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
{selectedScenario === 'pricing_elasticity' && (
<>
<div>
<label className="block text-xs font-semibold text-slate-700 dark:text-slate-300 mb-1">
Proposed Discount (%)
</label>
<input
type="number"
min="1"
max="70"
step="1"
value={inputParams.discount_pct || 15}
onChange={(e) =>
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"
/>
</div>
<div>
<label className="block text-xs font-semibold text-slate-700 dark:text-slate-300 mb-1">
Current Retail Price (INR)
</label>
<input
type="number"
min="100"
step="50"
value={inputParams.current_price || 3500}
onChange={(e) =>
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"
/>
</div>
<div>
<label className="block text-xs font-semibold text-slate-700 dark:text-slate-300 mb-1">
Cost / Procurement Price (INR)
</label>
<input
type="number"
min="50"
step="50"
value={inputParams.cost_price || 2100}
onChange={(e) =>
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"
/>
</div>
<div>
<label className="block text-xs font-semibold text-slate-700 dark:text-slate-300 mb-1">
Target Product Category
</label>
<select
value={inputParams.target_category || 'Display & Touch Screens'}
onChange={(e) => setInputParams({ ...inputParams, target_category: e.target.value })}
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"
>
<option value="Display & Touch Screens">Display & Touch Screens</option>
<option value="Battery Replacement">Battery Replacement</option>
<option value="Charging Ports & Flex">Charging Ports & Flex</option>
<option value="Back Glass & Housing">Back Glass & Housing</option>
</select>
</div>
</>
)}
{selectedScenario === 'whatsapp_preflight' && (
<>
<div className="md:col-span-2">
<label className="block text-xs font-semibold text-slate-700 dark:text-slate-300 mb-1">
WhatsApp Message Template / Copy
</label>
<textarea
rows={2}
value={
inputParams.message_template ||
'Exclusive 20% off all display repairs this weekend at iFixKart!'
}
onChange={(e) =>
setInputParams({ ...inputParams, message_template: e.target.value })
}
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"
/>
</div>
<div>
<label className="block text-xs font-semibold text-slate-700 dark:text-slate-300 mb-1">
Monthly Broadcast Frequency
</label>
<input
type="number"
min="1"
max="10"
value={inputParams.frequency_per_month || 2}
onChange={(e) =>
setInputParams({
...inputParams,
frequency_per_month: parseInt(e.target.value) || 1,
})
}
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"
/>
</div>
<div>
<label className="block text-xs font-semibold text-slate-700 dark:text-slate-300 mb-1">
Target Customer Segment
</label>
<select
value={inputParams.target_segment || 'Past Customers'}
onChange={(e) => setInputParams({ ...inputParams, target_segment: e.target.value })}
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"
>
<option value="Past Customers">Past Customers (Active)</option>
<option value="Dormant (6+ Months)">Dormant (6+ Months)</option>
<option value="Walk-in Leads">Walk-in Inquiries</option>
<option value="High-Value VIPs">High-Value VIPs</option>
</select>
</div>
</>
)}
{selectedScenario === 'workshop_surge' && (
<>
<div>
<label className="block text-xs font-semibold text-slate-700 dark:text-slate-300 mb-1">
Volume Surge Multiplier
</label>
<input
type="number"
step="0.1"
min="1.0"
max="4.0"
value={inputParams.surge_multiplier || 1.5}
onChange={(e) =>
setInputParams({
...inputParams,
surge_multiplier: parseFloat(e.target.value) || 1.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"
/>
</div>
<div>
<label className="block text-xs font-semibold text-slate-700 dark:text-slate-300 mb-1">
Parts Lead Time Delay (Days)
</label>
<input
type="number"
min="0"
max="14"
value={inputParams.parts_delay_days || 3}
onChange={(e) =>
setInputParams({
...inputParams,
parts_delay_days: parseInt(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"
/>
</div>
<div>
<label className="block text-xs font-semibold text-slate-700 dark:text-slate-300 mb-1">
Active Duty Technicians
</label>
<input
type="number"
min="1"
max="20"
value={inputParams.active_technicians || 4}
onChange={(e) =>
setInputParams({
...inputParams,
active_technicians: parseInt(e.target.value) || 1,
})
}
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"
/>
</div>
</>
)}
{selectedScenario === 'fleet_quote' && (
<>
<div>
<label className="block text-xs font-semibold text-slate-700 dark:text-slate-300 mb-1">
Device Batch Count
</label>
<input
type="number"
min="5"
max="500"
value={inputParams.device_count || 50}
onChange={(e) =>
setInputParams({ ...inputParams, device_count: parseInt(e.target.value) || 10 })
}
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"
/>
</div>
<div>
<label className="block text-xs font-semibold text-slate-700 dark:text-slate-300 mb-1">
Quoted Price / Unit (INR)
</label>
<input
type="number"
min="500"
step="100"
value={inputParams.quoted_price_per_unit || 4200}
onChange={(e) =>
setInputParams({
...inputParams,
quoted_price_per_unit: 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"
/>
</div>
<div>
<label className="block text-xs font-semibold text-slate-700 dark:text-slate-300 mb-1">
Warranty Coverage (Months)
</label>
<input
type="number"
min="1"
max="24"
value={inputParams.warranty_months || 6}
onChange={(e) =>
setInputParams({
...inputParams,
warranty_months: parseInt(e.target.value) || 1,
})
}
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"
/>
</div>
<div>
<label className="block text-xs font-semibold text-slate-700 dark:text-slate-300 mb-1">
SLA Turnaround (Days)
</label>
<input
type="number"
min="1"
max="14"
value={inputParams.turnaround_days || 3}
onChange={(e) =>
setInputParams({
...inputParams,
turnaround_days: parseInt(e.target.value) || 1,
})
}
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"
/>
</div>
</>
)}
</div>
</div>
{/* 5. Active Job Progress Tracker */}
{activeJob && (
<div className="bg-slate-900 text-white rounded-xl p-5 border border-slate-800 shadow-md">
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
<div className="flex items-center gap-3">
<div
className={`p-2 rounded-lg ${
activeJob.status === 'COMPLETED'
? 'bg-emerald-500/20 text-emerald-400'
: activeJob.status === 'RUNNING' || activeJob.status === 'QUEUED'
? 'bg-indigo-500/20 text-indigo-400 animate-pulse'
: 'bg-rose-500/20 text-rose-400'
}`}
>
{activeJob.status === 'COMPLETED' ? (
<CheckCircle2 className="w-5 h-5" />
) : activeJob.status === 'RUNNING' || activeJob.status === 'QUEUED' ? (
<Activity className="w-5 h-5 animate-spin" />
) : (
<XCircle className="w-5 h-5" />
)}
</div>
<div>
<div className="flex items-center gap-2">
<span className="text-xs font-mono text-slate-400">Job ID: {activeJob.id}</span>
<span
className={`text-xs px-2 py-0.5 rounded-full font-semibold uppercase tracking-wider ${
activeJob.status === 'COMPLETED'
? 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
: activeJob.status === 'RUNNING'
? 'bg-indigo-500/20 text-indigo-300 border border-indigo-500/30'
: activeJob.status === 'QUEUED'
? 'bg-amber-500/20 text-amber-300 border border-amber-500/30'
: 'bg-rose-500/20 text-rose-300 border border-rose-500/30'
}`}
>
{activeJob.status}
</span>
</div>
<div className="text-xs text-slate-400 mt-1 flex items-center gap-4">
<span>Scenario: <strong className="text-slate-200">{activeJob.scenario_type}</strong></span>
{activeJob.execution_time_ms && (
<span>Execution: <strong className="text-slate-200">{activeJob.execution_time_ms}ms</strong></span>
)}
{activeJob.total_cost_usd !== undefined && (
<span>Cost: <strong className="text-slate-200">${activeJob.total_cost_usd}</strong></span>
)}
</div>
</div>
</div>
{/* Stepper Status Indicator */}
<div className="flex items-center gap-2 text-xs">
<span className={`px-2 py-1 rounded ${activeJob.historical_baseline ? 'bg-emerald-950 text-emerald-300' : 'bg-slate-800 text-slate-500'}`}>
1. Baseline
</span>
<ChevronRight className="w-3.5 h-3.5 text-slate-600" />
<span className={`px-2 py-1 rounded ${activeJob.simulation_dispersion ? 'bg-emerald-950 text-emerald-300' : 'bg-slate-800 text-slate-500'}`}>
2. Personas (50)
</span>
<ChevronRight className="w-3.5 h-3.5 text-slate-600" />
<span className={`px-2 py-1 rounded ${activeJob.calibrated_projection ? 'bg-emerald-950 text-emerald-300' : 'bg-slate-800 text-slate-500'}`}>
3. Projection
</span>
<ChevronRight className="w-3.5 h-3.5 text-slate-600" />
<span className={`px-2 py-1 rounded ${activeJob.status === 'COMPLETED' ? 'bg-emerald-950 text-emerald-300' : 'bg-slate-800 text-slate-500'}`}>
4. Report
</span>
</div>
</div>
</div>
)}
{/* 6. Simulation Results Workspace */}
{activeJob && activeJob.status === 'COMPLETED' && (
<div className="space-y-6">
{/* Navigation Tabs */}
<div className="flex items-center gap-2 border-b border-slate-200 dark:border-slate-800 pb-2">
<button
onClick={() => setActiveTab('metrics')}
className={`px-4 py-2 text-sm font-semibold rounded-lg transition-colors flex items-center gap-2 ${
activeTab === 'metrics'
? 'bg-indigo-600 text-white'
: 'text-slate-600 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-800'
}`}
>
<BarChart2 className="w-4 h-4" />
Calibrated Projections
</button>
<button
onClick={() => setActiveTab('report')}
className={`px-4 py-2 text-sm font-semibold rounded-lg transition-colors flex items-center gap-2 ${
activeTab === 'report'
? 'bg-indigo-600 text-white'
: 'text-slate-600 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-800'
}`}
>
<FileText className="w-4 h-4" />
Executive Synthesis
</button>
<button
onClick={() => setActiveTab('interview')}
className={`px-4 py-2 text-sm font-semibold rounded-lg transition-colors flex items-center gap-2 ${
activeTab === 'interview'
? 'bg-indigo-600 text-white'
: 'text-slate-600 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-800'
}`}
>
<Bot className="w-4 h-4" />
Persona Interview Station
</button>
<button
onClick={() => setActiveTab('agents')}
className={`px-4 py-2 text-sm font-semibold rounded-lg transition-colors flex items-center gap-2 ${
activeTab === 'agents'
? 'bg-indigo-600 text-white'
: 'text-slate-600 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-800'
}`}
>
<Users className="w-4 h-4" />
50 Persona Ledger
</button>
</div>
{/* TAB 1: METRICS & CHARTS */}
{activeTab === 'metrics' && (
<div className="space-y-6">
{/* Key Summary Cards */}
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
{/* Baseline Card */}
<div className="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-xl p-5">
<span className="text-xs font-semibold text-slate-500 uppercase tracking-wider">
Historical Baseline
</span>
<div className="mt-2 text-2xl font-bold text-slate-900 dark:text-white">
{activeJob.historical_baseline?.historical_mean !== undefined
? `${(activeJob.historical_baseline.historical_mean * 100).toFixed(1)}%`
: 'N/A'}
</div>
<div className="mt-1 text-xs text-slate-500 flex items-center gap-1">
<span>95% CI:</span>
<span className="font-mono text-slate-700 dark:text-slate-300">
[{((activeJob.historical_baseline?.empirical_95_ci_lower || 0) * 100).toFixed(1)}% -{' '}
{((activeJob.historical_baseline?.empirical_95_ci_upper || 0) * 100).toFixed(1)}%]
</span>
</div>
<span className="inline-block mt-2 text-[10px] bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-400 px-2 py-0.5 rounded">
Source: {activeJob.historical_baseline?.baseline_source}
</span>
</div>
{/* Calibrated Projection Card */}
<div className="bg-white dark:bg-slate-900 border border-indigo-200 dark:border-indigo-900/50 rounded-xl p-5 shadow-sm">
<span className="text-xs font-semibold text-indigo-600 dark:text-indigo-400 uppercase tracking-wider">
Calibrated Projection
</span>
<div className="mt-2 text-2xl font-bold text-indigo-600 dark:text-indigo-400">
{activeJob.calibrated_projection?.point_estimate !== undefined
? `${(activeJob.calibrated_projection.point_estimate * 100).toFixed(1)}%`
: 'N/A'}
</div>
<div className="mt-1 text-xs text-slate-500 flex items-center gap-1">
<span>Credible Range:</span>
<span className="font-mono text-slate-700 dark:text-slate-300">
[{((activeJob.calibrated_projection?.credible_range_lower || 0) * 100).toFixed(1)}% -{' '}
{((activeJob.calibrated_projection?.credible_range_upper || 0) * 100).toFixed(1)}%]
</span>
</div>
<span className="inline-block mt-2 text-[10px] bg-indigo-50 dark:bg-indigo-950/50 text-indigo-700 dark:text-indigo-300 px-2 py-0.5 rounded border border-indigo-200 dark:border-indigo-800">
Weights: Hist {(activeJob.calibrated_projection?.historical_weight || 0) * 100}% / Swarm {(activeJob.calibrated_projection?.simulation_weight || 0) * 100}%
</span>
</div>
{/* Agent Dispersion Card */}
<div className="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-xl p-5">
<span className="text-xs font-semibold text-slate-500 uppercase tracking-wider">
Persona Disagreement Index
</span>
<div className="mt-2 text-2xl font-bold text-slate-900 dark:text-white">
{activeJob.simulation_dispersion?.agent_disagreement_index !== undefined
? `${(activeJob.simulation_dispersion.agent_disagreement_index * 100).toFixed(1)}%`
: 'N/A'}
</div>
<div className="mt-1 text-xs text-slate-500">
Hypothesis Spread: <span className="font-medium text-slate-700 dark:text-slate-300">{activeJob.simulation_dispersion?.hypothesis_spread_label}</span>
</div>
<span className="inline-block mt-2 text-[10px] bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-400 px-2 py-0.5 rounded">
Sample: 50 Personas (5 Archetypes)
</span>
</div>
{/* Primary Decision Verdict */}
<div className="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-xl p-5">
<span className="text-xs font-semibold text-slate-500 uppercase tracking-wider">
Engine Recommendation
</span>
<div className="mt-2 text-base font-bold text-slate-900 dark:text-white line-clamp-2">
{activeJob.summary_metrics?.elasticity_verdict ||
activeJob.summary_metrics?.safety_verdict ||
activeJob.summary_metrics?.sla_risk_level ||
activeJob.summary_metrics?.consensus_verdict ||
'Evaluated'}
</div>
<div className="mt-1 text-xs text-slate-500">
Tokens: {((activeJob.prompt_tokens || 0) + (activeJob.completion_tokens || 0)).toLocaleString()} total
</div>
</div>
</div>
{/* Chart Comparison */}
<div className="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-xl p-6 shadow-sm">
<h3 className="text-sm font-semibold text-slate-900 dark:text-white mb-4 flex items-center gap-2">
<BarChart2 className="w-4 h-4 text-indigo-500" />
Comparative Baseline vs. Swarm Projection Visualizer
</h3>
<div className="h-72 w-full">
<ResponsiveContainer width="100%" height="100%">
<BarChart data={getChartData()} margin={{ top: 20, right: 30, left: 20, bottom: 5 }}>
<CartesianGrid strokeDasharray="3 3" opacity={0.2} />
<XAxis dataKey="metric" stroke="#888888" fontSize={12} />
<YAxis stroke="#888888" fontSize={12} />
<Tooltip
contentStyle={{
backgroundColor: '#1e293b',
borderColor: '#334155',
borderRadius: '8px',
color: '#fff',
}}
/>
<Legend />
<Bar dataKey="Baseline" fill="#94a3b8" radius={[4, 4, 0, 0]} />
<Bar dataKey="Projected" fill="#6366f1" radius={[4, 4, 0, 0]} />
</BarChart>
</ResponsiveContainer>
</div>
</div>
</div>
)}
{/* TAB 2: EXECUTIVE REPORT */}
{activeTab === 'report' && (
<div className="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-xl p-8 shadow-sm">
<div className="prose dark:prose-invert max-w-none">
<pre className="whitespace-pre-wrap font-sans text-sm leading-relaxed text-slate-800 dark:text-slate-200 bg-transparent p-0 border-0">
{activeJob.report_markdown || 'No report generated.'}
</pre>
</div>
</div>
)}
{/* TAB 3: PERSONA INTERVIEW STATION */}
{activeTab === 'interview' && (
<div className="space-y-6">
<div className="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-xl p-6 shadow-sm">
<div className="border-b border-slate-100 dark:border-slate-800 pb-4 mb-5">
<h3 className="text-base font-semibold text-slate-900 dark:text-white flex items-center gap-2">
<Bot className="w-5 h-5 text-indigo-500" />
Interactive Persona Deep-Dive Interview
</h3>
<p className="text-xs text-slate-500 dark:text-slate-400 mt-1">
Select any simulated customer or stakeholder from this run and interview them in first-person
to understand their granular reasoning and purchase hesitation.
</p>
</div>
<div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-4">
<div>
<label className="block text-xs font-semibold text-slate-700 dark:text-slate-300 mb-1">
Target Simulated Agent
</label>
<select
value={selectedAgentId}
onChange={(e) => setSelectedAgentId(e.target.value)}
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"
>
{activeJob.agent_logs?.map((agent) => (
<option key={agent.agent_id} value={agent.agent_id}>
{agent.agent_id} — {agent.archetype} ({agent.decision || 'Participant'})
</option>
))}
</select>
</div>
<div className="md:col-span-2">
<label className="block text-xs font-semibold text-slate-700 dark:text-slate-300 mb-1">
Manager Interview Question
</label>
<div className="flex gap-2">
<input
type="text"
placeholder="e.g. Why did you choose to abandon your repair order after seeing this offer?"
value={interviewQuestion}
onChange={(e) => setInterviewQuestion(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && handleAskInterview()}
className="flex-1 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"
/>
<button
disabled={isInterviewing || !interviewQuestion.trim()}
onClick={handleAskInterview}
className="px-4 py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg text-sm font-semibold flex items-center gap-2 disabled:opacity-50 transition-colors"
>
{isInterviewing ? <Activity className="w-4 h-4 animate-spin" /> : <Send className="w-4 h-4" />}
Ask Agent
</button>
</div>
</div>
</div>
{/* Interview Answers Conversation */}
<div className="space-y-3 mt-6">
{interviewAnswers.length === 0 ? (
<div className="text-center py-8 text-xs text-slate-400 border border-dashed border-slate-200 dark:border-slate-800 rounded-lg">
No interviews recorded yet. Ask a question to begin chatting with this simulated persona.
</div>
) : (
interviewAnswers.map((item, idx) => (
<div
key={idx}
className="bg-slate-50 dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-xl p-4 space-y-2"
>
<div className="flex items-center justify-between text-xs">
<span className="font-semibold text-slate-900 dark:text-white flex items-center gap-2">
<UserCheck className="w-3.5 h-3.5 text-indigo-500" />
Agent: {item.agent_id}
</span>
<span className="text-slate-400 font-mono text-[11px]">
Latency: {item.latency_ms}ms
</span>
</div>
<div className="text-xs text-slate-600 dark:text-slate-400 italic">
"{item.question}"
</div>
<div className="text-sm font-medium text-slate-800 dark:text-slate-200 bg-white dark:bg-slate-900 p-3 rounded-lg border border-slate-100 dark:border-slate-800">
{item.answer}
</div>
</div>
))
)}
</div>
</div>
</div>
)}
{/* TAB 4: 50 PERSONA LEDGER */}
{activeTab === 'agents' && (
<div className="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-xl p-6 shadow-sm">
<h3 className="text-base font-semibold text-slate-900 dark:text-white mb-4">
50 Persona Decision Ledger
</h3>
<div className="overflow-x-auto max-h-96">
<table className="w-full text-left text-xs">
<thead className="bg-slate-50 dark:bg-slate-950 text-slate-500 uppercase sticky top-0">
<tr>
<th className="p-2.5">Agent ID</th>
<th className="p-2.5">Archetype</th>
<th className="p-2.5">Device</th>
<th className="p-2.5">Price Sensitivity</th>
<th className="p-2.5">Simulated Decision</th>
<th className="p-2.5">Action</th>
</tr>
</thead>
<tbody className="divide-y divide-slate-100 dark:divide-slate-800">
{activeJob.agent_logs?.map((agent) => (
<tr key={agent.agent_id} className="hover:bg-slate-50 dark:hover:bg-slate-800/50">
<td className="p-2.5 font-mono font-medium text-slate-900 dark:text-white">
{agent.agent_id}
</td>
<td className="p-2.5 text-slate-700 dark:text-slate-300">
{agent.archetype}
</td>
<td className="p-2.5 text-slate-500">
{agent.device || 'N/A'}
</td>
<td className="p-2.5 font-mono">
{agent.price_sensitivity !== undefined
? (agent.price_sensitivity * 100).toFixed(0) + '%'
: 'N/A'}
</td>
<td className="p-2.5">
<span
className={`px-2 py-0.5 rounded-full font-semibold ${
agent.decision === 'PURCHASE' || agent.decision === 'ACCEPT' || agent.decision === 'CLICK'
? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-950/60 dark:text-emerald-300'
: 'bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-300'
}`}
>
{agent.decision || 'N/A'}
</span>
</td>
<td className="p-2.5">
<button
onClick={() => {
setSelectedAgentId(agent.agent_id);
setActiveTab('interview');
}}
className="text-indigo-600 hover:text-indigo-700 font-semibold"
>
Interview
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
)}
</div>
)}
{/* 7. Historical Simulation Runs */}
<div className="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-xl p-6 shadow-sm">
<h3 className="text-base font-semibold text-slate-900 dark:text-white mb-4 flex items-center gap-2">
<Layers className="w-4 h-4 text-indigo-500" />
Recent Simulation History
</h3>
<div className="overflow-x-auto">
<table className="w-full text-left text-xs">
<thead className="bg-slate-50 dark:bg-slate-950 text-slate-500 uppercase">
<tr>
<th className="p-3">Job ID</th>
<th className="p-3">Scenario</th>
<th className="p-3">Status</th>
<th className="p-3">Execution Time</th>
<th className="p-3">Cost (USD)</th>
<th className="p-3">Created At</th>
<th className="p-3 text-right">Action</th>
</tr>
</thead>
<tbody className="divide-y divide-slate-100 dark:divide-slate-800">
{jobHistory.length === 0 ? (
<tr>
<td colSpan={7} className="p-4 text-center text-slate-400">
No simulation runs recorded yet.
</td>
</tr>
) : (
jobHistory.map((job) => (
<tr key={job.job_id} className="hover:bg-slate-50 dark:hover:bg-slate-800/50">
<td className="p-3 font-mono font-medium text-slate-900 dark:text-white">
{job.job_id}
</td>
<td className="p-3 capitalize text-slate-700 dark:text-slate-300">
{job.scenario_type.replace('_', ' ')}
</td>
<td className="p-3">
<span
className={`px-2 py-0.5 rounded-full text-[10px] font-semibold uppercase ${
job.status === 'COMPLETED'
? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-950/60 dark:text-emerald-300'
: job.status === 'RUNNING' || job.status === 'QUEUED'
? 'bg-indigo-100 text-indigo-700 dark:bg-indigo-950/60 dark:text-indigo-300'
: 'bg-rose-100 text-rose-700 dark:bg-rose-950/60 dark:text-rose-300'
}`}
>
{job.status}
</span>
</td>
<td className="p-3 text-slate-600 dark:text-slate-400">
{job.execution_time_ms ? `${job.execution_time_ms}ms` : '—'}
</td>
<td className="p-3 text-slate-600 dark:text-slate-400">
{job.total_cost_usd !== undefined ? `$${job.total_cost_usd}` : '—'}
</td>
<td className="p-3 text-slate-500">
{new Date(job.created_at).toLocaleString()}
</td>
<td className="p-3 text-right">
<button
onClick={() => loadJobDetail(job.job_id)}
className="px-2.5 py-1 text-xs font-semibold rounded bg-slate-100 hover:bg-slate-200 dark:bg-slate-800 dark:hover:bg-slate-700 text-slate-700 dark:text-slate-200 transition-colors"
>
Load Run
</button>
</td>
</tr>
))
)}
</tbody>
</table>
</div>
</div>
</div>
);
}