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

1055 lines
43 KiB
TypeScript

'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<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="flex flex-col gap-5 min-w-0">
<div className="flex flex-wrap items-center justify-between gap-3 min-w-0">
<div className="flex items-center gap-2 min-w-0">
<h1 className="text-lg font-semibold text-foreground">Prediction lab</h1>
<span className="inline-flex items-center justify-center min-w-5 h-5 px-1.5 crm-radius-toggle bg-primary/10 text-primary text-[11px] font-semibold leading-none">
{jobHistory.length}
</span>
</div>
<button type="button" onClick={fetchMetadataAndHistory} className={secondaryButton}>
<RotateCcw className="w-3.5 h-3.5" />
Refresh
</button>
</div>
<div className={`${shell} p-6`}>
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 border-b border-border pb-4 mb-4">
<div className="flex flex-wrap items-center gap-3 min-w-0">
<h2 className="text-[13px] font-semibold text-foreground">Parameters</h2>
<div className="w-full sm:w-64">
<CustomSelect
value={selectedScenario}
onChange={handleScenarioChange}
aria-label="Scenario"
options={(scenariosMeta?.available_scenarios?.length
? scenariosMeta.available_scenarios
: ['pricing_elasticity', 'whatsapp_preflight', 'workshop_surge', 'fleet_quote']
).map((id) => ({
value: id,
label: scenariosMeta?.scenarios[id]?.title || id.replaceAll('_', ' '),
}))}
/>
</div>
</div>
<div className="flex items-center gap-3">
{activeJob && ['QUEUED', 'CLAIMED', 'RUNNING'].includes(activeJob.status) ? (
<button
onClick={handleCancelJob}
className="inline-flex items-center justify-center gap-1.5 h-9 px-3 crm-radius-control bg-destructive hover:bg-destructive/90 text-white text-[13px] font-semibold cursor-pointer"
>
<StopCircle className="w-4 h-4" />
Cancel Simulation
</button>
) : (
<button
disabled={isSubmitting}
onClick={handleLaunchSimulation}
className={primaryButton}
>
{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={labelClass}>
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={fieldClass}
/>
</div>
<div>
<label className={labelClass}>
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={fieldClass}
/>
</div>
<div>
<label className={labelClass}>
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={fieldClass}
/>
</div>
<div>
<label className={labelClass}>
Target Product Category
</label>
<CustomSelect
value={inputParams.target_category || 'Display & Touch Screens'}
onChange={(value) => 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' },
]}
/>
</div>
</>
)}
{selectedScenario === 'whatsapp_preflight' && (
<>
<div className="md:col-span-2">
<label className={labelClass}>
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={areaClass}
/>
</div>
<div>
<label className={labelClass}>
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={fieldClass}
/>
</div>
<div>
<label className={labelClass}>
Target Customer Segment
</label>
<CustomSelect
value={inputParams.target_segment || 'Past Customers'}
onChange={(value) => setInputParams({ ...inputParams, target_segment: value })}
options={[
{ value: 'Past Customers', label: 'Past Customers (Active)' },
{ value: 'Dormant (6+ Months)', label: 'Dormant (6+ Months)' },
{ value: 'Walk-in Leads', label: 'Walk-in Inquiries' },
{ value: 'High-Value VIPs', label: 'High-Value VIPs' },
]}
/>
</div>
</>
)}
{selectedScenario === 'workshop_surge' && (
<>
<div>
<label className={labelClass}>
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={fieldClass}
/>
</div>
<div>
<label className={labelClass}>
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={fieldClass}
/>
</div>
<div>
<label className={labelClass}>
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={fieldClass}
/>
</div>
</>
)}
{selectedScenario === 'fleet_quote' && (
<>
<div>
<label className={labelClass}>
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={fieldClass}
/>
</div>
<div>
<label className={labelClass}>
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={fieldClass}
/>
</div>
<div>
<label className={labelClass}>
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={fieldClass}
/>
</div>
<div>
<label className={labelClass}>
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={fieldClass}
/>
</div>
</>
)}
</div>
</div>
{/* 5. Active Job Progress Tracker */}
{activeJob && (
<div className={`${shell} p-4`}>
<div className="flex flex-col lg:flex-row lg:items-center justify-between gap-3">
<div className="min-w-0">
<div className="flex flex-wrap items-center gap-2">
<span className="text-[13px] font-semibold text-foreground">{activeJob.id}</span>
<span
className={`inline-flex items-center px-2.5 py-1 crm-radius-badge text-[11px] font-semibold ${
activeJob.status === 'COMPLETED'
? 'bg-success/15 text-success'
: activeJob.status === 'RUNNING' || activeJob.status === 'QUEUED' || activeJob.status === 'CLAIMED'
? 'bg-primary/10 text-primary'
: 'bg-destructive/10 text-destructive'
}`}
>
{activeJob.status}
</span>
</div>
<p className="text-[12px] text-muted-foreground mt-1">
{activeJob.scenario_type}
{activeJob.execution_time_ms ? ` · ${activeJob.execution_time_ms}ms` : ''}
{activeJob.total_cost_usd !== undefined ? ` · $${activeJob.total_cost_usd}` : ''}
</p>
</div>
<div className="flex flex-wrap items-center gap-2 text-[12px]">
<span className={`inline-flex items-center px-2.5 py-1 crm-radius-badge font-semibold ${activeJob.historical_baseline ? 'bg-success/15 text-success' : 'bg-muted text-muted-foreground'}`}>
Baseline
</span>
<span className={`inline-flex items-center px-2.5 py-1 crm-radius-badge font-semibold ${activeJob.simulation_dispersion ? 'bg-success/15 text-success' : 'bg-muted text-muted-foreground'}`}>
Personas
</span>
<span className={`inline-flex items-center px-2.5 py-1 crm-radius-badge font-semibold ${activeJob.calibrated_projection ? 'bg-success/15 text-success' : 'bg-muted text-muted-foreground'}`}>
Projection
</span>
<span className={`inline-flex items-center px-2.5 py-1 crm-radius-badge font-semibold ${activeJob.status === 'COMPLETED' ? 'bg-success/15 text-success' : 'bg-muted text-muted-foreground'}`}>
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-border pb-2">
<button
onClick={() => setActiveTab('metrics')}
className={`inline-flex items-center gap-1.5 h-9 px-3 crm-radius-control text-[13px] font-semibold transition-colors ${
activeTab === 'metrics'
? 'bg-primary text-white'
: 'text-muted-foreground hover:bg-muted'
}`}
>
<BarChart2 className="w-4 h-4" />
Calibrated Projections
</button>
<button
onClick={() => setActiveTab('report')}
className={`inline-flex items-center gap-1.5 h-9 px-3 crm-radius-control text-[13px] font-semibold transition-colors ${
activeTab === 'report'
? 'bg-primary text-white'
: 'text-muted-foreground hover:bg-muted'
}`}
>
<FileText className="w-4 h-4" />
Executive Synthesis
</button>
<button
onClick={() => setActiveTab('interview')}
className={`inline-flex items-center gap-1.5 h-9 px-3 crm-radius-control text-[13px] font-semibold transition-colors ${
activeTab === 'interview'
? 'bg-primary text-white'
: 'text-muted-foreground hover:bg-muted'
}`}
>
<Bot className="w-4 h-4" />
Persona Interview Station
</button>
<button
onClick={() => setActiveTab('agents')}
className={`inline-flex items-center gap-1.5 h-9 px-3 crm-radius-control text-[13px] font-semibold transition-colors ${
activeTab === 'agents'
? 'bg-primary text-white'
: 'text-muted-foreground hover:bg-muted'
}`}
>
<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={`${shell} p-5`}>
<span className="text-[13px] text-muted-foreground">
Historical Baseline
</span>
<div className="mt-2 text-[22px] font-bold text-foreground tracking-tight">
{activeJob.historical_baseline?.historical_mean !== undefined
? `${(activeJob.historical_baseline.historical_mean * 100).toFixed(1)}%`
: 'N/A'}
</div>
<div className="mt-1 text-[12px] text-muted-foreground flex items-center gap-1">
<span>95% CI:</span>
<span className="font-mono text-foreground">
[{((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-flex mt-2 px-2.5 py-1 crm-radius-badge text-[11px] font-semibold bg-muted text-foreground">
Source: {activeJob.historical_baseline?.baseline_source}
</span>
</div>
{/* Calibrated Projection Card */}
<div className={`${shell} p-5`}>
<span className="text-[13px] text-muted-foreground">
Calibrated Projection
</span>
<div className="mt-2 text-[22px] font-bold text-foreground tracking-tight">
{activeJob.calibrated_projection?.point_estimate !== undefined
? `${(activeJob.calibrated_projection.point_estimate * 100).toFixed(1)}%`
: 'N/A'}
</div>
<div className="mt-1 text-[12px] text-muted-foreground flex items-center gap-1">
<span>Credible Range:</span>
<span className="font-mono text-foreground">
[{((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-flex mt-2 px-2.5 py-1 crm-radius-badge text-[11px] font-semibold bg-primary/10 text-primary">
Weights: Hist {(activeJob.calibrated_projection?.historical_weight || 0) * 100}% / Swarm {(activeJob.calibrated_projection?.simulation_weight || 0) * 100}%
</span>
</div>
{/* Agent Dispersion Card */}
<div className={`${shell} p-5`}>
<span className="text-[13px] text-muted-foreground">
Persona Disagreement Index
</span>
<div className="mt-2 text-[22px] font-bold text-foreground tracking-tight">
{activeJob.simulation_dispersion?.agent_disagreement_index !== undefined
? `${(activeJob.simulation_dispersion.agent_disagreement_index * 100).toFixed(1)}%`
: 'N/A'}
</div>
<div className="mt-1 text-[12px] text-muted-foreground">
Hypothesis Spread: <span className="font-medium text-foreground">{activeJob.simulation_dispersion?.hypothesis_spread_label}</span>
</div>
<span className="inline-flex mt-2 px-2.5 py-1 crm-radius-badge text-[11px] font-semibold bg-muted text-foreground">
Sample: 50 Personas (5 Archetypes)
</span>
</div>
{/* Primary Decision Verdict */}
<div className={`${shell} p-5`}>
<span className="text-[13px] text-muted-foreground">
Engine Recommendation
</span>
<div className="mt-2 text-base font-bold text-foreground 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-[12px] text-muted-foreground">
Tokens: {((activeJob.prompt_tokens || 0) + (activeJob.completion_tokens || 0)).toLocaleString()} total
</div>
</div>
</div>
{/* Chart Comparison */}
<div className={`${shell} p-6`}>
<h3 className="text-[13px] font-semibold text-foreground mb-4">
Baseline and projection
</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: 'var(--card)',
borderColor: 'var(--border)',
borderRadius: '8px',
color: 'var(--foreground)',
fontSize: '13px',
}}
/>
<Legend />
<Bar dataKey="Baseline" fill="#94a3b8" radius={[4, 4, 0, 0]} />
<Bar dataKey="Projected" fill="#108E7A" radius={[4, 4, 0, 0]} />
</BarChart>
</ResponsiveContainer>
</div>
</div>
</div>
)}
{/* TAB 2: EXECUTIVE REPORT */}
{activeTab === 'report' && (
<div className={`${shell} p-8`}>
<div className="prose dark:prose-invert max-w-none">
<pre className="whitespace-pre-wrap font-sans text-sm leading-relaxed text-foreground 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={`${shell} p-6`}>
<div className="border-b border-border pb-4 mb-5">
<h3 className="text-[13px] font-semibold text-foreground">Interview</h3>
<p className="text-[12px] text-muted-foreground mt-1">
Select a persona from this run and ask a question.
</p>
</div>
<div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-4">
<div>
<label className={labelClass}>
Target Simulated Agent
</label>
<CustomSelect
value={selectedAgentId}
onChange={setSelectedAgentId}
placeholder="Select agent"
options={(activeJob.agent_logs || []).map((agent) => ({
value: agent.agent_id,
label: `${agent.agent_id} — ${agent.archetype} (${agent.decision || 'Participant'})`,
}))}
/>
</div>
<div className="md:col-span-2">
<label className={labelClass}>
Manager Interview Question
</label>
<div className="flex gap-2">
<input
type="text"
placeholder="Question"
value={interviewQuestion}
onChange={(e) => setInterviewQuestion(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && handleAskInterview()}
className={fieldClass}
/>
<button
disabled={isInterviewing || !interviewQuestion.trim()}
onClick={handleAskInterview}
className={primaryButton}
>
{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-[13px] text-muted-foreground border border-dashed border-border crm-radius-control">
No interviews recorded yet. Ask a question to begin chatting with this simulated persona.
</div>
) : (
interviewAnswers.map((item, idx) => (
<div
key={idx}
className="bg-muted/40 border border-border rounded-xl p-4 space-y-2"
>
<div className="flex items-center justify-between text-xs">
<span className="text-[13px] font-semibold text-foreground">
Agent: {item.agent_id}
</span>
<span className="text-[11px] font-mono text-muted-foreground">
Latency: {item.latency_ms}ms
</span>
</div>
<div className="text-xs text-muted-foreground italic">
"{item.question}"
</div>
<div className="text-[13px] font-medium text-foreground bg-card p-3 crm-radius-control border border-border">
{item.answer}
</div>
</div>
))
)}
</div>
</div>
</div>
)}
{/* TAB 4: 50 PERSONA LEDGER */}
{activeTab === 'agents' && (
<div className={shell}>
<div className="px-4 py-3 border-b border-border">
<h3 className="text-[13px] font-semibold text-foreground">Personas</h3>
</div>
<div className="overflow-x-auto">
<table className="crm-data-table min-w-[860px]">
<thead>
<tr className="border-b border-border">
<th className="px-4 py-2.5 text-left font-medium text-muted-foreground">Agent ID</th>
<th className="px-4 py-2.5 text-left font-medium text-muted-foreground">Archetype</th>
<th className="px-4 py-2.5 text-left font-medium text-muted-foreground">Device</th>
<th className="px-4 py-2.5 text-right font-medium text-muted-foreground">Price sensitivity</th>
<th className="px-4 py-2.5 text-left font-medium text-muted-foreground">Decision</th>
<th className="px-4 py-2.5 text-right font-medium text-muted-foreground">Action</th>
</tr>
</thead>
<tbody>
{(activeJob.agent_logs || []).length === 0 ? (
<tr>
<td colSpan={6} className="px-4 py-16 text-center text-[13px] text-muted-foreground whitespace-normal">No personas returned</td>
</tr>
) : (activeJob.agent_logs || []).map((agent) => (
<tr key={agent.agent_id} className="border-b border-border last:border-b-0 hover:bg-muted/10">
<td className="px-4 py-2.5 text-[13px] font-semibold text-foreground">{agent.agent_id}</td>
<td className="px-4 py-2.5 text-[13px] text-foreground">{agent.archetype || '—'}</td>
<td className="px-4 py-2.5 text-[13px] text-muted-foreground">{agent.device || '—'}</td>
<td className="px-4 py-2.5 text-right text-[13px] text-foreground">
{agent.price_sensitivity !== undefined ? `${(agent.price_sensitivity * 100).toFixed(0)}%` : '—'}
</td>
<td className="px-4 py-2.5">
<span className={`inline-flex items-center px-2.5 py-1 crm-radius-badge text-[11px] font-semibold ${
agent.decision === 'PURCHASE' || agent.decision === 'ACCEPT' || agent.decision === 'CLICK'
? 'bg-success/15 text-success'
: 'bg-muted text-foreground'
}`}>
{agent.decision || '—'}
</span>
</td>
<td className="px-4 py-2.5 text-right">
<button
type="button"
onClick={() => {
setSelectedAgentId(agent.agent_id);
setActiveTab('interview');
}}
className="text-[13px] font-semibold text-primary cursor-pointer"
>
Interview
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
)}
</div>
)}
{/* 7. Historical Simulation Runs */}
<div className={shell}>
<div className="px-4 py-3 border-b border-border">
<h3 className="text-[13px] font-semibold text-foreground">Runs</h3>
</div>
<div className="overflow-x-auto">
<table className="crm-data-table min-w-[860px]">
<thead>
<tr className="border-b border-border">
<th className="px-4 py-2.5 text-left font-medium text-muted-foreground">Job ID</th>
<th className="px-4 py-2.5 text-left font-medium text-muted-foreground">Scenario</th>
<th className="px-4 py-2.5 text-left font-medium text-muted-foreground">Status</th>
<th className="px-4 py-2.5 text-right font-medium text-muted-foreground">Time</th>
<th className="px-4 py-2.5 text-right font-medium text-muted-foreground">Cost</th>
<th className="px-4 py-2.5 text-left font-medium text-muted-foreground">Created</th>
<th className="px-4 py-2.5 text-right font-medium text-muted-foreground">Action</th>
</tr>
</thead>
<tbody>
{jobHistory.length === 0 ? (
<tr>
<td colSpan={7} className="px-4 py-16 text-center text-[13px] text-muted-foreground whitespace-normal">
No runs yet
</td>
</tr>
) : jobHistory.map((job) => (
<tr key={job.job_id} className="border-b border-border last:border-b-0 hover:bg-muted/10">
<td className="px-4 py-2.5 text-[13px] font-semibold text-foreground">{job.job_id}</td>
<td className="px-4 py-2.5 text-[13px] text-foreground capitalize">{job.scenario_type.replace('_', ' ')}</td>
<td className="px-4 py-2.5">
<span className={`inline-flex items-center px-2.5 py-1 crm-radius-badge text-[11px] font-semibold ${
job.status === 'COMPLETED'
? 'bg-success/15 text-success'
: job.status === 'RUNNING' || job.status === 'QUEUED'
? 'bg-primary/10 text-primary'
: 'bg-destructive/10 text-destructive'
}`}>
{job.status}
</span>
</td>
<td className="px-4 py-2.5 text-right text-[13px] text-muted-foreground">{job.execution_time_ms ? `${job.execution_time_ms} ms` : '—'}</td>
<td className="px-4 py-2.5 text-right text-[13px] text-muted-foreground">{job.total_cost_usd !== undefined ? `$${job.total_cost_usd}` : '—'}</td>
<td className="px-4 py-2.5 text-[13px] text-muted-foreground whitespace-nowrap">{job.created_at ? new Date(job.created_at).toLocaleString() : '—'}</td>
<td className="px-4 py-2.5 text-right">
<button type="button" onClick={() => loadJobDetail(job.job_id)} className={secondaryButton}>
Open
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
</div>
);
}