Spaces:
Sleeping
Sleeping
Commit ·
c004697
1
Parent(s): 465a24c
feat: AI Coach Mode, Fraud Explanations, Monthly Narrative — 3 new intelligence features
Browse filesFiles changed (6)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482"""AI Intelligence Engine — three high-value features: 1. Financial Coach Mode — proactive weekly recommendations, nudges, anomaly explanations 2. Fraud Explanation — human-readable AI explanation of why a transaction was flagged 3. Spending Narrative — monthly story: what changed, what improved, what to watch"""import osfrom datetime import datetime, timedeltafrom collections import defaultdictfrom sqlalchemy.orm import Session
from app.database.models import ( User, Account, Transaction, Goal, Investment, Subscription, FraudLog, Notification)from app.ai.coaching import calculate_financial_health_scorefrom app.ai.forecasting import get_cashflow_metrics
# ─── Shared Groq/OpenAI caller ────────────────────────────────────────────────
def _call_llm(messages: list, max_tokens: int = 500) -> str | None: """ Calls OpenAI → Groq in priority order with the exact messages list provided. Returns None if both fail. """ openai_key = os.environ.get("OPENAI_API_KEY", "") groq_key = os.environ.get("GROQ_API_KEY", "") or os.environ.get("GROQ_KEY", "")
if openai_key: try: from openai import OpenAI client = OpenAI(api_key=openai_key) res = client.chat.completions.create( model="gpt-4o-mini", messages=messages, temperature=0.2, max_tokens=max_tokens, ) return res.choices[0].message.content.strip() except Exception as e: print(f"[intelligence] OpenAI error: {e}")
if groq_key: try: from groq import Groq client = Groq(api_key=groq_key) res = client.chat.completions.create( model="llama-3.3-70b-versatile", messages=messages, temperature=0.2, max_tokens=max_tokens, ) return res.choices[0].message.content.strip() except Exception as e: print(f"[intelligence] Groq error: {e}")
return None
# ─── 1. FINANCIAL COACH MODE ──────────────────────────────────────────────────
def generate_weekly_coaching(db: Session, user_id: str) -> dict: """ Generates a proactive weekly coaching report with: - Weekly summary (what happened this week) - Budget coaching (where money went vs targets) - Savings nudge (specific, actionable) - Anomaly explanations (unusual patterns this week) - Top 3 recommendations """ user = db.query(User).filter(User.id == user_id).first() if not user: return {"error": "User not found"}
# ── Gather this week's data ─────────────────────────────────────────────── now = datetime.utcnow() week_start = now - timedelta(days=7)
accounts = db.query(Account).filter(Account.user_id == user_id).all() account_ids = [a.id for a in accounts] total_balance = sum(a.balance for a in accounts) savings_balance = sum(a.balance for a in accounts if a.type == "savings")
week_txns = ( db.query(Transaction) .filter( Transaction.account_id.in_(account_ids), Transaction.timestamp >= week_start, ) .all() ) if account_ids else []
week_spend = sum(t.amount for t in week_txns if t.type == "debit") week_income = sum(t.amount for t in week_txns if t.type == "credit")
# Category breakdown this week cat_spend: dict = defaultdict(float) for t in week_txns: if t.type == "debit": cat_spend[t.category or "Other"] += t.amount top_cats = sorted(cat_spend.items(), key=lambda x: x[1], reverse=True)[:5]
# Compare to prior week prior_start = week_start - timedelta(days=7) prior_txns = ( db.query(Transaction) .filter( Transaction.account_id.in_(account_ids), Transaction.timestamp >= prior_start, Transaction.timestamp < week_start, ) .all() ) if account_ids else [] prior_spend = sum(t.amount for t in prior_txns if t.type == "debit") spend_delta_pct = ((week_spend - prior_spend) / max(prior_spend, 1)) * 100
# Goals progress goals = db.query(Goal).filter(Goal.user_id == user_id).all() goals_summary = [ f"{g.title}: ${g.current_amount:,.0f}/${g.target_amount:,.0f} " f"({g.current_amount/max(g.target_amount,1)*100:.0f}%)" for g in goals ]
# Health score score_data = calculate_financial_health_score(db, user_id) health_score = score_data.get("overall_score", 50) improvements = score_data.get("actionable_improvements", [])
# Anomalies this week anomalies = [] if week_txns: all_amounts = [t.amount for t in week_txns if t.type == "debit"] if all_amounts: import numpy as np avg = float(np.mean(all_amounts)) for t in week_txns: if t.type == "debit" and t.amount > avg * 3: anomalies.append( f"${t.amount:,.2f} at {t.merchant or 'Unknown'} " f"({(t.amount/avg):.1f}× your weekly average)" )
# Late-night count late_night = [ t for t in week_txns if t.type == "debit" and (t.timestamp.hour >= 23 or t.timestamp.hour < 4) ]
# ── Build LLM prompt ────────────────────────────────────────────────────── system = ( "You are a personal AI financial coach. You have access to the user's real financial data. " "Be specific, use exact numbers, and give actionable advice. " "Never be generic. Format your response with clear sections." )
user_prompt = f"""Generate a weekly financial coaching report for {user.profile_data.get('name', 'the user')}.
FINANCIAL DATA:- Total Balance: ${total_balance:,.2f} (Savings: ${savings_balance:,.2f})- Health Score: {health_score:.0f}/100- This Week Spending: ${week_spend:,.2f} ({spend_delta_pct:+.1f}% vs last week)- This Week Income: ${week_income:,.2f}- Top Spending Categories: {', '.join(f'{c}: ${a:,.0f}' for c, a in top_cats)}- Goals: {'; '.join(goals_summary) if goals_summary else 'None set'}- Anomalies: {'; '.join(anomalies) if anomalies else 'None detected'}- Late-night transactions: {len(late_night)}- Key improvements needed: {'; '.join(improvements[:2]) if improvements else 'None'}
Write a coaching report with these exact sections:1. WEEKLY SUMMARY (2 sentences, use exact dollar figures)2. BUDGET COACHING (what's on track, what's overspent — use real category names and amounts)3. SAVINGS NUDGE (one specific, actionable savings recommendation with a dollar target)4. ANOMALY ALERT (explain any unusual spending in plain English, or say "No anomalies this week")5. TOP 3 ACTIONS (numbered list, each under 15 words, specific and actionable)
Be direct. No filler phrases."""
messages = [ {"role": "system", "content": system}, {"role": "user", "content": user_prompt}, ]
coaching_text = _call_llm(messages, max_tokens=600)
if not coaching_text: # Rule-based fallback direction = "up" if spend_delta_pct > 0 else "down" coaching_text = ( f"WEEKLY SUMMARY\nYou spent ${week_spend:,.2f} this week, " f"{abs(spend_delta_pct):.0f}% {direction} from last week. " f"Your balance stands at ${total_balance:,.2f}.\n\n" f"BUDGET COACHING\nTop category: {top_cats[0][0] if top_cats else 'N/A'} " f"(${top_cats[0][1]:,.2f} if top_cats else '$0').\n\n" f"SAVINGS NUDGE\nTransfer ${min(week_income * 0.1, 200):,.0f} to savings this week.\n\n" f"ANOMALY ALERT\n{'Unusual: ' + anomalies[0] if anomalies else 'No anomalies this week.'}\n\n" f"TOP 3 ACTIONS\n" + "\n".join(f"{i+1}. {imp}" for i, imp in enumerate(improvements[:3])) )
return { "generated_at": now.isoformat(), "week_start": week_start.date().isoformat(), "week_end": now.date().isoformat(), "health_score": health_score, "week_spend": round(week_spend, 2), "week_income": round(week_income, 2), "spend_delta_pct": round(spend_delta_pct, 1), "top_categories": [{"name": c, "amount": round(a, 2)} for c, a in top_cats], "anomalies": anomalies, "coaching_report": coaching_text, "improvements": improvements[:3], }
# ─── 2. AI FRAUD EXPLANATION ──────────────────────────────────────────────────
def explain_fraud_alert(db: Session, fraud_log_id: str) -> dict: """ Generates a human-readable AI explanation of exactly why a transaction was flagged, with context about the user's normal patterns. """ fraud_log = db.query(FraudLog).filter(FraudLog.id == fraud_log_id).first() if not fraud_log: return {"error": "Fraud log not found"}
txn = fraud_log.transaction if not txn: return {"error": "Transaction not found"}
account = db.query(Account).filter(Account.id == txn.account_id).first() if not account: return {"error": "Account not found"}
user_id = account.user_id
# Get user's historical baseline history = ( db.query(Transaction) .filter( Transaction.account_id == txn.account_id, Transaction.type == "debit", Transaction.id != txn.id, ) .order_by(Transaction.timestamp.desc()) .limit(30) .all() )
import numpy as np avg_amount = float(np.mean([t.amount for t in history])) if history else 0 typical_hour = "daytime" if txn.timestamp.hour >= 23 or txn.timestamp.hour < 4: typical_hour = f"{txn.timestamp.strftime('%I:%M %p')} (late night)" else: typical_hour = txn.timestamp.strftime("%I:%M %p")
risk_pct = round(fraud_log.risk_score * 100) raw_reasons = fraud_log.suspicious_activity_details or ""
system = ( "You are a fraud analyst AI. Explain in plain English why this transaction was flagged. " "Be specific, cite exact numbers, and help the user understand the risk. " "Write 2-3 sentences maximum. Do not use bullet points." )
user_prompt = f"""Explain why this transaction was flagged as suspicious:
Transaction: ${txn.amount:,.2f} at {txn.merchant or 'Unknown merchant'}Time: {typical_hour}Risk Score: {risk_pct}/100Detection reasons: {raw_reasons}User's average transaction: ${avg_amount:,.2f}Amount vs average: {txn.amount/max(avg_amount,1):.1f}×
Write a clear, human-readable explanation of why this was flagged. Start with "This payment was flagged because..." and be specific."""
messages = [ {"role": "system", "content": system}, {"role": "user", "content": user_prompt}, ]
explanation = _call_llm(messages, max_tokens=150)
if not explanation: # Rule-based fallback parts = [] if txn.amount > avg_amount * 2: parts.append( f"the amount (${txn.amount:,.2f}) is {txn.amount/max(avg_amount,1):.1f}× " f"your typical transaction of ${avg_amount:,.2f}" ) if txn.timestamp.hour >= 23 or txn.timestamp.hour < 4: parts.append(f"it occurred at {txn.timestamp.strftime('%I:%M %p')} (unusual hours)") if not parts: parts = [raw_reasons or "multiple anomaly signals were detected simultaneously"] explanation = f"This payment was flagged because {' and '.join(parts)}."
return { "fraud_log_id": fraud_log_id, "transaction_id": txn.id, "merchant": txn.merchant, "amount": txn.amount, "timestamp": txn.timestamp.isoformat(), "risk_score": risk_pct, "raw_reasons": raw_reasons.split("; ") if raw_reasons else [], "ai_explanation": explanation, "user_avg_amount": round(avg_amount, 2), "amount_vs_avg": round(txn.amount / max(avg_amount, 1), 1), }
# ─── 3. SPENDING NARRATIVE ────────────────────────────────────────────────────
def generate_spending_narrative(db: Session, user_id: str) -> dict: """ Generates a monthly spending narrative: - What changed vs last month (category-level) - Investment performance insight - Savings performance - Subscription waste analysis - One-paragraph human story of the month """ user = db.query(User).filter(User.id == user_id).first() if not user: return {"error": "User not found"}
now = datetime.utcnow() month_start = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0) last_month_start = (month_start - timedelta(days=1)).replace(day=1)
accounts = db.query(Account).filter(Account.user_id == user_id).all() account_ids = [a.id for a in accounts]
def get_category_spend(start, end): txns = ( db.query(Transaction) .filter( Transaction.account_id.in_(account_ids), Transaction.type == "debit", Transaction.timestamp >= start, Transaction.timestamp < end, ) .all() ) if account_ids else [] cats: dict = defaultdict(float) for t in txns: cats[t.category or "Other"] += t.amount return dict(cats), txns
this_cats, this_txns = get_category_spend(month_start, now) last_cats, last_txns = get_category_spend(last_month_start, month_start)
this_total = sum(this_cats.values()) last_total = sum(last_cats.values()) total_delta_pct = ((this_total - last_total) / max(last_total, 1)) * 100
# Category changes all_cats = set(this_cats) | set(last_cats) cat_changes = [] for cat in all_cats: this_amt = this_cats.get(cat, 0) last_amt = last_cats.get(cat, 0) if last_amt > 0: delta_pct = ((this_amt - last_amt) / last_amt) * 100 cat_changes.append({ "category": cat, "this_month": round(this_amt, 2), "last_month": round(last_amt, 2), "delta_pct": round(delta_pct, 1), }) cat_changes.sort(key=lambda x: abs(x["delta_pct"]), reverse=True)
# Investment performance investments = db.query(Investment).filter(Investment.user_id == user_id).all() inv_total_invested = sum(i.amount_invested for i in investments) inv_total_value = sum(i.current_value for i in investments) inv_gain = inv_total_value - inv_total_invested inv_gain_pct = (inv_gain / max(inv_total_invested, 1)) * 100
# Savings savings_acct = next((a for a in accounts if a.type == "savings"), None) savings_balance = savings_acct.balance if savings_acct else 0
# Subscriptions subs = db.query(Subscription).filter( Subscription.user_id == user_id, Subscription.active == True ).all() monthly_sub_cost = sum( s.amount if s.billing_cycle == "monthly" else s.amount / 12 for s in subs )
# Income this month this_income = sum( t.amount for t in this_txns if t.type == "credit" ) if this_txns else 0 # Also check credit transactions income_txns = ( db.query(Transaction) .filter( Transaction.account_id.in_(account_ids), Transaction.type == "credit", Transaction.timestamp >= month_start, ) .all() ) if account_ids else [] this_income = sum(t.amount for t in income_txns)
# ── Build narrative prompt ──────────────────────────────────────────────── top_changes = cat_changes[:4] changes_text = "\n".join( f" - {c['category']}: ${c['this_month']:,.0f} this month vs ${c['last_month']:,.0f} last month " f"({c['delta_pct']:+.0f}%)" for c in top_changes )
system = ( "You are a personal finance narrator. Write in a warm, intelligent, first-person style " "as if you're a financial advisor summarizing the month for your client. " "Use exact numbers. Be insightful, not generic." )
user_prompt = f"""Write a monthly financial narrative for {user.profile_data.get('name', 'the user')}.
THIS MONTH'S DATA:- Total Spending: ${this_total:,.2f} ({total_delta_pct:+.1f}% vs last month)- Total Income: ${this_income:,.2f}- Savings Balance: ${savings_balance:,.2f}- Investment Portfolio: ${inv_total_value:,.2f} ({inv_gain_pct:+.1f}% return)- Monthly Subscriptions: ${monthly_sub_cost:,.2f}/month ({len(subs)} active)
CATEGORY CHANGES:{changes_text if changes_text else ' - No prior month data available'}
Write 4 short sections:1. MONTH IN REVIEW (1-2 sentences: overall spending story, use exact figures)2. WHAT IMPROVED (1 sentence: best positive change with exact numbers)3. WATCH OUT (1 sentence: biggest concern or overspend with exact numbers)4. NEXT MONTH GOAL (1 sentence: one specific, measurable target)
Keep each section to 1-2 sentences. Use real numbers throughout."""
messages = [ {"role": "system", "content": system}, {"role": "user", "content": user_prompt}, ]
narrative = _call_llm(messages, max_tokens=400)
if not narrative: direction = "increased" if total_delta_pct > 0 else "decreased" best_cat = min(cat_changes, key=lambda x: x["delta_pct"], default=None) worst_cat = max(cat_changes, key=lambda x: x["delta_pct"], default=None) narrative = ( f"MONTH IN REVIEW\nYour spending {direction} by {abs(total_delta_pct):.0f}% " f"to ${this_total:,.2f} this month.\n\n" f"WHAT IMPROVED\n" + (f"{best_cat['category']} spending dropped {abs(best_cat['delta_pct']):.0f}%." if best_cat and best_cat['delta_pct'] < 0 else "Spending patterns are stable.") + f"\n\nWATCH OUT\n" + (f"{worst_cat['category']} increased {worst_cat['delta_pct']:.0f}% — review this category." if worst_cat and worst_cat['delta_pct'] > 10 else "No major overspends detected.") + f"\n\nNEXT MONTH GOAL\nAim to keep total spending under ${this_total * 0.95:,.0f}." )
return { "month": month_start.strftime("%B %Y"), "generated_at": now.isoformat(), "summary": { "total_spend": round(this_total, 2), "total_income": round(this_income, 2), "spend_delta_pct": round(total_delta_pct, 1), "savings_balance": round(savings_balance, 2), "investment_value": round(inv_total_value, 2), "investment_gain_pct": round(inv_gain_pct, 1), "monthly_subscriptions": round(monthly_sub_cost, 2), }, "category_changes": cat_changes[:6], "narrative": narrative, }14 unmodified lines151617181920158 unmodified lines17918018114 unmodified linesfrom app.ai.subscriptions import analyze_subscriptionsfrom app.ai.fraud import evaluate_transaction_for_fraud, get_user_fraud_alertsfrom app.ai.chat import get_chat_responserouter = APIRouter(prefix="/api/ai", tags=["AI Intelligence"])158 unmodified linesuid = get_user_id_fallback(db, user_id)response_msg = get_chat_response(db, uid, req.message)return {"response": response_msg}14 unmodified lines15161718192021158 unmodified lines18018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822914 unmodified linesfrom app.ai.subscriptions import analyze_subscriptionsfrom app.ai.fraud import evaluate_transaction_for_fraud, get_user_fraud_alertsfrom app.ai.chat import get_chat_responsefrom app.ai.intelligence import generate_weekly_coaching, explain_fraud_alert, generate_spending_narrativerouter = APIRouter(prefix="/api/ai", tags=["AI Intelligence"])158 unmodified linesuid = get_user_id_fallback(db, user_id)response_msg = get_chat_response(db, uid, req.message)return {"response": response_msg}# ─── FINANCIAL COACH MODE ──────────────────────────────────────────────────────@router.get("/coach/weekly")def get_weekly_coaching(user_id: Optional[str] = None, db: Session = Depends(get_db)):"""Proactive weekly coaching report: summary, budget coaching, savings nudge,anomaly explanations, and top 3 actions — all grounded in real account data."""uid = get_user_id_fallback(db, user_id)cache_key = f"ai:coach:weekly:{uid}"cached = cache.get(cache_key)if cached:return cachedresult = generate_weekly_coaching(db, uid)cache.set(cache_key, result, ttl=3600) # cache 1 hourreturn result# ─── AI FRAUD EXPLANATION ──────────────────────────────────────────────────────@router.get("/fraud/explain/{fraud_log_id}")def get_fraud_explanation(fraud_log_id: str, db: Session = Depends(get_db)):"""Returns a human-readable AI explanation of exactly why a specifictransaction was flagged, with context about the user's normal patterns."""return explain_fraud_alert(db, fraud_log_id)# ─── SPENDING NARRATIVE ────────────────────────────────────────────────────────@router.get("/narrative/monthly")def get_monthly_narrative(user_id: Optional[str] = None, db: Session = Depends(get_db)):"""Monthly spending narrative: what changed, what improved, what to watch,investment insights, and a one-paragraph human story of the month."""uid = get_user_id_fallback(db, user_id)cache_key = f"ai:narrative:monthly:{uid}"cached = cache.get(cache_key)if cached:return cachedresult = generate_spending_narrative(db, uid)cache.set(cache_key, result, ttl=1800) # cache 30 minreturn result
6 unmodified lines789101112131415162 unmodified lines192021222324253 unmodified lines2930313233343514 unmodified lines505152535455569 unmodified lines666768697071727374757677787980818283848586873 unmodified lines9192939495969798991001011021031041051061071081091101111121 unmodified line1141151161171181191201211221231241 unmodified line1261271281291301311321331347 unmodified lines1421431441451461471481491501511521531541551561571581591601611621631 unmodified line1651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282291 unmodified line2312322332342352362372382398 unmodified lines24824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530612 unmodified lines3193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523531 unmodified line3553563573583593603613623633643653663671 unmodified line3693703713723733743753763773783793803813823833843853863871 unmodified line3893903913923933943953963973983994004014024034044054064074084094104114124134144154164176 unmodified lines4244254264274284294304314324334344354364374384394404414426 unmodified linesTooltip, ResponsiveContainer, RadarChart, Radar, PolarGrid,PolarAngleAxis, PolarRadiusAxis} from "recharts";import { TrendingUp, Sparkles, Calendar, Filter, AlertTriangle, RefreshCw } from "lucide-react";import { aiApi, dashboardApi } from "@/lib/api";// ─── Types ────────────────────────────────────────────────────────────────────interface CategoryData { name: string; value: number; color: string }interface CashFlowPoint { month: string; income: number; expenses: number; savings: number }2 unmodified lines"#ec4899", "#06b6d4", "#84cc16", "#f97316",];// ─── Animation ────────────────────────────────────────────────────────────────const containerVariants = {hidden: { opacity: 0 },visible: { opacity: 1, transition: { staggerChildren: 0.07 } },3 unmodified linesvisible: { opacity: 1, y: 0, transition: { duration: 0.45 } },};// ─── Custom Tooltip ───────────────────────────────────────────────────────────interface TooltipProps {active?: boolean;payload?: Array<{ name: string; value: number; color?: string; fill?: string }>;14 unmodified lines);}// ─── Heatmap Cell ─────────────────────────────────────────────────────────────function HeatmapCell({ value, max }: { value: number; max: number }) {const intensity = max > 0 ? Math.min(value / max, 1) : 0;const alpha = 0.08 + intensity * 0.85;9 unmodified linesconst DAYS = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];// ─── Main Page ────────────────────────────────────────────────────────────────export default function AnalyticsPage() {const [activeTab, setActiveTab] = useState<"overview" | "categories" | "networth">("overview");const [loading, setLoading] = useState(true);const [error, setError] = useState<string | null>(null);// Data stateconst [cashFlow, setCashFlow] = useState<CashFlowPoint[]>([]);const [categoryData, setCategoryData] = useState<CategoryData[]>([]);const [healthScore, setHealthScore] = useState<number>(0);const [radarData, setRadarData] = useState<Array<{ subject: string; A: number }>>([]);const [behaviorInsights, setBehaviorInsights] = useState<string[]>([]);const [heatmapData, setHeatmapData] = useState<number[][]>(Array.from({ length: 7 }, () => Array.from({ length: 12 }, () => 0)));const loadData = async () => {setLoading(true);setError(null);3 unmodified linesaiApi.healthScore(),aiApi.behaviorInsights(),]);// Cash flowsetCashFlow(dashData.cash_flow || []);// Category data with colorssetCategoryData((dashData.spending_by_category || []).slice(0, 8).map((c, i) => ({...c,color: CATEGORY_COLORS[i % CATEGORY_COLORS.length],})));// Health scoresetHealthScore(scoreData.overall_score || 0);// Radar from score categoriesconst cats = scoreData.categories || {};setRadarData(Object.entries(cats).map(([key, val]) => ({1 unmodified lineA: Math.round(((val as { score: number; max: number }).score / (val as { score: number; max: number }).max) * 100),})));// Behavior insightssetBehaviorInsights(behaviorData.insights || []);// Build heatmap from metrics (simulated weekly pattern from behavior data)const metrics = behaviorData.metrics || {};const weekendPct = (metrics.weekend_pct as number) || 0.3;const lateNight = (metrics.late_night_count as number) || 2;1 unmodified lineArray.from({ length: 7 }, (_, day) =>Array.from({ length: 12 }, (_, week) => {const base = 50 + Math.random() * 150;const weekendBoost = (day >= 5 ? weekendPct * 200 : 0);const lateBoost = (week > 8 ? lateNight * 10 : 0);return Math.round(base + weekendBoost + lateBoost);})));7 unmodified linesuseEffect(() => { loadData(); }, []);const heatmapMax = Math.max(...heatmapData.flat(), 1);// Build stacked bar data from cash flow (add category breakdown per month)const stackedData = cashFlow.map((m) => ({month: m.month,income: m.income,expenses: m.expenses,savings: m.savings,}));return (<motion.divvariants={containerVariants}initial="hidden"animate="visible"className="flex flex-col gap-6">{/* Header */}<motion.div variants={itemVariants} className="flex items-center justify-between"><div>1 unmodified line<p className="text-zinc-400 mt-1 text-sm">Deep insights into your financial behavior</p></div><div className="flex items-center gap-2"><buttononClick={loadData}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"><RefreshCw className={`h-3.5 w-3.5 ${loading ? "animate-spin" : ""}`} />Refresh</button><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"><Calendar className="h-3.5 w-3.5" />Last 6 months</button><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"><Filter className="h-3.5 w-3.5" />Filter</button></div></motion.div>{/* Error */}{error && (<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"><AlertTriangle className="h-4 w-4 text-amber-400 flex-shrink-0" /><p className="text-xs text-zinc-400"><span className="text-amber-400 font-medium">Backend offline</span> — showing cached data.</p></motion.div>)}{/* Tabs */}<motion.div variants={itemVariants} className="flex gap-1 rounded-xl border border-white/10 bg-white/5 p-1 w-fit">{(["overview", "categories", "networth"] as const).map((tab) => (<buttonkey={tab}onClick={() => setActiveTab(tab)}className={`rounded-lg px-4 py-2 text-xs font-medium capitalize transition-all ${activeTab === tab ? "bg-white/10 text-white shadow-sm" : "text-zinc-500 hover:text-zinc-300"}`}>{tab === "networth" ? "Net Worth" : tab.charAt(0).toUpperCase() + tab.slice(1)}</button>))}</motion.div>{/* ── Overview Tab ── */}{activeTab === "overview" && (<>{/* Cash Flow Chart */}<motion.div variants={itemVariants} className="glass-card p-6"><div className="flex items-center justify-between mb-6"><div><h2 className="text-base font-semibold text-white">Monthly Cash Flow</h2><p className="text-xs text-zinc-400 mt-0.5">Income vs Expenses vs Savings</p></div><div className="flex gap-3 flex-wrap">{[{ label: "Income", color: "#10b981" },{ label: "Expenses", color: "#f59e0b" },{ label: "Savings", color: "#3b82f6" },].map((l) => (<div key={l.label} className="flex items-center gap-1.5"><div className="h-2 w-2 rounded-full" style={{ background: l.color }} /><span className="text-xs text-zinc-400">{l.label}</span>1 unmodified line))}</div></div>{loading ? (<div className="h-[280px] shimmer rounded-xl" />) : (<ResponsiveContainer width="100%" height={280}><BarChart data={stackedData} margin={{ top: 5, right: 5, left: -20, bottom: 0 }}><CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.05)" />8 unmodified lines)}</motion.div>{/* Heatmap + Radar */}<div className="grid gap-6 lg:grid-cols-2">{/* Spending Heatmap */}<motion.div variants={itemVariants} className="glass-card p-6"><div className="mb-5"><h2 className="text-base font-semibold text-white">Spending Heatmap</h2><p className="text-xs text-zinc-400 mt-0.5">Daily activity over 12 weeks</p></div>{loading ? (<div className="h-[180px] shimmer rounded-xl" />) : (<><div className="space-y-1.5">{DAYS.map((day, dayIdx) => (<div key={day} className="flex items-center gap-2"><span className="text-xs text-zinc-500 w-7 flex-shrink-0">{day}</span><div className="flex gap-1">{heatmapData[dayIdx]?.map((val, week) => (<HeatmapCell key={week} value={val} max={heatmapMax} />))}</div></div>))}</div><div className="mt-4 flex items-center gap-2"><span className="text-xs text-zinc-500">Less</span>{[0.1, 0.3, 0.5, 0.7, 0.9].map((a) => (<div key={a} className="h-3 w-3 rounded-sm" style={{ background: `rgba(16,185,129,${a})` }} />))}<span className="text-xs text-zinc-500">More</span></div></>)}</motion.div>{/* Financial Health Radar */}<motion.div variants={itemVariants} className="glass-card p-6"><div className="mb-5"><h2 className="text-base font-semibold text-white">Financial Health Score</h2><p className="text-xs text-zinc-400 mt-0.5">Multi-dimensional AI assessment</p></div>{loading ? (<div className="h-[240px] shimmer rounded-xl" />) : (<><ResponsiveContainer width="100%" height={220}><RadarChart data={radarData.length ? radarData : [{ subject: "Savings", A: 80 },{ subject: "Spending", A: 70 },{ subject: "Income", A: 90 },{ subject: "Debt", A: 95 },{ subject: "Investment", A: 60 },]}><PolarGrid stroke="rgba(255,255,255,0.08)" /><PolarAngleAxis dataKey="subject" tick={{ fill: "#71717a", fontSize: 10 }} /><PolarRadiusAxis angle={30} domain={[0, 100]} tick={{ fill: "#71717a", fontSize: 9 }} />12 unmodified lines</>)}{/* ── Categories Tab ── */}{activeTab === "categories" && (<motion.div variants={itemVariants} className="glass-card p-6"><div className="flex items-center justify-between mb-6"><div><h2 className="text-base font-semibold text-white">Category Intelligence</h2><p className="text-xs text-zinc-400 mt-0.5">AI-powered spending analysis per category</p></div><div className="flex items-center gap-1.5 rounded-xl border border-emerald-500/20 bg-emerald-500/10 px-3 py-1.5"><Sparkles className="h-3.5 w-3.5 text-emerald-400" /><span className="text-xs text-emerald-400 font-medium">AI Active</span></div></div>{loading ? (<div className="space-y-3">{[1, 2, 3, 4, 5].map((i) => <div key={i} className="h-12 shimmer rounded-xl" />)}</div>) : (<div className="space-y-1">{categoryData.map((cat) => {const total = categoryData.reduce((s, c) => s + c.value, 0);const pct = total > 0 ? (cat.value / total) * 100 : 0;return (<motion.divkey={cat.name}whileHover={{ backgroundColor: "rgba(255,255,255,0.02)" }}className="flex items-center gap-4 rounded-xl px-3 py-3 transition-colors"><div className="h-3 w-3 rounded-full flex-shrink-0" style={{ background: cat.color }} /><div className="flex-1 min-w-0"><div className="flex items-center justify-between mb-1.5">1 unmodified line<span className="text-xs text-zinc-400">${cat.value.toLocaleString()} ({pct.toFixed(1)}%)</span></div><div className="h-1.5 w-full rounded-full bg-white/5 overflow-hidden"><motion.divinitial={{ width: 0 }}animate={{ width: `${pct}%` }}transition={{ duration: 0.8, ease: "easeOut", delay: 0.1 }}className="h-full rounded-full"style={{ background: cat.color }}/></div></div></motion.div>1 unmodified line})}</div>)}{/* AI Behavior Insights */}{behaviorInsights.length > 0 && (<div className="mt-6 rounded-xl border border-blue-500/20 bg-blue-500/5 p-4"><div className="flex items-start gap-3"><Sparkles className="h-4 w-4 text-blue-400 flex-shrink-0 mt-0.5" /><div><p className="text-sm font-medium text-white mb-2">AI Behavioral Insights</p><ul className="space-y-1">{behaviorInsights.slice(0, 3).map((insight, i) => (<li key={i} className="text-xs text-zinc-400">• {insight}</li>))}</ul></div></div></div>1 unmodified line</motion.div>)}{/* ── Net Worth Tab ── */}{activeTab === "networth" && (<motion.div variants={itemVariants} className="glass-card p-6"><div className="flex items-center justify-between mb-6"><div><h2 className="text-base font-semibold text-white">Net Worth Timeline</h2><p className="text-xs text-zinc-400 mt-0.5">Balance trajectory over time</p></div>{!loading && (<div className="text-right"><p className="text-2xl font-bold text-white">${cashFlow.length ? cashFlow[cashFlow.length - 1]?.income?.toLocaleString() : "—"}</p><div className="flex items-center gap-1 justify-end mt-0.5"><TrendingUp className="h-3.5 w-3.5 text-emerald-400" /><span className="text-xs text-emerald-400 font-medium">Growing</span></div></div>)}</div>{loading ? (<div className="h-[320px] shimmer rounded-xl" />) : (<ResponsiveContainer width="100%" height={320}><LineChart data={cashFlow} margin={{ top: 5, right: 5, left: -20, bottom: 0 }}><defs>6 unmodified lines<XAxis dataKey="month" tick={{ fill: "#71717a", fontSize: 11 }} axisLine={false} tickLine={false} /><YAxis tick={{ fill: "#71717a", fontSize: 11 }} axisLine={false} tickLine={false} tickFormatter={(v) => `$${(v / 1000).toFixed(0)}k`} /><Tooltip content={<CustomTooltip />} /><Line type="monotone" dataKey="income" name="Income" stroke="#10b981" strokeWidth={2.5}dot={{ fill: "#10b981", r: 4, strokeWidth: 0 }}activeDot={{ r: 6, fill: "#10b981", strokeWidth: 2, stroke: "#000" }}/><Line type="monotone" dataKey="savings" name="Savings" stroke="#3b82f6" strokeWidth={2}strokeDasharray="4 4"dot={{ fill: "#3b82f6", r: 3, strokeWidth: 0 }}/></LineChart></ResponsiveContainer>)}</motion.div>)}</motion.div>);}6 unmodified lines789101112131415161718192 unmodified lines2223242526273 unmodified lines31323334353614 unmodified lines5152535455569 unmodified lines666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081093 unmodified lines1131141151161171181191201211221231241251 unmodified line1271281291301311321331 unmodified line1351361371381391401417 unmodified lines1491501511521531541551561571581591601611621631641651661671681691701 unmodified line1721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162171 unmodified line2192202212222232242258 unmodified lines23423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826912 unmodified lines2822832842852862872882892902912922932942952962972982993003013023031 unmodified line3053063073083093103111 unmodified line3133143153163173183193203213223233243251 unmodified line3273283293303313323333343353363373383393403413423433443453463476 unmodified lines3543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765776 unmodified linesTooltip, ResponsiveContainer, RadarChart, Radar, PolarGrid,PolarAngleAxis, PolarRadiusAxis} from "recharts";import {TrendingUp, Sparkles, Calendar, Filter, AlertTriangle,RefreshCw, Brain, BookOpen,} from "lucide-react";import { aiApi, dashboardApi } from "@/lib/api";import { useAuthStore } from "@/lib/stores/authStore";interface CategoryData { name: string; value: number; color: string }interface CashFlowPoint { month: string; income: number; expenses: number; savings: number }2 unmodified lines"#ec4899", "#06b6d4", "#84cc16", "#f97316",];const containerVariants = {hidden: { opacity: 0 },visible: { opacity: 1, transition: { staggerChildren: 0.07 } },3 unmodified linesvisible: { opacity: 1, y: 0, transition: { duration: 0.45 } },};interface TooltipProps {active?: boolean;payload?: Array<{ name: string; value: number; color?: string; fill?: string }>;14 unmodified lines);}function HeatmapCell({ value, max }: { value: number; max: number }) {const intensity = max > 0 ? Math.min(value / max, 1) : 0;const alpha = 0.08 + intensity * 0.85;9 unmodified linesconst DAYS = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];type Tab = "overview" | "categories" | "networth" | "coach" | "narrative";type CoachData = {coaching_report: string; week_spend: number; week_income: number;spend_delta_pct: number; top_categories: Array<{ name: string; amount: number }>;anomalies: string[]; improvements: string[]; health_score: number;};type NarrativeData = {month: string; narrative: string;summary: {total_spend: number; total_income: number; spend_delta_pct: number;savings_balance: number; investment_value: number;investment_gain_pct: number; monthly_subscriptions: number;};category_changes: Array<{ category: string; this_month: number; last_month: number; delta_pct: number }>;};export default function AnalyticsPage() {const { user } = useAuthStore();const [activeTab, setActiveTab] = useState<Tab>("overview");const [loading, setLoading] = useState(true);const [error, setError] = useState<string | null>(null);const [cashFlow, setCashFlow] = useState<CashFlowPoint[]>([]);const [categoryData, setCategoryData] = useState<CategoryData[]>([]);const [healthScore, setHealthScore] = useState(0);const [radarData, setRadarData] = useState<Array<{ subject: string; A: number }>>([]);const [behaviorInsights, setBehaviorInsights] = useState<string[]>([]);const [heatmapData, setHeatmapData] = useState<number[][]>(Array.from({ length: 7 }, () => Array.from({ length: 12 }, () => 0)));const [coachData, setCoachData] = useState<CoachData | null>(null);const [narrativeData, setNarrativeData] = useState<NarrativeData | null>(null);const [coachLoading, setCoachLoading] = useState(false);const [narrativeLoading, setNarrativeLoading] = useState(false);const loadData = async () => {setLoading(true);setError(null);3 unmodified linesaiApi.healthScore(),aiApi.behaviorInsights(),]);setCashFlow(dashData.cash_flow || []);setCategoryData((dashData.spending_by_category || []).slice(0, 8).map((c, i) => ({...c, color: CATEGORY_COLORS[i % CATEGORY_COLORS.length],})));setHealthScore(scoreData.overall_score || 0);const cats = scoreData.categories || {};setRadarData(Object.entries(cats).map(([key, val]) => ({1 unmodified lineA: Math.round(((val as { score: number; max: number }).score / (val as { score: number; max: number }).max) * 100),})));setBehaviorInsights(behaviorData.insights || []);const metrics = behaviorData.metrics || {};const weekendPct = (metrics.weekend_pct as number) || 0.3;const lateNight = (metrics.late_night_count as number) || 2;1 unmodified lineArray.from({ length: 7 }, (_, day) =>Array.from({ length: 12 }, (_, week) => {const base = 50 + Math.random() * 150;return Math.round(base + (day >= 5 ? weekendPct * 200 : 0) + (week > 8 ? lateNight * 10 : 0));})));7 unmodified linesuseEffect(() => { loadData(); }, []);const heatmapMax = Math.max(...heatmapData.flat(), 1);const stackedData = cashFlow.map((m) => ({ month: m.month, income: m.income, expenses: m.expenses, savings: m.savings }));const handleTabClick = (tab: Tab) => {setActiveTab(tab);if (tab === "coach" && !coachData) {setCoachLoading(true);aiApi.weeklyCoaching(user?.user_id).then(setCoachData).catch(() => {}).finally(() => setCoachLoading(false));}if (tab === "narrative" && !narrativeData) {setNarrativeLoading(true);aiApi.monthlyNarrative(user?.user_id).then(setNarrativeData).catch(() => {}).finally(() => setNarrativeLoading(false));}};return (<motion.div variants={containerVariants} initial="hidden" animate="visible" className="flex flex-col gap-6">{/* Header */}<motion.div variants={itemVariants} className="flex items-center justify-between"><div>1 unmodified line<p className="text-zinc-400 mt-1 text-sm">Deep insights into your financial behavior</p></div><div className="flex items-center gap-2"><button onClick={loadData} 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"><RefreshCw className={`h-3.5 w-3.5 ${loading ? "animate-spin" : ""}`} />Refresh</button><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"><Calendar className="h-3.5 w-3.5" />Last 6 months</button><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"><Filter className="h-3.5 w-3.5" />Filter</button></div></motion.div>{error && (<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"><AlertTriangle className="h-4 w-4 text-amber-400 flex-shrink-0" /><p className="text-xs text-zinc-400"><span className="text-amber-400 font-medium">Backend offline</span> — showing cached data.</p></motion.div>)}{/* Tab bar */}<motion.div variants={itemVariants} className="flex gap-1 rounded-xl border border-white/10 bg-white/5 p-1 w-fit flex-wrap">{(["overview", "categories", "networth", "coach", "narrative"] as Tab[]).map((tab) => (<button key={tab} onClick={() => handleTabClick(tab)}className={`rounded-lg px-4 py-2 text-xs font-medium transition-all flex items-center gap-1.5 ${activeTab === tab ? "bg-white/10 text-white shadow-sm" : "text-zinc-500 hover:text-zinc-300"}`}>{tab === "coach" && <Brain className="h-3 w-3" />}{tab === "narrative" && <BookOpen className="h-3 w-3" />}{tab === "networth" ? "Net Worth" : tab === "coach" ? "AI Coach" : tab === "narrative" ? "Monthly Story" : tab.charAt(0).toUpperCase() + tab.slice(1)}{tab === "coach" && <span className="rounded-full bg-emerald-500/20 text-emerald-400 text-[9px] px-1.5 py-0.5 font-bold">NEW</span>}</button>))}</motion.div>{/* ── Overview ── */}{activeTab === "overview" && (<><motion.div variants={itemVariants} className="glass-card p-6"><div className="flex items-center justify-between mb-6"><div><h2 className="text-base font-semibold text-white">Monthly Cash Flow</h2><p className="text-xs text-zinc-400 mt-0.5">Income vs Expenses vs Savings</p></div><div className="flex gap-3 flex-wrap">{[{ label: "Income", color: "#10b981" }, { label: "Expenses", color: "#f59e0b" }, { label: "Savings", color: "#3b82f6" }].map((l) => (<div key={l.label} className="flex items-center gap-1.5"><div className="h-2 w-2 rounded-full" style={{ background: l.color }} /><span className="text-xs text-zinc-400">{l.label}</span>1 unmodified line))}</div></div>{loading ? <div className="h-[280px] shimmer rounded-xl" /> : (<ResponsiveContainer width="100%" height={280}><BarChart data={stackedData} margin={{ top: 5, right: 5, left: -20, bottom: 0 }}><CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.05)" />8 unmodified lines)}</motion.div><div className="grid gap-6 lg:grid-cols-2"><motion.div variants={itemVariants} className="glass-card p-6"><div className="mb-5"><h2 className="text-base font-semibold text-white">Spending Heatmap</h2><p className="text-xs text-zinc-400 mt-0.5">Daily activity over 12 weeks</p></div>{loading ? <div className="h-[180px] shimmer rounded-xl" /> : (<><div className="space-y-1.5">{DAYS.map((day, dayIdx) => (<div key={day} className="flex items-center gap-2"><span className="text-xs text-zinc-500 w-7 flex-shrink-0">{day}</span><div className="flex gap-1">{heatmapData[dayIdx]?.map((val, week) => <HeatmapCell key={week} value={val} max={heatmapMax} />)}</div></div>))}</div><div className="mt-4 flex items-center gap-2"><span className="text-xs text-zinc-500">Less</span>{[0.1, 0.3, 0.5, 0.7, 0.9].map((a) => <div key={a} className="h-3 w-3 rounded-sm" style={{ background: `rgba(16,185,129,${a})` }} />)}<span className="text-xs text-zinc-500">More</span></div></>)}</motion.div><motion.div variants={itemVariants} className="glass-card p-6"><div className="mb-5"><h2 className="text-base font-semibold text-white">Financial Health Score</h2><p className="text-xs text-zinc-400 mt-0.5">Multi-dimensional AI assessment</p></div>{loading ? <div className="h-[240px] shimmer rounded-xl" /> : (<><ResponsiveContainer width="100%" height={220}><RadarChart data={radarData.length ? radarData : [{ subject: "Savings", A: 80 }, { subject: "Spending", A: 70 }, { subject: "Income", A: 90 }, { subject: "Debt", A: 95 }, { subject: "Investment", A: 60 }]}><PolarGrid stroke="rgba(255,255,255,0.08)" /><PolarAngleAxis dataKey="subject" tick={{ fill: "#71717a", fontSize: 10 }} /><PolarRadiusAxis angle={30} domain={[0, 100]} tick={{ fill: "#71717a", fontSize: 9 }} />12 unmodified lines</>)}{/* ── Categories ── */}{activeTab === "categories" && (<motion.div variants={itemVariants} className="glass-card p-6"><div className="flex items-center justify-between mb-6"><div><h2 className="text-base font-semibold text-white">Category Intelligence</h2><p className="text-xs text-zinc-400 mt-0.5">AI-powered spending analysis per category</p></div><div className="flex items-center gap-1.5 rounded-xl border border-emerald-500/20 bg-emerald-500/10 px-3 py-1.5"><Sparkles className="h-3.5 w-3.5 text-emerald-400" /><span className="text-xs text-emerald-400 font-medium">AI Active</span></div></div>{loading ? <div className="space-y-3">{[1,2,3,4,5].map((i) => <div key={i} className="h-12 shimmer rounded-xl" />)}</div> : (<div className="space-y-1">{categoryData.map((cat) => {const total = categoryData.reduce((s, c) => s + c.value, 0);const pct = total > 0 ? (cat.value / total) * 100 : 0;return (<motion.div key={cat.name} whileHover={{ backgroundColor: "rgba(255,255,255,0.02)" }} className="flex items-center gap-4 rounded-xl px-3 py-3 transition-colors"><div className="h-3 w-3 rounded-full flex-shrink-0" style={{ background: cat.color }} /><div className="flex-1 min-w-0"><div className="flex items-center justify-between mb-1.5">1 unmodified line<span className="text-xs text-zinc-400">${cat.value.toLocaleString()} ({pct.toFixed(1)}%)</span></div><div className="h-1.5 w-full rounded-full bg-white/5 overflow-hidden"><motion.div initial={{ width: 0 }} animate={{ width: `${pct}%` }} transition={{ duration: 0.8, ease: "easeOut", delay: 0.1 }} className="h-full rounded-full" style={{ background: cat.color }} /></div></div></motion.div>1 unmodified line})}</div>)}{behaviorInsights.length > 0 && (<div className="mt-6 rounded-xl border border-blue-500/20 bg-blue-500/5 p-4"><div className="flex items-start gap-3"><Sparkles className="h-4 w-4 text-blue-400 flex-shrink-0 mt-0.5" /><div><p className="text-sm font-medium text-white mb-2">AI Behavioral Insights</p><ul className="space-y-1">{behaviorInsights.slice(0, 3).map((insight, i) => <li key={i} className="text-xs text-zinc-400">• {insight}</li>)}</ul></div></div></div>1 unmodified line</motion.div>)}{/* ── Net Worth ── */}{activeTab === "networth" && (<motion.div variants={itemVariants} className="glass-card p-6"><div className="flex items-center justify-between mb-6"><div><h2 className="text-base font-semibold text-white">Net Worth Timeline</h2><p className="text-xs text-zinc-400 mt-0.5">Balance trajectory over time</p></div>{!loading && (<div className="text-right"><p className="text-2xl font-bold text-white">${cashFlow.length ? cashFlow[cashFlow.length - 1]?.income?.toLocaleString() : "—"}</p><div className="flex items-center gap-1 justify-end mt-0.5"><TrendingUp className="h-3.5 w-3.5 text-emerald-400" /><span className="text-xs text-emerald-400 font-medium">Growing</span></div></div>)}</div>{loading ? <div className="h-[320px] shimmer rounded-xl" /> : (<ResponsiveContainer width="100%" height={320}><LineChart data={cashFlow} margin={{ top: 5, right: 5, left: -20, bottom: 0 }}><defs>6 unmodified lines<XAxis dataKey="month" tick={{ fill: "#71717a", fontSize: 11 }} axisLine={false} tickLine={false} /><YAxis tick={{ fill: "#71717a", fontSize: 11 }} axisLine={false} tickLine={false} tickFormatter={(v) => `$${(v / 1000).toFixed(0)}k`} /><Tooltip content={<CustomTooltip />} /><Line type="monotone" dataKey="income" name="Income" stroke="#10b981" strokeWidth={2.5} dot={{ fill: "#10b981", r: 4, strokeWidth: 0 }} activeDot={{ r: 6, fill: "#10b981", strokeWidth: 2, stroke: "#000" }} /><Line type="monotone" dataKey="savings" name="Savings" stroke="#3b82f6" strokeWidth={2} strokeDasharray="4 4" dot={{ fill: "#3b82f6", r: 3, strokeWidth: 0 }} /></LineChart></ResponsiveContainer>)}</motion.div>)}{/* ── AI Coach ── */}{activeTab === "coach" && (<motion.div variants={itemVariants} className="space-y-4">{coachLoading ? (<div className="glass-card p-8 flex flex-col items-center gap-4"><div className="flex h-12 w-12 items-center justify-center rounded-2xl bg-emerald-500/15 border border-emerald-500/20"><Brain className="h-6 w-6 text-emerald-400 animate-pulse" /></div><p className="text-sm text-zinc-400">Generating your weekly coaching report...</p><div className="flex gap-1">{[0,1,2].map(i => (<motion.div key={i} animate={{ y: [0,-4,0] }} transition={{ duration: 0.6, repeat: Infinity, delay: i*0.15 }} className="h-1.5 w-1.5 rounded-full bg-emerald-400" />))}</div></div>) : coachData ? (<><div className="grid grid-cols-3 gap-4"><div className="glass-card p-4"><p className="text-xs text-zinc-400">This Week Spend</p><p className="text-xl font-bold text-white mt-1">${coachData.week_spend.toLocaleString("en-US", { minimumFractionDigits: 2 })}</p><p className={`text-xs mt-1 ${coachData.spend_delta_pct > 0 ? "text-red-400" : "text-emerald-400"}`}>{coachData.spend_delta_pct > 0 ? "▲" : "▼"} {Math.abs(coachData.spend_delta_pct).toFixed(1)}% vs last week</p></div><div className="glass-card p-4"><p className="text-xs text-zinc-400">This Week Income</p><p className="text-xl font-bold text-emerald-400 mt-1">${coachData.week_income.toLocaleString("en-US", { minimumFractionDigits: 2 })}</p></div><div className="glass-card p-4"><p className="text-xs text-zinc-400">Health Score</p><p className="text-xl font-bold text-blue-400 mt-1">{coachData.health_score.toFixed(0)}/100</p></div></div>{coachData.top_categories.length > 0 && (<div className="glass-card p-5"><p className="text-sm font-semibold text-white mb-3">Top Spending This Week</p><div className="space-y-2">{coachData.top_categories.map((cat, i) => {const max = coachData.top_categories[0].amount;return (<div key={i} className="flex items-center gap-3"><span className="text-xs text-zinc-400 w-24 truncate">{cat.name}</span><div className="flex-1 h-1.5 rounded-full bg-white/5 overflow-hidden"><motion.div initial={{ width: 0 }} animate={{ width: `${(cat.amount/max)*100}%` }} transition={{ duration: 0.6, delay: i*0.1 }} className="h-full rounded-full bg-gradient-to-r from-blue-500 to-cyan-500" /></div><span className="text-xs font-medium text-white w-16 text-right">${cat.amount.toLocaleString()}</span></div>);})}</div></div>)}{coachData.anomalies.length > 0 && (<div className="rounded-xl border border-amber-500/20 bg-amber-500/5 p-4"><div className="flex items-start gap-2"><AlertTriangle className="h-4 w-4 text-amber-400 flex-shrink-0 mt-0.5" /><div><p className="text-xs font-semibold text-amber-400 mb-1">Anomalies Detected This Week</p>{coachData.anomalies.map((a, i) => <p key={i} className="text-xs text-zinc-300">• {a}</p>)}</div></div></div>)}<div className="glass-card p-6"><div className="flex items-center gap-2 mb-4"><div className="flex h-8 w-8 items-center justify-center rounded-xl bg-emerald-500/15 border border-emerald-500/20"><Brain className="h-4 w-4 text-emerald-400" /></div><div><p className="text-sm font-semibold text-white">Weekly AI Coaching Report</p><p className="text-xs text-zinc-500">Powered by Groq · Based on your real account data</p></div></div><div className="space-y-1">{coachData.coaching_report.split("\n").map((line, i) => {if (!line.trim()) return <div key={i} className="h-2" />;const isHeader = /^[0-9]+\.|^[A-Z\s]{4,}$/.test(line.trim()) && line.length < 40;return isHeader? <p key={i} className="text-xs font-bold text-emerald-400 uppercase tracking-wider mt-3 mb-1">{line}</p>: <p key={i} className="text-sm text-zinc-300 leading-relaxed">{line}</p>;})}</div></div>{coachData.improvements.length > 0 && (<div className="glass-card p-5"><p className="text-sm font-semibold text-white mb-3">Top Actions This Week</p><div className="space-y-2">{coachData.improvements.map((imp, i) => (<div key={i} className="flex items-start gap-3 rounded-xl bg-white/3 border border-white/8 px-3 py-2.5"><span className="flex h-5 w-5 items-center justify-center rounded-full bg-emerald-500/20 text-emerald-400 text-xs font-bold flex-shrink-0">{i+1}</span><p className="text-xs text-zinc-300">{imp}</p></div>))}</div></div>)}</>) : (<div className="glass-card p-8 text-center"><Brain className="h-10 w-10 text-zinc-700 mx-auto mb-3" /><p className="text-sm text-zinc-500">Could not load coaching data</p></div>)}</motion.div>)}{/* ── Monthly Story ── */}{activeTab === "narrative" && (<motion.div variants={itemVariants} className="space-y-4">{narrativeLoading ? (<div className="glass-card p-8 flex flex-col items-center gap-4"><div className="flex h-12 w-12 items-center justify-center rounded-2xl bg-blue-500/15 border border-blue-500/20"><BookOpen className="h-6 w-6 text-blue-400 animate-pulse" /></div><p className="text-sm text-zinc-400">Writing your monthly financial story...</p><div className="flex gap-1">{[0,1,2].map(i => (<motion.div key={i} animate={{ y: [0,-4,0] }} transition={{ duration: 0.6, repeat: Infinity, delay: i*0.15 }} className="h-1.5 w-1.5 rounded-full bg-blue-400" />))}</div></div>) : narrativeData ? (<><div className="flex items-center justify-between"><div><h2 className="text-xl font-bold text-white">{narrativeData.month}</h2><p className="text-xs text-zinc-500 mt-0.5">AI-generated financial story</p></div><div className={`rounded-xl border px-3 py-1.5 text-xs font-semibold ${narrativeData.summary.spend_delta_pct <= 0 ? "border-emerald-500/30 bg-emerald-500/10 text-emerald-400" : "border-red-500/30 bg-red-500/10 text-red-400"}`}>{narrativeData.summary.spend_delta_pct > 0 ? "▲" : "▼"} {Math.abs(narrativeData.summary.spend_delta_pct).toFixed(1)}% spending</div></div><div className="grid grid-cols-2 sm:grid-cols-4 gap-3">{[{ label: "Total Spend", value: `$${narrativeData.summary.total_spend.toLocaleString()}`, color: "text-white" },{ label: "Total Income", value: `$${narrativeData.summary.total_income.toLocaleString()}`, color: "text-emerald-400" },{ label: "Savings", value: `$${narrativeData.summary.savings_balance.toLocaleString()}`, color: "text-blue-400" },{ label: "Portfolio", value: `$${narrativeData.summary.investment_value.toLocaleString()}`, color: narrativeData.summary.investment_gain_pct >= 0 ? "text-emerald-400" : "text-red-400" },].map((s) => (<div key={s.label} className="glass-card p-4"><p className="text-xs text-zinc-400">{s.label}</p><p className={`text-lg font-bold mt-1 ${s.color}`}>{s.value}</p></div>))}</div>{narrativeData.category_changes.length > 0 && (<div className="glass-card p-5"><p className="text-sm font-semibold text-white mb-3">Category Changes vs Last Month</p><div className="space-y-2">{narrativeData.category_changes.slice(0, 6).map((c, i) => (<div key={i} className="flex items-center gap-3"><span className="text-xs text-zinc-400 w-24 truncate">{c.category}</span><div className="flex-1 flex items-center gap-2"><span className="text-xs text-zinc-500 w-16 text-right">${c.last_month.toLocaleString()}</span><div className="flex-1 h-1 rounded-full bg-white/5" /><span className="text-xs font-medium text-white w-16">${c.this_month.toLocaleString()}</span></div><span className={`text-xs font-bold w-14 text-right ${c.delta_pct > 10 ? "text-red-400" : c.delta_pct < -5 ? "text-emerald-400" : "text-zinc-400"}`}>{c.delta_pct > 0 ? "+" : ""}{c.delta_pct.toFixed(0)}%</span></div>))}</div></div>)}<div className="glass-card p-6"><div className="flex items-center gap-2 mb-4"><div className="flex h-8 w-8 items-center justify-center rounded-xl bg-blue-500/15 border border-blue-500/20"><BookOpen className="h-4 w-4 text-blue-400" /></div><div><p className="text-sm font-semibold text-white">Your Monthly Financial Story</p><p className="text-xs text-zinc-500">AI-written · Based on your real transactions</p></div></div><div className="space-y-1">{narrativeData.narrative.split("\n").map((line, i) => {if (!line.trim()) return <div key={i} className="h-2" />;const isHeader = /^[A-Z\s]{4,}$/.test(line.trim()) && line.length < 30;return isHeader? <p key={i} className="text-xs font-bold text-blue-400 uppercase tracking-wider mt-3 mb-1">{line}</p>: <p key={i} className="text-sm text-zinc-300 leading-relaxed">{line}</p>;})}</div></div><div className="flex items-center gap-3 rounded-2xl border border-purple-500/20 bg-purple-500/5 px-5 py-3"><Sparkles className="h-4 w-4 text-purple-400 flex-shrink-0" /><p className="text-xs text-zinc-400"><span className="text-purple-400 font-medium">${narrativeData.summary.monthly_subscriptions.toFixed(2)}/month</span>{" "}in active subscriptions · Review unused ones to reclaim budget.</p></div></>) : (<div className="glass-card p-8 text-center"><BookOpen className="h-10 w-10 text-zinc-700 mx-auto mb-3" /><p className="text-sm text-zinc-500">Could not load narrative data</p></div>)}</motion.div>)}</motion.div>);}
19 unmodified lines2021222324252627282919 unmodified lines// ─── Suggested Prompts ────────────────────────────────────────────────────────const suggestions = [{ icon: TrendingUp, label: "Forecast my balance", color: "text-emerald-400", bg: "bg-emerald-500/10 border-emerald-500/20" },{ icon: PieChart, label: "Analyze my spending", color: "text-blue-400", bg: "bg-blue-500/10 border-blue-500/20" },{ icon: Shield, label: "Check fraud risk", color: "text-purple-400", bg: "bg-purple-500/10 border-purple-500/20" },{ icon: Zap, label: "Optimize my budget", color: "text-amber-400", bg: "bg-amber-500/10 border-amber-500/20" },];// ─── AI Orb ───────────────────────────────────────────────────────────────────19 unmodified lines2021222324252627282919 unmodified lines// ─── Suggested Prompts ────────────────────────────────────────────────────────const suggestions = [{ icon: TrendingUp, label: "What's my total balance?", color: "text-emerald-400", bg: "bg-emerald-500/10 border-emerald-500/20" },{ icon: PieChart, label: "Analyze my spending this month", color: "text-blue-400", bg: "bg-blue-500/10 border-blue-500/20" },{ icon: Shield, label: "Explain my fraud alerts", color: "text-purple-400", bg: "bg-purple-500/10 border-purple-500/20" },{ icon: Zap, label: "Give me a savings nudge", color: "text-amber-400", bg: "bg-amber-500/10 border-amber-500/20" },];// ─── AI Orb ───────────────────────────────────────────────────────────────────
1234567"use client";import { useState, useEffect, useCallback } from "react";import { motion } from "framer-motion";import {Shield, AlertTriangle, CheckCircle, RefreshCw,TrendingUp, Clock, Zap, Eye, XCircle, Activity123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413"use client";import { useState, useEffect, useCallback } from "react";import { motion, AnimatePresence } from "framer-motion";import {Shield, AlertTriangle, CheckCircle, RefreshCw,TrendingUp, Clock, Zap, Eye, XCircle, Activity,Sparkles, ChevronDown, ChevronUp, Loader2,} from "lucide-react";import { aiApi } from "@/lib/api";import { useAuthStore } from "@/lib/stores/authStore";interface FraudAlert {id: string;fraud_log_id?: string;risk_score: number;details: string;status?: string;transaction_id?: string;merchant?: string;amount?: number;timestamp?: string;}interface FraudData {total_alerts: number;pending_reviews: number;alerts: FraudAlert[];}interface FraudExplanation {ai_explanation: string;raw_reasons: string[];amount_vs_avg: number;user_avg_amount: number;}function Skeleton({ className }: { className?: string }) {return <div className={`shimmer rounded-lg ${className}`} />;}function RiskBadge({ score }: { score: number }) {const level =score >= 70 ? { label: "High Risk", color: "text-red-400", bg: "bg-red-500/10 border-red-500/20" }: score >= 40 ? { label: "Suspicious", color: "text-amber-400", bg: "bg-amber-500/10 border-amber-500/20" }: { label: "Low Risk", color: "text-emerald-400", bg: "bg-emerald-500/10 border-emerald-500/20" };return (<span className={`rounded-full border px-2.5 py-1 text-xs font-semibold ${level.color} ${level.bg}`}>{level.label}</span>);}function RiskBar({ score }: { score: number }) {const color = score >= 70 ? "#ef4444" : score >= 40 ? "#f59e0b" : "#10b981";return (<div className="flex items-center gap-2"><div className="h-1.5 w-24 rounded-full bg-white/10 overflow-hidden"><motion.divinitial={{ width: 0 }}animate={{ width: `${score}%` }}transition={{ duration: 0.8, ease: "easeOut" }}className="h-full rounded-full"style={{ background: color }}/></div><span className="text-xs font-mono" style={{ color }}>{score}</span></div>);}// ─── Alert Row with expandable AI explanation ─────────────────────────────────function AlertRow({ alert, index }: { alert: FraudAlert; index: number }) {const [expanded, setExpanded] = useState(false);const [explanation, setExplanation] = useState<FraudExplanation | null>(null);const [loadingExpl, setLoadingExpl] = useState(false);const loadExplanation = async () => {const logId = alert.fraud_log_id || alert.id;if (!logId || explanation) { setExpanded(!expanded); return; }setExpanded(true);setLoadingExpl(true);try {const res = await aiApi.fraudExplain(logId);setExplanation(res);} catch {setExplanation({ai_explanation: alert.details || "Suspicious activity detected based on transaction patterns.",raw_reasons: typeof alert.details === "string" ? alert.details.split("; ") : [],amount_vs_avg: 0,user_avg_amount: 0,});} finally {setLoadingExpl(false);}};return (<motion.divinitial={{ opacity: 0, x: -8 }}animate={{ opacity: 1, x: 0 }}transition={{ delay: index * 0.04 }}className={`border-b border-white/5 last:border-0 ${alert.risk_score >= 70 ? "bg-red-500/2" : ""}`}>{/* Main row */}<divclassName="flex items-center gap-4 px-6 py-4 hover:bg-white/[0.02] transition-colors cursor-pointer"onClick={loadExplanation}><div className={`flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-xl border ${alert.risk_score >= 70 ? "bg-red-500/10 border-red-500/20": alert.risk_score >= 40 ? "bg-amber-500/10 border-amber-500/20": "bg-emerald-500/10 border-emerald-500/20"}`}>{alert.risk_score >= 70 ? <XCircle className="h-5 w-5 text-red-400" />: alert.risk_score >= 40 ? <AlertTriangle className="h-5 w-5 text-amber-400" />: <CheckCircle className="h-5 w-5 text-emerald-400" />}</div><div className="flex-1 min-w-0"><div className="flex items-center gap-2 flex-wrap"><p className="text-sm font-medium text-white truncate">{alert.merchant || `Transaction ${(alert.transaction_id || alert.id).slice(0, 8)}...`}</p><RiskBadge score={alert.risk_score} />{alert.status && (<span className="rounded-full border border-white/10 bg-white/5 px-2 py-0.5 text-[10px] text-zinc-400 capitalize">{alert.status}</span>)}</div><p className="text-xs text-zinc-500 mt-0.5 truncate">{typeof alert.details === "string" ? alert.details: Array.isArray(alert.details) ? (alert.details as string[]).join(" · "): "Suspicious activity detected"}</p></div><div className="flex-shrink-0 hidden sm:block"><RiskBar score={alert.risk_score} /></div>{alert.amount != null && (<div className="flex-shrink-0 text-right"><p className="text-sm font-semibold text-white">${Math.abs(alert.amount).toFixed(2)}</p></div>)}<div className="flex-shrink-0 flex items-center gap-1 text-zinc-500"><Sparkles className="h-3.5 w-3.5 text-cyan-400" />{expanded ? <ChevronUp className="h-3.5 w-3.5" /> : <ChevronDown className="h-3.5 w-3.5" />}</div></div>{/* AI Explanation panel */}<AnimatePresence>{expanded && (<motion.divinitial={{ height: 0, opacity: 0 }}animate={{ height: "auto", opacity: 1 }}exit={{ height: 0, opacity: 0 }}transition={{ duration: 0.25 }}className="overflow-hidden"><div className="mx-6 mb-4 rounded-xl border border-cyan-500/20 bg-cyan-500/5 p-4"><div className="flex items-start gap-2"><Sparkles className="h-4 w-4 text-cyan-400 flex-shrink-0 mt-0.5" /><div className="flex-1"><p className="text-xs font-semibold text-cyan-400 mb-2">AI Fraud Explanation</p>{loadingExpl ? (<div className="flex items-center gap-2"><Loader2 className="h-3.5 w-3.5 animate-spin text-cyan-400" /><span className="text-xs text-zinc-400">Analyzing transaction patterns...</span></div>) : explanation ? (<div className="space-y-3"><p className="text-sm text-zinc-200 leading-relaxed">{explanation.ai_explanation}</p>{explanation.raw_reasons.length > 0 && (<div className="space-y-1"><p className="text-xs font-medium text-zinc-400">Detection signals:</p>{explanation.raw_reasons.map((r, i) => (<div key={i} className="flex items-start gap-1.5"><div className="h-1.5 w-1.5 rounded-full bg-amber-400 flex-shrink-0 mt-1.5" /><p className="text-xs text-zinc-400">{r}</p></div>))}</div>)}{explanation.amount_vs_avg > 0 && (<div className="flex items-center gap-4 pt-1 border-t border-white/8"><div><p className="text-[10px] text-zinc-500">This transaction</p><p className="text-sm font-bold text-white">${alert.amount?.toFixed(2)}</p></div><div className="text-zinc-600">vs</div><div><p className="text-[10px] text-zinc-500">Your average</p><p className="text-sm font-bold text-zinc-300">${explanation.user_avg_amount.toFixed(2)}</p></div><div className="ml-auto"><span className="rounded-full bg-red-500/15 border border-red-500/30 px-2 py-0.5 text-xs font-bold text-red-400">{explanation.amount_vs_avg.toFixed(1)}× average</span></div></div>)}</div>) : null}</div></div></div></motion.div>)}</AnimatePresence></motion.div>);}const containerVariants = {hidden: { opacity: 0 },visible: { opacity: 1, transition: { staggerChildren: 0.07 } },};const itemVariants = {hidden: { opacity: 0, y: 16 },visible: { opacity: 1, y: 0, transition: { duration: 0.4 } },};export default function SecurityPage() {const { user } = useAuthStore();const [data, setData] = useState<FraudData | null>(null);const [loading, setLoading] = useState(true);const [error, setError] = useState<string | null>(null);const [filter, setFilter] = useState<"all" | "high" | "pending">("all");const load = useCallback(async () => {setLoading(true);setError(null);try {const res = await aiApi.fraudAnalysis(user?.user_id);const raw = res as unknown as Record<string, unknown>;const alerts: FraudAlert[] = (raw.alerts as FraudAlert[]) || [];setData({total_alerts: (raw.total_alerts as number) ?? alerts.length,pending_reviews: (raw.pending_reviews as number) ?? alerts.filter((a) => a.status === "pending").length,alerts,});} catch (err) {setError((err as Error).message);} finally {setLoading(false);}}, [user?.user_id]);useEffect(() => { load(); }, [load]);const alerts = data?.alerts || [];const filtered = alerts.filter((a) => {if (filter === "high") return a.risk_score >= 70;if (filter === "pending") return a.status === "pending" || !a.status;return true;});const highRiskCount = alerts.filter((a) => a.risk_score >= 70).length;const suspiciousCount = alerts.filter((a) => a.risk_score >= 40 && a.risk_score < 70).length;const safeCount = alerts.filter((a) => a.risk_score < 40).length;const avgScore = alerts.length? Math.round(alerts.reduce((s, a) => s + a.risk_score, 0) / alerts.length): 0;return (<motion.div variants={containerVariants} initial="hidden" animate="visible" className="flex flex-col gap-6">{/* Header */}<motion.div variants={itemVariants} className="flex items-center justify-between"><div><h1 className="text-3xl font-bold tracking-tight text-white">Security Center</h1><p className="text-zinc-400 mt-1 text-sm">AI-powered fraud detection · Click any alert for a full AI explanation</p></div><button onClick={load} 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"><RefreshCw className={`h-3.5 w-3.5 ${loading ? "animate-spin" : ""}`} />Refresh</button></motion.div>{error && (<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"><AlertTriangle className="h-4 w-4 text-amber-400 flex-shrink-0" /><p className="text-xs text-zinc-400"><span className="text-amber-400 font-medium">Could not load fraud data</span> — {error}</p></motion.div>)}{/* AI Shield Banner */}<motion.div variants={itemVariants} className="flex items-center gap-4 rounded-2xl border border-emerald-500/20 bg-gradient-to-r from-emerald-500/10 via-cyan-500/5 to-blue-500/10 px-5 py-4"><div className="flex h-10 w-10 items-center justify-center rounded-xl bg-emerald-500/20 border border-emerald-500/30 flex-shrink-0"><Shield className="h-5 w-5 text-emerald-400" /></div><div className="flex-1"><p className="text-sm font-semibold text-white">AI Fraud Shield Active</p><p className="text-xs text-zinc-400 mt-0.5">Click any flagged transaction to get a full AI explanation of exactly why it was flagged.</p></div><div className="flex items-center gap-1.5"><div className="h-2 w-2 rounded-full bg-emerald-400 animate-pulse" /><span className="text-xs text-emerald-400 font-medium">Live</span></div></motion.div>{/* Stats */}<div className="grid grid-cols-2 gap-4 sm:grid-cols-4">{[{ label: "Total Alerts", value: loading ? "—" : String(data?.total_alerts ?? 0), icon: Activity, color: "text-blue-400", border: "border-blue-500/20", bg: "from-blue-500/10 to-blue-500/5" },{ label: "High Risk", value: loading ? "—" : String(highRiskCount), icon: XCircle, color: "text-red-400", border: "border-red-500/20", bg: "from-red-500/10 to-red-500/5" },{ label: "Suspicious", value: loading ? "—" : String(suspiciousCount), icon: AlertTriangle, color: "text-amber-400", border: "border-amber-500/20", bg: "from-amber-500/10 to-amber-500/5" },{ label: "Avg Risk Score", value: loading ? "—" : `${avgScore}/100`, icon: TrendingUp, color: "text-purple-400", border: "border-purple-500/20", bg: "from-purple-500/10 to-purple-500/5" },].map((stat) => (<motion.div key={stat.label} variants={itemVariants} className={`rounded-2xl border ${stat.border} bg-gradient-to-br ${stat.bg} p-5`}><div className="flex items-start justify-between"><div><p className="text-xs text-zinc-400 uppercase tracking-wider">{stat.label}</p><p className={`mt-2 text-2xl font-bold ${stat.color}`}>{stat.value}</p></div><stat.icon className={`h-5 w-5 ${stat.color} opacity-60`} /></div></motion.div>))}</div>{/* Detection Rules */}<motion.div variants={itemVariants} className="glass-card p-6"><h2 className="text-base font-semibold text-white mb-4">Active Detection Rules</h2><div className="grid gap-3 sm:grid-cols-2">{[{ icon: TrendingUp, label: "Amount Spike Detection", desc: "Flags transactions 3.5× above your average" },{ icon: Clock, label: "Late-Night Monitoring", desc: "Alerts on activity between 11PM – 4AM" },{ icon: Zap, label: "Rapid Transaction Guard", desc: "Detects multiple transactions within 3 minutes" },{ icon: Eye, label: "Duplicate Payment Check", desc: "Catches same merchant + amount within 10 minutes" },].map((rule) => (<div key={rule.label} className="flex items-start gap-3 rounded-xl border border-white/8 bg-white/[0.02] p-4"><div className="flex h-8 w-8 items-center justify-center rounded-lg bg-emerald-500/10 border border-emerald-500/20 flex-shrink-0"><rule.icon className="h-4 w-4 text-emerald-400" /></div><div className="flex-1 min-w-0"><div className="flex items-center justify-between gap-2"><p className="text-sm font-medium text-white">{rule.label}</p><div className="flex items-center gap-1 flex-shrink-0"><div className="h-1.5 w-1.5 rounded-full bg-emerald-400" /><span className="text-[10px] text-emerald-400">ON</span></div></div><p className="text-xs text-zinc-500 mt-0.5">{rule.desc}</p></div></div>))}</div></motion.div>{/* Alerts Table */}<motion.div variants={itemVariants} className="glass-card overflow-hidden"><div className="flex items-center justify-between px-6 py-4 border-b border-white/8"><div><h2 className="text-base font-semibold text-white">Fraud Alerts</h2><p className="text-xs text-zinc-400 mt-0.5">{loading ? "Loading..." : `${filtered.length} alert${filtered.length !== 1 ? "s" : ""} · Click any row for AI explanation`}</p></div><div className="flex items-center gap-1 rounded-xl border border-white/10 bg-white/5 p-1">{(["all", "high", "pending"] as const).map((f) => (<button key={f} onClick={() => setFilter(f)}className={`rounded-lg px-3 py-1.5 text-xs font-medium capitalize transition-all ${filter === f ? "bg-white/10 text-white" : "text-zinc-500 hover:text-zinc-300"}`}>{f === "all" ? "All" : f === "high" ? "High Risk" : "Pending"}</button>))}</div></div>{loading ? (<div className="space-y-px p-4">{[1, 2, 3].map((i) => <Skeleton key={i} className="h-16 w-full rounded-xl" />)}</div>) : filtered.length === 0 ? (<div className="flex flex-col items-center gap-3 py-16 text-center"><CheckCircle className="h-12 w-12 text-emerald-500/40" /><p className="text-sm font-medium text-zinc-400">{alerts.length === 0 ? "No fraud alerts detected" : "No alerts match this filter"}</p><p className="text-xs text-zinc-600">{alerts.length === 0 ? "All transactions look clean. AI Shield is monitoring in real-time." : "Try a different filter."}</p></div>) : (<div>{filtered.map((alert, i) => (<AlertRow key={alert.id} alert={alert} index={i} />))}</div>)}</motion.div>{!loading && safeCount > 0 && (<motion.div variants={itemVariants} className="flex items-center gap-3 rounded-2xl border border-emerald-500/20 bg-emerald-500/5 px-5 py-3"><CheckCircle className="h-4 w-4 text-emerald-400 flex-shrink-0" /><p className="text-xs text-zinc-400"><span className="text-emerald-400 font-medium">{safeCount} transaction{safeCount !== 1 ? "s" : ""} verified safe</span>{" "}— risk score below threshold. No action required.</p></motion.div>)}</motion.div>);}import {Shield, AlertTriangle, CheckCircle, RefreshCw,TrendingUp, Clock, Zap, Eye, XCircle, Activity
212 unmodified lines213214215216217218212 unmodified linesbody: JSON.stringify({ amount, merchant, category }),});},};// ─── Notifications ────────────────────────────────────────────────────────────212 unmodified lines213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276212 unmodified linesbody: JSON.stringify({ amount, merchant, category }),});},// ── Coach Mode ──────────────────────────────────────────────────────────────weeklyCoaching: (userId?: string) => {const qs = userId ? `?user_id=${userId}` : "";return apiFetch<{generated_at: string;week_start: string;week_end: string;health_score: number;week_spend: number;week_income: number;spend_delta_pct: number;top_categories: Array<{ name: string; amount: number }>;anomalies: string[];coaching_report: string;improvements: string[];}>(`/api/ai/coach/weekly${qs}`);},// ── Fraud Explanation ───────────────────────────────────────────────────────fraudExplain: (fraudLogId: string) =>apiFetch<{fraud_log_id: string;transaction_id: string;merchant: string;amount: number;timestamp: string;risk_score: number;raw_reasons: string[];ai_explanation: string;user_avg_amount: number;amount_vs_avg: number;}>(`/api/ai/fraud/explain/${fraudLogId}`),// ── Monthly Narrative ───────────────────────────────────────────────────────monthlyNarrative: (userId?: string) => {const qs = userId ? `?user_id=${userId}` : "";return apiFetch<{month: string;generated_at: string;summary: {total_spend: number;total_income: number;spend_delta_pct: number;savings_balance: number;investment_value: number;investment_gain_pct: number;monthly_subscriptions: number;};category_changes: Array<{category: string;this_month: number;last_month: number;delta_pct: number;}>;narrative: string;}>(`/api/ai/narrative/monthly${qs}`);},};// ─── Notifications ────────────────────────────────────────────────────────────
backend/app/ai/intelligence.pyAdded+482
backend/app/ai/router.py+48
frontend/src/app/analytics/page.tsx+296-161
frontend/src/app/chat/page.tsx+4-4
frontend/src/app/security/page.tsx+407-1
frontend/src/lib/api.ts+58