'use client'; import { useState, useEffect, useCallback } from 'react'; import { RefreshCw, Shield, AlertTriangle, CheckCircle, TrendingUp, Activity, Zap } from 'lucide-react'; import Sidebar from '@/components/Sidebar'; import SimulationEngine from '@/components/SimulationEngine'; import ChatPanel from '@/components/ChatPanel'; // Use environment variable or relative URL for production const API_URL = process.env.NEXT_PUBLIC_API_URL || ''; interface Transaction { id: number; amount: number; merchant: string; category: string; is_fraud: number; prediction: string; final_score: number; classical_score: number; quantum_score: number; quantum_details: { vqc: number; qaoa: number; qnn: number; }; } interface Metrics { total: number; flagged: number; actual_fraud: number; accuracy: number; precision: number; recall: number; f1: number; tp: number; fp: number; tn: number; fn: number; } export default function Home() { const [mounted, setMounted] = useState(false); const [activeTab, setActiveTab] = useState('dashboard'); const [isRunning, setIsRunning] = useState(false); const [transactions, setTransactions] = useState([]); const [metrics, setMetrics] = useState({ total: 0, flagged: 0, actual_fraud: 0, accuracy: 0, precision: 0, recall: 0, f1: 0, tp: 0, fp: 0, tn: 0, fn: 0 }); const [lastUpdated, setLastUpdated] = useState(null); // Hydration fix useEffect(() => { setMounted(true); setLastUpdated(new Date()); }, []); // Stable callbacks for SimulationEngine const handleTransactionUpdate = useCallback((transaction: Transaction, newMetrics: Metrics) => { setTransactions(prev => [transaction, ...prev].slice(0, 50)); setMetrics(newMetrics); setLastUpdated(new Date()); }, []); const handleRunningChange = useCallback((running: boolean) => { setIsRunning(running); }, []); // Manual refresh const processOneTransaction = useCallback(async () => { try { const response = await fetch(`${API_URL}/api/process-random`); if (response.ok) { const data = await response.json(); handleTransactionUpdate(data.transaction, data.metrics); } } catch (error) { console.error('Failed to process transaction:', error); } }, [handleTransactionUpdate]); const getRiskColor = (score: number) => { if (score >= 0.7) return 'text-red-700 bg-red-100'; if (score >= 0.4) return 'text-amber-700 bg-amber-100'; return 'text-green-700 bg-green-100'; }; const getRiskLevel = (score: number) => { if (score >= 0.7) return { label: 'HIGH', color: 'text-red-600 bg-red-50 border-red-200' }; if (score >= 0.4) return { label: 'MEDIUM', color: 'text-amber-600 bg-amber-50 border-amber-200' }; return { label: 'LOW', color: 'text-green-600 bg-green-50 border-green-200' }; }; // Page titles and descriptions const pageInfo: Record = { dashboard: { title: 'Dashboard', subtitle: 'Live Transaction Monitoring' }, models: { title: 'Model Performance', subtitle: 'Quantum & Classical Model Analysis' }, settings: { title: 'Settings', subtitle: 'System Configuration' }, }; const currentPage = pageInfo[activeTab] || pageInfo.dashboard; return (
{/* Header */}

{currentPage.title}

{currentPage.subtitle}

{/* System Status */}
{isRunning ? 'Processing' : 'Idle'}
{/* Model Status */}
Quantum Ready
{/* Transaction Count */}
{metrics.total} txns
{/* Refresh */}

Last updated: {mounted && lastUpdated ? lastUpdated.toLocaleTimeString() : '--:--:--'}

{/* Dashboard View */} {activeTab === 'dashboard' && ( <> {/* Simulation Engine - Isolated Component */} {/* Stats Row */}
} label="Transactions" value={metrics.total} color="white" /> } label="Flagged" value={metrics.flagged} color="yellow" /> } label="Actual Fraud" value={metrics.actual_fraud} color="red" /> } label="Accuracy" value={`${(metrics.accuracy * 100).toFixed(1)}%`} color="green" /> } label="Precision" value={`${(metrics.precision * 100).toFixed(1)}%`} color="green" /> } label="F1 Score" value={`${(metrics.f1 * 100).toFixed(1)}%`} color="yellow" />
{/* Main Grid */}
{/* Transaction Table */}

Live Transactions

{transactions.length} records
{transactions.length === 0 ? ( ) : ( transactions.map((tx, idx) => { const risk = getRiskLevel(tx.final_score); return ( ); }) )}
ID Amount Category
C/Q
Final Risk Prediction Actual
Click "Start" to begin processing transactions
#{tx.id} ${tx.amount.toFixed(2)} {tx.category}
{((tx.classical_score || tx.final_score * 0.8) * 100).toFixed(0)}% / {((tx.quantum_score || tx.final_score * 0.2) * 100).toFixed(0)}%
{(tx.final_score * 100).toFixed(0)}% {risk.label} {tx.prediction} {tx.is_fraud ? 'Fraud' : 'Legit'}
{/* Chat Panel - Isolated Component */}
{/* Bottom Row - Model Performance & Confusion Matrix */}
{/* Live Quantum Analysis */}

