mohsin-devs commited on
Commit
0f226f2
·
1 Parent(s): 26e2a42

Fix: Unignore and track frontend/src/ directory in Git

Browse files
.gitignore CHANGED
@@ -5,8 +5,7 @@ session.json
5
  chat_history.json
6
  users.json
7
  BankBot_Accuracy_Document.docx
8
- generate_accuracy.py
9
- src/
10
  .env
11
  .env.local
12
  .env.production
 
5
  chat_history.json
6
  users.json
7
  BankBot_Accuracy_Document.docx
8
+ # Unignored frontend/src
 
9
  .env
10
  .env.local
11
  .env.production
frontend/src/app/analytics/page.tsx ADDED
@@ -0,0 +1,442 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "use client";
2
+
3
+ import { useState, useEffect } from "react";
4
+ import { motion } from "framer-motion";
5
+ import {
6
+ BarChart, Bar, LineChart, Line, XAxis, YAxis, CartesianGrid,
7
+ Tooltip, ResponsiveContainer, RadarChart, Radar, PolarGrid,
8
+ PolarAngleAxis, PolarRadiusAxis
9
+ } from "recharts";
10
+ import { TrendingUp, Sparkles, Calendar, Filter, AlertTriangle, RefreshCw } from "lucide-react";
11
+ import { aiApi, dashboardApi } from "@/lib/api";
12
+
13
+ // ─── Types ────────────────────────────────────────────────────────────────────
14
+ interface CategoryData { name: string; value: number; color: string }
15
+ interface CashFlowPoint { month: string; income: number; expenses: number; savings: number }
16
+
17
+ const CATEGORY_COLORS = [
18
+ "#3b82f6", "#10b981", "#f59e0b", "#8b5cf6",
19
+ "#ec4899", "#06b6d4", "#84cc16", "#f97316",
20
+ ];
21
+
22
+ // ─── Animation ────────────────────────────────────────────────────────────────
23
+ const containerVariants = {
24
+ hidden: { opacity: 0 },
25
+ visible: { opacity: 1, transition: { staggerChildren: 0.07 } },
26
+ };
27
+ const itemVariants = {
28
+ hidden: { opacity: 0, y: 16 },
29
+ visible: { opacity: 1, y: 0, transition: { duration: 0.45 } },
30
+ };
31
+
32
+ // ─── Custom Tooltip ───────────────────────────────────────────────────────────
33
+ interface TooltipProps {
34
+ active?: boolean;
35
+ payload?: Array<{ name: string; value: number; color?: string; fill?: string }>;
36
+ label?: string;
37
+ }
38
+ function CustomTooltip({ active, payload, label }: TooltipProps) {
39
+ if (!active || !payload?.length) return null;
40
+ return (
41
+ <div className="glass-card p-3 text-xs space-y-1 min-w-[130px]">
42
+ <p className="text-zinc-400 font-medium mb-1">{label}</p>
43
+ {payload.map((entry) => (
44
+ <div key={entry.name} className="flex justify-between gap-3">
45
+ <span style={{ color: entry.color || entry.fill }}>{entry.name}</span>
46
+ <span className="text-white font-semibold">${(entry.value || 0).toLocaleString()}</span>
47
+ </div>
48
+ ))}
49
+ </div>
50
+ );
51
+ }
52
+
53
+ // ─── Heatmap Cell ─────────────────────────────────────────────────────────────
54
+ function HeatmapCell({ value, max }: { value: number; max: number }) {
55
+ const intensity = max > 0 ? Math.min(value / max, 1) : 0;
56
+ const alpha = 0.08 + intensity * 0.85;
57
+ return (
58
+ <motion.div
59
+ whileHover={{ scale: 1.3, zIndex: 10 }}
60
+ className="h-5 w-5 rounded-sm cursor-pointer"
61
+ style={{ background: `rgba(16, 185, 129, ${alpha})` }}
62
+ title={`$${value.toFixed(0)}`}
63
+ />
64
+ );
65
+ }
66
+
67
+ const DAYS = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
68
+
69
+ // ─── Main Page ────────────────────────────────────────────────────────────────
70
+ export default function AnalyticsPage() {
71
+ const [activeTab, setActiveTab] = useState<"overview" | "categories" | "networth">("overview");
72
+ const [loading, setLoading] = useState(true);
73
+ const [error, setError] = useState<string | null>(null);
74
+
75
+ // Data state
76
+ const [cashFlow, setCashFlow] = useState<CashFlowPoint[]>([]);
77
+ const [categoryData, setCategoryData] = useState<CategoryData[]>([]);
78
+ const [healthScore, setHealthScore] = useState<number>(0);
79
+ const [radarData, setRadarData] = useState<Array<{ subject: string; A: number }>>([]);
80
+ const [behaviorInsights, setBehaviorInsights] = useState<string[]>([]);
81
+ const [heatmapData, setHeatmapData] = useState<number[][]>(
82
+ Array.from({ length: 7 }, () => Array.from({ length: 12 }, () => 0))
83
+ );
84
+
85
+ const loadData = async () => {
86
+ setLoading(true);
87
+ setError(null);
88
+ try {
89
+ const [dashData, scoreData, behaviorData] = await Promise.all([
90
+ dashboardApi.overview(),
91
+ aiApi.healthScore(),
92
+ aiApi.behaviorInsights(),
93
+ ]);
94
+
95
+ // Cash flow
96
+ setCashFlow(dashData.cash_flow || []);
97
+
98
+ // Category data with colors
99
+ setCategoryData(
100
+ (dashData.spending_by_category || []).slice(0, 8).map((c, i) => ({
101
+ ...c,
102
+ color: CATEGORY_COLORS[i % CATEGORY_COLORS.length],
103
+ }))
104
+ );
105
+
106
+ // Health score
107
+ setHealthScore(scoreData.overall_score || 0);
108
+
109
+ // Radar from score categories
110
+ const cats = scoreData.categories || {};
111
+ setRadarData(
112
+ Object.entries(cats).map(([key, val]) => ({
113
+ subject: key.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase()),
114
+ A: Math.round(((val as { score: number; max: number }).score / (val as { score: number; max: number }).max) * 100),
115
+ }))
116
+ );
117
+
118
+ // Behavior insights
119
+ setBehaviorInsights(behaviorData.insights || []);
120
+
121
+ // Build heatmap from metrics (simulated weekly pattern from behavior data)
122
+ const metrics = behaviorData.metrics || {};
123
+ const weekendPct = (metrics.weekend_pct as number) || 0.3;
124
+ const lateNight = (metrics.late_night_count as number) || 2;
125
+ setHeatmapData(
126
+ Array.from({ length: 7 }, (_, day) =>
127
+ Array.from({ length: 12 }, (_, week) => {
128
+ const base = 50 + Math.random() * 150;
129
+ const weekendBoost = (day >= 5 ? weekendPct * 200 : 0);
130
+ const lateBoost = (week > 8 ? lateNight * 10 : 0);
131
+ return Math.round(base + weekendBoost + lateBoost);
132
+ })
133
+ )
134
+ );
135
+ } catch (err) {
136
+ setError((err as Error).message);
137
+ } finally {
138
+ setLoading(false);
139
+ }
140
+ };
141
+
142
+ useEffect(() => { loadData(); }, []);
143
+
144
+ const heatmapMax = Math.max(...heatmapData.flat(), 1);
145
+
146
+ // Build stacked bar data from cash flow (add category breakdown per month)
147
+ const stackedData = cashFlow.map((m) => ({
148
+ month: m.month,
149
+ income: m.income,
150
+ expenses: m.expenses,
151
+ savings: m.savings,
152
+ }));
153
+
154
+ return (
155
+ <motion.div
156
+ variants={containerVariants}
157
+ initial="hidden"
158
+ animate="visible"
159
+ className="flex flex-col gap-6"
160
+ >
161
+ {/* Header */}
162
+ <motion.div variants={itemVariants} className="flex items-center justify-between">
163
+ <div>
164
+ <h1 className="text-3xl font-bold tracking-tight text-white">Analytics</h1>
165
+ <p className="text-zinc-400 mt-1 text-sm">Deep insights into your financial behavior</p>
166
+ </div>
167
+ <div className="flex items-center gap-2">
168
+ <button
169
+ onClick={loadData}
170
+ className="flex items-center gap-2 rounded-xl border border-white/10 bg-white/5 px-3 py-2 text-xs text-zinc-400 hover:text-white transition-colors"
171
+ >
172
+ <RefreshCw className={`h-3.5 w-3.5 ${loading ? "animate-spin" : ""}`} />
173
+ Refresh
174
+ </button>
175
+ <button className="flex items-center gap-2 rounded-xl border border-white/10 bg-white/5 px-3 py-2 text-xs text-zinc-400 hover:text-white transition-colors">
176
+ <Calendar className="h-3.5 w-3.5" />
177
+ Last 6 months
178
+ </button>
179
+ <button className="flex items-center gap-2 rounded-xl border border-white/10 bg-white/5 px-3 py-2 text-xs text-zinc-400 hover:text-white transition-colors">
180
+ <Filter className="h-3.5 w-3.5" />
181
+ Filter
182
+ </button>
183
+ </div>
184
+ </motion.div>
185
+
186
+ {/* Error */}
187
+ {error && (
188
+ <motion.div variants={itemVariants} className="flex items-center gap-3 rounded-2xl border border-amber-500/20 bg-amber-500/5 px-5 py-3">
189
+ <AlertTriangle className="h-4 w-4 text-amber-400 flex-shrink-0" />
190
+ <p className="text-xs text-zinc-400">
191
+ <span className="text-amber-400 font-medium">Backend offline</span> — showing cached data.
192
+ </p>
193
+ </motion.div>
194
+ )}
195
+
196
+ {/* Tabs */}
197
+ <motion.div variants={itemVariants} className="flex gap-1 rounded-xl border border-white/10 bg-white/5 p-1 w-fit">
198
+ {(["overview", "categories", "networth"] as const).map((tab) => (
199
+ <button
200
+ key={tab}
201
+ onClick={() => setActiveTab(tab)}
202
+ className={`rounded-lg px-4 py-2 text-xs font-medium capitalize transition-all ${
203
+ activeTab === tab ? "bg-white/10 text-white shadow-sm" : "text-zinc-500 hover:text-zinc-300"
204
+ }`}
205
+ >
206
+ {tab === "networth" ? "Net Worth" : tab.charAt(0).toUpperCase() + tab.slice(1)}
207
+ </button>
208
+ ))}
209
+ </motion.div>
210
+
211
+ {/* ── Overview Tab ── */}
212
+ {activeTab === "overview" && (
213
+ <>
214
+ {/* Cash Flow Chart */}
215
+ <motion.div variants={itemVariants} className="glass-card p-6">
216
+ <div className="flex items-center justify-between mb-6">
217
+ <div>
218
+ <h2 className="text-base font-semibold text-white">Monthly Cash Flow</h2>
219
+ <p className="text-xs text-zinc-400 mt-0.5">Income vs Expenses vs Savings</p>
220
+ </div>
221
+ <div className="flex gap-3 flex-wrap">
222
+ {[
223
+ { label: "Income", color: "#10b981" },
224
+ { label: "Expenses", color: "#f59e0b" },
225
+ { label: "Savings", color: "#3b82f6" },
226
+ ].map((l) => (
227
+ <div key={l.label} className="flex items-center gap-1.5">
228
+ <div className="h-2 w-2 rounded-full" style={{ background: l.color }} />
229
+ <span className="text-xs text-zinc-400">{l.label}</span>
230
+ </div>
231
+ ))}
232
+ </div>
233
+ </div>
234
+ {loading ? (
235
+ <div className="h-[280px] shimmer rounded-xl" />
236
+ ) : (
237
+ <ResponsiveContainer width="100%" height={280}>
238
+ <BarChart data={stackedData} margin={{ top: 5, right: 5, left: -20, bottom: 0 }}>
239
+ <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.05)" />
240
+ <XAxis dataKey="month" tick={{ fill: "#71717a", fontSize: 11 }} axisLine={false} tickLine={false} />
241
+ <YAxis tick={{ fill: "#71717a", fontSize: 11 }} axisLine={false} tickLine={false} />
242
+ <Tooltip content={<CustomTooltip />} />
243
+ <Bar dataKey="income" name="Income" fill="#10b981" radius={[4, 4, 0, 0]} />
244
+ <Bar dataKey="expenses" name="Expenses" fill="#f59e0b" radius={[4, 4, 0, 0]} />
245
+ <Bar dataKey="savings" name="Savings" fill="#3b82f6" radius={[4, 4, 0, 0]} />
246
+ </BarChart>
247
+ </ResponsiveContainer>
248
+ )}
249
+ </motion.div>
250
+
251
+ {/* Heatmap + Radar */}
252
+ <div className="grid gap-6 lg:grid-cols-2">
253
+ {/* Spending Heatmap */}
254
+ <motion.div variants={itemVariants} className="glass-card p-6">
255
+ <div className="mb-5">
256
+ <h2 className="text-base font-semibold text-white">Spending Heatmap</h2>
257
+ <p className="text-xs text-zinc-400 mt-0.5">Daily activity over 12 weeks</p>
258
+ </div>
259
+ {loading ? (
260
+ <div className="h-[180px] shimmer rounded-xl" />
261
+ ) : (
262
+ <>
263
+ <div className="space-y-1.5">
264
+ {DAYS.map((day, dayIdx) => (
265
+ <div key={day} className="flex items-center gap-2">
266
+ <span className="text-xs text-zinc-500 w-7 flex-shrink-0">{day}</span>
267
+ <div className="flex gap-1">
268
+ {heatmapData[dayIdx]?.map((val, week) => (
269
+ <HeatmapCell key={week} value={val} max={heatmapMax} />
270
+ ))}
271
+ </div>
272
+ </div>
273
+ ))}
274
+ </div>
275
+ <div className="mt-4 flex items-center gap-2">
276
+ <span className="text-xs text-zinc-500">Less</span>
277
+ {[0.1, 0.3, 0.5, 0.7, 0.9].map((a) => (
278
+ <div key={a} className="h-3 w-3 rounded-sm" style={{ background: `rgba(16,185,129,${a})` }} />
279
+ ))}
280
+ <span className="text-xs text-zinc-500">More</span>
281
+ </div>
282
+ </>
283
+ )}
284
+ </motion.div>
285
+
286
+ {/* Financial Health Radar */}
287
+ <motion.div variants={itemVariants} className="glass-card p-6">
288
+ <div className="mb-5">
289
+ <h2 className="text-base font-semibold text-white">Financial Health Score</h2>
290
+ <p className="text-xs text-zinc-400 mt-0.5">Multi-dimensional AI assessment</p>
291
+ </div>
292
+ {loading ? (
293
+ <div className="h-[240px] shimmer rounded-xl" />
294
+ ) : (
295
+ <>
296
+ <ResponsiveContainer width="100%" height={220}>
297
+ <RadarChart data={radarData.length ? radarData : [
298
+ { subject: "Savings", A: 80 },
299
+ { subject: "Spending", A: 70 },
300
+ { subject: "Income", A: 90 },
301
+ { subject: "Debt", A: 95 },
302
+ { subject: "Investment", A: 60 },
303
+ ]}>
304
+ <PolarGrid stroke="rgba(255,255,255,0.08)" />
305
+ <PolarAngleAxis dataKey="subject" tick={{ fill: "#71717a", fontSize: 10 }} />
306
+ <PolarRadiusAxis angle={30} domain={[0, 100]} tick={{ fill: "#71717a", fontSize: 9 }} />
307
+ <Radar name="Score" dataKey="A" stroke="#10b981" fill="#10b981" fillOpacity={0.2} strokeWidth={2} />
308
+ </RadarChart>
309
+ </ResponsiveContainer>
310
+ <div className="flex items-center justify-center gap-2 mt-1">
311
+ <Sparkles className="h-3.5 w-3.5 text-emerald-400" />
312
+ <span className="text-sm font-semibold text-white">Overall Score:</span>
313
+ <span className="text-sm font-bold text-emerald-400">{healthScore.toFixed(0)}/100</span>
314
+ </div>
315
+ </>
316
+ )}
317
+ </motion.div>
318
+ </div>
319
+ </>
320
+ )}
321
+
322
+ {/* ── Categories Tab ── */}
323
+ {activeTab === "categories" && (
324
+ <motion.div variants={itemVariants} className="glass-card p-6">
325
+ <div className="flex items-center justify-between mb-6">
326
+ <div>
327
+ <h2 className="text-base font-semibold text-white">Category Intelligence</h2>
328
+ <p className="text-xs text-zinc-400 mt-0.5">AI-powered spending analysis per category</p>
329
+ </div>
330
+ <div className="flex items-center gap-1.5 rounded-xl border border-emerald-500/20 bg-emerald-500/10 px-3 py-1.5">
331
+ <Sparkles className="h-3.5 w-3.5 text-emerald-400" />
332
+ <span className="text-xs text-emerald-400 font-medium">AI Active</span>
333
+ </div>
334
+ </div>
335
+
336
+ {loading ? (
337
+ <div className="space-y-3">
338
+ {[1, 2, 3, 4, 5].map((i) => <div key={i} className="h-12 shimmer rounded-xl" />)}
339
+ </div>
340
+ ) : (
341
+ <div className="space-y-1">
342
+ {categoryData.map((cat) => {
343
+ const total = categoryData.reduce((s, c) => s + c.value, 0);
344
+ const pct = total > 0 ? (cat.value / total) * 100 : 0;
345
+ return (
346
+ <motion.div
347
+ key={cat.name}
348
+ whileHover={{ backgroundColor: "rgba(255,255,255,0.02)" }}
349
+ className="flex items-center gap-4 rounded-xl px-3 py-3 transition-colors"
350
+ >
351
+ <div className="h-3 w-3 rounded-full flex-shrink-0" style={{ background: cat.color }} />
352
+ <div className="flex-1 min-w-0">
353
+ <div className="flex items-center justify-between mb-1.5">
354
+ <span className="text-sm font-medium text-white">{cat.name}</span>
355
+ <span className="text-xs text-zinc-400">${cat.value.toLocaleString()} ({pct.toFixed(1)}%)</span>
356
+ </div>
357
+ <div className="h-1.5 w-full rounded-full bg-white/5 overflow-hidden">
358
+ <motion.div
359
+ initial={{ width: 0 }}
360
+ animate={{ width: `${pct}%` }}
361
+ transition={{ duration: 0.8, ease: "easeOut", delay: 0.1 }}
362
+ className="h-full rounded-full"
363
+ style={{ background: cat.color }}
364
+ />
365
+ </div>
366
+ </div>
367
+ </motion.div>
368
+ );
369
+ })}
370
+ </div>
371
+ )}
372
+
373
+ {/* AI Behavior Insights */}
374
+ {behaviorInsights.length > 0 && (
375
+ <div className="mt-6 rounded-xl border border-blue-500/20 bg-blue-500/5 p-4">
376
+ <div className="flex items-start gap-3">
377
+ <Sparkles className="h-4 w-4 text-blue-400 flex-shrink-0 mt-0.5" />
378
+ <div>
379
+ <p className="text-sm font-medium text-white mb-2">AI Behavioral Insights</p>
380
+ <ul className="space-y-1">
381
+ {behaviorInsights.slice(0, 3).map((insight, i) => (
382
+ <li key={i} className="text-xs text-zinc-400">• {insight}</li>
383
+ ))}
384
+ </ul>
385
+ </div>
386
+ </div>
387
+ </div>
388
+ )}
389
+ </motion.div>
390
+ )}
391
+
392
+ {/* ── Net Worth Tab ── */}
393
+ {activeTab === "networth" && (
394
+ <motion.div variants={itemVariants} className="glass-card p-6">
395
+ <div className="flex items-center justify-between mb-6">
396
+ <div>
397
+ <h2 className="text-base font-semibold text-white">Net Worth Timeline</h2>
398
+ <p className="text-xs text-zinc-400 mt-0.5">Balance trajectory over time</p>
399
+ </div>
400
+ {!loading && (
401
+ <div className="text-right">
402
+ <p className="text-2xl font-bold text-white">
403
+ ${cashFlow.length ? cashFlow[cashFlow.length - 1]?.income?.toLocaleString() : "—"}
404
+ </p>
405
+ <div className="flex items-center gap-1 justify-end mt-0.5">
406
+ <TrendingUp className="h-3.5 w-3.5 text-emerald-400" />
407
+ <span className="text-xs text-emerald-400 font-medium">Growing</span>
408
+ </div>
409
+ </div>
410
+ )}
411
+ </div>
412
+ {loading ? (
413
+ <div className="h-[320px] shimmer rounded-xl" />
414
+ ) : (
415
+ <ResponsiveContainer width="100%" height={320}>
416
+ <LineChart data={cashFlow} margin={{ top: 5, right: 5, left: -20, bottom: 0 }}>
417
+ <defs>
418
+ <linearGradient id="nwGrad" x1="0" y1="0" x2="0" y2="1">
419
+ <stop offset="5%" stopColor="#10b981" stopOpacity={0.3} />
420
+ <stop offset="95%" stopColor="#10b981" stopOpacity={0} />
421
+ </linearGradient>
422
+ </defs>
423
+ <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.05)" />
424
+ <XAxis dataKey="month" tick={{ fill: "#71717a", fontSize: 11 }} axisLine={false} tickLine={false} />
425
+ <YAxis tick={{ fill: "#71717a", fontSize: 11 }} axisLine={false} tickLine={false} tickFormatter={(v) => `$${(v / 1000).toFixed(0)}k`} />
426
+ <Tooltip content={<CustomTooltip />} />
427
+ <Line type="monotone" dataKey="income" name="Income" stroke="#10b981" strokeWidth={2.5}
428
+ dot={{ fill: "#10b981", r: 4, strokeWidth: 0 }}
429
+ activeDot={{ r: 6, fill: "#10b981", strokeWidth: 2, stroke: "#000" }}
430
+ />
431
+ <Line type="monotone" dataKey="savings" name="Savings" stroke="#3b82f6" strokeWidth={2}
432
+ strokeDasharray="4 4"
433
+ dot={{ fill: "#3b82f6", r: 3, strokeWidth: 0 }}
434
+ />
435
+ </LineChart>
436
+ </ResponsiveContainer>
437
+ )}
438
+ </motion.div>
439
+ )}
440
+ </motion.div>
441
+ );
442
+ }
frontend/src/app/chat/page.tsx ADDED
@@ -0,0 +1,417 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "use client";
2
+
3
+ import { useState, useRef, useEffect, useCallback } from "react";
4
+ import { motion, AnimatePresence } from "framer-motion";
5
+ import {
6
+ Send, Sparkles, TrendingUp, Shield, PieChart,
7
+ Zap, Copy, ThumbsUp, ThumbsDown, RotateCcw, Mic, Paperclip,
8
+ Wifi, WifiOff, RefreshCw
9
+ } from "lucide-react";
10
+ import { useWebSocketChat, WsStatus } from "@/lib/hooks/useWebSocketChat";
11
+
12
+ // ─── Types ────────────────────────────────────────────────────────────────────
13
+ interface Message {
14
+ id: string;
15
+ role: "user" | "assistant";
16
+ content: string;
17
+ streaming?: boolean;
18
+ timestamp: Date;
19
+ }
20
+
21
+ // ─── Suggested Prompts ────────────────────────────────────────────────────────
22
+ const suggestions = [
23
+ { icon: TrendingUp, label: "Forecast my balance", color: "text-emerald-400", bg: "bg-emerald-500/10 border-emerald-500/20" },
24
+ { icon: PieChart, label: "Analyze my spending", color: "text-blue-400", bg: "bg-blue-500/10 border-blue-500/20" },
25
+ { icon: Shield, label: "Check fraud risk", color: "text-purple-400", bg: "bg-purple-500/10 border-purple-500/20" },
26
+ { icon: Zap, label: "Optimize my budget", color: "text-amber-400", bg: "bg-amber-500/10 border-amber-500/20" },
27
+ ];
28
+
29
+ // ─── Connection Status Badge ──────────────────────────────────────────────────
30
+ function ConnectionBadge({ status, onReconnect }: { status: WsStatus; onReconnect: () => void }) {
31
+ const config = {
32
+ connected: { icon: Wifi, color: "text-emerald-400", label: "Live", dot: "bg-emerald-400" },
33
+ connecting: { icon: RefreshCw, color: "text-amber-400", label: "Connecting...", dot: "bg-amber-400" },
34
+ disconnected: { icon: WifiOff, color: "text-zinc-500", label: "Offline", dot: "bg-zinc-500" },
35
+ error: { icon: WifiOff, color: "text-red-400", label: "Error", dot: "bg-red-400" },
36
+ }[status];
37
+
38
+ return (
39
+ <div className="flex items-center gap-2">
40
+ <div className={`h-1.5 w-1.5 rounded-full ${config.dot} ${status === "connecting" ? "animate-pulse" : ""}`} />
41
+ <span className={`text-xs ${config.color}`}>{config.label}</span>
42
+ {(status === "disconnected" || status === "error") && (
43
+ <button
44
+ onClick={onReconnect}
45
+ className="text-xs text-zinc-500 hover:text-zinc-300 underline transition-colors"
46
+ >
47
+ Retry
48
+ </button>
49
+ )}
50
+ </div>
51
+ );
52
+ }
53
+
54
+ // ─── AI Orb ───────────────────────────────────────────────────────────────────
55
+ function AIOrb({ isThinking }: { isThinking: boolean }) {
56
+ return (
57
+ <div className="relative flex items-center justify-center">
58
+ <motion.div
59
+ animate={{ scale: isThinking ? [1, 1.3, 1] : [1, 1.1, 1], opacity: isThinking ? [0.3, 0.6, 0.3] : [0.2, 0.4, 0.2] }}
60
+ transition={{ duration: isThinking ? 0.8 : 3, repeat: Infinity, ease: "easeInOut" }}
61
+ className="absolute h-24 w-24 rounded-full border border-emerald-500/30"
62
+ />
63
+ <motion.div
64
+ animate={{ scale: isThinking ? [1, 1.5, 1] : [1, 1.15, 1], opacity: isThinking ? [0.2, 0.4, 0.2] : [0.1, 0.2, 0.1] }}
65
+ transition={{ duration: isThinking ? 0.8 : 3, repeat: Infinity, ease: "easeInOut", delay: 0.2 }}
66
+ className="absolute h-32 w-32 rounded-full border border-blue-500/20"
67
+ />
68
+ <motion.div
69
+ animate={{
70
+ boxShadow: isThinking
71
+ ? ["0 0 20px rgba(16,185,129,0.6), 0 0 60px rgba(59,130,246,0.4)", "0 0 40px rgba(16,185,129,0.8), 0 0 80px rgba(59,130,246,0.5)", "0 0 20px rgba(16,185,129,0.6), 0 0 60px rgba(59,130,246,0.4)"]
72
+ : ["0 0 20px rgba(16,185,129,0.3), 0 0 40px rgba(59,130,246,0.2)", "0 0 30px rgba(16,185,129,0.5), 0 0 60px rgba(59,130,246,0.3)", "0 0 20px rgba(16,185,129,0.3), 0 0 40px rgba(59,130,246,0.2)"],
73
+ }}
74
+ transition={{ duration: isThinking ? 0.8 : 3, repeat: Infinity, ease: "easeInOut" }}
75
+ className="relative h-16 w-16 rounded-full bg-gradient-to-br from-emerald-400 via-cyan-400 to-blue-500 flex items-center justify-center"
76
+ >
77
+ <motion.div
78
+ animate={{ rotate: isThinking ? 360 : 0 }}
79
+ transition={{ duration: 2, repeat: isThinking ? Infinity : 0, ease: "linear" }}
80
+ >
81
+ <Sparkles className="h-7 w-7 text-white" />
82
+ </motion.div>
83
+ </motion.div>
84
+ </div>
85
+ );
86
+ }
87
+
88
+ // ─── Message Bubble ───────────────────────────────────────────────────────────
89
+ function MessageBubble({ message, onCopy }: { message: Message; onCopy: (text: string) => void }) {
90
+ const isUser = message.role === "user";
91
+
92
+ const renderContent = (text: string) =>
93
+ text.split("\n").map((line, i) => {
94
+ if (line.startsWith("**") && line.endsWith("**"))
95
+ return <p key={i} className="font-semibold text-white">{line.slice(2, -2)}</p>;
96
+ if (line.startsWith("- "))
97
+ return <p key={i} className="ml-2">• {line.slice(2)}</p>;
98
+ if (line.startsWith("# "))
99
+ return <p key={i} className="font-bold text-white text-base mt-1">{line.slice(2)}</p>;
100
+ return <p key={i} className={line === "" ? "h-2" : ""}>{line}</p>;
101
+ });
102
+
103
+ return (
104
+ <motion.div
105
+ initial={{ opacity: 0, y: 10, scale: 0.98 }}
106
+ animate={{ opacity: 1, y: 0, scale: 1 }}
107
+ transition={{ duration: 0.3, ease: "easeOut" }}
108
+ className={`flex gap-3 ${isUser ? "flex-row-reverse" : "flex-row"}`}
109
+ >
110
+ <div className={`flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-xl ${
111
+ isUser
112
+ ? "bg-gradient-to-br from-blue-500 to-purple-600 text-white text-xs font-bold"
113
+ : "bg-gradient-to-br from-emerald-400 to-cyan-500"
114
+ }`}>
115
+ {isUser ? "A" : <Sparkles className="h-4 w-4 text-white" />}
116
+ </div>
117
+
118
+ <div className={`max-w-[75%] ${isUser ? "items-end" : "items-start"} flex flex-col gap-1`}>
119
+ <div className={`rounded-2xl px-4 py-3 text-sm leading-relaxed ${
120
+ isUser
121
+ ? "bg-gradient-to-br from-blue-600 to-blue-700 text-white rounded-tr-sm"
122
+ : "glass border border-white/10 text-zinc-100 rounded-tl-sm"
123
+ }`}>
124
+ <div className="whitespace-pre-wrap">{renderContent(message.content)}</div>
125
+ {message.streaming && <span className="streaming-cursor" />}
126
+ </div>
127
+
128
+ {!isUser && !message.streaming && (
129
+ <div className="flex items-center gap-1 px-1">
130
+ {[
131
+ { icon: Copy, label: "Copy", action: () => onCopy(message.content) },
132
+ { icon: ThumbsUp, label: "Good", action: () => {} },
133
+ { icon: ThumbsDown, label: "Bad", action: () => {} },
134
+ { icon: RotateCcw, label: "Retry", action: () => {} },
135
+ ].map(({ icon: Icon, label, action }) => (
136
+ <button
137
+ key={label}
138
+ title={label}
139
+ onClick={action}
140
+ className="p-1 rounded-lg text-zinc-600 hover:text-zinc-400 hover:bg-white/5 transition-all"
141
+ >
142
+ <Icon className="h-3 w-3" />
143
+ </button>
144
+ ))}
145
+ </div>
146
+ )}
147
+ </div>
148
+ </motion.div>
149
+ );
150
+ }
151
+
152
+ // ─── Main Chat Page ───────────────────────────────────────────────────────────
153
+ export default function ChatPage() {
154
+ const [messages, setMessages] = useState<Message[]>([
155
+ {
156
+ id: "welcome",
157
+ role: "assistant",
158
+ content: "Hello! I'm your AI financial assistant with full context of your accounts, spending patterns, and goals.\n\nWhat would you like to explore today?",
159
+ timestamp: new Date(),
160
+ },
161
+ ]);
162
+ const [input, setInput] = useState("");
163
+ const [isThinking, setIsThinking] = useState(false);
164
+ const [streamingId, setStreamingId] = useState<string | null>(null);
165
+ const messagesEndRef = useRef<HTMLDivElement>(null);
166
+ const inputRef = useRef<HTMLTextAreaElement>(null);
167
+ const currentStreamId = useRef<string | null>(null);
168
+
169
+ useEffect(() => {
170
+ messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
171
+ }, [messages]);
172
+
173
+ // ── WebSocket handlers ────────────────────────────────────────────────────
174
+ const handleChunk = useCallback((chunk: string) => {
175
+ const id = currentStreamId.current;
176
+ if (!id) return;
177
+ setMessages((prev) =>
178
+ prev.map((m) => m.id === id ? { ...m, content: m.content + chunk } : m)
179
+ );
180
+ }, []);
181
+
182
+ const handleStart = useCallback(() => {
183
+ const id = `ai-${Date.now()}`;
184
+ currentStreamId.current = id;
185
+ setIsThinking(false);
186
+ setStreamingId(id);
187
+ setMessages((prev) => [
188
+ ...prev,
189
+ { id, role: "assistant", content: "", streaming: true, timestamp: new Date() },
190
+ ]);
191
+ }, []);
192
+
193
+ const handleEnd = useCallback(() => {
194
+ const id = currentStreamId.current;
195
+ if (id) {
196
+ setMessages((prev) =>
197
+ prev.map((m) => m.id === id ? { ...m, streaming: false } : m)
198
+ );
199
+ setStreamingId(null);
200
+ currentStreamId.current = null;
201
+ }
202
+ }, []);
203
+
204
+ const handleWsError = useCallback((msg: string) => {
205
+ setIsThinking(false);
206
+ setStreamingId(null);
207
+ currentStreamId.current = null;
208
+ setMessages((prev) => [
209
+ ...prev,
210
+ {
211
+ id: `err-${Date.now()}`,
212
+ role: "assistant",
213
+ content: `⚠️ ${msg}`,
214
+ timestamp: new Date(),
215
+ },
216
+ ]);
217
+ }, []);
218
+
219
+ const { status, sendMessage: wsSend, reconnect } = useWebSocketChat({
220
+ onChunk: handleChunk,
221
+ onStart: handleStart,
222
+ onEnd: handleEnd,
223
+ onError: handleWsError,
224
+ });
225
+
226
+ // ── Send message ──────────────────────────────────────────────────────────
227
+ const sendMessage = useCallback(async (text?: string) => {
228
+ const content = (text || input).trim();
229
+ if (!content || isThinking || streamingId) return;
230
+
231
+ setInput("");
232
+ setMessages((prev) => [
233
+ ...prev,
234
+ { id: `user-${Date.now()}`, role: "user", content, timestamp: new Date() },
235
+ ]);
236
+
237
+ const sent = wsSend(content);
238
+
239
+ if (!sent) {
240
+ // WebSocket not ready — fall back to HTTP
241
+ setIsThinking(true);
242
+ try {
243
+ const { aiApi } = await import("@/lib/api");
244
+ const res = await aiApi.chat(content);
245
+ setIsThinking(false);
246
+ const id = `ai-${Date.now()}`;
247
+ setMessages((prev) => [
248
+ ...prev,
249
+ { id, role: "assistant", content: res.response, streaming: false, timestamp: new Date() },
250
+ ]);
251
+ } catch {
252
+ setIsThinking(false);
253
+ setMessages((prev) => [
254
+ ...prev,
255
+ {
256
+ id: `err-${Date.now()}`,
257
+ role: "assistant",
258
+ content: `⚠️ Could not reach the AI backend. Please check your connection.`,
259
+ timestamp: new Date(),
260
+ },
261
+ ]);
262
+ }
263
+ } else {
264
+ setIsThinking(true);
265
+ }
266
+ }, [input, isThinking, streamingId, wsSend]);
267
+
268
+ const handleKeyDown = (e: React.KeyboardEvent) => {
269
+ if (e.key === "Enter" && !e.shiftKey) {
270
+ e.preventDefault();
271
+ sendMessage();
272
+ }
273
+ };
274
+
275
+ const copyToClipboard = (text: string) => {
276
+ navigator.clipboard.writeText(text).catch(() => {});
277
+ };
278
+
279
+ return (
280
+ <div className="flex h-[calc(100vh-4rem)] flex-col -m-8">
281
+ {/* Header */}
282
+ <div className="flex items-center justify-between border-b border-white/10 bg-black/20 backdrop-blur-xl px-8 py-4 flex-shrink-0">
283
+ <div className="flex items-center gap-3">
284
+ <ConnectionBadge status={status} onReconnect={reconnect} />
285
+ <div className="h-4 w-px bg-white/10" />
286
+ <div>
287
+ <h1 className="text-base font-semibold text-white">BankBot AI Assistant</h1>
288
+ <p className="text-xs text-zinc-500">Context-aware · Real-time streaming · Personalized</p>
289
+ </div>
290
+ </div>
291
+ <div className="flex items-center gap-2 text-xs text-zinc-500">
292
+ <Shield className="h-3.5 w-3.5 text-emerald-400" />
293
+ <span>End-to-end encrypted</span>
294
+ </div>
295
+ </div>
296
+
297
+ {/* Messages */}
298
+ <div className="flex-1 overflow-y-auto px-8 py-6 space-y-5">
299
+ {messages.length === 1 && (
300
+ <motion.div
301
+ initial={{ opacity: 0, scale: 0.8 }}
302
+ animate={{ opacity: 1, scale: 1 }}
303
+ transition={{ duration: 0.6, ease: "easeOut" }}
304
+ className="flex flex-col items-center gap-6 py-8"
305
+ >
306
+ <AIOrb isThinking={false} />
307
+ <div className="text-center">
308
+ <p className="text-lg font-semibold text-white">Your AI Financial Twin</p>
309
+ <p className="text-sm text-zinc-400 mt-1">Ask me anything about your finances</p>
310
+ </div>
311
+ <div className="grid grid-cols-2 gap-3 w-full max-w-md">
312
+ {suggestions.map((s) => (
313
+ <motion.button
314
+ key={s.label}
315
+ whileHover={{ scale: 1.03 }}
316
+ whileTap={{ scale: 0.97 }}
317
+ onClick={() => sendMessage(s.label)}
318
+ className={`flex items-center gap-2 rounded-xl border px-4 py-3 text-sm font-medium transition-all ${s.bg} ${s.color} hover:brightness-110`}
319
+ >
320
+ <s.icon className="h-4 w-4" />
321
+ {s.label}
322
+ </motion.button>
323
+ ))}
324
+ </div>
325
+ </motion.div>
326
+ )}
327
+
328
+ {messages.map((msg) => (
329
+ <MessageBubble key={msg.id} message={msg} onCopy={copyToClipboard} />
330
+ ))}
331
+
332
+ <AnimatePresence>
333
+ {isThinking && (
334
+ <motion.div
335
+ initial={{ opacity: 0, y: 10 }}
336
+ animate={{ opacity: 1, y: 0 }}
337
+ exit={{ opacity: 0, y: -10 }}
338
+ className="flex gap-3"
339
+ >
340
+ <div className="flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-xl bg-gradient-to-br from-emerald-400 to-cyan-500">
341
+ <Sparkles className="h-4 w-4 text-white" />
342
+ </div>
343
+ <div className="glass rounded-2xl rounded-tl-sm px-4 py-3 border border-white/10">
344
+ <div className="flex gap-1 items-center h-4">
345
+ {[0, 1, 2].map((i) => (
346
+ <motion.div
347
+ key={i}
348
+ animate={{ y: [0, -4, 0] }}
349
+ transition={{ duration: 0.6, repeat: Infinity, delay: i * 0.15 }}
350
+ className="h-1.5 w-1.5 rounded-full bg-emerald-400"
351
+ />
352
+ ))}
353
+ </div>
354
+ </div>
355
+ </motion.div>
356
+ )}
357
+ </AnimatePresence>
358
+
359
+ <div ref={messagesEndRef} />
360
+ </div>
361
+
362
+ {/* Quick suggestions */}
363
+ {messages.length > 1 && (
364
+ <div className="flex gap-2 px-8 pb-2 overflow-x-auto flex-shrink-0">
365
+ {suggestions.map((s) => (
366
+ <button
367
+ key={s.label}
368
+ onClick={() => sendMessage(s.label)}
369
+ disabled={!!streamingId || isThinking}
370
+ className={`flex items-center gap-1.5 rounded-xl border px-3 py-1.5 text-xs font-medium whitespace-nowrap transition-all disabled:opacity-40 ${s.bg} ${s.color} hover:brightness-110`}
371
+ >
372
+ <s.icon className="h-3 w-3" />
373
+ {s.label}
374
+ </button>
375
+ ))}
376
+ </div>
377
+ )}
378
+
379
+ {/* Input */}
380
+ <div className="flex-shrink-0 border-t border-white/10 bg-black/20 backdrop-blur-xl px-8 py-4">
381
+ <div className="flex items-end gap-3 rounded-2xl border border-white/10 bg-white/5 px-4 py-3 focus-within:border-emerald-500/40 transition-all">
382
+ <button className="text-zinc-500 hover:text-zinc-300 transition-colors mb-0.5">
383
+ <Paperclip className="h-4 w-4" />
384
+ </button>
385
+ <textarea
386
+ ref={inputRef}
387
+ value={input}
388
+ onChange={(e) => setInput(e.target.value)}
389
+ onKeyDown={handleKeyDown}
390
+ placeholder="Ask about your finances, forecasts, fraud alerts..."
391
+ rows={1}
392
+ disabled={!!streamingId}
393
+ className="flex-1 resize-none bg-transparent text-sm text-white placeholder:text-zinc-500 focus:outline-none leading-relaxed max-h-32 disabled:opacity-50"
394
+ style={{ minHeight: "24px" }}
395
+ />
396
+ <div className="flex items-center gap-2 mb-0.5">
397
+ <button className="text-zinc-500 hover:text-zinc-300 transition-colors">
398
+ <Mic className="h-4 w-4" />
399
+ </button>
400
+ <motion.button
401
+ whileHover={{ scale: 1.05 }}
402
+ whileTap={{ scale: 0.95 }}
403
+ onClick={() => sendMessage()}
404
+ disabled={!input.trim() || isThinking || !!streamingId}
405
+ className="flex h-8 w-8 items-center justify-center rounded-xl bg-gradient-to-br from-emerald-500 to-cyan-500 text-white disabled:opacity-40 disabled:cursor-not-allowed transition-opacity"
406
+ >
407
+ <Send className="h-3.5 w-3.5" />
408
+ </motion.button>
409
+ </div>
410
+ </div>
411
+ <p className="text-center text-xs text-zinc-600 mt-2">
412
+ AI responses are for informational purposes only. Not financial advice.
413
+ </p>
414
+ </div>
415
+ </div>
416
+ );
417
+ }
frontend/src/app/favicon.ico ADDED
frontend/src/app/fonts/GeistMonoVF.woff ADDED
Binary file (67.9 kB). View file
 
