import React from 'react'; import { useDashboardStats, useReports, useEscalations, useAIInsights, useServiceNarrative } from '@nexus/shared'; import { Terminal, Activity, Shield, Clock, MessageSquare, Cpu, AlertTriangle, TrendingUp } from 'lucide-react'; import { motion } from 'framer-motion'; import ReactMarkdown from 'react-markdown'; import styles from './AnalyticsDashboard.module.css'; interface AnalyticsDashboardProps { workspaceId?: string; onTicketSelect?: (ticket: any) => void; readOnly?: boolean; } const MiniTrend = ({ data, color }: { data: number[], color: string }) => { if (data.length < 2) return null; const min = Math.min(...data); const max = Math.max(...data); const range = max - min || 1; const width = 60; const height = 24; const points = data.map((val, i) => { const x = (i / (data.length - 1)) * width; const y = height - ((val - min) / range) * height; return `${x},${y}`; }).join(' '); return (
); }; export const AnalyticsDashboard: React.FC = ({ workspaceId, onTicketSelect, readOnly }) => { const { stats, loading: statsLoading } = useDashboardStats(workspaceId); const { daily, sla, loading: reportsLoading } = useReports(workspaceId); const { breaches, audit, loading: escLoading } = useEscalations(workspaceId); const { insights, loading: aiLoading } = useAIInsights(workspaceId); const { narrative, loading: narrativeLoading } = useServiceNarrative(workspaceId); const isLoading = statsLoading || reportsLoading || escLoading || aiLoading || narrativeLoading; const hasData = stats && daily.length > 0; if (isLoading && !hasData) { return (
Initializing Neural Analytics Suite...
); } // 1. Process Daily Stats for Category Intensity & Trends const dailyVolumes = daily.map(d => d.total); const categories = daily.reduce((acc: any, day: any, index: number) => { Object.entries(day.categories).forEach(([cat, count]: [string, any]) => { if (!acc[cat]) acc[cat] = { total: 0, weekly: 0, previous: 0 }; acc[cat].total += count; // Velocity check: Last 7 days vs previous 23 if (index >= daily.length - 7) { acc[cat].weekly += count; } else { acc[cat].previous += count; } }); return acc; }, {}); const sortedCategories = Object.entries(categories) .map(([name, data]: any) => { const weeklyAvg = data.weekly / 7; const prevAvg = data.previous / 23; const ratio = prevAvg > 0 ? weeklyAvg / prevAvg : (data.weekly > 0 ? 2 : 1); let velocity: 'surge' | 'stable' | 'declining' = 'stable'; if (ratio > 1.25) velocity = 'surge'; else if (ratio < 0.75) velocity = 'declining'; return { name, count: data.total, velocity, ratio }; }) .sort((a, b) => b.count - a.count) .slice(0, 5); const maxCatCount = Math.max(...sortedCategories.map(c => c.count), 1); // 2. Performance Vitals const vitals = [ { label: "TOTAL TICKETS (30D)", value: stats?.total_tickets || 0, sub: "Active Stream", icon: , color: "#3B82F6", trend: dailyVolumes }, { label: "SLA COMPLIANCE", value: `${((sla?.sla_compliance_rate || 0) * 100).toFixed(0)}%`, sub: `${sla?.on_time_tickets} On Time`, icon: , color: "#10B981" }, { label: "AVG RESOLUTION", value: `${stats?.performance?.avg_resolution_hours || 0}h`, sub: "Lead Time", icon: , color: "#8B5CF6" }, { label: "SERVICE CSAT", value: stats?.performance?.csat_score ?? 0.0, sub: "User Sentiment", icon: , color: "#F59E0B" }, ]; return (
{/* 1. Global Vitals Row */}
{vitals.map(v => (
{v.icon}
{v.label} {v.value} {v.sub}
{v.trend && (
)}
))}
{/* 2. AI Sentinel Section */}

SENTINEL AI INSIGHTS

Autonomous Narrative Analysis
{aiLoading &&
}
{narrative?.insights || "Analyzing service patterns... neural pathways converging."}
{!readOnly && (
{insights?.actions.map((action: string, i: number) => (
{i + 1}

{action}

))}
)}
{/* 3. Categorical Intensity (Internal Sidebar) */}

OPERATIONAL INTENSITY

Category Mix (30D)
`${(i / 29) * 300},${50 - (v / Math.max(...dailyVolumes, 1)) * 50}`).join(' L ')}`} fill="none" stroke="#3B82F6" strokeWidth="2" initial={{ pathLength: 0 }} animate={{ pathLength: 1 }} transition={{ duration: 1.5, ease: "easeInOut" }} /> `${(i / 29) * 300},${50 - (v / Math.max(...dailyVolumes, 1)) * 50}`).join(' L ')} L 300,50 L 0,50 Z`} fill="rgba(59, 130, 246, 0.1)" initial={{ opacity: 0 }} animate={{ opacity: 1 }} transition={{ delay: 1, duration: 1 }} />
{sortedCategories.map(c => (
{c.name} {c.velocity}
))}
{/* 4. Operational Audit Ledger */}

STRATEGIC AUDIT LEDGER

Recent Escalations & Shifts
{audit.slice(0, 8).map((entry: any) => (
{new Date(entry.created_at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
{entry.action.replace('_', ' ').toUpperCase()}

Ticket ref: {entry.entity_id.slice(0, 8)}...

))}
{/* 5. SLA Risk & Breach Matrix (Wide Bottom) */}

SLA RISK & BREACH MATRIX

Autonomous Early Warning System
{breaches.length > 0 ? ( breaches.map((b: any) => ( onTicketSelect?.(b)} > )) ) : ( )}
URGENCY PRIORITY TICKET ID TITLE TIME STATUS
RISK: {b.risk_score}%
{b.priority} #{b.id.slice(0, 8).toUpperCase()} {b.title} {b.is_breached ? ( `OVERDUE ${Math.round(b.age_minutes - b.threshold)}m` ) : ( BREACH IN {Math.round(b.minutes_remaining)}m )}
Global Compliance Maintained
); };