Live Quantum Analysis

{transactions.length > 0 ? ( <>
{/* Latest Transaction Quantum Breakdown */}
Transaction #{transactions[0].id} {transactions[0].prediction}

{((transactions[0].classical_score || 0) * 100).toFixed(1)}%

Classical

{((transactions[0].quantum_score || 0) * 100).toFixed(1)}%

Quantum

{/* Quantum Model Scores */}
{[ { name: 'VQC', value: transactions[0].quantum_details?.vqc || 0, color: 'bg-indigo-500', desc: 'Variational Quantum Classifier' }, { name: 'QAOA', value: transactions[0].quantum_details?.qaoa || 0, color: 'bg-purple-500', desc: 'Quantum Optimization' }, { name: 'QNN', value: transactions[0].quantum_details?.qnn || 0, color: 'bg-violet-500', desc: 'Quantum Neural Network' } ].map((model) => (
{model.name}
{(model.value * 100).toFixed(0)}%
))}
Final Score = 0.5 ? 'text-red-600' : 'text-green-600'}`}> {(transactions[0].final_score * 100).toFixed(1)}%
) : (
Start simulation to see live quantum analysis
)}
{/* Confusion Matrix */}

Confusion Matrix

{metrics.tp}

True Positive

{metrics.fp}

False Positive

{metrics.fn}

False Negative

{metrics.tn}

True Negative

{/* Model Weights */}

Model Weights

Classical Model 80%
Quantum Ensemble 20%
Ensemble Accuracy {(metrics.accuracy * 100).toFixed(1) || '0.0'}%
System Status Online
)} {/* Models View */} {activeTab === 'models' && (
{/* Model Architecture Overview */}

Hybrid Model Architecture

Our fraud detection system uses a hybrid ensemble combining classical machine learning with quantum computing for enhanced pattern recognition.

{/* Classical Model */}

Classical Model

80%

XGBoost Gradient Boosting

  • • High accuracy on structured data
  • • Fast inference time
  • • Handles missing values
{/* Quantum Ensemble */}

Quantum Ensemble

20%

VQC + QAOA + QNN

  • • Detects quantum patterns
  • • Finds subtle correlations
  • • Improves edge cases
{/* Quantum Models Detail */}
VQC

Variational Quantum Classifier

40% of quantum weight

Uses parameterized quantum circuits for classification. Learns optimal rotations for feature encoding.

Qubits 4
QAOA

Quantum Approximate Optimization

30% of quantum weight

Finds optimal solutions for combinatorial problems. Used for feature subset selection.

Layers 2
QNN

Quantum Neural Network

30% of quantum weight

Deep quantum circuits with entanglement layers. Captures complex non-linear patterns.

Depth 3
{/* Performance Metrics */}

Current Session Performance

{(metrics.accuracy * 100).toFixed(1)}%

Accuracy

{(metrics.precision * 100).toFixed(1)}%

Precision

{(metrics.recall * 100).toFixed(1)}%

Recall

{(metrics.f1 * 100).toFixed(1)}%

F1 Score

)} {/* Settings View */} {activeTab === 'settings' && (

System Settings

API Endpoint

Backend server URL

{API_URL}

Classical Weight

XGBoost contribution

80%

Quantum Weight

Ensemble contribution

20%

Fraud Threshold

Score cutoff for flagging

0.5

Transaction Buffer

Max transactions in view

50
{/* HuggingFace Cloud Integration */}
🤗

HuggingFace Cloud Integration

Offload heavy ML computations to HuggingFace Inference API to reduce local system burden.

Status

Cloud inference availability

Check Backend

Setup Instructions

  1. Get free API key from huggingface.co/settings/tokens
  2. Create a .env file in project root
  3. Add: HUGGINGFACE_API_KEY=your_key_here
  4. Restart the backend server
💡 Free tier includes ~30K requests/month - perfect for development and testing!

About

QuantumShield is a hybrid quantum-classical fraud detection system. It combines the power of XGBoost for handling structured transaction data with quantum computing circuits (VQC, QAOA, QNN) for enhanced pattern recognition.

Built with PennyLane Next.js Frontend FastAPI Backend 🤗 HuggingFace
)}
); } function StatCard({ icon, label, value, color }: { icon: React.ReactNode; label: string; value: string | number; color: string }) { const colors: Record = { white: 'bg-white border-gray-200', yellow: 'bg-amber-50 border-amber-200', red: 'bg-red-50 border-red-200', green: 'bg-green-50 border-green-200', }; const textColors: Record = { white: 'text-gray-900', yellow: 'text-amber-600', red: 'text-red-600', green: 'text-green-600', }; const iconColors: Record = { white: 'text-gray-500', yellow: 'text-amber-500', red: 'text-red-500', green: 'text-green-500', }; return (
{icon} {label}

{value}

); }