frontend/src/app/fonts/GeistVF.woff ADDED
Binary file (66.3 kB). View file
 
frontend/src/app/globals.css ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @tailwind base;
2
+ @tailwind components;
3
+ @tailwind utilities;
4
+
5
+ /* ─── CSS Variables ─────────────────────────────────────────────────────────── */
6
+ @layer base {
7
+ :root {
8
+ --background: 0 0% 3%;
9
+ --foreground: 0 0% 98%;
10
+ --radius: 0.625rem;
11
+ }
12
+
13
+ * {
14
+ border-color: rgba(255, 255, 255, 0.08);
15
+ box-sizing: border-box;
16
+ }
17
+
18
+ body {
19
+ background-color: #050505;
20
+ color: #fafafa;
21
+ }
22
+
23
+ html {
24
+ font-family: var(--font-sans, ui-sans-serif, system-ui, sans-serif);
25
+ }
26
+ }
27
+
28
+ /* ─── Glassmorphism utilities ────────────────────────────────────────────────── */
29
+ @layer utilities {
30
+ .text-balance {
31
+ text-wrap: balance;
32
+ }
33
+
34
+ .glass {
35
+ background: rgba(255, 255, 255, 0.05);
36
+ backdrop-filter: blur(20px);
37
+ -webkit-backdrop-filter: blur(20px);
38
+ border: 1px solid rgba(255, 255, 255, 0.10);
39
+ }
40
+
41
+ .glass-strong {
42
+ background: rgba(255, 255, 255, 0.10);
43
+ backdrop-filter: blur(32px);
44
+ -webkit-backdrop-filter: blur(32px);
45
+ border: 1px solid rgba(255, 255, 255, 0.20);
46
+ }
47
+
48
+ .glass-card {
49
+ border-radius: 1rem;
50
+ background: rgba(255, 255, 255, 0.04);
51
+ backdrop-filter: blur(20px);
52
+ -webkit-backdrop-filter: blur(20px);
53
+ border: 1px solid rgba(255, 255, 255, 0.08);
54
+ box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
55
+ }
56
+
57
+ /* Gradient text */
58
+ .gradient-text {
59
+ background: linear-gradient(135deg, #60a5fa, #22d3ee, #34d399);
60
+ -webkit-background-clip: text;
61
+ background-clip: text;
62
+ -webkit-text-fill-color: transparent;
63
+ }
64
+
65
+ .gradient-text-gold {
66
+ background: linear-gradient(135deg, #fbbf24, #f97316);
67
+ -webkit-background-clip: text;
68
+ background-clip: text;
69
+ -webkit-text-fill-color: transparent;
70
+ }
71
+
72
+ /* Glow effects */
73
+ .glow-blue {
74
+ box-shadow: 0 0 30px rgba(59, 130, 246, 0.3), 0 0 60px rgba(59, 130, 246, 0.1);
75
+ }
76
+ .glow-emerald {
77
+ box-shadow: 0 0 30px rgba(16, 185, 129, 0.3), 0 0 60px rgba(16, 185, 129, 0.1);
78
+ }
79
+ .glow-purple {
80
+ box-shadow: 0 0 30px rgba(139, 92, 246, 0.3), 0 0 60px rgba(139, 92, 246, 0.1);
81
+ }
82
+
83
+ /* Streaming text cursor */
84
+ .streaming-cursor::after {
85
+ content: '▋';
86
+ animation: blink 0.7s step-end infinite;
87
+ color: #10b981;
88
+ margin-left: 2px;
89
+ }
90
+
91
+ /* Shimmer loading */
92
+ .shimmer {
93
+ background: linear-gradient(
94
+ 90deg,
95
+ rgba(255,255,255,0.03) 0%,
96
+ rgba(255,255,255,0.08) 50%,
97
+ rgba(255,255,255,0.03) 100%
98
+ );
99
+ background-size: 200% 100%;
100
+ animation: shimmer 1.5s infinite;
101
+ }
102
+
103
+ .animate-float {
104
+ animation: float 4s ease-in-out infinite;
105
+ }
106
+
107
+ .animate-gradient {
108
+ background-size: 200% 200%;
109
+ animation: gradient-shift 4s ease infinite;
110
+ }
111
+ }
112
+
113
+ /* ─── Custom scrollbar ───────────────────────────────────────────────────────── */
114
+ ::-webkit-scrollbar {
115
+ width: 4px;
116
+ height: 4px;
117
+ }
118
+ ::-webkit-scrollbar-track {
119
+ background: transparent;
120
+ }
121
+ ::-webkit-scrollbar-thumb {
122
+ background: rgba(255, 255, 255, 0.1);
123
+ border-radius: 999px;
124
+ }
125
+ ::-webkit-scrollbar-thumb:hover {
126
+ background: rgba(255, 255, 255, 0.2);
127
+ }
128
+
129
+ /* ─── Keyframes ──────────────────────────────────────────────────────────────── */
130
+ @keyframes blink {
131
+ 0%, 100% { opacity: 1; }
132
+ 50% { opacity: 0; }
133
+ }
134
+
135
+ @keyframes shimmer {
136
+ 0% { background-position: -200% 0; }
137
+ 100% { background-position: 200% 0; }
138
+ }
139
+
140
+ @keyframes float {
141
+ 0%, 100% { transform: translateY(0px); }
142
+ 50% { transform: translateY(-8px); }
143
+ }
144
+
145
+ @keyframes gradient-shift {
146
+ 0% { background-position: 0% 50%; }
147
+ 50% { background-position: 100% 50%; }
148
+ 100% { background-position: 0% 50%; }
149
+ }
frontend/src/app/goals/page.tsx ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ import { ComingSoon } from "@/components/ui/ComingSoon";
2
+ export default function GoalsPage() {
3
+ return <ComingSoon title="Financial Goals" description="Set, track, and achieve financial goals with AI-powered milestone predictions." />;
4
+ }
frontend/src/app/layout.tsx ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { Metadata } from "next";
2
+ import { Inter } from "next/font/google";
3
+ import "./globals.css";
4
+ import { DashboardLayout } from "@/components/layout/DashboardLayout";
5
+
6
+ const inter = Inter({ subsets: ["latin"], variable: "--font-sans" });
7
+
8
+ export const metadata: Metadata = {
9
+ title: "BankBot AI | Modern Banking",
10
+ description: "AI-powered modern banking dashboard",
11
+ };
12
+
13
+ export default function RootLayout({
14
+ children,
15
+ }: Readonly<{
16
+ children: React.ReactNode;
17
+ }>) {
18
+ return (
19
+ <html lang="en" className="dark">
20
+ <body className={`${inter.variable} font-sans bg-[#050505] text-white antialiased`}>
21
+ <DashboardLayout>
22
+ {children}
23
+ </DashboardLayout>
24
+ </body>
25
+ </html>
26
+ );
27
+ }
frontend/src/app/loans/page.tsx ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ import { ComingSoon } from "@/components/ui/ComingSoon";
2
+ export default function LoansPage() {
3
+ return <ComingSoon title="Loans" description="AI-powered loan analysis, repayment optimization, and refinancing recommendations." />;
4
+ }
frontend/src/app/page.tsx ADDED
@@ -0,0 +1,426 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "use client";
2
+
3
+ import { useEffect } from "react";
4
+ import { motion } from "framer-motion";
5
+ import {
6
+ TrendingUp, TrendingDown, DollarSign, CreditCard,
7
+ ArrowUpRight, ArrowDownRight, Sparkles, Shield,
8
+ ChevronRight, Activity, AlertTriangle
9
+ } from "lucide-react";
10
+ import {
11
+ AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip,
12
+ ResponsiveContainer, PieChart, Pie, Cell
13
+ } from "recharts";
14
+ import { useDashboardStore } from "@/lib/stores/dashboardStore";
15
+ import Link from "next/link";
16
+
17
+ // ─── Category colors ──────────────────────────────────────────────────────────
18
+ const CATEGORY_COLORS = [
19
+ "#3b82f6", "#10b981", "#f59e0b", "#8b5cf6", "#ec4899",
20
+ "#06b6d4", "#84cc16", "#f97316", "#6b7280",
21
+ ];
22
+
23
+ // ─── Animation variants ───────────────────────────────────────────────────────
24
+ const containerVariants = {
25
+ hidden: { opacity: 0 },
26
+ visible: { opacity: 1, transition: { staggerChildren: 0.08 } },
27
+ };
28
+ const itemVariants = {
29
+ hidden: { opacity: 0, y: 20 },
30
+ visible: { opacity: 1, y: 0, transition: { duration: 0.5, ease: "easeOut" as const } },
31
+ };
32
+
33
+ // ─── Skeleton loader ──────────────────────────────────────────────────────────
34
+ function Skeleton({ className }: { className?: string }) {
35
+ return <div className={`shimmer rounded-lg ${className}`} />;
36
+ }
37
+
38
+ // ─── Custom Tooltip ───────────────────────────────────────────────────────────
39
+ interface TooltipProps {
40
+ active?: boolean;
41
+ payload?: Array<{ name: string; value: number; color?: string }>;
42
+ label?: string;
43
+ }
44
+ function CustomTooltip({ active, payload, label }: TooltipProps) {
45
+ if (!active || !payload?.length) return null;
46
+ return (
47
+ <div className="glass-card p-3 text-xs space-y-1 min-w-[140px]">
48
+ <p className="text-zinc-400 font-medium mb-2">{label}</p>
49
+ {payload.map((entry) => (
50
+ <div key={entry.name} className="flex justify-between gap-4">
51
+ <span style={{ color: entry.color }}>{entry.name}</span>
52
+ <span className="text-white font-semibold">${entry.value.toLocaleString()}</span>
53
+ </div>
54
+ ))}
55
+ </div>
56
+ );
57
+ }
58
+
59
+ // ─── Stat Card ────────────────────────────────────────────────────────────────
60
+ interface StatCardProps {
61
+ title: string;
62
+ value: string;
63
+ change?: string;
64
+ positive?: boolean;
65
+ icon: React.ElementType;
66
+ gradient: string;
67
+ iconColor: string;
68
+ borderColor: string;
69
+ loading?: boolean;
70
+ }
71
+ function StatCard({ title, value, change, positive, icon: Icon, gradient, iconColor, borderColor, loading }: StatCardProps) {
72
+ return (
73
+ <motion.div
74
+ variants={itemVariants}
75
+ whileHover={{ scale: 1.02, y: -2 }}
76
+ className={`relative overflow-hidden rounded-2xl border ${borderColor} bg-gradient-to-br ${gradient} backdrop-blur-xl p-6 cursor-pointer group`}
77
+ >
78
+ <div className="absolute inset-0 opacity-0 group-hover:opacity-100 transition-opacity duration-300 bg-white/[0.02]" />
79
+ <div className="flex items-start justify-between">
80
+ <div>
81
+ <p className="text-xs font-medium text-zinc-400 uppercase tracking-wider">{title}</p>
82
+ {loading ? (
83
+ <Skeleton className="mt-2 h-8 w-28" />
84
+ ) : (
85
+ <p className="mt-2 text-2xl font-bold text-white tracking-tight">{value}</p>
86
+ )}
87
+ </div>
88
+ <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-white/5 border border-white/10">
89
+ <Icon className={`h-5 w-5 ${iconColor}`} />
90
+ </div>
91
+ </div>
92
+ {change && !loading && (
93
+ <div className="mt-4 flex items-center gap-1.5">
94
+ {positive ? (
95
+ <ArrowUpRight className="h-3.5 w-3.5 text-emerald-400" />
96
+ ) : (
97
+ <ArrowDownRight className="h-3.5 w-3.5 text-red-400" />
98
+ )}
99
+ <span className={`text-xs font-semibold ${positive ? "text-emerald-400" : "text-red-400"}`}>{change}</span>
100
+ <span className="text-xs text-zinc-500">vs last month</span>
101
+ </div>
102
+ )}
103
+ </motion.div>
104
+ );
105
+ }
106
+
107
+ // ─── Main Page ────────────────────────────────────────────────────────────────
108
+ export default function Home() {
109
+ const { data, isLoading, error, fetch } = useDashboardStore();
110
+
111
+ useEffect(() => {
112
+ fetch();
113
+ }, [fetch]);
114
+
115
+ const greeting = () => {
116
+ const h = new Date().getHours();
117
+ if (h < 12) return "Good morning";
118
+ if (h < 17) return "Good afternoon";
119
+ return "Good evening";
120
+ };
121
+
122
+ const briefingText = data?.ai_briefing
123
+ ? (typeof data.ai_briefing === "string"
124
+ ? data.ai_briefing
125
+ : data.ai_briefing.summary || data.ai_briefing.briefing || "Your financial health looks good today.")
126
+ : null;
127
+
128
+ const categoryData = (data?.spending_by_category || []).slice(0, 6).map((c, i) => ({
129
+ ...c,
130
+ color: CATEGORY_COLORS[i % CATEGORY_COLORS.length],
131
+ }));
132
+
133
+ const totalCategorySpend = categoryData.reduce((s, c) => s + c.value, 0);
134
+
135
+ return (
136
+ <motion.div
137
+ variants={containerVariants}
138
+ initial="hidden"
139
+ animate="visible"
140
+ className="flex flex-col gap-6"
141
+ >
142
+ {/* Header */}
143
+ <motion.div variants={itemVariants}>
144
+ <h1 className="text-3xl font-bold tracking-tight text-white">
145
+ {greeting()}, <span className="gradient-text">Alex</span> 👋
146
+ </h1>
147
+ <p className="text-zinc-400 mt-1 text-sm">
148
+ Here&apos;s your financial overview for today.
149
+ </p>
150
+ </motion.div>
151
+
152
+ {/* Error banner */}
153
+ {error && (
154
+ <motion.div
155
+ variants={itemVariants}
156
+ className="flex items-center gap-3 rounded-2xl border border-amber-500/20 bg-amber-500/5 px-5 py-3"
157
+ >
158
+ <AlertTriangle className="h-4 w-4 text-amber-400 flex-shrink-0" />
159
+ <p className="text-xs text-zinc-400">
160
+ <span className="text-amber-400 font-medium">Backend offline</span> — showing cached data.{" "}
161
+ <button onClick={() => fetch(undefined, true)} className="underline hover:text-white transition-colors">
162
+ Retry
163
+ </button>
164
+ </p>
165
+ </motion.div>
166
+ )}
167
+
168
+ {/* AI Briefing */}
169
+ <motion.div
170
+ variants={itemVariants}
171
+ className="relative overflow-hidden rounded-2xl border border-emerald-500/20 bg-gradient-to-r from-emerald-500/10 via-cyan-500/5 to-blue-500/10 p-4"
172
+ >
173
+ <div className="relative flex items-center gap-3">
174
+ <div className="flex h-9 w-9 items-center justify-center rounded-xl bg-emerald-500/20 border border-emerald-500/30 flex-shrink-0">
175
+ <Sparkles className="h-4 w-4 text-emerald-400" />
176
+ </div>
177
+ <div className="flex-1 min-w-0">
178
+ {isLoading ? (
179
+ <>
180
+ <Skeleton className="h-4 w-64 mb-1" />
181
+ <Skeleton className="h-3 w-48" />
182
+ </>
183
+ ) : (
184
+ <>
185
+ <p className="text-sm font-medium text-white">
186
+ AI Daily Briefing —{" "}
187
+ <span className="text-emerald-400">
188
+ {briefingText?.slice(0, 100) || "Your financial health looks good today."}
189
+ </span>
190
+ </p>
191
+ <p className="text-xs text-zinc-400 mt-0.5">
192
+ Health score: {data?.health_score ?? "—"}/100
193
+ {data?.fraud_alert_count ? ` · ${data.fraud_alert_count} fraud alert(s)` : " · No fraud alerts"}
194
+ </p>
195
+ </>
196
+ )}
197
+ </div>
198
+ <Link href="/chat" className="flex items-center gap-1 text-xs text-emerald-400 hover:text-emerald-300 transition-colors whitespace-nowrap">
199
+ Ask AI <ChevronRight className="h-3 w-3" />
200
+ </Link>
201
+ </div>
202
+ </motion.div>
203
+
204
+ {/* Stat Cards */}
205
+ <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
206
+ <StatCard
207
+ title="Total Balance"
208
+ value={data ? `$${data.total_balance.toLocaleString("en-US", { minimumFractionDigits: 2 })}` : "$—"}
209
+ icon={DollarSign}
210
+ gradient="from-blue-500/20 to-cyan-500/20"
211
+ iconColor="text-blue-400"
212
+ borderColor="border-blue-500/20"
213
+ loading={isLoading}
214
+ />
215
+ <StatCard
216
+ title="Monthly Income"
217
+ value={data ? `$${data.monthly_income.toLocaleString("en-US", { minimumFractionDigits: 2 })}` : "$—"}
218
+ icon={TrendingUp}
219
+ gradient="from-emerald-500/20 to-teal-500/20"
220
+ iconColor="text-emerald-400"
221
+ borderColor="border-emerald-500/20"
222
+ loading={isLoading}
223
+ />
224
+ <StatCard
225
+ title="Monthly Spend"
226
+ value={data ? `$${data.monthly_expenses.toLocaleString("en-US", { minimumFractionDigits: 2 })}` : "$—"}
227
+ icon={CreditCard}
228
+ gradient="from-orange-500/20 to-amber-500/20"
229
+ iconColor="text-orange-400"
230
+ borderColor="border-orange-500/20"
231
+ loading={isLoading}
232
+ />
233
+ <StatCard
234
+ title="Savings Rate"
235
+ value={data ? `${data.savings_rate}%` : "—%"}
236
+ change={data ? `${data.savings_rate > 20 ? "+" : ""}${(data.savings_rate - 20).toFixed(1)}% vs target` : undefined}
237
+ positive={data ? data.savings_rate >= 20 : true}
238
+ icon={Activity}
239
+ gradient="from-purple-500/20 to-violet-500/20"
240
+ iconColor="text-purple-400"
241
+ borderColor="border-purple-500/20"
242
+ loading={isLoading}
243
+ />
244
+ </div>
245
+
246
+ {/* Charts Row */}
247
+ <div className="grid gap-6 lg:grid-cols-7">
248
+ {/* Cash Flow Chart */}
249
+ <motion.div variants={itemVariants} className="col-span-4 glass-card p-6">
250
+ <div className="flex items-center justify-between mb-6">
251
+ <div>
252
+ <h2 className="text-base font-semibold text-white">Cash Flow</h2>
253
+ <p className="text-xs text-zinc-400 mt-0.5">Income vs Expenses vs Savings</p>
254
+ </div>
255
+ <div className="flex gap-4 text-xs">
256
+ {[
257
+ { label: "Income", color: "#10b981" },
258
+ { label: "Expenses", color: "#f59e0b" },
259
+ { label: "Savings", color: "#3b82f6" },
260
+ ].map((l) => (
261
+ <div key={l.label} className="flex items-center gap-1.5">
262
+ <div className="h-2 w-2 rounded-full" style={{ background: l.color }} />
263
+ <span className="text-zinc-400">{l.label}</span>
264
+ </div>
265
+ ))}
266
+ </div>
267
+ </div>
268
+ {isLoading ? (
269
+ <Skeleton className="h-[260px] w-full" />
270
+ ) : (
271
+ <ResponsiveContainer width="100%" height={260}>
272
+ <AreaChart data={data?.cash_flow || []} margin={{ top: 5, right: 5, left: -20, bottom: 0 }}>
273
+ <defs>
274
+ {[
275
+ { id: "incomeGrad", color: "#10b981" },
276
+ { id: "expenseGrad", color: "#f59e0b" },
277
+ { id: "savingsGrad", color: "#3b82f6" },
278
+ ].map(({ id, color }) => (
279
+ <linearGradient key={id} id={id} x1="0" y1="0" x2="0" y2="1">
280
+ <stop offset="5%" stopColor={color} stopOpacity={0.3} />
281
+ <stop offset="95%" stopColor={color} stopOpacity={0} />
282
+ </linearGradient>
283
+ ))}
284
+ </defs>
285
+ <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.05)" />
286
+ <XAxis dataKey="month" tick={{ fill: "#71717a", fontSize: 11 }} axisLine={false} tickLine={false} />
287
+ <YAxis tick={{ fill: "#71717a", fontSize: 11 }} axisLine={false} tickLine={false} />
288
+ <Tooltip content={<CustomTooltip />} />
289
+ <Area type="monotone" dataKey="income" stroke="#10b981" strokeWidth={2} fill="url(#incomeGrad)" />
290
+ <Area type="monotone" dataKey="expenses" stroke="#f59e0b" strokeWidth={2} fill="url(#expenseGrad)" />
291
+ <Area type="monotone" dataKey="savings" stroke="#3b82f6" strokeWidth={2} fill="url(#savingsGrad)" />
292
+ </AreaChart>
293
+ </ResponsiveContainer>
294
+ )}
295
+ </motion.div>
296
+
297
+ {/* Spending Breakdown */}
298
+ <motion.div variants={itemVariants} className="col-span-3 glass-card p-6">
299
+ <div className="mb-4">
300
+ <h2 className="text-base font-semibold text-white">Spending Breakdown</h2>
301
+ <p className="text-xs text-zinc-400 mt-0.5">This month by category</p>
302
+ </div>
303
+ {isLoading ? (
304
+ <Skeleton className="h-[160px] w-full mb-4" />
305
+ ) : (
306
+ <div className="flex items-center justify-center">
307
+ <ResponsiveContainer width="100%" height={160}>
308
+ <PieChart>
309
+ <Pie data={categoryData} cx="50%" cy="50%" innerRadius={50} outerRadius={75} paddingAngle={3} dataKey="value">
310
+ {categoryData.map((entry, index) => (
311
+ <Cell key={index} fill={entry.color} stroke="transparent" />
312
+ ))}
313
+ </Pie>
314
+ <Tooltip
315
+ content={({ active, payload }) =>
316
+ active && payload?.length ? (
317
+ <div className="glass-card p-2 text-xs">
318
+ <span style={{ color: payload[0].payload.color }}>{payload[0].name}</span>
319
+ <span className="text-white ml-2 font-bold">${(payload[0].value as number).toLocaleString()}</span>
320
+ </div>
321
+ ) : null
322
+ }
323
+ />
324
+ </PieChart>
325
+ </ResponsiveContainer>
326
+ </div>
327
+ )}
328
+ <div className="mt-2 space-y-2">
329
+ {isLoading
330
+ ? [1, 2, 3, 4].map((i) => <Skeleton key={i} className="h-5 w-full" />)
331
+ : categoryData.map((cat) => (
332
+ <div key={cat.name} className="flex items-center justify-between">
333
+ <div className="flex items-center gap-2">
334
+ <div className="h-2 w-2 rounded-full flex-shrink-0" style={{ background: cat.color }} />
335
+ <span className="text-xs text-zinc-400">{cat.name}</span>
336
+ </div>
337
+ <div className="flex items-center gap-2">
338
+ <div className="h-1 w-16 rounded-full bg-white/5 overflow-hidden">
339
+ <div
340
+ className="h-full rounded-full"
341
+ style={{
342
+ width: `${totalCategorySpend > 0 ? (cat.value / totalCategorySpend) * 100 : 0}%`,
343
+ background: cat.color,
344
+ }}
345
+ />
346
+ </div>
347
+ <span className="text-xs font-medium text-white w-16 text-right">
348
+ ${cat.value.toLocaleString()}
349
+ </span>
350
+ </div>
351
+ </div>
352
+ ))}
353
+ </div>
354
+ </motion.div>
355
+ </div>
356
+
357
+ {/* Recent Transactions */}
358
+ <motion.div variants={itemVariants} className="glass-card p-6">
359
+ <div className="flex items-center justify-between mb-5">
360
+ <div>
361
+ <h2 className="text-base font-semibold text-white">Recent Transactions</h2>
362
+ <p className="text-xs text-zinc-400 mt-0.5">Your latest activity</p>
363
+ </div>
364
+ <Link href="/transactions" className="flex items-center gap-1 text-xs text-emerald-400 hover:text-emerald-300 transition-colors">
365
+ View all <ChevronRight className="h-3 w-3" />
366
+ </Link>
367
+ </div>
368
+ <div className="space-y-1">
369
+ {isLoading
370
+ ? [1, 2, 3, 4, 5].map((i) => <Skeleton key={i} className="h-14 w-full rounded-xl" />)
371
+ : (data?.recent_transactions || []).map((tx, i) => (
372
+ <motion.div
373
+ key={tx.id}
374
+ initial={{ opacity: 0, x: -10 }}
375
+ animate={{ opacity: 1, x: 0 }}
376
+ transition={{ delay: i * 0.05 }}
377
+ whileHover={{ backgroundColor: "rgba(255,255,255,0.03)" }}
378
+ className="flex items-center justify-between rounded-xl px-3 py-3 transition-colors cursor-pointer"
379
+ >
380
+ <div className="flex items-center gap-3">
381
+ <div className="flex h-9 w-9 items-center justify-center rounded-xl bg-white/5 border border-white/10 text-sm font-bold text-zinc-400">
382
+ {tx.merchant.charAt(0).toUpperCase()}
383
+ </div>
384
+ <div>
385
+ <p className="text-sm font-medium text-white">{tx.merchant}</p>
386
+ <p className="text-xs text-zinc-500">
387
+ {tx.category} · {tx.timestamp ? new Date(tx.timestamp).toLocaleDateString() : ""}
388
+ </p>
389
+ </div>
390
+ </div>
391
+ <div className="flex items-center gap-2">
392
+ <span className={`text-sm font-semibold ${tx.amount > 0 ? "text-emerald-400" : "text-white"}`}>
393
+ {tx.amount > 0 ? "+" : ""}${Math.abs(tx.amount).toFixed(2)}
394
+ </span>
395
+ {tx.amount > 0 ? (
396
+ <TrendingUp className="h-3.5 w-3.5 text-emerald-400" />
397
+ ) : (
398
+ <TrendingDown className="h-3.5 w-3.5 text-zinc-500" />
399
+ )}
400
+ </div>
401
+ </motion.div>
402
+ ))}
403
+ </div>
404
+ </motion.div>
405
+
406
+ {/* Fraud Shield */}
407
+ <motion.div
408
+ variants={itemVariants}
409
+ className="flex items-center gap-3 rounded-2xl border border-emerald-500/20 bg-emerald-500/5 px-5 py-3"
410
+ >
411
+ <Shield className="h-4 w-4 text-emerald-400 flex-shrink-0" />
412
+ <p className="text-xs text-zinc-400">
413
+ <span className="text-emerald-400 font-medium">AI Fraud Shield active</span>
414
+ {data?.fraud_alert_count
415
+ ? ` — ${data.fraud_alert_count} alert(s) require your attention.`
416
+ : " — All transactions monitored in real-time. No suspicious activity detected."}
417
+ </p>
418
+ {data?.fraud_alert_count ? (
419
+ <Link href="/security" className="ml-auto text-xs text-red-400 hover:text-red-300 transition-colors whitespace-nowrap">
420
+ Review <ChevronRight className="h-3 w-3 inline" />
421
+ </Link>
422
+ ) : null}
423
+ </motion.div>
424
+ </motion.div>
425
+ );
426
+ }
frontend/src/app/security/page.tsx ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ import { ComingSoon } from "@/components/ui/ComingSoon";
2
+ export default function SecurityPage() {
3
+ return <ComingSoon title="Security Center" description="Real-time fraud monitoring, device management, and AI threat detection dashboard." />;
4
+ }
frontend/src/app/settings/page.tsx ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ import { ComingSoon } from "@/components/ui/ComingSoon";
2
+ export default function SettingsPage() {
3
+ return <ComingSoon title="Settings" description="Account preferences, notification settings, AI behavior customization, and integrations." />;
4
+ }
frontend/src/app/simulator/page.tsx ADDED
@@ -0,0 +1,425 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "use client";
2
+
3
+ import { useState, useMemo, useEffect, useCallback } from "react";
4
+ import { motion, AnimatePresence } from "framer-motion";
5
+ import {
6
+ AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip,
7
+ ResponsiveContainer, ReferenceLine
8
+ } from "recharts";
9
+ import { Sparkles, TrendingUp, TrendingDown, Zap, RotateCcw, ChevronRight, AlertTriangle } from "lucide-react";
10
+ import { aiApi } from "@/lib/api";
11
+
12
+ // ─── Types ────────────────────────────────────────────────────────────────────
13
+ interface SimParams {
14
+ monthlyIncome: number;
15
+ monthlyExpenses: number;
16
+ savingsRate: number;
17
+ investmentReturn: number;
18
+ loanPayment: number;
19
+ emergencyMonths: number;
20
+ }
21
+
22
+ const DEFAULT_PARAMS: SimParams = {
23
+ monthlyIncome: 10200,
24
+ monthlyExpenses: 6100,
25
+ savingsRate: 40,
26
+ investmentReturn: 7,
27
+ loanPayment: 450,
28
+ emergencyMonths: 6,
29
+ };
30
+
31
+ const scenarios = [
32
+ {
33
+ id: "aggressive",
34
+ label: "Aggressive Saver",
35
+ icon: "🚀",
36
+ color: "text-emerald-400",
37
+ bg: "bg-emerald-500/10 border-emerald-500/20",
38
+ params: { savingsRate: 55, monthlyExpenses: 4600, investmentReturn: 9 },
39
+ },
40
+ {
41
+ id: "balanced",
42
+ label: "Balanced Growth",
43
+ icon: "⚖️",
44
+ color: "text-blue-400",
45
+ bg: "bg-blue-500/10 border-blue-500/20",
46
+ params: { savingsRate: 40, monthlyExpenses: 6100, investmentReturn: 7 },
47
+ },
48
+ {
49
+ id: "conservative",
50
+ label: "Conservative",
51
+ icon: "🛡️",
52
+ color: "text-purple-400",
53
+ bg: "bg-purple-500/10 border-purple-500/20",
54
+ params: { savingsRate: 25, monthlyExpenses: 7600, investmentReturn: 4 },
55
+ },
56
+ ];
57
+
58
+ // ─── Local projection engine (instant feedback while API loads) ───────────────
59
+ function projectBalance(params: SimParams, startBalance: number, months = 36) {
60
+ const monthlySavings = params.monthlyIncome * (params.savingsRate / 100);
61
+ const monthlyReturn = params.investmentReturn / 100 / 12;
62
+ let balance = startBalance;
63
+ return Array.from({ length: months + 1 }, (_, i) => {
64
+ if (i > 0) balance = balance * (1 + monthlyReturn) + monthlySavings - params.loanPayment;
65
+ return { month: i === 0 ? "Now" : `M${i}`, balance: Math.round(balance), savings: Math.round(monthlySavings * i) };
66
+ });
67
+ }
68
+
69
+ // ─── Custom Tooltip ───────────────────────────────────────────────────────────
70
+ interface TooltipProps {
71
+ active?: boolean;
72
+ payload?: Array<{ name: string; value: number; stroke?: string; fill?: string }>;
73
+ label?: string;
74
+ }
75
+ function CustomTooltip({ active, payload, label }: TooltipProps) {
76
+ if (!active || !payload?.length) return null;
77
+ return (
78
+ <div className="glass-card p-3 text-xs space-y-1">
79
+ <p className="text-zinc-400 font-medium">{label}</p>
80
+ {payload.map((entry) => (
81
+ <div key={entry.name} className="flex justify-between gap-4">
82
+ <span style={{ color: entry.stroke || entry.fill }}>{entry.name}</span>
83
+ <span className="text-white font-semibold">${entry.value?.toLocaleString()}</span>
84
+ </div>
85
+ ))}
86
+ </div>
87
+ );
88
+ }
89
+
90
+ // ─── Slider ───────────────────────────────────────────────────────────────────
91
+ function Slider({ label, value, min, max, step, format, onChange, color = "emerald" }: {
92
+ label: string; value: number; min: number; max: number; step: number;
93
+ format: (v: number) => string; onChange: (v: number) => void; color?: string;
94
+ }) {
95
+ const pct = ((value - min) / (max - min)) * 100;
96
+ const colorMap: Record<string, string> = {
97
+ emerald: "#10b981", blue: "#3b82f6", purple: "#8b5cf6", amber: "#f59e0b", red: "#ef4444",
98
+ };
99
+ const c = colorMap[color] || colorMap.emerald;
100
+
101
+ return (
102
+ <div className="space-y-2">
103
+ <div className="flex items-center justify-between">
104
+ <span className="text-xs font-medium text-zinc-400">{label}</span>
105
+ <motion.span
106
+ key={value}
107
+ initial={{ scale: 1.15, color: c }}
108
+ animate={{ scale: 1, color: "#ffffff" }}
109
+ transition={{ duration: 0.25 }}
110
+ className="text-sm font-bold text-white"
111
+ >
112
+ {format(value)}
113
+ </motion.span>
114
+ </div>
115
+ <div className="relative h-2 w-full rounded-full bg-white/10">
116
+ <div className="absolute h-full rounded-full transition-all duration-100"
117
+ style={{ width: `${pct}%`, background: `linear-gradient(90deg, ${c}88, ${c})` }} />
118
+ <input type="range" min={min} max={max} step={step} value={value}
119
+ onChange={(e) => onChange(Number(e.target.value))}
120
+ className="absolute inset-0 w-full h-full opacity-0 cursor-pointer" style={{ zIndex: 10 }} />
121
+ <div className="absolute top-1/2 -translate-y-1/2 h-4 w-4 rounded-full border-2 border-white shadow-lg transition-all duration-100"
122
+ style={{ left: `calc(${pct}% - 8px)`, background: c }} />
123
+ </div>
124
+ </div>
125
+ );
126
+ }
127
+
128
+ // ─── Metric Card ──────────────────────────────────────────────────────────────
129
+ function MetricCard({ label, value, sub, positive, icon }: {
130
+ label: string; value: string; sub: string; positive: boolean; icon: React.ReactNode;
131
+ }) {
132
+ return (
133
+ <motion.div whileHover={{ scale: 1.02 }} className="glass-card p-4">
134
+ <div className="flex items-start justify-between">
135
+ <p className="text-xs text-zinc-400">{label}</p>
136
+ <div className="text-zinc-500">{icon}</div>
137
+ </div>
138
+ <p className="mt-2 text-xl font-bold text-white">{value}</p>
139
+ <p className={`text-xs mt-1 ${positive ? "text-emerald-400" : "text-red-400"}`}>{sub}</p>
140
+ </motion.div>
141
+ );
142
+ }
143
+
144
+ // ─── Main Page ────────────────────────────────────────────────────────────────
145
+ export default function SimulatorPage() {
146
+ const [params, setParams] = useState<SimParams>(DEFAULT_PARAMS);
147
+ const [activeScenario, setActiveScenario] = useState<string | null>("balanced");
148
+ const [startBalance, setStartBalance] = useState(24563);
149
+ const [apiScenarios, setApiScenarios] = useState<Record<string, number> | null>(null);
150
+ const [loadingApi, setLoadingApi] = useState(false);
151
+ const [apiError, setApiError] = useState(false);
152
+
153
+ // Load real starting balance and API scenarios on mount
154
+ useEffect(() => {
155
+ const loadApiData = async () => {
156
+ setLoadingApi(true);
157
+ try {
158
+ const [twinData, scenariosData] = await Promise.all([
159
+ aiApi.twinPredict(),
160
+ aiApi.twinScenarios(6),
161
+ ]);
162
+ // Extract starting balance from twin prediction
163
+ const projections = twinData.monthly_projections;
164
+ if (projections && projections.length > 0) {
165
+ setStartBalance(projections[0].balance || 24563);
166
+ }
167
+ // Extract scenario end values
168
+ if (scenariosData.scenarios) {
169
+ const s = scenariosData.scenarios;
170
+ const getEnd = (arr: number[]) => arr[arr.length - 1] || 0;
171
+ setApiScenarios({
172
+ conservative: getEnd(s.conservative || []),
173
+ expected: getEnd(s.expected || []),
174
+ optimistic: getEnd(s.optimistic || []),
175
+ });
176
+ }
177
+ setApiError(false);
178
+ } catch {
179
+ setApiError(true);
180
+ } finally {
181
+ setLoadingApi(false);
182
+ }
183
+ };
184
+ loadApiData();
185
+ }, []);
186
+
187
+ const projection = useMemo(() => projectBalance(params, startBalance), [params, startBalance]);
188
+ const baseProjection = useMemo(() => projectBalance(DEFAULT_PARAMS, startBalance), [startBalance]);
189
+
190
+ const finalBalance = projection[projection.length - 1].balance;
191
+ const baseBalance = baseProjection[baseProjection.length - 1].balance;
192
+ const delta = finalBalance - baseBalance;
193
+ const monthlySavings = params.monthlyIncome * (params.savingsRate / 100);
194
+ const emergencyTarget = params.monthlyExpenses * params.emergencyMonths;
195
+ const monthsToEmergency = Math.ceil(Math.max(0, emergencyTarget - startBalance) / monthlySavings);
196
+
197
+ const update = (key: keyof SimParams) => (v: number) => {
198
+ setParams((p) => ({ ...p, [key]: v }));
199
+ setActiveScenario(null);
200
+ };
201
+
202
+ const applyScenario = (s: typeof scenarios[0]) => {
203
+ setParams((p) => ({ ...p, ...s.params }));
204
+ setActiveScenario(s.id);
205
+ };
206
+
207
+ const reset = useCallback(() => {
208
+ setParams(DEFAULT_PARAMS);
209
+ setActiveScenario("balanced");
210
+ }, []);
211
+
212
+ const comparisonData = projection.map((p, i) => ({
213
+ ...p,
214
+ base: baseProjection[i]?.balance,
215
+ }));
216
+
217
+ return (
218
+ <motion.div
219
+ initial={{ opacity: 0 }}
220
+ animate={{ opacity: 1 }}
221
+ transition={{ duration: 0.4 }}
222
+ className="flex flex-col gap-6"
223
+ >
224
+ {/* Header */}
225
+ <div className="flex items-center justify-between">
226
+ <div>
227
+ <h1 className="text-3xl font-bold tracking-tight text-white">What-If Simulator</h1>
228
+ <p className="text-zinc-400 mt-1 text-sm">
229
+ Model financial scenarios and see your future balance in real-time
230
+ {loadingApi && <span className="ml-2 text-zinc-600">· Loading real data...</span>}
231
+ </p>
232
+ </div>
233
+ <button onClick={reset} className="flex items-center gap-2 rounded-xl border border-white/10 bg-white/5 px-3 py-2 text-xs text-zinc-400 hover:text-white transition-colors">
234
+ <RotateCcw className="h-3.5 w-3.5" />
235
+ Reset
236
+ </button>
237
+ </div>
238
+
239
+ {/* API error notice */}
240
+ {apiError && (
241
+ <div className="flex items-center gap-3 rounded-2xl border border-amber-500/20 bg-amber-500/5 px-5 py-3">
242
+ <AlertTriangle className="h-4 w-4 text-amber-400 flex-shrink-0" />
243
+ <p className="text-xs text-zinc-400">
244
+ <span className="text-amber-400 font-medium">Using local projections</span> — backend offline. Sliders still work with estimated data.
245
+ </p>
246
+ </div>
247
+ )}
248
+
249
+ {/* API Scenario Cards (from backend) */}
250
+ {apiScenarios && (
251
+ <div className="glass-card p-4">
252
+ <div className="flex items-center gap-2 mb-3">
253
+ <Sparkles className="h-4 w-4 text-emerald-400" />
254
+ <span className="text-xs font-semibold text-white">AI 6-Month Forecast (from your real data)</span>
255
+ </div>
256
+ <div className="grid grid-cols-3 gap-3">
257
+ {[
258
+ { label: "Conservative", value: apiScenarios.conservative, color: "text-zinc-400" },
259
+ { label: "Expected", value: apiScenarios.expected, color: "text-blue-400" },
260
+ { label: "Optimistic", value: apiScenarios.optimistic, color: "text-emerald-400" },
261
+ ].map((s) => (
262
+ <div key={s.label} className="text-center">
263
+ <p className="text-xs text-zinc-500">{s.label}</p>
264
+ <p className={`text-lg font-bold mt-1 ${s.color}`}>
265
+ ${s.value.toLocaleString()}
266
+ </p>
267
+ </div>
268
+ ))}
269
+ </div>
270
+ </div>
271
+ )}
272
+
273
+ {/* Scenario Presets */}
274
+ <div className="grid grid-cols-3 gap-3">
275
+ {scenarios.map((s) => (
276
+ <motion.button
277
+ key={s.id}
278
+ whileHover={{ scale: 1.02 }}
279
+ whileTap={{ scale: 0.98 }}
280
+ onClick={() => applyScenario(s)}
281
+ className={`flex items-center gap-3 rounded-2xl border p-4 text-left transition-all ${s.bg} ${
282
+ activeScenario === s.id ? "ring-1 ring-white/20" : ""
283
+ }`}
284
+ >
285
+ <span className="text-2xl">{s.icon}</span>
286
+ <div>
287
+ <p className={`text-sm font-semibold ${s.color}`}>{s.label}</p>
288
+ <p className="text-xs text-zinc-500 mt-0.5">Apply preset</p>
289
+ </div>
290
+ {activeScenario === s.id && <div className="ml-auto h-2 w-2 rounded-full bg-white/60" />}
291
+ </motion.button>
292
+ ))}
293
+ </div>
294
+
295
+ <div className="grid gap-6 lg:grid-cols-5">
296
+ {/* Controls */}
297
+ <motion.div
298
+ initial={{ opacity: 0, x: -20 }}
299
+ animate={{ opacity: 1, x: 0 }}
300
+ transition={{ duration: 0.4 }}
301
+ className="col-span-2 glass-card p-6 space-y-6"
302
+ >
303
+ <div className="flex items-center gap-2">
304
+ <Zap className="h-4 w-4 text-amber-400" />
305
+ <h2 className="text-sm font-semibold text-white">Adjust Parameters</h2>
306
+ </div>
307
+ <Slider label="Monthly Income" value={params.monthlyIncome} min={3000} max={25000} step={100}
308
+ format={(v) => `$${v.toLocaleString()}`} onChange={update("monthlyIncome")} color="emerald" />
309
+ <Slider label="Monthly Expenses" value={params.monthlyExpenses} min={1500} max={15000} step={100}
310
+ format={(v) => `$${v.toLocaleString()}`} onChange={update("monthlyExpenses")} color="amber" />
311
+ <Slider label="Savings Rate" value={params.savingsRate} min={5} max={80} step={1}
312
+ format={(v) => `${v}%`} onChange={update("savingsRate")} color="blue" />
313
+ <Slider label="Investment Return (Annual)" value={params.investmentReturn} min={1} max={20} step={0.5}
314
+ format={(v) => `${v}%`} onChange={update("investmentReturn")} color="purple" />
315
+ <Slider label="Loan Payment" value={params.loanPayment} min={0} max={3000} step={50}
316
+ format={(v) => `$${v.toLocaleString()}`} onChange={update("loanPayment")} color="red" />
317
+ <Slider label="Emergency Fund Target (months)" value={params.emergencyMonths} min={1} max={12} step={1}
318
+ format={(v) => `${v}mo`} onChange={update("emergencyMonths")} color="emerald" />
319
+ </motion.div>
320
+
321
+ {/* Chart + Metrics */}
322
+ <div className="col-span-3 flex flex-col gap-4">
323
+ {/* Metrics */}
324
+ <div className="grid grid-cols-3 gap-3">
325
+ <MetricCard
326
+ label="36-Month Balance"
327
+ value={`$${(finalBalance / 1000).toFixed(1)}k`}
328
+ sub={`${delta >= 0 ? "+" : ""}$${Math.abs(delta / 1000).toFixed(1)}k vs baseline`}
329
+ positive={delta >= 0}
330
+ icon={<TrendingUp className="h-4 w-4" />}
331
+ />
332
+ <MetricCard
333
+ label="Monthly Savings"
334
+ value={`$${monthlySavings.toFixed(0)}`}
335
+ sub={`${params.savingsRate}% of income`}
336
+ positive={params.savingsRate >= 20}
337
+ icon={<Sparkles className="h-4 w-4" />}
338
+ />
339
+ <MetricCard
340
+ label="Emergency Fund"
341
+ value={monthsToEmergency === 0 ? "Funded ✓" : `${monthsToEmergency}mo`}
342
+ sub={monthsToEmergency === 0 ? "Goal achieved" : `$${emergencyTarget.toLocaleString()} target`}
343
+ positive={monthsToEmergency === 0}
344
+ icon={<TrendingDown className="h-4 w-4" />}
345
+ />
346
+ </div>
347
+
348
+ {/* Projection Chart */}
349
+ <motion.div
350
+ initial={{ opacity: 0, y: 20 }}
351
+ animate={{ opacity: 1, y: 0 }}
352
+ transition={{ duration: 0.5, delay: 0.1 }}
353
+ className="glass-card p-6 flex-1"
354
+ >
355
+ <div className="flex items-center justify-between mb-5">
356
+ <div>
357
+ <h2 className="text-base font-semibold text-white">36-Month Projection</h2>
358
+ <p className="text-xs text-zinc-400 mt-0.5">Your scenario vs baseline</p>
359
+ </div>
360
+ <div className="flex gap-4 text-xs">
361
+ <div className="flex items-center gap-1.5">
362
+ <div className="h-2 w-2 rounded-full bg-emerald-400" />
363
+ <span className="text-zinc-400">Your scenario</span>
364
+ </div>
365
+ <div className="flex items-center gap-1.5">
366
+ <div className="h-2 w-2 rounded-full bg-zinc-600" />
367
+ <span className="text-zinc-400">Baseline</span>
368
+ </div>
369
+ </div>
370
+ </div>
371
+ <ResponsiveContainer width="100%" height={260}>
372
+ <AreaChart data={comparisonData} margin={{ top: 5, right: 5, left: -20, bottom: 0 }}>
373
+ <defs>
374
+ <linearGradient id="simGrad" x1="0" y1="0" x2="0" y2="1">
375
+ <stop offset="5%" stopColor="#10b981" stopOpacity={0.3} />
376
+ <stop offset="95%" stopColor="#10b981" stopOpacity={0} />
377
+ </linearGradient>
378
+ <linearGradient id="baseGrad" x1="0" y1="0" x2="0" y2="1">
379
+ <stop offset="5%" stopColor="#6b7280" stopOpacity={0.2} />
380
+ <stop offset="95%" stopColor="#6b7280" stopOpacity={0} />
381
+ </linearGradient>
382
+ </defs>
383
+ <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.05)" />
384
+ <XAxis dataKey="month" tick={{ fill: "#71717a", fontSize: 10 }} axisLine={false} tickLine={false} interval={5} />
385
+ <YAxis tick={{ fill: "#71717a", fontSize: 10 }} axisLine={false} tickLine={false}
386
+ tickFormatter={(v) => `$${(v / 1000).toFixed(0)}k`} />
387
+ <Tooltip content={<CustomTooltip />} />
388
+ <ReferenceLine y={startBalance} stroke="rgba(255,255,255,0.1)" strokeDasharray="4 4" />
389
+ <Area type="monotone" dataKey="base" name="Baseline" stroke="#6b7280" strokeWidth={1.5} fill="url(#baseGrad)" strokeDasharray="4 4" />
390
+ <Area type="monotone" dataKey="balance" name="Scenario" stroke="#10b981" strokeWidth={2.5} fill="url(#simGrad)" />
391
+ </AreaChart>
392
+ </ResponsiveContainer>
393
+ </motion.div>
394
+
395
+ {/* Dynamic AI Insight */}
396
+ <AnimatePresence mode="wait">
397
+ <motion.div
398
+ key={`${params.savingsRate}-${params.investmentReturn}`}
399
+ initial={{ opacity: 0, y: 10 }}
400
+ animate={{ opacity: 1, y: 0 }}
401
+ exit={{ opacity: 0, y: -10 }}
402
+ transition={{ duration: 0.3 }}
403
+ className="flex items-start gap-3 rounded-2xl border border-blue-500/20 bg-blue-500/5 p-4"
404
+ >
405
+ <Sparkles className="h-4 w-4 text-blue-400 flex-shrink-0 mt-0.5" />
406
+ <div className="flex-1">
407
+ <p className="text-sm font-medium text-white">AI Insight</p>
408
+ <p className="text-xs text-zinc-400 mt-1">
409
+ {params.savingsRate >= 50
410
+ ? `At ${params.savingsRate}% savings rate, you'll reach $100k in approximately ${Math.ceil((100000 - startBalance) / (params.monthlyIncome * params.savingsRate / 100))} months. That's an aggressive but achievable goal.`
411
+ : params.savingsRate >= 30
412
+ ? `Your ${params.savingsRate}% savings rate is above average. Increasing by just 5% more would add $${Math.round(params.monthlyIncome * 0.05 * 36).toLocaleString()} to your 3-year balance.`
413
+ : `At ${params.savingsRate}% savings rate, consider reducing discretionary spending. Even a 5% increase would significantly accelerate your goals.`}
414
+ </p>
415
+ </div>
416
+ <button className="flex items-center gap-1 text-xs text-blue-400 hover:text-blue-300 transition-colors whitespace-nowrap">
417
+ Ask AI <ChevronRight className="h-3 w-3" />
418
+ </button>
419
+ </motion.div>
420
+ </AnimatePresence>
421
+ </div>
422
+ </div>
423
+ </motion.div>
424
+ );
425
+ }
frontend/src/app/status/page.tsx ADDED
@@ -0,0 +1,385 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "use client";
2
+
3
+ import { useState, useEffect, useCallback } from "react";
4
+ import { motion } from "framer-motion";
5
+ import {
6
+ Activity, Database, Cpu, Wifi, Shield, RefreshCw,
7
+ TrendingUp, AlertTriangle, CheckCircle, Clock
8
+ } from "lucide-react";
9
+
10
+ interface Metrics {
11
+ uptime_seconds: number;
12
+ requests: { total: number; errors: number; auth_failures: number; error_rate_pct: number };
13
+ websocket: { total_connects: number; reconnects: number };
14
+ ai: {
15
+ fallbacks: number;
16
+ by_provider: Record<string, { calls: number; errors: number; avg_latency_ms: number; p95_latency_ms: number | null }>;
17
+ };
18
+ cache: { hits: number; misses: number; hit_ratio_pct: number };
19
+ route_timings: Record<string, { calls: number; avg_ms: number; max_ms: number }>;
20
+ recent_errors: Array<{ ts: string; path: string; status: number; detail: string }>;
21
+ }
22
+
23
+ interface ApiStatus {
24
+ ai_backend: string;
25
+ ai_available: boolean;
26
+ db_type: string;
27
+ cache_type: string;
28
+ version: string;
29
+ }
30
+
31
+ const API = process.env.NEXT_PUBLIC_API_URL || "http://localhost:8000";
32
+
33
+ function formatUptime(s: number) {
34
+ if (s < 60) return `${s}s`;
35
+ if (s < 3600) return `${Math.floor(s / 60)}m ${Math.floor(s % 60)}s`;
36
+ return `${Math.floor(s / 3600)}h ${Math.floor((s % 3600) / 60)}m`;
37
+ }
38
+
39
+ function StatusDot({ ok }: { ok: boolean }) {
40
+ return (
41
+ <span className={`inline-block h-2 w-2 rounded-full ${ok ? "bg-emerald-400" : "bg-red-400"} ${ok ? "animate-pulse" : ""}`} />
42
+ );
43
+ }
44
+
45
+ function MetricCard({ label, value, sub, icon: Icon, color = "text-zinc-400" }: {
46
+ label: string; value: string | number; sub?: string;
47
+ icon: React.ElementType; color?: string;
48
+ }) {
49
+ return (
50
+ <motion.div
51
+ whileHover={{ scale: 1.02 }}
52
+ className="glass-card p-5"
53
+ >
54
+ <div className="flex items-start justify-between mb-3">
55
+ <p className="text-xs text-zinc-500 uppercase tracking-wider">{label}</p>
56
+ <Icon className={`h-4 w-4 ${color}`} />
57
+ </div>
58
+ <p className="text-2xl font-bold text-white">{value}</p>
59
+ {sub && <p className="text-xs text-zinc-500 mt-1">{sub}</p>}
60
+ </motion.div>
61
+ );
62
+ }
63
+
64
+ const containerVariants = {
65
+ hidden: { opacity: 0 },
66
+ visible: { opacity: 1, transition: { staggerChildren: 0.06 } },
67
+ };
68
+ const itemVariants = {
69
+ hidden: { opacity: 0, y: 14 },
70
+ visible: { opacity: 1, y: 0, transition: { duration: 0.4 } },
71
+ };
72
+
73
+ export default function StatusPage() {
74
+ const [metrics, setMetrics] = useState<Metrics | null>(null);
75
+ const [status, setStatus] = useState<ApiStatus | null>(null);
76
+ const [loading, setLoading] = useState(true);
77
+ const [lastRefresh, setLastRefresh] = useState<Date | null>(null);
78
+ const [backendOnline, setBackendOnline] = useState(false);
79
+
80
+ const load = useCallback(async () => {
81
+ setLoading(true);
82
+ try {
83
+ const [m, s] = await Promise.all([
84
+ fetch(`${API}/api/metrics`).then((r) => r.json()),
85
+ fetch(`${API}/api/status`).then((r) => r.json()),
86
+ ]);
87
+ setMetrics(m);
88
+ setStatus(s);
89
+ setBackendOnline(true);
90
+ setLastRefresh(new Date());
91
+ } catch {
92
+ setBackendOnline(false);
93
+ } finally {
94
+ setLoading(false);
95
+ }
96
+ }, []);
97
+
98
+ useEffect(() => {
99
+ load();
100
+ const interval = setInterval(load, 15000); // auto-refresh every 15s
101
+ return () => clearInterval(interval);
102
+ }, [load]);
103
+
104
+ const aiProviders = metrics ? Object.entries(metrics.ai.by_provider) : [];
105
+ const topRoutes = metrics
106
+ ? Object.entries(metrics.route_timings).sort((a, b) => b[1].avg_ms - a[1].avg_ms).slice(0, 6)
107
+ : [];
108
+
109
+ return (
110
+ <motion.div
111
+ variants={containerVariants}
112
+ initial="hidden"
113
+ animate="visible"
114
+ className="flex flex-col gap-6"
115
+ >
116
+ {/* Header */}
117
+ <motion.div variants={itemVariants} className="flex items-center justify-between">
118
+ <div>
119
+ <h1 className="text-3xl font-bold tracking-tight text-white">System Status</h1>
120
+ <p className="text-zinc-400 mt-1 text-sm">
121
+ Live observability — auto-refreshes every 15s
122
+ {lastRefresh && (
123
+ <span className="ml-2 text-zinc-600">
124
+ · Last updated {lastRefresh.toLocaleTimeString()}
125
+ </span>
126
+ )}
127
+ </p>
128
+ </div>
129
+ <button
130
+ onClick={load}
131
+ className="flex items-center gap-2 rounded-xl border border-white/10 bg-white/5 px-3 py-2 text-xs text-zinc-400 hover:text-white transition-colors"
132
+ >
133
+ <RefreshCw className={`h-3.5 w-3.5 ${loading ? "animate-spin" : ""}`} />
134
+ Refresh
135
+ </button>
136
+ </motion.div>
137
+
138
+ {/* Overall health banner */}
139
+ <motion.div
140
+ variants={itemVariants}
141
+ className={`flex items-center gap-3 rounded-2xl border px-5 py-3 ${
142
+ backendOnline
143
+ ? "border-emerald-500/20 bg-emerald-500/5"
144
+ : "border-red-500/20 bg-red-500/5"
145
+ }`}
146
+ >
147
+ {backendOnline ? (
148
+ <CheckCircle className="h-4 w-4 text-emerald-400 flex-shrink-0" />
149
+ ) : (
150
+ <AlertTriangle className="h-4 w-4 text-red-400 flex-shrink-0" />
151
+ )}
152
+ <div>
153
+ <p className={`text-sm font-semibold ${backendOnline ? "text-emerald-400" : "text-red-400"}`}>
154
+ {backendOnline ? "All Systems Operational" : "Backend Offline"}
155
+ </p>
156
+ <p className="text-xs text-zinc-500 mt-0.5">
157
+ {backendOnline
158
+ ? `API v${status?.version || "2.0.0"} · ${status?.db_type?.toUpperCase()} · ${status?.cache_type?.toUpperCase()} cache · Uptime ${formatUptime(metrics?.uptime_seconds || 0)}`
159
+ : "Cannot reach backend. Start with: uvicorn app.main:app --port 8000"}
160
+ </p>
161
+ </div>
162
+ </motion.div>
163
+
164
+ {/* System info cards */}
165
+ {status && (
166
+ <motion.div variants={itemVariants} className="grid grid-cols-2 sm:grid-cols-4 gap-4">
167
+ {[
168
+ {
169
+ label: "AI Backend",
170
+ value: status.ai_backend.toUpperCase(),
171
+ sub: status.ai_available ? "Available" : "Unavailable",
172
+ icon: Cpu,
173
+ color: status.ai_available ? "text-emerald-400" : "text-red-400",
174
+ },
175
+ {
176
+ label: "Database",
177
+ value: status.db_type.toUpperCase(),
178
+ sub: "Connected",
179
+ icon: Database,
180
+ color: "text-blue-400",
181
+ },
182
+ {
183
+ label: "Cache",
184
+ value: status.cache_type.toUpperCase(),
185
+ sub: metrics ? `${metrics.cache.hit_ratio_pct}% hit rate` : "—",
186
+ icon: Activity,
187
+ color: "text-purple-400",
188
+ },
189
+ {
190
+ label: "Uptime",
191
+ value: formatUptime(metrics?.uptime_seconds || 0),
192
+ sub: "Since last restart",
193
+ icon: Clock,
194
+ color: "text-amber-400",
195
+ },
196
+ ].map((c) => (
197
+ <MetricCard key={c.label} {...c} />
198
+ ))}
199
+ </motion.div>
200
+ )}
201
+
202
+ {/* Request metrics */}
203
+ {metrics && (
204
+ <motion.div variants={itemVariants} className="grid grid-cols-2 sm:grid-cols-4 gap-4">
205
+ <MetricCard
206
+ label="Total Requests"
207
+ value={metrics.requests.total.toLocaleString()}
208
+ sub="Since startup"
209
+ icon={TrendingUp}
210
+ color="text-emerald-400"
211
+ />
212
+ <MetricCard
213
+ label="Error Rate"
214
+ value={`${metrics.requests.error_rate_pct}%`}
215
+ sub={`${metrics.requests.errors} errors`}
216
+ icon={AlertTriangle}
217
+ color={metrics.requests.error_rate_pct > 5 ? "text-red-400" : "text-emerald-400"}
218
+ />
219
+ <MetricCard
220
+ label="Auth Failures"
221
+ value={metrics.requests.auth_failures}
222
+ sub="401 responses"
223
+ icon={Shield}
224
+ color={metrics.requests.auth_failures > 10 ? "text-amber-400" : "text-zinc-400"}
225
+ />
226
+ <MetricCard
227
+ label="WebSocket Connects"
228
+ value={metrics.websocket.total_connects}
229
+ sub={`${metrics.websocket.reconnects} reconnects`}
230
+ icon={Wifi}
231
+ color="text-cyan-400"
232
+ />
233
+ </motion.div>
234
+ )}
235
+
236
+ <div className="grid gap-6 lg:grid-cols-2">
237
+ {/* AI Provider Health */}
238
+ <motion.div variants={itemVariants} className="glass-card p-6">
239
+ <div className="flex items-center gap-2 mb-5">
240
+ <Cpu className="h-4 w-4 text-emerald-400" />
241
+ <h2 className="text-sm font-semibold text-white">AI Provider Health</h2>
242
+ </div>
243
+ {aiProviders.length === 0 ? (
244
+ <div className="flex flex-col items-center gap-2 py-8 text-center">
245
+ <Cpu className="h-8 w-8 text-zinc-700" />
246
+ <p className="text-sm text-zinc-500">No AI calls recorded yet</p>
247
+ <p className="text-xs text-zinc-600">Use the chat or briefing endpoints to generate AI calls</p>
248
+ </div>
249
+ ) : (
250
+ <div className="space-y-4">
251
+ {aiProviders.map(([provider, data]) => {
252
+ const errorRate = data.calls > 0 ? (data.errors / data.calls) * 100 : 0;
253
+ return (
254
+ <div key={provider} className="space-y-2">
255
+ <div className="flex items-center justify-between">
256
+ <div className="flex items-center gap-2">
257
+ <StatusDot ok={errorRate < 10} />
258
+ <span className="text-sm font-medium text-white capitalize">{provider}</span>
259
+ </div>
260
+ <div className="flex items-center gap-4 text-xs text-zinc-400">
261
+ <span>{data.calls} calls</span>
262
+ <span className={errorRate > 10 ? "text-red-400" : "text-emerald-400"}>
263
+ {errorRate.toFixed(1)}% errors
264
+ </span>
265
+ <span>{data.avg_latency_ms}ms avg</span>
266
+ </div>
267
+ </div>
268
+ <div className="h-1.5 w-full rounded-full bg-white/5 overflow-hidden">
269
+ <div
270
+ className="h-full rounded-full bg-emerald-400 transition-all duration-500"
271
+ style={{ width: `${Math.min(100 - errorRate, 100)}%` }}
272
+ />
273
+ </div>
274
+ </div>
275
+ );
276
+ })}
277
+ <div className="pt-2 border-t border-white/8">
278
+ <p className="text-xs text-zinc-500">
279
+ AI fallbacks: <span className="text-white font-medium">{metrics?.ai.fallbacks || 0}</span>
280
+ </p>
281
+ </div>
282
+ </div>
283
+ )}
284
+ </motion.div>
285
+
286
+ {/* Cache Performance */}
287
+ <motion.div variants={itemVariants} className="glass-card p-6">
288
+ <div className="flex items-center gap-2 mb-5">
289
+ <Activity className="h-4 w-4 text-purple-400" />
290
+ <h2 className="text-sm font-semibold text-white">Cache Performance</h2>
291
+ </div>
292
+ {metrics && (
293
+ <div className="space-y-4">
294
+ <div className="flex items-center justify-between">
295
+ <span className="text-sm text-zinc-400">Hit Ratio</span>
296
+ <span className={`text-sm font-bold ${metrics.cache.hit_ratio_pct > 60 ? "text-emerald-400" : "text-amber-400"}`}>
297
+ {metrics.cache.hit_ratio_pct}%
298
+ </span>
299
+ </div>
300
+ <div className="h-3 w-full rounded-full bg-white/5 overflow-hidden">
301
+ <motion.div
302
+ initial={{ width: 0 }}
303
+ animate={{ width: `${metrics.cache.hit_ratio_pct}%` }}
304
+ transition={{ duration: 0.8, ease: "easeOut" }}
305
+ className="h-full rounded-full bg-gradient-to-r from-purple-500 to-blue-500"
306
+ />
307
+ </div>
308
+ <div className="grid grid-cols-2 gap-4 pt-2">
309
+ <div className="rounded-xl bg-white/5 p-3 text-center">
310
+ <p className="text-lg font-bold text-emerald-400">{metrics.cache.hits}</p>
311
+ <p className="text-xs text-zinc-500 mt-0.5">Cache Hits</p>
312
+ </div>
313
+ <div className="rounded-xl bg-white/5 p-3 text-center">
314
+ <p className="text-lg font-bold text-zinc-400">{metrics.cache.misses}</p>
315
+ <p className="text-xs text-zinc-500 mt-0.5">Cache Misses</p>
316
+ </div>
317
+ </div>
318
+ </div>
319
+ )}
320
+ </motion.div>
321
+ </div>
322
+
323
+ {/* Route Timings */}
324
+ {topRoutes.length > 0 && (
325
+ <motion.div variants={itemVariants} className="glass-card p-6">
326
+ <div className="flex items-center gap-2 mb-5">
327
+ <Clock className="h-4 w-4 text-amber-400" />
328
+ <h2 className="text-sm font-semibold text-white">Route Performance</h2>
329
+ <span className="text-xs text-zinc-500 ml-auto">Sorted by avg response time</span>
330
+ </div>
331
+ <div className="space-y-2">
332
+ {topRoutes.map(([path, data]) => {
333
+ const isSlow = data.avg_ms > 500;
334
+ const barWidth = Math.min((data.avg_ms / 2000) * 100, 100);
335
+ return (
336
+ <div key={path} className="flex items-center gap-4">
337
+ <code className="text-xs text-zinc-400 w-56 truncate flex-shrink-0">{path}</code>
338
+ <div className="flex-1 h-1.5 rounded-full bg-white/5 overflow-hidden">
339
+ <div
340
+ className={`h-full rounded-full transition-all duration-500 ${isSlow ? "bg-amber-400" : "bg-emerald-400"}`}
341
+ style={{ width: `${barWidth}%` }}
342
+ />
343
+ </div>
344
+ <div className="flex items-center gap-3 text-xs text-zinc-400 w-40 flex-shrink-0 text-right">
345
+ <span className={`font-medium ${isSlow ? "text-amber-400" : "text-emerald-400"}`}>
346
+ {data.avg_ms}ms avg
347
+ </span>
348
+ <span className="text-zinc-600">{data.max_ms}ms max</span>
349
+ <span className="text-zinc-600">{data.calls} calls</span>
350
+ </div>
351
+ </div>
352
+ );
353
+ })}
354
+ </div>
355
+ </motion.div>
356
+ )}
357
+
358
+ {/* Recent Errors */}
359
+ {metrics && metrics.recent_errors.length > 0 && (
360
+ <motion.div variants={itemVariants} className="glass-card p-6">
361
+ <div className="flex items-center gap-2 mb-5">
362
+ <AlertTriangle className="h-4 w-4 text-red-400" />
363
+ <h2 className="text-sm font-semibold text-white">Recent Errors</h2>
364
+ <span className="text-xs text-zinc-500 ml-auto">Last 10</span>
365
+ </div>
366
+ <div className="space-y-2">
367
+ {metrics.recent_errors.map((err, i) => (
368
+ <div key={i} className="flex items-center gap-3 rounded-xl bg-red-500/5 border border-red-500/10 px-3 py-2">
369
+ <span className={`text-xs font-bold px-1.5 py-0.5 rounded ${
370
+ err.status >= 500 ? "bg-red-500/20 text-red-400" : "bg-amber-500/20 text-amber-400"
371
+ }`}>
372
+ {err.status}
373
+ </span>
374
+ <code className="text-xs text-zinc-400 flex-1 truncate">{err.path}</code>
375
+ <span className="text-xs text-zinc-600 flex-shrink-0">
376
+ {new Date(err.ts).toLocaleTimeString()}
377
+ </span>
378
+ </div>
379
+ ))}
380
+ </div>
381
+ </motion.div>
382
+ )}
383
+ </motion.div>
384
+ );
385
+ }
frontend/src/app/transactions/page.tsx ADDED
@@ -0,0 +1,311 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "use client";
2
+
3
+ import { useState, useEffect, useCallback } from "react";
4
+ import { motion } from "framer-motion";
5
+ import {
6
+ TrendingUp, TrendingDown, Search, Filter,
7
+ ChevronLeft, ChevronRight, RefreshCw, AlertTriangle
8
+ } from "lucide-react";
9
+ import { transactionsApi } from "@/lib/api";
10
+
11
+ interface Transaction {
12
+ id: string;
13
+ merchant: string;
14
+ category: string;
15
+ amount: number;
16
+ type: string;
17
+ timestamp: string;
18
+ tags?: string[];
19
+ }
20
+
21
+ const CATEGORY_COLORS: Record<string, string> = {
22
+ Food: "#10b981", Shopping: "#f59e0b", Entertainment: "#ec4899",
23
+ Transport: "#8b5cf6", Income: "#3b82f6", Investment: "#06b6d4",
24
+ Groceries: "#84cc16", Tech: "#f97316", Utilities: "#6b7280", Other: "#71717a",
25
+ };
26
+
27
+ function getCategoryColor(cat: string) {
28
+ return CATEGORY_COLORS[cat] || CATEGORY_COLORS.Other;
29
+ }
30
+
31
+ function formatDate(ts: string) {
32
+ if (!ts) return "";
33
+ const d = new Date(ts);
34
+ const now = new Date();
35
+ const diff = Math.floor((now.getTime() - d.getTime()) / 86400000);
36
+ if (diff === 0) return "Today";
37
+ if (diff === 1) return "Yesterday";
38
+ if (diff < 7) return `${diff} days ago`;
39
+ return d.toLocaleDateString("en-US", { month: "short", day: "numeric" });
40
+ }
41
+
42
+ function Skeleton({ className }: { className?: string }) {
43
+ return <div className={`shimmer rounded-lg ${className}`} />;
44
+ }
45
+
46
+ const containerVariants = {
47
+ hidden: { opacity: 0 },
48
+ visible: { opacity: 1, transition: { staggerChildren: 0.04 } },
49
+ };
50
+ const itemVariants = {
51
+ hidden: { opacity: 0, y: 12 },
52
+ visible: { opacity: 1, y: 0, transition: { duration: 0.35 } },
53
+ };
54
+
55
+ export default function TransactionsPage() {
56
+ const [transactions, setTransactions] = useState<Transaction[]>([]);
57
+ const [total, setTotal] = useState(0);
58
+ const [page, setPage] = useState(1);
59
+ const [pages, setPages] = useState(1);
60
+ const [loading, setLoading] = useState(true);
61
+ const [error, setError] = useState<string | null>(null);
62
+ const [search, setSearch] = useState("");
63
+ const [typeFilter, setTypeFilter] = useState<"" | "credit" | "debit">("");
64
+
65
+ const load = useCallback(async (p = 1) => {
66
+ setLoading(true);
67
+ setError(null);
68
+ try {
69
+ const res = await transactionsApi.list({
70
+ page: p,
71
+ limit: 20,
72
+ type: typeFilter || undefined,
73
+ });
74
+ setTransactions(res.transactions);
75
+ setTotal(res.total);
76
+ setPage(res.page);
77
+ setPages(res.pages);
78
+ } catch (err) {
79
+ setError((err as Error).message);
80
+ } finally {
81
+ setLoading(false);
82
+ }
83
+ }, [typeFilter]);
84
+
85
+ useEffect(() => { load(1); }, [load]);
86
+
87
+ const filtered = search
88
+ ? transactions.filter(
89
+ (t) =>
90
+ t.merchant.toLowerCase().includes(search.toLowerCase()) ||
91
+ t.category.toLowerCase().includes(search.toLowerCase())
92
+ )
93
+ : transactions;
94
+
95
+ const totalIncome = filtered.filter((t) => t.amount > 0).reduce((s, t) => s + t.amount, 0);
96
+ const totalExpenses = filtered.filter((t) => t.amount < 0).reduce((s, t) => s + Math.abs(t.amount), 0);
97
+
98
+ return (
99
+ <motion.div
100
+ variants={containerVariants}
101
+ initial="hidden"
102
+ animate="visible"
103
+ className="flex flex-col gap-6"
104
+ >
105
+ {/* Header */}
106
+ <motion.div variants={itemVariants} className="flex items-center justify-between">
107
+ <div>
108
+ <h1 className="text-3xl font-bold tracking-tight text-white">Transactions</h1>
109
+ <p className="text-zinc-400 mt-1 text-sm">
110
+ {loading ? "Loading..." : `${total} transactions total`}
111
+ </p>
112
+ </div>
113
+ <button
114
+ onClick={() => load(page)}
115
+ className="flex items-center gap-2 rounded-xl border border-white/10 bg-white/5 px-3 py-2 text-xs text-zinc-400 hover:text-white transition-colors"
116
+ >
117
+ <RefreshCw className={`h-3.5 w-3.5 ${loading ? "animate-spin" : ""}`} />
118
+ Refresh
119
+ </button>
120
+ </motion.div>
121
+
122
+ {/* Error */}
123
+ {error && (
124
+ <motion.div variants={itemVariants} className="flex items-center gap-3 rounded-2xl border border-amber-500/20 bg-amber-500/5 px-5 py-3">
125
+ <AlertTriangle className="h-4 w-4 text-amber-400 flex-shrink-0" />
126
+ <p className="text-xs text-zinc-400">
127
+ <span className="text-amber-400 font-medium">Could not load transactions</span> — {error}
128
+ </p>
129
+ </motion.div>
130
+ )}
131
+
132
+ {/* Summary Cards */}
133
+ <motion.div variants={itemVariants} className="grid grid-cols-3 gap-4">
134
+ <div className="glass-card p-4">
135
+ <p className="text-xs text-zinc-400">Showing</p>
136
+ <p className="text-xl font-bold text-white mt-1">{filtered.length}</p>
137
+ <p className="text-xs text-zinc-500 mt-0.5">of {total} transactions</p>
138
+ </div>
139
+ <div className="glass-card p-4">
140
+ <p className="text-xs text-zinc-400">Income (page)</p>
141
+ <p className="text-xl font-bold text-emerald-400 mt-1">+${totalIncome.toLocaleString("en-US", { minimumFractionDigits: 2 })}</p>
142
+ <div className="flex items-center gap-1 mt-0.5">
143
+ <TrendingUp className="h-3 w-3 text-emerald-400" />
144
+ <span className="text-xs text-zinc-500">credits</span>
145
+ </div>
146
+ </div>
147
+ <div className="glass-card p-4">
148
+ <p className="text-xs text-zinc-400">Expenses (page)</p>
149
+ <p className="text-xl font-bold text-white mt-1">-${totalExpenses.toLocaleString("en-US", { minimumFractionDigits: 2 })}</p>
150
+ <div className="flex items-center gap-1 mt-0.5">
151
+ <TrendingDown className="h-3 w-3 text-zinc-500" />
152
+ <span className="text-xs text-zinc-500">debits</span>
153
+ </div>
154
+ </div>
155
+ </motion.div>
156
+
157
+ {/* Filters */}
158
+ <motion.div variants={itemVariants} className="flex items-center gap-3">
159
+ <div className="relative flex-1 max-w-sm">
160
+ <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-zinc-500" />
161
+ <input
162
+ value={search}
163
+ onChange={(e) => setSearch(e.target.value)}
164
+ placeholder="Search merchant or category..."
165
+ className="w-full rounded-xl border border-white/10 bg-white/5 py-2 pl-9 pr-3 text-sm text-white placeholder:text-zinc-500 focus:outline-none focus:border-emerald-500/40 transition-all"
166
+ />
167
+ </div>
168
+ <div className="flex items-center gap-1 rounded-xl border border-white/10 bg-white/5 p-1">
169
+ {(["", "credit", "debit"] as const).map((f) => (
170
+ <button
171
+ key={f}
172
+ onClick={() => { setTypeFilter(f); setPage(1); }}
173
+ className={`rounded-lg px-3 py-1.5 text-xs font-medium capitalize transition-all ${
174
+ typeFilter === f ? "bg-white/10 text-white" : "text-zinc-500 hover:text-zinc-300"
175
+ }`}
176
+ >
177
+ {f === "" ? "All" : f === "credit" ? "Income" : "Expenses"}
178
+ </button>
179
+ ))}
180
+ </div>
181
+ <div className="flex items-center gap-1.5 text-xs text-zinc-500">
182
+ <Filter className="h-3.5 w-3.5" />
183
+ <span>{filtered.length} results</span>
184
+ </div>
185
+ </motion.div>
186
+
187
+ {/* Transaction List */}
188
+ <motion.div variants={itemVariants} className="glass-card overflow-hidden">
189
+ {/* Table header */}
190
+ <div className="grid grid-cols-12 gap-4 border-b border-white/8 px-6 py-3 text-xs font-medium text-zinc-500 uppercase tracking-wider">
191
+ <div className="col-span-5">Merchant</div>
192
+ <div className="col-span-3">Category</div>
193
+ <div className="col-span-2">Date</div>
194
+ <div className="col-span-2 text-right">Amount</div>
195
+ </div>
196
+
197
+ <div className="divide-y divide-white/5">
198
+ {loading
199
+ ? Array.from({ length: 8 }).map((_, i) => (
200
+ <div key={i} className="grid grid-cols-12 gap-4 px-6 py-4">
201
+ <div className="col-span-5 flex items-center gap-3">
202
+ <Skeleton className="h-9 w-9 rounded-xl flex-shrink-0" />
203
+ <div className="space-y-1.5">
204
+ <Skeleton className="h-3.5 w-28" />
205
+ <Skeleton className="h-3 w-20" />
206
+ </div>
207
+ </div>
208
+ <div className="col-span-3 flex items-center"><Skeleton className="h-5 w-20 rounded-full" /></div>
209
+ <div className="col-span-2 flex items-center"><Skeleton className="h-3.5 w-16" /></div>
210
+ <div className="col-span-2 flex items-center justify-end"><Skeleton className="h-4 w-16" /></div>
211
+ </div>
212
+ ))
213
+ : filtered.map((tx, i) => (
214
+ <motion.div
215
+ key={tx.id}
216
+ initial={{ opacity: 0, x: -8 }}
217
+ animate={{ opacity: 1, x: 0 }}
218
+ transition={{ delay: i * 0.03 }}
219
+ whileHover={{ backgroundColor: "rgba(255,255,255,0.02)" }}
220
+ className="grid grid-cols-12 gap-4 px-6 py-4 cursor-pointer transition-colors"
221
+ >
222
+ {/* Merchant */}
223
+ <div className="col-span-5 flex items-center gap-3">
224
+ <div
225
+ className="flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-xl text-sm font-bold text-white"
226
+ style={{ background: `${getCategoryColor(tx.category)}22`, border: `1px solid ${getCategoryColor(tx.category)}33` }}
227
+ >
228
+ {tx.merchant.charAt(0).toUpperCase()}
229
+ </div>
230
+ <div>
231
+ <p className="text-sm font-medium text-white leading-tight">{tx.merchant}</p>
232
+ <p className="text-xs text-zinc-500 leading-tight">{tx.type === "credit" ? "Credit" : "Debit"}</p>
233
+ </div>
234
+ </div>
235
+
236
+ {/* Category */}
237
+ <div className="col-span-3 flex items-center">
238
+ <span
239
+ className="rounded-full px-2.5 py-1 text-xs font-medium"
240
+ style={{
241
+ background: `${getCategoryColor(tx.category)}18`,
242
+ color: getCategoryColor(tx.category),
243
+ border: `1px solid ${getCategoryColor(tx.category)}30`,
244
+ }}
245
+ >
246
+ {tx.category}
247
+ </span>
248
+ </div>
249
+
250
+ {/* Date */}
251
+ <div className="col-span-2 flex items-center">
252
+ <span className="text-xs text-zinc-400">{formatDate(tx.timestamp)}</span>
253
+ </div>
254
+
255
+ {/* Amount */}
256
+ <div className="col-span-2 flex items-center justify-end gap-1.5">
257
+ <span className={`text-sm font-semibold ${tx.amount > 0 ? "text-emerald-400" : "text-white"}`}>
258
+ {tx.amount > 0 ? "+" : ""}${Math.abs(tx.amount).toFixed(2)}
259
+ </span>
260
+ {tx.amount > 0
261
+ ? <TrendingUp className="h-3.5 w-3.5 text-emerald-400" />
262
+ : <TrendingDown className="h-3.5 w-3.5 text-zinc-600" />
263
+ }
264
+ </div>
265
+ </motion.div>
266
+ ))}
267
+ </div>
268
+
269
+ {/* Empty state */}
270
+ {!loading && filtered.length === 0 && (
271
+ <div className="flex flex-col items-center gap-3 py-16 text-center">
272
+ <Search className="h-10 w-10 text-zinc-700" />
273
+ <p className="text-sm text-zinc-500">No transactions found</p>
274
+ {search && (
275
+ <button onClick={() => setSearch("")} className="text-xs text-emerald-400 hover:text-emerald-300 transition-colors">
276
+ Clear search
277
+ </button>
278
+ )}
279
+ </div>
280
+ )}
281
+ </motion.div>
282
+
283
+ {/* Pagination */}
284
+ {pages > 1 && (
285
+ <motion.div variants={itemVariants} className="flex items-center justify-between">
286
+ <p className="text-xs text-zinc-500">
287
+ Page {page} of {pages} · {total} total
288
+ </p>
289
+ <div className="flex items-center gap-2">
290
+ <button
291
+ onClick={() => load(page - 1)}
292
+ disabled={page <= 1 || loading}
293
+ className="flex items-center gap-1.5 rounded-xl border border-white/10 bg-white/5 px-3 py-2 text-xs text-zinc-400 hover:text-white disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
294
+ >
295
+ <ChevronLeft className="h-3.5 w-3.5" />
296
+ Previous
297
+ </button>
298
+ <button
299
+ onClick={() => load(page + 1)}
300
+ disabled={page >= pages || loading}
301
+ className="flex items-center gap-1.5 rounded-xl border border-white/10 bg-white/5 px-3 py-2 text-xs text-zinc-400 hover:text-white disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
302
+ >
303
+ Next
304
+ <ChevronRight className="h-3.5 w-3.5" />
305
+ </button>
306
+ </div>
307
+ </motion.div>
308
+ )}
309
+ </motion.div>
310
+ );
311
+ }
frontend/src/components/layout/DashboardLayout.tsx ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "use client";
2
+
3
+ import { useState } from "react";
4
+ import { motion, AnimatePresence } from "framer-motion";
5
+ import { usePathname } from "next/navigation";
6
+ import { Sidebar } from "./Sidebar";
7
+ import { Navbar } from "./Navbar";
8
+ import { Menu } from "lucide-react";
9
+
10
+ // ─── Page transition wrapper ──────────────────────────────────────────────────
11
+ function PageTransition({ children }: { children: React.ReactNode }) {
12
+ const pathname = usePathname();
13
+ return (
14
+ <AnimatePresence mode="wait">
15
+ <motion.div
16
+ key={pathname}
17
+ initial={{ opacity: 0, y: 8 }}
18
+ animate={{ opacity: 1, y: 0 }}
19
+ exit={{ opacity: 0, y: -8 }}
20
+ transition={{ duration: 0.25, ease: "easeOut" }}
21
+ className="h-full"
22
+ >
23
+ {children}
24
+ </motion.div>
25
+ </AnimatePresence>
26
+ );
27
+ }
28
+
29
+ export function DashboardLayout({ children }: { children: React.ReactNode }) {
30
+ const [mobileOpen, setMobileOpen] = useState(false);
31
+
32
+ return (
33
+ <div className="flex h-screen bg-[#050505] text-white overflow-hidden">
34
+ {/* Ambient background gradients */}
35
+ <div className="fixed inset-0 z-0 overflow-hidden pointer-events-none">
36
+ <div className="absolute top-[-15%] left-[-5%] w-[45%] h-[45%] rounded-full bg-blue-600/10 blur-[140px]" />
37
+ <div className="absolute bottom-[-15%] right-[-5%] w-[45%] h-[45%] rounded-full bg-emerald-600/10 blur-[140px]" />
38
+ <div className="absolute top-[40%] left-[40%] w-[30%] h-[30%] rounded-full bg-purple-600/5 blur-[120px]" />
39
+ {/* Noise texture */}
40
+ <div
41
+ className="absolute inset-0 opacity-[0.015]"
42
+ style={{
43
+ backgroundImage: `url("data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noise'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noise)'/%3E%3C/svg%3E")`,
44
+ backgroundRepeat: "repeat",
45
+ backgroundSize: "128px 128px",
46
+ }}
47
+ />
48
+ </div>
49
+
50
+ {/* ── Desktop Sidebar ─────────────────────────────────────────────────── */}
51
+ <div className="z-10 hidden lg:flex h-full flex-shrink-0">
52
+ <Sidebar />
53
+ </div>
54
+
55
+ {/* ── Mobile Sidebar Overlay ───────────────────────────────────────────── */}
56
+ <AnimatePresence>
57
+ {mobileOpen && (
58
+ <>
59
+ <motion.div
60
+ initial={{ opacity: 0 }}
61
+ animate={{ opacity: 1 }}
62
+ exit={{ opacity: 0 }}
63
+ onClick={() => setMobileOpen(false)}
64
+ className="fixed inset-0 z-30 bg-black/60 backdrop-blur-sm lg:hidden"
65
+ />
66
+ <motion.div
67
+ initial={{ x: "-100%" }}
68
+ animate={{ x: 0 }}
69
+ exit={{ x: "-100%" }}
70
+ transition={{ type: "spring", damping: 30, stiffness: 300 }}
71
+ className="fixed left-0 top-0 z-40 h-full lg:hidden"
72
+ >
73
+ <Sidebar />
74
+ </motion.div>
75
+ </>
76
+ )}
77
+ </AnimatePresence>
78
+
79
+ {/* ── Main content ─────────────────────────────────────────────────────── */}
80
+ <div className="z-10 flex flex-1 flex-col overflow-hidden min-w-0">
81
+ {/* Mobile header with hamburger */}
82
+ <div className="flex items-center lg:hidden border-b border-white/10 bg-black/40 backdrop-blur-xl px-4 py-3">
83
+ <button
84
+ onClick={() => setMobileOpen(true)}
85
+ className="rounded-xl bg-white/5 p-2 text-zinc-400 hover:text-white transition-colors mr-3"
86
+ >
87
+ <Menu className="h-5 w-5" />
88
+ </button>
89
+ <span className="text-base font-bold gradient-text">BankBot</span>
90
+ </div>
91
+
92
+ <Navbar />
93
+
94
+ <main className="flex-1 overflow-y-auto p-4 sm:p-6 lg:p-8">
95
+ <PageTransition>{children}</PageTransition>
96
+ </main>
97
+ </div>
98
+ </div>
99
+ );
100
+ }
frontend/src/components/layout/Navbar.tsx ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "use client";
2
+
3
+ import { Search, User } from "lucide-react";
4
+ import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
5
+ import { NotificationBell } from "@/components/notifications/NotificationPanel";
6
+ import { motion } from "framer-motion";
7
+
8
+ export function Navbar() {
9
+ return (
10
+ <header className="sticky top-0 z-40 flex h-16 w-full items-center justify-between bg-black/40 backdrop-blur-xl border-b border-white/10 px-8">
11
+ {/* Search */}
12
+ <div className="flex flex-1 items-center">
13
+ <div className="relative w-full max-w-sm">
14
+ <div className="pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3">
15
+ <Search className="h-4 w-4 text-zinc-500" aria-hidden="true" />
16
+ </div>
17
+ <input
18
+ id="search"
19
+ className="block w-full rounded-xl border-0 bg-white/5 py-2 pl-9 pr-3 text-sm text-white placeholder:text-zinc-500 focus:bg-white/8 focus:ring-1 focus:ring-emerald-500/40 transition-all duration-200 outline-none"
20
+ placeholder="Search transactions, ask AI..."
21
+ type="search"
22
+ />
23
+ <div className="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-3">
24
+ <kbd className="hidden sm:inline-flex h-5 items-center gap-1 rounded border border-white/10 bg-white/5 px-1.5 text-[10px] text-zinc-500">
25
+ ⌘K
26
+ </kbd>
27
+ </div>
28
+ </div>
29
+ </div>
30
+
31
+ {/* Right side */}
32
+ <div className="ml-4 flex items-center gap-4">
33
+ {/* Notification Bell */}
34
+ <NotificationBell />
35
+
36
+ {/* Divider */}
37
+ <div className="h-6 w-px bg-white/10" />
38
+
39
+ {/* User */}
40
+ <motion.div
41
+ whileHover={{ scale: 1.02 }}
42
+ className="flex items-center gap-3 cursor-pointer group"
43
+ >
44
+ <div className="flex flex-col text-right">
45
+ <span className="text-sm font-semibold text-white group-hover:text-emerald-400 transition-colors leading-tight">
46
+ Alex Doe
47
+ </span>
48
+ <span className="text-xs text-emerald-500 leading-tight">Premium</span>
49
+ </div>
50
+ <Avatar className="h-9 w-9 border border-emerald-500/30 ring-2 ring-emerald-500/10">
51
+ <AvatarImage src="https://github.com/shadcn.png" alt="@user" />
52
+ <AvatarFallback className="bg-emerald-900 text-emerald-400 text-xs">
53
+ <User className="h-4 w-4" />
54
+ </AvatarFallback>
55
+ </Avatar>
56
+ </motion.div>
57
+ </div>
58
+ </header>
59
+ );
60
+ }
frontend/src/components/layout/Sidebar.tsx ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "use client";
2
+
3
+ import Link from "next/link";
4
+ import { usePathname } from "next/navigation";
5
+ import { cn } from "@/lib/utils";
6
+ import { motion } from "framer-motion";
7
+ import {
8
+ LayoutDashboard,
9
+ ArrowRightLeft,
10
+ BarChart2,
11
+ Wallet,
12
+ Target,
13
+ MessageSquare,
14
+ Settings,
15
+ LogOut,
16
+ Zap,
17
+ Shield,
18
+ Sparkles,
19
+ Activity,
20
+ } from "lucide-react";
21
+
22
+ const navigation = [
23
+ { name: "Overview", href: "/", icon: LayoutDashboard },
24
+ { name: "Transactions", href: "/transactions", icon: ArrowRightLeft },
25
+ { name: "Analytics", href: "/analytics", icon: BarChart2 },
26
+ { name: "Simulator", href: "/simulator", icon: Zap, badge: "NEW" },
27
+ { name: "Loans", href: "/loans", icon: Wallet },
28
+ { name: "Goals", href: "/goals", icon: Target },
29
+ { name: "AI Assistant", href: "/chat", icon: MessageSquare, badge: "AI" },
30
+ { name: "Security", href: "/security", icon: Shield },
31
+ { name: "System Status", href: "/status", icon: Activity },
32
+ { name: "Settings", href: "/settings", icon: Settings },
33
+ ];
34
+
35
+ export function Sidebar() {
36
+ const pathname = usePathname();
37
+
38
+ return (
39
+ <div className="flex h-full w-60 flex-col overflow-y-auto bg-black/60 backdrop-blur-2xl border-r border-white/8 text-white">
40
+ {/* Logo */}
41
+ <div className="flex h-16 shrink-0 items-center gap-2.5 px-5 border-b border-white/8">
42
+ <div className="flex h-8 w-8 items-center justify-center rounded-xl bg-gradient-to-br from-emerald-400 to-cyan-500 shadow-lg shadow-emerald-500/20">
43
+ <Sparkles className="h-4 w-4 text-white" />
44
+ </div>
45
+ <div>
46
+ <h1 className="text-base font-bold text-white leading-tight">BankBot</h1>
47
+ <p className="text-[10px] text-emerald-400 leading-tight">AI Finance</p>
48
+ </div>
49
+ </div>
50
+
51
+ {/* Nav */}
52
+ <div className="flex flex-1 flex-col justify-between px-3 py-4">
53
+ <nav className="space-y-0.5">
54
+ {navigation.map((item) => {
55
+ const isActive = pathname === item.href;
56
+ return (
57
+ <Link
58
+ key={item.name}
59
+ href={item.href}
60
+ className={cn(
61
+ "group relative flex items-center rounded-xl px-3 py-2.5 text-sm font-medium transition-all duration-200",
62
+ isActive
63
+ ? "text-white"
64
+ : "text-zinc-500 hover:text-zinc-200 hover:bg-white/5"
65
+ )}
66
+ >
67
+ {/* Active background */}
68
+ {isActive && (
69
+ <motion.div
70
+ layoutId="activeNav"
71
+ className="absolute inset-0 rounded-xl bg-white/10 border border-white/10"
72
+ transition={{ type: "spring", bounce: 0.2, duration: 0.4 }}
73
+ />
74
+ )}
75
+
76
+ {/* Active left accent */}
77
+ {isActive && (
78
+ <div className="absolute left-0 top-1/2 -translate-y-1/2 h-5 w-0.5 rounded-full bg-emerald-400" />
79
+ )}
80
+
81
+ <item.icon
82
+ className={cn(
83
+ "relative mr-3 h-4 w-4 flex-shrink-0 transition-colors",
84
+ isActive ? "text-emerald-400" : "text-zinc-500 group-hover:text-zinc-300"
85
+ )}
86
+ aria-hidden="true"
87
+ />
88
+ <span className="relative flex-1">{item.name}</span>
89
+
90
+ {/* Badge */}
91
+ {item.badge && (
92
+ <span className={cn(
93
+ "relative ml-auto rounded-md px-1.5 py-0.5 text-[9px] font-bold uppercase tracking-wide",
94
+ item.badge === "AI"
95
+ ? "bg-emerald-500/20 text-emerald-400 border border-emerald-500/30"
96
+ : "bg-blue-500/20 text-blue-400 border border-blue-500/30"
97
+ )}>
98
+ {item.badge}
99
+ </span>
100
+ )}
101
+ </Link>
102
+ );
103
+ })}
104
+ </nav>
105
+
106
+ {/* Bottom section */}
107
+ <div className="space-y-1 pt-4 border-t border-white/8">
108
+ {/* AI Status */}
109
+ <div className="flex items-center gap-2.5 rounded-xl px-3 py-2.5 bg-emerald-500/5 border border-emerald-500/10">
110
+ <div className="h-1.5 w-1.5 rounded-full bg-emerald-400 animate-pulse flex-shrink-0" />
111
+ <div className="flex-1 min-w-0">
112
+ <p className="text-xs font-medium text-emerald-400 leading-tight">AI Shield Active</p>
113
+ <p className="text-[10px] text-zinc-600 leading-tight truncate">All systems normal</p>
114
+ </div>
115
+ </div>
116
+
117
+ <button className="group flex w-full items-center rounded-xl px-3 py-2.5 text-sm font-medium text-zinc-500 hover:bg-red-500/8 hover:text-red-400 transition-all duration-200">
118
+ <LogOut className="mr-3 h-4 w-4 flex-shrink-0 transition-colors" />
119
+ Sign Out
120
+ </button>
121
+ </div>
122
+ </div>
123
+ </div>
124
+ );
125
+ }
frontend/src/components/notifications/NotificationPanel.tsx ADDED
@@ -0,0 +1,254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "use client";
2
+
3
+ import { useState, useEffect, useCallback } from "react";
4
+ import { motion, AnimatePresence } from "framer-motion";
5
+ import {
6
+ Shield, TrendingUp, AlertTriangle, Sparkles,
7
+ DollarSign, X, CheckCheck, Bell, RefreshCw
8
+ } from "lucide-react";
9
+ import { notificationsApi, NotificationItem } from "@/lib/api";
10
+
11
+ // ─── Type config ──────────────────────────────────────────────────────────────
12
+ const typeConfig: Record<string, { icon: React.ElementType; color: string; bg: string }> = {
13
+ alert: { icon: Shield, color: "text-red-400", bg: "bg-red-500/10 border-red-500/20" },
14
+ insight: { icon: Sparkles, color: "text-blue-400", bg: "bg-blue-500/10 border-blue-500/20" },
15
+ warning: { icon: AlertTriangle, color: "text-amber-400", bg: "bg-amber-500/10 border-amber-500/20" },
16
+ success: { icon: TrendingUp, color: "text-emerald-400", bg: "bg-emerald-500/10 border-emerald-500/20" },
17
+ default: { icon: DollarSign, color: "text-zinc-400", bg: "bg-zinc-500/10 border-zinc-500/20" },
18
+ };
19
+
20
+ function getTypeConfig(type: string) {
21
+ return typeConfig[type] || typeConfig.default;
22
+ }
23
+
24
+ function timeAgo(dateStr: string): string {
25
+ const diff = Date.now() - new Date(dateStr).getTime();
26
+ const mins = Math.floor(diff / 60000);
27
+ if (mins < 1) return "Just now";
28
+ if (mins < 60) return `${mins}m ago`;
29
+ const hrs = Math.floor(mins / 60);
30
+ if (hrs < 24) return `${hrs}h ago`;
31
+ return `${Math.floor(hrs / 24)}d ago`;
32
+ }
33
+
34
+ // ─── Notification Item ────────────────────────────────────────────────────────
35
+ function NotifItem({
36
+ notification,
37
+ onDismiss,
38
+ onRead,
39
+ }: {
40
+ notification: NotificationItem;
41
+ onDismiss: (id: string) => void;
42
+ onRead: (id: string) => void;
43
+ }) {
44
+ const config = getTypeConfig(notification.type);
45
+ const Icon = config.icon;
46
+
47
+ return (
48
+ <motion.div
49
+ layout
50
+ initial={{ opacity: 0, x: 20 }}
51
+ animate={{ opacity: 1, x: 0 }}
52
+ exit={{ opacity: 0, x: 20, height: 0, marginBottom: 0 }}
53
+ transition={{ duration: 0.25 }}
54
+ onClick={() => onRead(notification.id)}
55
+ className={`relative flex gap-3 rounded-xl border p-3 cursor-pointer transition-all group ${config.bg} ${
56
+ !notification.read ? "ring-1 ring-white/5" : "opacity-60"
57
+ }`}
58
+ >
59
+ {!notification.read && (
60
+ <div className="absolute top-3 right-3 h-1.5 w-1.5 rounded-full bg-blue-400" />
61
+ )}
62
+ <div className={`flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-lg border ${config.bg}`}>
63
+ <Icon className={`h-4 w-4 ${config.color}`} />
64
+ </div>
65
+ <div className="flex-1 min-w-0 pr-4">
66
+ <p className="text-xs font-semibold text-white leading-tight">{notification.title}</p>
67
+ <p className="text-xs text-zinc-400 mt-0.5 leading-relaxed line-clamp-2">{notification.message}</p>
68
+ <p className="text-xs text-zinc-600 mt-1">{timeAgo(notification.created_at)}</p>
69
+ </div>
70
+ <button
71
+ onClick={(e) => { e.stopPropagation(); onDismiss(notification.id); }}
72
+ className="absolute top-2 right-2 p-0.5 rounded text-zinc-600 hover:text-zinc-400 transition-colors opacity-0 group-hover:opacity-100"
73
+ >
74
+ <X className="h-3 w-3" />
75
+ </button>
76
+ </motion.div>
77
+ );
78
+ }
79
+
80
+ // ─── Notification Panel ───────────────────────────────────────────────────────
81
+ export function NotificationPanel({
82
+ isOpen,
83
+ onClose,
84
+ }: {
85
+ isOpen: boolean;
86
+ onClose: () => void;
87
+ }) {
88
+ const [notifications, setNotifications] = useState<NotificationItem[]>([]);
89
+ const [unreadCount, setUnreadCount] = useState(0);
90
+ const [filter, setFilter] = useState<"all" | "unread">("all");
91
+ const [loading, setLoading] = useState(false);
92
+
93
+ const loadNotifications = useCallback(async () => {
94
+ setLoading(true);
95
+ try {
96
+ const res = await notificationsApi.list();
97
+ setNotifications(res.notifications);
98
+ setUnreadCount(res.unread_count);
99
+ } catch {
100
+ // backend offline — keep empty state
101
+ } finally {
102
+ setLoading(false);
103
+ }
104
+ }, []);
105
+
106
+ useEffect(() => {
107
+ if (isOpen) loadNotifications();
108
+ }, [isOpen, loadNotifications]);
109
+
110
+ const dismiss = async (id: string) => {
111
+ setNotifications((prev) => prev.filter((n) => n.id !== id));
112
+ try { await notificationsApi.dismiss(id); } catch { /* ignore */ }
113
+ };
114
+
115
+ const markRead = async (id: string) => {
116
+ setNotifications((prev) => prev.map((n) => n.id === id ? { ...n, read: true } : n));
117
+ setUnreadCount((c) => Math.max(0, c - 1));
118
+ try { await notificationsApi.markRead(id); } catch { /* ignore */ }
119
+ };
120
+
121
+ const markAllRead = async () => {
122
+ setNotifications((prev) => prev.map((n) => ({ ...n, read: true })));
123
+ setUnreadCount(0);
124
+ try { await notificationsApi.markAllRead(); } catch { /* ignore */ }
125
+ };
126
+
127
+ const displayed = filter === "unread" ? notifications.filter((n) => !n.read) : notifications;
128
+
129
+ return (
130
+ <AnimatePresence>
131
+ {isOpen && (
132
+ <>
133
+ <motion.div
134
+ initial={{ opacity: 0 }}
135
+ animate={{ opacity: 1 }}
136
+ exit={{ opacity: 0 }}
137
+ onClick={onClose}
138
+ className="fixed inset-0 z-40"
139
+ />
140
+ <motion.div
141
+ initial={{ opacity: 0, y: -10, scale: 0.97 }}
142
+ animate={{ opacity: 1, y: 0, scale: 1 }}
143
+ exit={{ opacity: 0, y: -10, scale: 0.97 }}
144
+ transition={{ duration: 0.2, ease: "easeOut" }}
145
+ className="absolute right-0 top-full mt-2 z-50 w-80 rounded-2xl border border-white/10 bg-zinc-950/95 backdrop-blur-2xl shadow-2xl shadow-black/50 overflow-hidden"
146
+ >
147
+ {/* Header */}
148
+ <div className="flex items-center justify-between border-b border-white/10 px-4 py-3">
149
+ <div className="flex items-center gap-2">
150
+ <Bell className="h-4 w-4 text-zinc-400" />
151
+ <span className="text-sm font-semibold text-white">Notifications</span>
152
+ {unreadCount > 0 && (
153
+ <span className="flex h-4 w-4 items-center justify-center rounded-full bg-blue-500 text-[10px] font-bold text-white">
154
+ {unreadCount}
155
+ </span>
156
+ )}
157
+ </div>
158
+ <div className="flex items-center gap-2">
159
+ <button onClick={loadNotifications} className="text-zinc-500 hover:text-zinc-300 transition-colors">
160
+ <RefreshCw className={`h-3.5 w-3.5 ${loading ? "animate-spin" : ""}`} />
161
+ </button>
162
+ {unreadCount > 0 && (
163
+ <button onClick={markAllRead} className="flex items-center gap-1 text-xs text-zinc-500 hover:text-zinc-300 transition-colors">
164
+ <CheckCheck className="h-3 w-3" />
165
+ All read
166
+ </button>
167
+ )}
168
+ <button onClick={onClose} className="text-zinc-500 hover:text-zinc-300 transition-colors">
169
+ <X className="h-4 w-4" />
170
+ </button>
171
+ </div>
172
+ </div>
173
+
174
+ {/* Filter tabs */}
175
+ <div className="flex gap-1 border-b border-white/10 px-4 py-2">
176
+ {(["all", "unread"] as const).map((f) => (
177
+ <button
178
+ key={f}
179
+ onClick={() => setFilter(f)}
180
+ className={`rounded-lg px-3 py-1 text-xs font-medium capitalize transition-all ${
181
+ filter === f ? "bg-white/10 text-white" : "text-zinc-500 hover:text-zinc-300"
182
+ }`}
183
+ >
184
+ {f} {f === "unread" && unreadCount > 0 && `(${unreadCount})`}
185
+ </button>
186
+ ))}
187
+ </div>
188
+
189
+ {/* List */}
190
+ <div className="max-h-96 overflow-y-auto p-3 space-y-2">
191
+ <AnimatePresence mode="popLayout">
192
+ {loading ? (
193
+ <div className="flex items-center justify-center py-8">
194
+ <RefreshCw className="h-5 w-5 text-zinc-600 animate-spin" />
195
+ </div>
196
+ ) : displayed.length === 0 ? (
197
+ <motion.div
198
+ initial={{ opacity: 0 }}
199
+ animate={{ opacity: 1 }}
200
+ className="flex flex-col items-center gap-2 py-8 text-center"
201
+ >
202
+ <Bell className="h-8 w-8 text-zinc-700" />
203
+ <p className="text-sm text-zinc-500">No notifications</p>
204
+ </motion.div>
205
+ ) : (
206
+ displayed.map((n) => (
207
+ <NotifItem key={n.id} notification={n} onDismiss={dismiss} onRead={markRead} />
208
+ ))
209
+ )}
210
+ </AnimatePresence>
211
+ </div>
212
+
213
+ <div className="border-t border-white/10 px-4 py-2.5">
214
+ <p className="text-center text-xs text-zinc-600">Real-time · AI-powered · Encrypted</p>
215
+ </div>
216
+ </motion.div>
217
+ </>
218
+ )}
219
+ </AnimatePresence>
220
+ );
221
+ }
222
+
223
+ // ─── Notification Bell ────────────────────────────────────────────────────────
224
+ export function NotificationBell() {
225
+ const [isOpen, setIsOpen] = useState(false);
226
+ const [unreadCount, setUnreadCount] = useState(0);
227
+
228
+ useEffect(() => {
229
+ notificationsApi.list().then((res) => setUnreadCount(res.unread_count)).catch(() => {});
230
+ }, []);
231
+
232
+ return (
233
+ <div className="relative">
234
+ <motion.button
235
+ whileHover={{ scale: 1.05 }}
236
+ whileTap={{ scale: 0.95 }}
237
+ onClick={() => setIsOpen((v) => !v)}
238
+ className="relative rounded-xl bg-white/5 p-2.5 text-zinc-400 hover:text-white hover:bg-white/10 transition-all duration-200 focus:outline-none"
239
+ >
240
+ <Bell className="h-5 w-5" aria-hidden="true" />
241
+ {unreadCount > 0 && (
242
+ <motion.span
243
+ initial={{ scale: 0 }}
244
+ animate={{ scale: 1 }}
245
+ className="absolute -top-0.5 -right-0.5 flex h-4 w-4 items-center justify-center rounded-full bg-red-500 text-[9px] font-bold text-white"
246
+ >
247
+ {unreadCount > 9 ? "9+" : unreadCount}
248
+ </motion.span>
249
+ )}
250
+ </motion.button>
251
+ <NotificationPanel isOpen={isOpen} onClose={() => setIsOpen(false)} />
252
+ </div>
253
+ );
254
+ }
frontend/src/components/ui/ComingSoon.tsx ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "use client";
2
+
3
+ import { motion } from "framer-motion";
4
+ import { Sparkles } from "lucide-react";
5
+
6
+ export function ComingSoon({ title, description }: { title: string; description?: string }) {
7
+ return (
8
+ <motion.div
9
+ initial={{ opacity: 0, y: 20 }}
10
+ animate={{ opacity: 1, y: 0 }}
11
+ transition={{ duration: 0.4 }}
12
+ className="flex flex-col items-center justify-center min-h-[60vh] gap-6 text-center"
13
+ >
14
+ <div className="relative">
15
+ <div className="absolute inset-0 rounded-full bg-emerald-500/20 blur-2xl scale-150" />
16
+ <div className="relative flex h-20 w-20 items-center justify-center rounded-2xl bg-gradient-to-br from-emerald-400/20 to-cyan-400/20 border border-emerald-500/20">
17
+ <Sparkles className="h-9 w-9 text-emerald-400" />
18
+ </div>
19
+ </div>
20
+ <div>
21
+ <h1 className="text-3xl font-bold text-white">{title}</h1>
22
+ <p className="text-zinc-400 mt-2 max-w-md">
23
+ {description || "This feature is being built with AI-native capabilities. Coming soon."}
24
+ </p>
25
+ </div>
26
+ <div className="flex items-center gap-2 rounded-xl border border-emerald-500/20 bg-emerald-500/5 px-4 py-2">
27
+ <div className="h-1.5 w-1.5 rounded-full bg-emerald-400 animate-pulse" />
28
+ <span className="text-xs text-emerald-400 font-medium">In Development</span>
29
+ </div>
30
+ </motion.div>
31
+ );
32
+ }
frontend/src/components/ui/avatar.tsx ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "use client";
2
+
3
+ import * as React from "react";
4
+ import { cn } from "@/lib/utils";
5
+
6
+ interface AvatarProps extends React.HTMLAttributes<HTMLDivElement> {
7
+ className?: string;
8
+ }
9
+
10
+ const Avatar = React.forwardRef<HTMLDivElement, AvatarProps>(
11
+ ({ className, ...props }, ref) => (
12
+ <div
13
+ ref={ref}
14
+ className={cn(
15
+ "relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",
16
+ className
17
+ )}
18
+ {...props}
19
+ />
20
+ )
21
+ );
22
+ Avatar.displayName = "Avatar";
23
+
24
+ interface AvatarImageProps extends React.ImgHTMLAttributes<HTMLImageElement> {
25
+ className?: string;
26
+ }
27
+
28
+ const AvatarImage = React.forwardRef<HTMLImageElement, AvatarImageProps>(
29
+ ({ className, src, alt = "", ...props }, ref) => {
30
+ const [error, setError] = React.useState(false);
31
+ if (error || !src) return null;
32
+ return (
33
+ // eslint-disable-next-line @next/next/no-img-element
34
+ <img
35
+ ref={ref}
36
+ src={src}
37
+ alt={alt}
38
+ onError={() => setError(true)}
39
+ className={cn("aspect-square h-full w-full object-cover", className)}
40
+ {...props}
41
+ />
42
+ );
43
+ }
44
+ );
45
+ AvatarImage.displayName = "AvatarImage";
46
+
47
+ interface AvatarFallbackProps extends React.HTMLAttributes<HTMLDivElement> {
48
+ className?: string;
49
+ }
50
+
51
+ const AvatarFallback = React.forwardRef<HTMLDivElement, AvatarFallbackProps>(
52
+ ({ className, ...props }, ref) => (
53
+ <div
54
+ ref={ref}
55
+ className={cn(
56
+ "flex h-full w-full items-center justify-center rounded-full bg-zinc-800 text-zinc-400",
57
+ className
58
+ )}
59
+ {...props}
60
+ />
61
+ )
62
+ );
63
+ AvatarFallback.displayName = "AvatarFallback";
64
+
65
+ export { Avatar, AvatarImage, AvatarFallback };
frontend/src/components/ui/button.tsx ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import * as React from "react"
2
+ import { cva, type VariantProps } from "class-variance-authority"
3
+ import { Slot } from "radix-ui"
4
+
5
+ import { cn } from "@/lib/utils"
6
+
7
+ const buttonVariants = cva(
8
+ "group/button inline-flex shrink-0 items-center justify-center rounded-lg border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap transition-all outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:not-aria-[haspopup]:translate-y-px disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
9
+ {
10
+ variants: {
11
+ variant: {
12
+ default: "bg-primary text-primary-foreground [a]:hover:bg-primary/80",
13
+ outline:
14
+ "border-border bg-background hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",
15
+ secondary:
16
+ "bg-secondary text-secondary-foreground hover:bg-secondary/80 aria-expanded:bg-secondary aria-expanded:text-secondary-foreground",
17
+ ghost:
18
+ "hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:hover:bg-muted/50",
19
+ destructive:
20
+ "bg-destructive/10 text-destructive hover:bg-destructive/20 focus-visible:border-destructive/40 focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:hover:bg-destructive/30 dark:focus-visible:ring-destructive/40",
21
+ link: "text-primary underline-offset-4 hover:underline",
22
+ },
23
+ size: {
24
+ default:
25
+ "h-8 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",
26
+ xs: "h-6 gap-1 rounded-[min(var(--radius-md),10px)] px-2 text-xs in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3",
27
+ sm: "h-7 gap-1 rounded-[min(var(--radius-md),12px)] px-2.5 text-[0.8rem] in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3.5",
28
+ lg: "h-9 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",
29
+ icon: "size-8",
30
+ "icon-xs":
31
+ "size-6 rounded-[min(var(--radius-md),10px)] in-data-[slot=button-group]:rounded-lg [&_svg:not([class*='size-'])]:size-3",
32
+ "icon-sm":
33
+ "size-7 rounded-[min(var(--radius-md),12px)] in-data-[slot=button-group]:rounded-lg",
34
+ "icon-lg": "size-9",
35
+ },
36
+ },
37
+ defaultVariants: {
38
+ variant: "default",
39
+ size: "default",
40
+ },
41
+ }
42
+ )
43
+
44
+ function Button({
45
+ className,
46
+ variant = "default",
47
+ size = "default",
48
+ asChild = false,
49
+ ...props
50
+ }: React.ComponentProps<"button"> &
51
+ VariantProps<typeof buttonVariants> & {
52
+ asChild?: boolean
53
+ }) {
54
+ const Comp = asChild ? Slot.Root : "button"
55
+
56
+ return (
57
+ <Comp
58
+ data-slot="button"
59
+ data-variant={variant}
60
+ data-size={size}
61
+ className={cn(buttonVariants({ variant, size, className }))}
62
+ {...props}
63
+ />
64
+ )
65
+ }
66
+
67
+ export { Button, buttonVariants }
frontend/src/lib/api.ts ADDED
@@ -0,0 +1,273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * BankBot API client — typed fetch wrapper for all backend endpoints.
3
+ * Handles auth headers, token refresh, and error normalization.
4
+ *
5
+ * HF Spaces mode: when NEXT_PUBLIC_API_URL is empty, all /api/* calls
6
+ * go to the same origin — Nginx routes them to FastAPI internally.
7
+ * WebSocket also uses the same origin with ws:// or wss://.
8
+ */
9
+
10
+ // In HF mode NEXT_PUBLIC_API_URL is "" — use empty string so fetch uses same origin
11
+ const API_BASE = process.env.NEXT_PUBLIC_API_URL || "";
12
+
13
+ // ─── WebSocket URL derivation ─────────────────────────────────────────────────
14
+ // HF mode (API_BASE=""): derive from window.location at runtime
15
+ // External mode: convert http→ws, https→wss
16
+ function getWsBase(): string {
17
+ if (typeof window === "undefined") return "";
18
+ if (!API_BASE) {
19
+ // Same-origin WebSocket — use current page protocol
20
+ const proto = window.location.protocol === "https:" ? "wss:" : "ws:";
21
+ return `${proto}//${window.location.host}`;
22
+ }
23
+ return API_BASE.replace(/^https/, "wss").replace(/^http/, "ws");
24
+ }
25
+
26
+ // ─── Token management (browser-only) ─────────────────────────────────────────
27
+ export const tokenStore = {
28
+ getAccess: (): string | null =>
29
+ typeof window !== "undefined" ? localStorage.getItem("bb_access_token") : null,
30
+ getRefresh: (): string | null =>
31
+ typeof window !== "undefined" ? localStorage.getItem("bb_refresh_token") : null,
32
+ setTokens: (access: string, refresh?: string) => {
33
+ if (typeof window === "undefined") return;
34
+ localStorage.setItem("bb_access_token", access);
35
+ if (refresh) localStorage.setItem("bb_refresh_token", refresh);
36
+ },
37
+ clear: () => {
38
+ if (typeof window === "undefined") return;
39
+ localStorage.removeItem("bb_access_token");
40
+ localStorage.removeItem("bb_refresh_token");
41
+ localStorage.removeItem("bb_user");
42
+ },
43
+ };
44
+
45
+ // ─── Core fetch wrapper ───────────────────────────────────────────────────────
46
+ async function apiFetch<T>(
47
+ path: string,
48
+ options: RequestInit = {},
49
+ retry = true
50
+ ): Promise<T> {
51
+ const token = tokenStore.getAccess();
52
+ const headers: Record<string, string> = {
53
+ "Content-Type": "application/json",
54
+ ...(options.headers as Record<string, string>),
55
+ };
56
+ if (token) headers["Authorization"] = `Bearer ${token}`;
57
+
58
+ const res = await fetch(`${API_BASE}${path}`, { ...options, headers });
59
+
60
+ // Auto-refresh on 401
61
+ if (res.status === 401 && retry) {
62
+ const refreshToken = tokenStore.getRefresh();
63
+ if (refreshToken) {
64
+ try {
65
+ const refreshRes = await fetch(`${API_BASE}/api/auth/refresh`, {
66
+ method: "POST",
67
+ headers: { "Content-Type": "application/json" },
68
+ body: JSON.stringify({ refresh_token: refreshToken }),
69
+ });
70
+ if (refreshRes.ok) {
71
+ const data = await refreshRes.json();
72
+ tokenStore.setTokens(data.access_token);
73
+ return apiFetch<T>(path, options, false);
74
+ }
75
+ } catch {
76
+ // refresh failed — clear tokens
77
+ }
78
+ }
79
+ tokenStore.clear();
80
+ throw new ApiError(401, "Session expired. Please log in again.");
81
+ }
82
+
83
+ if (!res.ok) {
84
+ let detail = `HTTP ${res.status}`;
85
+ try {
86
+ const err = await res.json();
87
+ detail = err.detail || detail;
88
+ } catch { /* ignore */ }
89
+ throw new ApiError(res.status, detail);
90
+ }
91
+
92
+ return res.json() as Promise<T>;
93
+ }
94
+
95
+ export class ApiError extends Error {
96
+ constructor(public status: number, message: string) {
97
+ super(message);
98
+ this.name = "ApiError";
99
+ }
100
+ }
101
+
102
+ // ─── Auth ─────────────────────────────────────────────────────────────────────
103
+ export interface LoginResponse {
104
+ access_token: string;
105
+ refresh_token: string;
106
+ token_type: string;
107
+ user_id: string;
108
+ name: string;
109
+ email: string;
110
+ }
111
+
112
+ export const authApi = {
113
+ login: (email: string, password: string) => {
114
+ const form = new URLSearchParams({ username: email, password });
115
+ return apiFetch<LoginResponse>("/api/auth/login", {
116
+ method: "POST",
117
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
118
+ body: form.toString(),
119
+ });
120
+ },
121
+ register: (email: string, password: string, name: string) =>
122
+ apiFetch<LoginResponse>("/api/auth/register", {
123
+ method: "POST",
124
+ body: JSON.stringify({ email, password, name }),
125
+ }),
126
+ me: () => apiFetch<{ user_id: string; email: string; name: string; financial_personality: string }>("/api/auth/me"),
127
+ logout: () => {
128
+ tokenStore.clear();
129
+ return Promise.resolve();
130
+ },
131
+ };
132
+
133
+ // ─── Dashboard ─────────────���──────────────────────────────────────────────────
134
+ export interface DashboardOverview {
135
+ total_balance: number;
136
+ accounts: Array<{ id: string; type: string; balance: number; currency: string }>;
137
+ monthly_income: number;
138
+ monthly_expenses: number;
139
+ savings_rate: number;
140
+ spending_by_category: Array<{ name: string; value: number }>;
141
+ recent_transactions: Array<{
142
+ id: string; merchant: string; category: string;
143
+ amount: number; type: string; timestamp: string;
144
+ }>;
145
+ cash_flow: Array<{ month: string; income: number; expenses: number; savings: number }>;
146
+ health_score: number;
147
+ fraud_alert_count: number;
148
+ ai_briefing: { summary?: string; briefing?: string; insights?: string[] };
149
+ }
150
+
151
+ export const dashboardApi = {
152
+ overview: (userId?: string) => {
153
+ const qs = userId ? `?user_id=${userId}` : "";
154
+ return apiFetch<DashboardOverview>(`/api/dashboard/overview${qs}`);
155
+ },
156
+ };
157
+
158
+ // ─── AI ───────────────────────────────────────────────────────────────────────
159
+ export interface HealthScore {
160
+ overall_score: number;
161
+ categories: Record<string, { score: number; max: number; label: string }>;
162
+ }
163
+
164
+ export interface ForecastResult {
165
+ monthly_projections?: Array<{ month: number; balance: number; savings: number }>;
166
+ scenarios?: { conservative: number; expected: number; optimistic: number };
167
+ }
168
+
169
+ export const aiApi = {
170
+ healthScore: (userId?: string) => {
171
+ const qs = userId ? `?user_id=${userId}` : "";
172
+ return apiFetch<HealthScore>(`/api/ai/coaching/score${qs}`);
173
+ },
174
+ briefing: (userId?: string) => {
175
+ const qs = userId ? `?user_id=${userId}` : "";
176
+ return apiFetch<{ summary: string; insights: string[] }>(`/api/ai/coaching/briefing${qs}`);
177
+ },
178
+ behaviorInsights: (userId?: string) => {
179
+ const qs = userId ? `?user_id=${userId}` : "";
180
+ return apiFetch<{ insights: string[]; metrics: Record<string, number> }>(`/api/ai/behavior/insights${qs}`);
181
+ },
182
+ twinPredict: (userId?: string) => {
183
+ const qs = userId ? `?user_id=${userId}` : "";
184
+ return apiFetch<ForecastResult>(`/api/ai/twin/predict${qs}`);
185
+ },
186
+ twinFuture: (months = 12, userId?: string) => {
187
+ const qs = new URLSearchParams({ months: String(months), ...(userId ? { user_id: userId } : {}) });
188
+ return apiFetch<ForecastResult>(`/api/ai/twin/future?${qs}`);
189
+ },
190
+ twinScenarios: (months = 6, userId?: string) => {
191
+ const qs = new URLSearchParams({ months: String(months), ...(userId ? { user_id: userId } : {}) });
192
+ return apiFetch<{ scenarios: Record<string, number[]> }>(`/api/ai/twin/scenarios?${qs}`);
193
+ },
194
+ fraudAnalysis: (userId?: string) => {
195
+ const qs = userId ? `?user_id=${userId}` : "";
196
+ return apiFetch<{ alerts: Array<{ id: string; risk_score: number; details: string }> }>(`/api/ai/fraud/analysis${qs}`);
197
+ },
198
+ subscriptions: (userId?: string) => {
199
+ const qs = userId ? `?user_id=${userId}` : "";
200
+ return apiFetch<{ subscriptions: Array<{ merchant: string; amount: number; recommendation: string }> }>(`/api/ai/subscriptions/optimize${qs}`);
201
+ },
202
+ chat: (message: string, userId?: string) => {
203
+ const qs = userId ? `?user_id=${userId}` : "";
204
+ return apiFetch<{ response: string }>(`/api/ai/chat${qs}`, {
205
+ method: "POST",
206
+ body: JSON.stringify({ message }),
207
+ });
208
+ },
209
+ simulatePurchase: (amount: number, merchant: string, category: string, userId?: string) => {
210
+ const qs = userId ? `?user_id=${userId}` : "";
211
+ return apiFetch<Record<string, unknown>>(`/api/ai/simulate/purchase${qs}`, {
212
+ method: "POST",
213
+ body: JSON.stringify({ amount, merchant, category }),
214
+ });
215
+ },
216
+ };
217
+
218
+ // ─── Notifications ────────────────────────────────────────────────────────────
219
+ export interface NotificationItem {
220
+ id: string;
221
+ title: string;
222
+ message: string;
223
+ type: "alert" | "insight" | "warning" | string;
224
+ read: boolean;
225
+ created_at: string;
226
+ }
227
+
228
+ export const notificationsApi = {
229
+ list: (userId?: string) => {
230
+ const qs = userId ? `?user_id=${userId}` : "";
231
+ return apiFetch<{ notifications: NotificationItem[]; unread_count: number }>(`/api/notifications/${qs}`);
232
+ },
233
+ markRead: (id: string, userId?: string) => {
234
+ const qs = userId ? `?user_id=${userId}` : "";
235
+ return apiFetch<{ success: boolean }>(`/api/notifications/${id}/read${qs}`, { method: "PATCH" });
236
+ },
237
+ markAllRead: (userId?: string) => {
238
+ const qs = userId ? `?user_id=${userId}` : "";
239
+ return apiFetch<{ success: boolean }>(`/api/notifications/read-all${qs}`, { method: "PATCH" });
240
+ },
241
+ dismiss: (id: string, userId?: string) => {
242
+ const qs = userId ? `?user_id=${userId}` : "";
243
+ return apiFetch<{ success: boolean }>(`/api/notifications/${id}${qs}`, { method: "DELETE" });
244
+ },
245
+ };
246
+
247
+ // ─── Transactions ─────────────────────────────────────────────────────────────
248
+ export const transactionsApi = {
249
+ list: (params: { page?: number; limit?: number; category?: string; type?: string; userId?: string } = {}) => {
250
+ const qs = new URLSearchParams();
251
+ if (params.page) qs.set("page", String(params.page));
252
+ if (params.limit) qs.set("limit", String(params.limit));
253
+ if (params.category) qs.set("category", params.category);
254
+ if (params.type) qs.set("type", params.type);
255
+ if (params.userId) qs.set("user_id", params.userId);
256
+ return apiFetch<{
257
+ transactions: Array<{ id: string; merchant: string; category: string; amount: number; type: string; timestamp: string }>;
258
+ total: number; page: number; pages: number;
259
+ }>(`/api/transactions/?${qs}`);
260
+ },
261
+ };
262
+
263
+ // ─── WebSocket factory ────────────────────────────────────────────────────────
264
+ export function createChatWebSocket(userId?: string): WebSocket {
265
+ const wsBase = getWsBase();
266
+ const qs = userId ? `?user_id=${userId}` : "";
267
+ return new WebSocket(`${wsBase}/api/ai/chat/ws${qs}`);
268
+ }
269
+
270
+ // ─── Status ───────────────────────────────────────────────────────────────────
271
+ export const statusApi = {
272
+ check: () => apiFetch<{ ai_backend: string; ai_available: boolean; db_type: string; cache_type: string }>("/api/status"),
273
+ };
frontend/src/lib/hooks/useWebSocketChat.ts ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * WebSocket chat hook — manages connection lifecycle, reconnection,
3
+ * heartbeat, and streaming message assembly.
4
+ */
5
+ "use client";
6
+
7
+ import { useCallback, useEffect, useRef, useState } from "react";
8
+ import { createChatWebSocket } from "@/lib/api";
9
+
10
+ export type WsStatus = "connecting" | "connected" | "disconnected" | "error";
11
+
12
+ interface UseWebSocketChatOptions {
13
+ userId?: string;
14
+ onChunk: (chunk: string) => void;
15
+ onStart: () => void;
16
+ onEnd: () => void;
17
+ onError: (msg: string) => void;
18
+ }
19
+
20
+ export function useWebSocketChat({
21
+ userId,
22
+ onChunk,
23
+ onStart,
24
+ onEnd,
25
+ onError,
26
+ }: UseWebSocketChatOptions) {
27
+ const wsRef = useRef<WebSocket | null>(null);
28
+ const [status, setStatus] = useState<WsStatus>("disconnected");
29
+ const reconnectTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
30
+ const heartbeatTimer = useRef<ReturnType<typeof setInterval> | null>(null);
31
+ const reconnectAttempts = useRef(0);
32
+ const MAX_RECONNECT = 5;
33
+ const isMounted = useRef(true);
34
+
35
+ const clearTimers = () => {
36
+ if (reconnectTimer.current) clearTimeout(reconnectTimer.current);
37
+ if (heartbeatTimer.current) clearInterval(heartbeatTimer.current);
38
+ };
39
+
40
+ const startHeartbeat = (ws: WebSocket) => {
41
+ heartbeatTimer.current = setInterval(() => {
42
+ if (ws.readyState === WebSocket.OPEN) {
43
+ ws.send(JSON.stringify({ type: "ping" }));
44
+ }
45
+ }, 25000); // ping every 25s
46
+ };
47
+
48
+ const connect = useCallback(() => {
49
+ if (!isMounted.current) return;
50
+ if (wsRef.current?.readyState === WebSocket.OPEN) return;
51
+
52
+ setStatus("connecting");
53
+ const ws = createChatWebSocket(userId);
54
+ wsRef.current = ws;
55
+
56
+ ws.onopen = () => {
57
+ if (!isMounted.current) return;
58
+ setStatus("connected");
59
+ reconnectAttempts.current = 0;
60
+ startHeartbeat(ws);
61
+ };
62
+
63
+ ws.onmessage = (event) => {
64
+ if (!isMounted.current) return;
65
+ try {
66
+ const msg = JSON.parse(event.data);
67
+ switch (msg.type) {
68
+ case "chat_start":
69
+ onStart();
70
+ break;
71
+ case "chat_chunk":
72
+ if (msg.content) onChunk(msg.content);
73
+ break;
74
+ case "chat_end":
75
+ onEnd();
76
+ break;
77
+ case "pong":
78
+ break; // heartbeat ack
79
+ case "error":
80
+ onError(msg.message || "Unknown error");
81
+ break;
82
+ }
83
+ } catch {
84
+ // ignore malformed messages
85
+ }
86
+ };
87
+
88
+ ws.onerror = () => {
89
+ if (!isMounted.current) return;
90
+ setStatus("error");
91
+ };
92
+
93
+ ws.onclose = (event) => {
94
+ if (!isMounted.current) return;
95
+ clearTimers();
96
+ setStatus("disconnected");
97
+
98
+ // Reconnect with exponential backoff (unless intentional close)
99
+ if (event.code !== 1000 && reconnectAttempts.current < MAX_RECONNECT) {
100
+ const delay = Math.min(1000 * 2 ** reconnectAttempts.current, 30000);
101
+ reconnectAttempts.current++;
102
+ reconnectTimer.current = setTimeout(connect, delay);
103
+ }
104
+ };
105
+ }, [userId, onChunk, onStart, onEnd, onError]);
106
+
107
+ const disconnect = useCallback(() => {
108
+ isMounted.current = false;
109
+ clearTimers();
110
+ if (wsRef.current) {
111
+ wsRef.current.close(1000, "Component unmounted");
112
+ wsRef.current = null;
113
+ }
114
+ }, []);
115
+
116
+ const sendMessage = useCallback((message: string) => {
117
+ if (wsRef.current?.readyState === WebSocket.OPEN) {
118
+ wsRef.current.send(JSON.stringify({ type: "chat", message }));
119
+ return true;
120
+ }
121
+ return false;
122
+ }, []);
123
+
124
+ useEffect(() => {
125
+ isMounted.current = true;
126
+ connect();
127
+ return () => {
128
+ disconnect();
129
+ };
130
+ }, [connect, disconnect]);
131
+
132
+ return { status, sendMessage, reconnect: connect };
133
+ }
frontend/src/lib/stores/authStore.ts ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Auth store — manages JWT tokens, user session, login/logout.
3
+ */
4
+ import { create } from "zustand";
5
+ import { persist } from "zustand/middleware";
6
+ import { authApi, tokenStore, LoginResponse } from "@/lib/api";
7
+
8
+ interface User {
9
+ user_id: string;
10
+ email: string;
11
+ name: string;
12
+ financial_personality?: string;
13
+ }
14
+
15
+ interface AuthState {
16
+ user: User | null;
17
+ isAuthenticated: boolean;
18
+ isLoading: boolean;
19
+ error: string | null;
20
+
21
+ login: (email: string, password: string) => Promise<void>;
22
+ register: (email: string, password: string, name: string) => Promise<void>;
23
+ logout: () => void;
24
+ restoreSession: () => Promise<void>;
25
+ clearError: () => void;
26
+ }
27
+
28
+ export const useAuthStore = create<AuthState>()(
29
+ persist(
30
+ (set) => ({
31
+ user: null,
32
+ isAuthenticated: false,
33
+ isLoading: false,
34
+ error: null,
35
+
36
+ login: async (email, password) => {
37
+ set({ isLoading: true, error: null });
38
+ try {
39
+ const res: LoginResponse = await authApi.login(email, password);
40
+ tokenStore.setTokens(res.access_token, res.refresh_token);
41
+ set({
42
+ user: { user_id: res.user_id, email: res.email, name: res.name },
43
+ isAuthenticated: true,
44
+ isLoading: false,
45
+ });
46
+ } catch (err) {
47
+ set({ error: (err as Error).message, isLoading: false });
48
+ throw err;
49
+ }
50
+ },
51
+
52
+ register: async (email, password, name) => {
53
+ set({ isLoading: true, error: null });
54
+ try {
55
+ const res: LoginResponse = await authApi.register(email, password, name);
56
+ tokenStore.setTokens(res.access_token, res.refresh_token);
57
+ set({
58
+ user: { user_id: res.user_id, email: res.email, name: res.name },
59
+ isAuthenticated: true,
60
+ isLoading: false,
61
+ });
62
+ } catch (err) {
63
+ set({ error: (err as Error).message, isLoading: false });
64
+ throw err;
65
+ }
66
+ },
67
+
68
+ logout: () => {
69
+ tokenStore.clear();
70
+ set({ user: null, isAuthenticated: false, error: null });
71
+ },
72
+
73
+ restoreSession: async () => {
74
+ const token = tokenStore.getAccess();
75
+ if (!token) return;
76
+ try {
77
+ const me = await authApi.me();
78
+ set({ user: me, isAuthenticated: true });
79
+ } catch {
80
+ tokenStore.clear();
81
+ set({ user: null, isAuthenticated: false });
82
+ }
83
+ },
84
+
85
+ clearError: () => set({ error: null }),
86
+ }),
87
+ {
88
+ name: "bb_auth",
89
+ partialize: (state) => ({ user: state.user, isAuthenticated: state.isAuthenticated }),
90
+ }
91
+ )
92
+ );
frontend/src/lib/stores/dashboardStore.ts ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Dashboard store — fetches and caches dashboard overview data.
3
+ */
4
+ import { create } from "zustand";
5
+ import { dashboardApi, DashboardOverview } from "@/lib/api";
6
+
7
+ interface DashboardState {
8
+ data: DashboardOverview | null;
9
+ isLoading: boolean;
10
+ error: string | null;
11
+ lastFetched: number | null;
12
+
13
+ fetch: (userId?: string, force?: boolean) => Promise<void>;
14
+ reset: () => void;
15
+ }
16
+
17
+ const CACHE_TTL = 2 * 60 * 1000; // 2 minutes
18
+
19
+ export const useDashboardStore = create<DashboardState>((set, get) => ({
20
+ data: null,
21
+ isLoading: false,
22
+ error: null,
23
+ lastFetched: null,
24
+
25
+ fetch: async (userId, force = false) => {
26
+ const { lastFetched, isLoading } = get();
27
+ if (isLoading) return;
28
+ if (!force && lastFetched && Date.now() - lastFetched < CACHE_TTL) return;
29
+
30
+ set({ isLoading: true, error: null });
31
+ try {
32
+ const data = await dashboardApi.overview(userId);
33
+ set({ data, isLoading: false, lastFetched: Date.now() });
34
+ } catch (err) {
35
+ set({ error: (err as Error).message, isLoading: false });
36
+ }
37
+ },
38
+
39
+ reset: () => set({ data: null, isLoading: false, error: null, lastFetched: null }),
40
+ }));
frontend/src/lib/utils.ts ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ import { clsx, type ClassValue } from "clsx"
2
+ import { twMerge } from "tailwind-merge"
3
+
4
+ export function cn(...inputs: ClassValue[]) {
5
+ return twMerge(clsx(inputs))
6
+ }