Complete FlowState project - 6 pages, 3 API routes, all components, build verified
Browse filesFiles changed (25)
- next-env.d.ts+3
- package.json+7-22
- src/app/(dashboard)/agent/page.tsx+53-31
- src/app/(dashboard)/analytics/page.tsx+59-61
- src/app/(dashboard)/campaigns/page.tsx+46-40
- src/app/(dashboard)/leaderboard/page.tsx+54-48
- src/app/(dashboard)/page.tsx+106-39
- src/app/(dashboard)/wallets/page.tsx+50-48
- src/app/api/torque/campaigns/route.ts+1-1
- src/app/api/torque/events/route.ts+1-1
- src/app/globals.css+7-1
- src/app/layout.tsx+4-5
- src/components/layout/Sidebar.tsx+19-14
- src/components/layout/Topbar.tsx+20-6
- src/components/ui/AgentFeed.tsxAdded+46
- src/components/ui/CampaignBadge.tsxAdded+21
- src/components/ui/RiskBadge.tsxAdded+21
- src/components/ui/StatCard.tsx+6-5
- src/lib/agent-engine.tsAdded+70
- src/lib/mock-data.tsAdded+121
- src/lib/torque-mcp.tsAdded+54
- src/lib/types.ts+35-9
- src/lib/utils.ts+14-15
- tailwind.config.js+9-3
- tsconfig.json+4-13
12/// <reference types="next" />/// <reference types="next/image-types/global" />12345/// <reference types="next" />/// <reference types="next/image-types/global" />// NOTE: This file should not be edited// see https://nextjs.org/docs/app/building-your-application/configuring/typescript for more information.
12345678910111213141516171819202122232425262728{"name": "flowstate","version": "1.0.0","scripts": {"dev": "next dev","build": "next build","start": "next start"},"dependencies": {"@types/node": "^20.0.0","@types/react": "^18.3.0","@types/react-dom": "^18.3.0","autoprefixer": "^10.4.0","clsx": "^2.1.0","date-fns": "^4.1.0","framer-motion": "^12.0.0","lucide-react": "^1.0.0","next": "^14.2.0","postcss": "^8.5.0","react": "^18.3.0","react-dom": "^18.3.0","recharts": "^2.12.0","tailwind-merge": "^2.3.0","tailwindcss": "^3.4.0","typescript": "^5.4.0","zustand": "^5.0.0"}}12345678910111213{"name": "flowstate","version": "1.0.0","private": true,"scripts": { "dev": "next dev", "build": "next build", "start": "next start" },"dependencies": {"@types/node": "^20.0.0", "@types/react": "^18.3.0", "@types/react-dom": "^18.3.0","autoprefixer": "^10.4.0", "clsx": "^2.1.0", "date-fns": "^4.1.0","lucide-react": "^1.0.0", "next": "^14.2.0", "postcss": "^8.5.0","react": "^18.3.0", "react-dom": "^18.3.0", "recharts": "^2.12.0","tailwind-merge": "^2.3.0", "tailwindcss": "^3.4.0", "typescript": "^5.4.0"}}
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576'use client'import { cn } from '@/lib/utils'import { Brain, Zap, Shield, Eye, Play, Pause, Bot, CheckCircle, ArrowRight, Cpu, RefreshCw, GitBranch, Target, Activity, AlertTriangle } from 'lucide-react'import { useState, useEffect } from 'react'const msgs = ['🔍 Scanning 312,847 active wallets...', '⚠️ Critical: 7xKXtg...AsU inactive 10d', '🎁 Gift sent: 0.5 SOL via Torque MCP', '📊 Leaderboard: 12,847 scored', '🎟️ Raffle: 9WzDXw...WWM 3x tickets', '🔥 Comeback: HN7cAB...WrH after 12d', '💰 Rebate 2x activated for HN7cAB...WrH', '🤖 Auto-creating Weekend Streak Challenge', '✅ Campaign created — Budget: 5,000 SOL', '📈 Retention up 0.5%', '🛡️ Sybil check: 99.7% legit', '🎯 Targeting 1,234 wallets']export default function AgentPage() {const [running, setRunning] = useState(true)const [tab, setTab] = useState<'feed' | 'config'>('feed')const [feed, setFeed] = useState<{text:string;time:string}[]>([])useEffect(() => {const init = msgs.slice(0,6).map((t,i) => ({text:t, time: new Date(Date.now()-i*120000).toLocaleTimeString('en-US',{hour12:false})}))setFeed(init)if (!running) returnlet c = 6const iv = setInterval(() => { const t = msgs[c++ % msgs.length]; setFeed(p => [{text:t, time: new Date().toLocaleTimeString('en-US',{hour12:false})}, ...p].slice(0,25)) }, 3000)return () => clearInterval(iv)}, [running])return (<div className="p-6 space-y-6"><div className="flex items-center justify-between"><div className="flex items-center gap-4"><div className={cn('w-12 h-12 rounded-xl flex items-center justify-center', running ? 'bg-trading-up/10 animate-pulse-glow' : 'bg-surface-elevated')}><Brain className={cn('w-6 h-6', running ? 'text-trading-up' : 'text-muted')} /></div><div><h1 className="text-display-sm text-[#eaecef]">AI Agent</h1><p className="text-body-md text-muted mt-0.5">Autonomous churn detection & retention engine</p></div></div><div className="flex items-center gap-3"><div className={cn('px-4 py-2 rounded-lg border', running ? 'bg-trading-up/10 border-trading-up/30 text-trading-up' : 'bg-surface-card border-hairline-dark text-muted')}><div className="flex items-center gap-2"><div className={cn('w-2.5 h-2.5 rounded-full', running ? 'bg-trading-up animate-pulse' : 'bg-muted')} /><span className="text-button font-semibold">{running ? 'RUNNING' : 'PAUSED'}</span></div></div><button onClick={() => setRunning(!running)} className={cn('flex items-center gap-2 px-5 py-2.5 rounded-md text-button font-semibold transition', running ? 'bg-trading-down/10 text-trading-down border border-trading-down/30' : 'bg-brand-yellow text-ink')}>{running ? <><Pause className="w-4 h-4" />Pause</> : <><Play className="w-4 h-4" />Start</>}</button></div></div><div className="grid grid-cols-4 gap-4">{[{i:Activity,l:'Actions Today',v:'3,847',c:'text-brand-yellow'},{i:Eye,l:'Wallets Scanned',v:'312.8K',c:'text-info'},{i:Shield,l:'Wallets Saved',v:'15.2K',c:'text-trading-up'},{i:Target,l:'Churn Prevented',v:'23.9K',c:'text-brand-yellow'}].map(s => { const I = s.i; return (<div key={s.l} className="rounded-xl bg-surface-card border border-hairline-dark p-4"><div className="flex items-center gap-2 mb-2"><I className={cn('w-4 h-4', s.c)} /><span className="text-caption text-muted">{s.l}</span></div><p className={cn('font-mono text-title-lg tabular-nums', s.c === 'text-info' ? 'text-[#eaecef]' : s.c)}>{s.v}</p></div>)})}</div><div className="flex items-center gap-1 p-1 rounded-lg bg-surface-card border border-hairline-dark w-fit">{(['feed','config'] as const).map(t => <button key={t} onClick={() => setTab(t)} className={cn('px-5 py-2 rounded-md text-button transition capitalize', tab === t ? 'bg-brand-yellow text-ink font-semibold' : 'text-muted hover:text-[#eaecef]')}>{t === 'feed' ? 'Live Feed' : 'Configuration'}</button>)}</div>{tab === 'feed' && (<div className="rounded-xl bg-surface-card border border-hairline-dark overflow-hidden"><div className="p-4 border-b border-hairline-dark flex items-center justify-between"><div className="flex items-center gap-2"><Bot className="w-4 h-4 text-brand-yellow" /><span className="text-title-sm">Real-Time Agent Feed</span>{running && <div className="w-2 h-2 rounded-full bg-trading-up animate-pulse" />}</div><span className="text-caption text-muted">{feed.length} messages</span></div><div className="max-h-[500px] overflow-y-auto divide-y divide-hairline-dark/50">{feed.map((m,i) => (<div key={`${m.time}-${i}`} className={cn('flex items-start gap-4 px-5 py-3', i===0 && running && 'animate-slide-up bg-brand-yellow/5')}><span className="font-mono text-caption text-muted tabular-nums whitespace-nowrap mt-0.5">{m.time}</span><span className="text-body-sm text-[#eaecef]">{m.text}</span></div>))}</div></div>)}{tab === 'config' && (<div className="grid grid-cols-1 lg:grid-cols-2 gap-6"><div className="rounded-xl bg-surface-card border border-hairline-dark p-5"><h3 className="text-title-sm mb-4 flex items-center gap-2"><AlertTriangle className="w-4 h-4 text-brand-yellow" />Detection Thresholds</h3>{[{l:'critical',d:10,v:90},{l:'high',d:7,v:60},{l:'medium',d:5,v:30}].map(t => (<div key={t.l} className="p-3 rounded-lg bg-surface-elevated border border-hairline-dark/50 mb-3"><span className={cn('text-caption font-semibold uppercase', t.l==='critical'?'text-trading-down':t.l==='high'?'text-[#ff9500]':'text-brand-yellow')}>{t.l}</span><div className="grid grid-cols-2 gap-3 mt-2"><div><span className="text-caption text-muted">Inactive Days</span><p className="font-mono text-num-md text-[#eaecef]">≥ {t.d}</p></div><div><span className="text-caption text-muted">Volume Drop</span><p className="font-mono text-num-md text-[#eaecef]">≥ {t.v}%</p></div></div></div>))}</div><div className="rounded-xl bg-surface-card border border-hairline-dark p-5"><h3 className="text-title-sm mb-4 flex items-center gap-2"><Cpu className="w-4 h-4 text-brand-yellow" />Agent Config</h3>{[['Scan Interval','30s'],['Protocols','6'],['Torque MCP','Connected'],['Helius','Active'],['Sybil Filter','Enabled']].map(([k,v]) => (<div key={k} className="flex items-center justify-between py-2 border-b border-hairline-dark/50"><span className="text-body-sm text-muted">{k}</span><span className={cn('font-mono text-num-sm', v==='Connected'||v==='Active'||v==='Enabled' ? 'text-trading-up font-semibold' : 'text-[#eaecef]')}>{v}</span></div>))}</div></div>)}<div className="rounded-xl bg-brand-yellow/5 border border-brand-yellow/20 p-6"><h3 className="text-title-sm text-brand-yellow mb-3">How FlowState AI Agent Works</h3><div className="grid grid-cols-5 gap-3 items-center">{[{i:Eye,l:'Monitor',d:'Helius webhooks scan txns'},{i:Brain,l:'Detect',d:'AI scores churn risk'},{i:Zap,l:'Decide',d:'Select incentive type'},{i:Bot,l:'Execute',d:'Fire via Torque MCP'},{i:RefreshCw,l:'Learn',d:'Track outcomes'}].map((s,i) => (<div key={s.l} className="text-center"><div className="w-10 h-10 rounded-lg bg-surface-card border border-brand-yellow/30 flex items-center justify-center mx-auto mb-2"><s.i className="w-5 h-5 text-brand-yellow" /></div><p className="text-caption text-brand-yellow font-semibold">{s.l}</p><p className="text-[10px] text-muted mt-0.5">{s.d}</p></div>))}</div></div>1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798'use client'import { cn, fmtNum } from '@/lib/utils'import { stats, agentMsgs } from '@/lib/mock-data'import { Brain, Zap, Shield, Eye, Play, Pause, Bot, ArrowRight, Cpu, RefreshCw, Target, Activity, AlertTriangle } from 'lucide-react'import { useState, useEffect } from 'react'export default function AgentPage() {const [on, setOn] = useState(true)const [tab, setTab] = useState<'feed'|'config'>('feed')const [feed, setFeed] = useState<{text:string;time:string}[]>([])useEffect(() => {const init = agentMsgs.slice(0,8).map((t,i) => ({text:t, time: new Date(Date.now()-i*120000).toLocaleTimeString('en-US',{hour12:false})}))setFeed(init)if (!on) returnlet c = 8const iv = setInterval(() => {const t = agentMsgs[c++ % agentMsgs.length]setFeed(p => [{text:t, time: new Date().toLocaleTimeString('en-US',{hour12:false})}, ...p].slice(0,30))}, 3000)return () => clearInterval(iv)}, [on])return (<div className="p-6 space-y-6"><div className="flex items-center justify-between"><div className="flex items-center gap-4"><div className={cn('w-12 h-12 rounded-xl flex items-center justify-center', on?'bg-trading-up/10 animate-pulse-glow':'bg-surface-elevated')}><Brain className={cn('w-6 h-6', on?'text-trading-up':'text-muted')}/></div><div><h1 className="text-display-sm text-[#eaecef]">AI Agent</h1><p className="text-body-md text-muted mt-0.5">Autonomous churn detection & retention engine</p></div></div><div className="flex items-center gap-3"><div className={cn('px-4 py-2 rounded-lg border', on?'bg-trading-up/10 border-trading-up/30 text-trading-up':'bg-surface-card border-hairline-dark text-muted')}><div className="flex items-center gap-2"><div className={cn('w-2.5 h-2.5 rounded-full', on?'bg-trading-up animate-pulse':'bg-muted')}/><span className="text-button font-semibold">{on?'RUNNING':'PAUSED'}</span></div></div><button onClick={() => setOn(!on)} className={cn('flex items-center gap-2 px-5 py-2.5 rounded-md text-button font-semibold transition', on?'bg-trading-down/10 text-trading-down border border-trading-down/30 hover:bg-trading-down/20':'bg-brand-yellow text-ink hover:bg-brand-yellow-active')}>{on?<Pause className="w-4 h-4"/>:<Play className="w-4 h-4"/>}{on?'Pause Agent':'Start Agent'}</button></div></div><div className="grid grid-cols-2 lg:grid-cols-4 gap-4">{[{i:Activity,l:'Actions Today',v:fmtNum(stats.agentActionsToday),c:'text-brand-yellow'},{i:Eye,l:'Wallets Scanned',v:fmtNum(stats.activeWallets),c:'text-info'},{i:Shield,l:'Wallets Saved',v:fmtNum(stats.walletsSaved),c:'text-trading-up'},{i:Target,l:'Churn Prevented',v:fmtNum(stats.walletsAtRisk),c:'text-brand-yellow'}].map(s=>{const I=s.i;return(<div key={s.l} className="rounded-xl bg-surface-card border border-hairline-dark p-4"><div className="flex items-center gap-2 mb-2"><I className={cn('w-4 h-4',s.c)}/><span className="text-caption text-muted">{s.l}</span></div><p className={cn('font-mono text-title-lg tabular-nums',s.c==='text-info'?'text-[#eaecef]':s.c)}>{s.v}</p></div>)})}</div><div className="flex items-center gap-1 p-1 rounded-lg bg-surface-card border border-hairline-dark w-fit">{(['feed','config'] as const).map(t => <button key={t} onClick={()=>setTab(t)} className={cn('px-5 py-2 rounded-md text-button transition capitalize', tab===t?'bg-brand-yellow text-ink font-semibold':'text-muted hover:text-[#eaecef]')}>{t==='feed'?'Live Feed':'Configuration'}</button>)}</div>{tab === 'feed' && (<div className="rounded-xl bg-surface-card border border-hairline-dark overflow-hidden"><div className="p-4 border-b border-hairline-dark flex items-center justify-between"><div className="flex items-center gap-2"><Bot className="w-4 h-4 text-brand-yellow"/><span className="text-title-sm">Real-Time Agent Feed</span>{on && <div className="w-2 h-2 rounded-full bg-trading-up animate-pulse"/>}</div><span className="text-caption text-muted">{feed.length} messages</span></div><div className="max-h-[500px] overflow-y-auto divide-y divide-hairline-dark/50">{feed.map((m,i) => (<div key={`${m.time}-${i}`} className={cn('flex items-start gap-4 px-5 py-3 transition-colors', i===0 && on && 'animate-slide-up bg-brand-yellow/5')}><span className="font-mono text-caption text-muted tabular-nums whitespace-nowrap mt-0.5">{m.time}</span><span className="text-body-sm text-[#eaecef]">{m.text}</span></div>))}</div></div>)}{tab === 'config' && (<div className="grid grid-cols-1 lg:grid-cols-2 gap-6"><div className="rounded-xl bg-surface-card border border-hairline-dark p-5"><h3 className="text-title-sm mb-4 flex items-center gap-2"><AlertTriangle className="w-4 h-4 text-brand-yellow"/>Detection Thresholds</h3><div className="space-y-3">{[{l:'critical',d:10,v:90},{l:'high',d:7,v:60},{l:'medium',d:5,v:30}].map(t => (<div key={t.l} className="p-3 rounded-lg bg-surface-elevated border border-hairline-dark/50"><span className={cn('text-caption font-semibold uppercase', t.l==='critical'?'text-trading-down':t.l==='high'?'text-[#ff9500]':'text-brand-yellow')}>{t.l}</span><div className="grid grid-cols-2 gap-3 mt-2"><div><span className="text-caption text-muted">Inactive Days</span><p className="font-mono text-num-md text-[#eaecef]">{'\u2265'} {t.d}</p></div><div><span className="text-caption text-muted">Volume Drop</span><p className="font-mono text-num-md text-[#eaecef]">{'\u2265'} {t.v}%</p></div></div></div>))}</div></div><div className="rounded-xl bg-surface-card border border-hairline-dark p-5"><h3 className="text-title-sm mb-4 flex items-center gap-2"><Cpu className="w-4 h-4 text-brand-yellow"/>Agent Configuration</h3><div className="space-y-0">{[['Scan Interval','30s'],['Monitored Protocols','6'],['Torque MCP','Connected'],['Helius Webhooks','Active'],['Sybil Filter','Enabled']].map(([k,v]) => (<div key={k} className="flex items-center justify-between py-2 border-b border-hairline-dark/50"><span className="text-body-sm text-muted">{k}</span><span className={cn('font-mono text-num-sm',v==='Connected'||v==='Active'||v==='Enabled'?'text-trading-up font-semibold':'text-[#eaecef]')}>{v}</span></div>))}</div></div></div>)}<div className="rounded-xl bg-brand-yellow/5 border border-brand-yellow/20 p-6"><h3 className="text-title-sm text-brand-yellow mb-3">How FlowState AI Agent Works</h3><div className="grid grid-cols-5 gap-3 items-center">{[{i:Eye,l:'Monitor',d:'Helius webhooks scan Solana txns'},{i:Brain,l:'Detect',d:'AI scores churn risk per wallet'},{i:Zap,l:'Decide',d:'Select optimal incentive type'},{i:Bot,l:'Execute',d:'Fire events via Torque MCP'},{i:RefreshCw,l:'Learn',d:'Track outcomes, improve model'}].map((s,i) => (<div key={s.l} className="text-center"><div className="w-10 h-10 rounded-lg bg-surface-card border border-brand-yellow/30 flex items-center justify-center mx-auto mb-2"><s.i className="w-5 h-5 text-brand-yellow"/></div><p className="text-caption text-brand-yellow font-semibold">{s.l}</p><p className="text-[10px] text-muted mt-0.5">{s.d}</p>{i < 4 && <ArrowRight className="w-4 h-4 text-brand-yellow/30 mx-auto mt-2 hidden lg:block"/>}</div>))}</div></div>
12345678910111213141516171819202122232425262728294 unmodified lines34353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394'use client'import { TrendingUp, TrendingDown, Target, Zap, Award, Clock } from 'lucide-react'import { cn } from '@/lib/utils'const cohorts = [{ week: 'Mar 3', d1: 100, d7: 72, d14: 58, d30: 41, d60: 28 },{ week: 'Mar 10', d1: 100, d7: 74, d14: 61, d30: 44, d60: 31 },{ week: 'Mar 17', d1: 100, d7: 76, d14: 63, d30: 47, d60: 33 },{ week: 'Mar 24', d1: 100, d7: 78, d14: 65, d30: 49, d60: 35 },{ week: 'Mar 31', d1: 100, d7: 79, d14: 67, d30: 52, d60: 0 },{ week: 'Apr 7', d1: 100, d7: 81, d14: 69, d30: 0, d60: 0 },{ week: 'Apr 14', d1: 100, d7: 83, d14: 0, d30: 0, d60: 0 },{ week: 'Apr 21', d1: 100, d7: 0, d14: 0, d30: 0, d60: 0 },]const events = [{ event: 'churn_risk_high', count: 2341, color: '#f6465d', max: 34567 },{ event: 'churn_risk_medium', count: 5678, color: '#ff9500', max: 34567 },{ event: 'comeback_detected', count: 8923, color: '#0ecb81', max: 34567 },{ event: 'streak_maintained', count: 34567, color: '#FCD535', max: 34567 },{ event: 'volume_milestone', count: 12345, color: '#2dbdb6', max: 34567 },{ event: 'referral_from_saved', count: 4567, color: '#a78bfa', max: 34567 },{ event: 'inactivity_detected', count: 21011, color: '#707a8a', max: 34567 },]function fmt(n: number) { return n >= 1000 ? `${(n/1000).toFixed(1)}K` : String(n) }function getColor(v: number) {if (v === 0) return 'bg-surface-elevated text-muted'4 unmodified lines}export default function AnalyticsPage() {return (<div className="p-6 space-y-6"><div><h1 className="text-display-sm text-[#eaecef]">Analytics</h1><p className="text-body-md text-muted mt-1">Deep retention insights, cohort analysis & ROI tracking</p></div><div className="grid grid-cols-2 lg:grid-cols-5 gap-4">{[{ label: 'Avg Retention', value: '67.3%', change: '+9.6%', up: true, icon: Target },{ label: 'Churn Rate', value: '4.2%', change: '-4.3%', up: false, icon: TrendingDown },{ label: 'Campaign ROI', value: '847%', change: '+15.2%', up: true, icon: TrendingUp },{ label: 'Saved Wallets', value: '15.2K', change: '+23.4%', up: true, icon: Award },{ label: 'Agent Actions', value: '3,847', change: '+12.1%', up: true, icon: Zap },].map(k => { const I = k.icon; return (<div key={k.label} className="rounded-xl bg-surface-card border border-hairline-dark p-4"><div className="flex items-center justify-between mb-2"><span className="text-caption text-muted">{k.label}</span><I className="w-4 h-4 text-muted" /></div><div className="font-mono text-title-lg text-[#eaecef] tabular-nums">{k.value}</div><span className={cn('font-mono text-num-sm', k.up ? 'text-trading-up' : 'text-trading-down')}>{k.change}</span></div>)})}</div><div className="rounded-xl bg-surface-card border border-hairline-dark p-5"><div className="flex items-center justify-between mb-4"><div><h3 className="text-title-sm">Retention Cohorts</h3><p className="text-caption text-muted mt-0.5">FlowState launched Mar 31</p></div><div className="flex items-center gap-2"><div className="flex items-center gap-1"><div className="w-3 h-3 rounded-sm bg-trading-down/30" /><span className="text-[10px] text-muted">Low</span></div><div className="flex items-center gap-1"><div className="w-3 h-3 rounded-sm bg-brand-yellow/50" /><span className="text-[10px] text-muted">Mid</span></div><div className="flex items-center gap-1"><div className="w-3 h-3 rounded-sm bg-trading-up/80" /><span className="text-[10px] text-muted">High</span></div></div></div><table className="w-full"><thead><tr className="border-b border-hairline-dark"><th className="text-left text-caption text-muted uppercase px-4 py-2">Cohort</th><th className="text-center text-caption text-muted uppercase px-4 py-2">Day 1</th><th className="text-center text-caption text-muted uppercase px-4 py-2">Day 7</th><th className="text-center text-caption text-muted uppercase px-4 py-2">Day 14</th><th className="text-center text-caption text-muted uppercase px-4 py-2">Day 30</th><th className="text-center text-caption text-muted uppercase px-4 py-2">Day 60</th></tr></thead><tbody>{cohorts.map(c => (<tr key={c.week} className="border-b border-hairline-dark/50"><td className="px-4 py-2"><div className="flex items-center gap-2"><Clock className="w-3.5 h-3.5 text-muted" /><span className="text-body-sm text-muted font-mono">{c.week}</span></div></td>{[c.d1, c.d7, c.d14, c.d30, c.d60].map((v, i) => (<td key={i} className="px-4 py-2 text-center"><span className={cn('inline-block min-w-[48px] px-2 py-1 rounded font-mono text-num-sm tabular-nums', getColor(v))}>{v === 0 ? '\u2014' : `${v}%`}</span></td>))}</tr>))}</tbody></table><div className="mt-4 p-3 rounded-lg bg-trading-up/5 border border-trading-up/20"><p className="text-body-sm text-trading-up">📈 <strong>FlowState Impact:</strong> Cohorts after Mar 31 show +7pp higher day-7 retention and +11pp higher day-14 retention.</p></div></div><div className="rounded-xl bg-surface-card border border-hairline-dark p-5"><h3 className="text-title-sm mb-4">Torque Custom Events Breakdown</h3><div className="space-y-4">{events.map(e => (<div key={e.event} className="space-y-1.5"><div className="flex items-center justify-between"><code className="font-mono text-caption text-muted">{e.event}</code><span className="font-mono text-num-sm text-[#eaecef] tabular-nums">{fmt(e.count)}</span></div><div className="h-2 rounded-full bg-surface-elevated overflow-hidden"><div className="h-full rounded-full transition-all duration-700" style={{ width: `${(e.count / e.max) * 100}%`, backgroundColor: e.color }} /></div></div>))}</div></div>123456789101112131415164 unmodified lines212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192'use client'import { TrendingUp, TrendingDown, Target, Zap, Award, Clock } from 'lucide-react'import { cn, fmtNum } from '@/lib/utils'import { cohorts, eventBreakdown, dailyEvents, roiData } from '@/lib/mock-data'import { BarChart, Bar, LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts'const Tip = ({ active, payload, label }: any) => {if (!active || !payload?.length) return nullreturn (<div className="bg-surface-elevated border border-hairline-dark rounded-lg p-3 shadow-lg"><p className="text-caption text-muted mb-1">{label}</p>{payload.map((p: any, i: number) => <p key={i} className="font-mono text-num-sm" style={{color:p.color}}>{p.name}: {typeof p.value==='number' && p.value>1000 ? fmtNum(p.value) : p.value}</p>)}</div>)}function getColor(v: number) {if (v === 0) return 'bg-surface-elevated text-muted'4 unmodified lines}export default function AnalyticsPage() {const maxEvt = Math.max(...eventBreakdown.map(e => e.count))return (<div className="p-6 space-y-6"><div><h1 className="text-display-sm text-[#eaecef]">Analytics</h1><p className="text-body-md text-muted mt-1">Deep retention insights, cohort analysis & ROI tracking</p></div><div className="grid grid-cols-2 lg:grid-cols-5 gap-4">{[{ l:'Avg Retention', v:'67.3%', c:'+9.6%', up:true, i:Target },{ l:'Churn Rate', v:'4.2%', c:'-4.3%', up:false, i:TrendingDown },{ l:'Campaign ROI', v:'847%', c:'+15.2%', up:true, i:TrendingUp },{ l:'Saved Wallets', v:'15.2K', c:'+23.4%', up:true, i:Award },{ l:'Agent Actions', v:'3,847', c:'+12.1%', up:true, i:Zap },].map(k => { const I = k.i; return (<div key={k.l} className="rounded-xl bg-surface-card border border-hairline-dark p-4"><div className="flex items-center justify-between mb-2"><span className="text-caption text-muted">{k.l}</span><I className="w-4 h-4 text-muted"/></div><div className="font-mono text-title-lg text-[#eaecef] tabular-nums">{k.v}</div><span className={cn('font-mono text-num-sm tabular-nums', k.up?'text-trading-up':'text-trading-down')}>{k.c}</span></div>)})}</div><div className="grid grid-cols-1 lg:grid-cols-2 gap-6"><div className="rounded-xl bg-surface-card border border-hairline-dark p-5"><h3 className="text-title-sm mb-4">Daily Custom Events</h3><ResponsiveContainer width="100%" height={250}><BarChart data={dailyEvents}><CartesianGrid strokeDasharray="3 3" stroke="#2b3139"/><XAxis dataKey="date" tick={{fill:'#707a8a',fontSize:11}} axisLine={{stroke:'#2b3139'}}/><YAxis tick={{fill:'#707a8a',fontSize:11}} axisLine={{stroke:'#2b3139'}}/><Tooltip content={<Tip/>}/><Bar dataKey="value" fill="#FCD535" radius={[4,4,0,0]} name="Events"/></BarChart></ResponsiveContainer></div><div className="rounded-xl bg-surface-card border border-hairline-dark p-5"><h3 className="text-title-sm mb-4">Campaign ROI Over Time</h3><ResponsiveContainer width="100%" height={250}><LineChart data={roiData}><CartesianGrid strokeDasharray="3 3" stroke="#2b3139"/><XAxis dataKey="date" tick={{fill:'#707a8a',fontSize:11}} axisLine={{stroke:'#2b3139'}}/><YAxis tick={{fill:'#707a8a',fontSize:11}} axisLine={{stroke:'#2b3139'}} unit="%"/><Tooltip content={<Tip/>}/><Line type="monotone" dataKey="value" stroke="#0ecb81" strokeWidth={2.5} dot={{fill:'#0ecb81',r:4}} name="ROI %"/></LineChart></ResponsiveContainer></div></div><div className="rounded-xl bg-surface-card border border-hairline-dark p-5"><div className="flex items-center justify-between mb-4"><div><h3 className="text-title-sm">Retention Cohorts</h3><p className="text-caption text-muted mt-0.5">Weekly cohort heatmap — FlowState launched Mar 31</p></div></div><table className="w-full"><thead><tr className="border-b border-hairline-dark"><th className="text-left text-caption text-muted uppercase px-4 py-2">Cohort</th><th className="text-center text-caption text-muted uppercase px-4 py-2">Day 1</th><th className="text-center text-caption text-muted uppercase px-4 py-2">Day 7</th><th className="text-center text-caption text-muted uppercase px-4 py-2">Day 14</th><th className="text-center text-caption text-muted uppercase px-4 py-2">Day 30</th><th className="text-center text-caption text-muted uppercase px-4 py-2">Day 60</th></tr></thead><tbody>{cohorts.map(c => (<tr key={c.week} className="border-b border-hairline-dark/50"><td className="px-4 py-2"><div className="flex items-center gap-2"><Clock className="w-3.5 h-3.5 text-muted"/><span className="text-body-sm text-muted font-mono">{c.week}</span></div></td>{[c.d1,c.d7,c.d14,c.d30,c.d60].map((v,i) => (<td key={i} className="px-4 py-2 text-center"><span className={cn('inline-block min-w-[48px] px-2 py-1 rounded font-mono text-num-sm tabular-nums', getColor(v))}>{v===0?'\u2014':v+'%'}</span></td>))}</tr>))}</tbody></table><div className="mt-4 p-3 rounded-lg bg-trading-up/5 border border-trading-up/20"><p className="text-body-sm text-trading-up">{'\u{1F4C8}'} <strong>FlowState Impact:</strong> Cohorts after Mar 31 show +7pp higher day-7 retention and +11pp higher day-14 retention vs pre-launch.</p></div></div><div className="rounded-xl bg-surface-card border border-hairline-dark p-5"><h3 className="text-title-sm mb-4">Torque Custom Events Breakdown</h3><div className="space-y-4">{eventBreakdown.map(e => (<div key={e.event} className="space-y-1.5"><div className="flex items-center justify-between"><code className="font-mono text-caption text-muted">{e.event}</code><span className="font-mono text-num-sm text-[#eaecef] tabular-nums">{fmtNum(e.count)}</span></div><div className="h-2 rounded-full bg-surface-elevated overflow-hidden"><div className="h-full rounded-full transition-all duration-700" style={{width:(e.count/maxEvt*100)+'%',backgroundColor:e.color}}/></div></div>))}</div></div>
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758'use client'import { Plus, Bot, Users, Activity, DollarSign, Trophy, Gift, Ticket, Percent } from 'lucide-react'import { cn } from '@/lib/utils'const campaigns = [{ id: '1', name: 'Weekly Volume Champions', type: 'leaderboard' as const, status: 'active', desc: 'Top 50 traders by weekly swap volume earn SOL rewards', budget: 50000, participants: 12847, events: 89432, ai: true, formula: 'SUM(swap_volume)' },{ id: '2', name: 'Comeback Raffle', type: 'raffle' as const, status: 'active', desc: 'Returning users after 7+ days get raffle tickets', budget: 25000, participants: 3456, events: 8923, ai: true },{ id: '3', name: 'Anti-Churn Gift Drop', type: 'gift' as const, status: 'active', desc: 'High churn risk wallets receive 0.5 SOL gift', budget: 15000, participants: 1234, events: 4567, ai: true },{ id: '4', name: 'Streak Multiplier Rebate', type: 'rebate' as const, status: 'active', desc: '7+ day streak unlocks 2x fee rebate for 48h', budget: 75000, participants: 8932, events: 45678, ai: true, formula: 'streak_days >= 7' },{ id: '5', name: 'DeFi Explorer Rewards', type: 'leaderboard' as const, status: 'active', desc: 'Multi-protocol users rank higher', budget: 30000, participants: 6789, events: 23456, ai: false, formula: 'COUNT(protocols) * SUM(volume)' },{ id: '6', name: 'New User Welcome Gift', type: 'gift' as const, status: 'ended', desc: 'First-time users who complete 3 swaps receive SOL', budget: 10000, participants: 4567, events: 12345, ai: false },]const typeConfig = { leaderboard: { icon: Trophy, color: 'text-brand-yellow', bg: 'bg-brand-yellow/10', label: 'Leaderboard' }, gift: { icon: Gift, color: 'text-brand-turquoise', bg: 'bg-brand-turquoise/10', label: 'Gift' }, raffle: { icon: Ticket, color: 'text-[#a78bfa]', bg: 'bg-[#a78bfa]/10', label: 'Raffle' }, rebate: { icon: Percent, color: 'text-trading-up', bg: 'bg-trading-up/10', label: 'Rebate' } }const statusColors = { active: 'bg-trading-up/10 text-trading-up', ended: 'bg-brand-yellow/10 text-brand-yellow', draft: 'bg-muted/10 text-muted', distributed: 'bg-brand-turquoise/10 text-brand-turquoise' }function fmt(n: number) { return n >= 1000 ? `${(n/1000).toFixed(1)}K` : String(n) }function fmtC(n: number) { return `$${n.toLocaleString()}` }export default function CampaignsPage() {return (<div className="p-6 space-y-6"><div className="flex items-center justify-between"><div><h1 className="text-display-sm text-[#eaecef]">Campaigns</h1><p className="text-body-md text-muted mt-1">Manage Torque campaigns — leaderboards, rebates, raffles & gifts</p></div><button className="flex items-center gap-2 px-5 py-2.5 rounded-md bg-brand-yellow text-ink text-button font-semibold hover:bg-brand-yellow-active transition"><Plus className="w-4 h-4" />Create Campaign</button></div><div className="grid grid-cols-4 gap-4"><div className="rounded-xl bg-surface-card border border-hairline-dark p-4"><span className="text-caption text-muted">Total Budget</span><p className="font-mono text-title-lg text-[#eaecef] mt-1">{fmtC(205000)}</p></div><div className="rounded-xl bg-surface-card border border-hairline-dark p-4"><span className="text-caption text-muted">Distributed</span><p className="font-mono text-title-lg text-trading-up mt-1">{fmtC(42801)}</p></div><div className="rounded-xl bg-surface-card border border-hairline-dark p-4"><span className="text-caption text-muted">Total Participants</span><p className="font-mono text-title-lg text-[#eaecef] mt-1">{fmt(47825)}</p></div><div className="rounded-xl bg-surface-card border border-hairline-dark p-4"><div className="flex items-center gap-1.5"><Bot className="w-3.5 h-3.5 text-brand-yellow" /><span className="text-caption text-muted">AI Created</span></div><p className="font-mono text-title-lg text-brand-yellow mt-1">4/6</p></div></div><div className="grid grid-cols-1 lg:grid-cols-2 gap-4">{campaigns.map(c => {const tc = typeConfig[c.type]; const Icon = tc.icon; const sc = statusColors[c.status as keyof typeof statusColors] || statusColors.activereturn (<div key={c.id} className="rounded-xl bg-surface-card border border-hairline-dark p-5 hover:border-brand-yellow/30 transition-all group cursor-pointer"><div className="flex items-start justify-between mb-3"><div className="flex items-center gap-2"><div className={cn('inline-flex items-center gap-1.5 px-2.5 py-1 rounded-md', tc.bg)}><Icon className={cn('w-3.5 h-3.5', tc.color)} /><span className={cn('text-caption font-semibold', tc.color)}>{tc.label}</span></div><span className={cn('text-[10px] font-semibold uppercase px-2 py-0.5 rounded-pill', sc)}>{c.status}</span></div>{c.ai && <div className="flex items-center gap-1 px-2 py-0.5 rounded-pill bg-brand-yellow/10"><Bot className="w-3 h-3 text-brand-yellow" /><span className="text-[10px] text-brand-yellow font-semibold">AI</span></div>}</div><h3 className="text-title-sm text-[#eaecef] group-hover:text-brand-yellow transition-colors">{c.name}</h3><p className="text-body-sm text-muted mt-1 line-clamp-2">{c.desc}</p>{c.formula && <code className="inline-block mt-2 text-[11px] font-mono text-brand-yellow/70 bg-brand-yellow/5 px-2 py-0.5 rounded">{c.formula}</code>}<div className="grid grid-cols-3 gap-3 mt-4 pt-4 border-t border-hairline-dark/50"><div><div className="flex items-center gap-1 text-caption text-muted"><Users className="w-3 h-3" /><span>Users</span></div><span className="font-mono text-num-sm text-[#eaecef]">{fmt(c.participants)}</span></div><div><div className="flex items-center gap-1 text-caption text-muted"><Activity className="w-3 h-3" /><span>Events</span></div><span className="font-mono text-num-sm text-[#eaecef]">{fmt(c.events)}</span></div><div><div className="flex items-center gap-1 text-caption text-muted"><DollarSign className="w-3 h-3" /><span>Budget</span></div><span className="font-mono text-num-sm text-brand-yellow">{fmtC(c.budget)}</span></div></div></div>)})}</div></div>)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364'use client'import { Plus, Bot, Users, Activity, DollarSign, Trophy, Gift, Ticket, Percent } from 'lucide-react'import { cn, fmtNum, fmtUsd } from '@/lib/utils'import { campaigns } from '@/lib/mock-data'import { CampaignBadge } from '@/components/ui/CampaignBadge'import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts'import type { CampaignType } from '@/lib/types'const perfData = [{ name: 'Vol Champions', p: 12847, e: 89432 }, { name: 'Comeback', p: 3456, e: 8923 },{ name: 'Anti-Churn', p: 1234, e: 4567 }, { name: 'Streak', p: 8932, e: 45678 }, { name: 'Explorer', p: 6789, e: 23456 },]const Tip = ({ active, payload, label }: any) => {if (!active || !payload?.length) return nullreturn (<div className="bg-surface-elevated border border-hairline-dark rounded-lg p-3 shadow-lg"><p className="text-caption text-muted mb-1">{label}</p>{payload.map((p: any, i: number) => <p key={i} className="font-mono text-num-sm" style={{color:p.color}}>{p.name}: {fmtNum(p.value)}</p>)}</div>)}const sc: Record<string, string> = { active:'bg-trading-up/10 text-trading-up', ended:'bg-brand-yellow/10 text-brand-yellow', draft:'bg-muted/10 text-muted', distributed:'bg-brand-turquoise/10 text-brand-turquoise' }export default function CampaignsPage() {const total = campaigns.reduce((s,c) => s+c.budget, 0)const dist = campaigns.reduce((s,c) => s+c.rewardsDistributed, 0)const parts = campaigns.reduce((s,c) => s+c.participantCount, 0)const ai = campaigns.filter(c => c.createdBy === 'ai-agent').lengthreturn (<div className="p-6 space-y-6"><div className="flex items-center justify-between"><div><h1 className="text-display-sm text-[#eaecef]">Campaigns</h1><p className="text-body-md text-muted mt-1">Manage Torque campaigns — leaderboards, rebates, raffles & gifts</p></div><button className="flex items-center gap-2 px-5 py-2.5 rounded-md bg-brand-yellow text-ink text-button font-semibold hover:bg-brand-yellow-active transition"><Plus className="w-4 h-4"/>Create Campaign</button></div><div className="grid grid-cols-4 gap-4"><div className="rounded-xl bg-surface-card border border-hairline-dark p-4"><span className="text-caption text-muted">Total Budget</span><p className="font-mono text-title-lg text-[#eaecef] mt-1 tabular-nums">{fmtUsd(total)}</p></div><div className="rounded-xl bg-surface-card border border-hairline-dark p-4"><span className="text-caption text-muted">Distributed</span><p className="font-mono text-title-lg text-trading-up mt-1 tabular-nums">{fmtUsd(dist)}</p></div><div className="rounded-xl bg-surface-card border border-hairline-dark p-4"><span className="text-caption text-muted">Participants</span><p className="font-mono text-title-lg text-[#eaecef] mt-1 tabular-nums">{fmtNum(parts)}</p></div><div className="rounded-xl bg-surface-card border border-hairline-dark p-4"><div className="flex items-center gap-1.5"><Bot className="w-3.5 h-3.5 text-brand-yellow"/><span className="text-caption text-muted">AI Created</span></div><p className="font-mono text-title-lg text-brand-yellow mt-1 tabular-nums">{ai}/{campaigns.length}</p></div></div><div className="rounded-xl bg-surface-card border border-hairline-dark p-5"><h3 className="text-title-sm mb-4">Campaign Performance</h3><ResponsiveContainer width="100%" height={250}><BarChart data={perfData}><CartesianGrid strokeDasharray="3 3" stroke="#2b3139"/><XAxis dataKey="name" tick={{fill:'#707a8a',fontSize:11}} axisLine={{stroke:'#2b3139'}}/><YAxis tick={{fill:'#707a8a',fontSize:11}} axisLine={{stroke:'#2b3139'}}/><Tooltip content={<Tip/>}/><Bar dataKey="p" fill="#FCD535" radius={[4,4,0,0]} name="Participants"/><Bar dataKey="e" fill="#0ecb81" radius={[4,4,0,0]} name="Events"/></BarChart></ResponsiveContainer></div><div className="grid grid-cols-1 lg:grid-cols-2 gap-4">{campaigns.map(c => (<div key={c.id} className="rounded-xl bg-surface-card border border-hairline-dark p-5 hover:border-brand-yellow/30 transition-all group cursor-pointer"><div className="flex items-start justify-between mb-3"><div className="flex items-center gap-2"><CampaignBadge type={c.type as CampaignType}/><span className={cn('text-[10px] font-semibold uppercase px-2 py-0.5 rounded-pill', sc[c.status] || sc.active)}>{c.status}</span></div>{c.createdBy === 'ai-agent' && <div className="flex items-center gap-1 px-2 py-0.5 rounded-pill bg-brand-yellow/10"><Bot className="w-3 h-3 text-brand-yellow"/><span className="text-[10px] text-brand-yellow font-semibold">AI</span></div>}</div><h3 className="text-title-sm text-[#eaecef] group-hover:text-brand-yellow transition-colors">{c.name}</h3><p className="text-body-sm text-muted mt-1 line-clamp-2">{c.description}</p>{c.formula && <code className="inline-block mt-2 text-[11px] font-mono text-brand-yellow/70 bg-brand-yellow/5 px-2 py-0.5 rounded">{c.formula}</code>}<div className="grid grid-cols-3 gap-3 mt-4 pt-4 border-t border-hairline-dark/50"><div><div className="flex items-center gap-1 text-caption text-muted"><Users className="w-3 h-3"/><span>Users</span></div><span className="font-mono text-num-sm text-[#eaecef] tabular-nums">{fmtNum(c.participantCount)}</span></div><div><div className="flex items-center gap-1 text-caption text-muted"><Activity className="w-3 h-3"/><span>Events</span></div><span className="font-mono text-num-sm text-[#eaecef] tabular-nums">{fmtNum(c.eventsProcessed)}</span></div><div><div className="flex items-center gap-1 text-caption text-muted"><DollarSign className="w-3 h-3"/><span>Budget</span></div><span className="font-mono text-num-sm text-brand-yellow tabular-nums">{fmtUsd(c.budget)}</span></div></div></div>))}</div></div>)
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768'use client'import { Trophy, Crown, Medal, Award, Flame, ArrowUp, ArrowDown } from 'lucide-react'import { cn } from '@/lib/utils'const entries = [{ rank: 1, wallet: 'BKiKp1...mS2', score: 98750, change: 12.5, volume: '$28.5M', streak: 62, protocols: ['Jupiter','Raydium','Drift','Marginfi','Kamino','Tensor'], rewards: '$5,000' },{ rank: 2, wallet: '5Q544f...4j1', score: 87234, change: 8.3, volume: '$15.2M', streak: 47, protocols: ['Jupiter','Raydium','Drift','Marginfi','Kamino'], rewards: '$3,500' },{ rank: 3, wallet: 'Fq8xSc...BHu', score: 76543, change: -2.1, volume: '$12.3M', streak: 31, protocols: ['Jupiter','Raydium','Drift'], rewards: '$2,500' },{ rank: 4, wallet: 'HN7cAB...WrH', score: 65432, change: 15.7, volume: '$8.7M', streak: 14, protocols: ['Jupiter','Raydium','Drift','Kamino'], rewards: '$1,800' },{ rank: 5, wallet: '4zMMC9...cDU', score: 54321, change: 3.4, volume: '$3.5M', streak: 5, protocols: ['Kamino','Jupiter'], rewards: '$1,200' },]export default function LeaderboardPage() {return (<div className="p-6 space-y-6"><div><h1 className="text-display-sm text-[#eaecef]">Leaderboard</h1><p className="text-body-md text-muted mt-1">Cross-protocol DeFi Power Rankings powered by Torque</p></div><div className="grid grid-cols-3 gap-4">{entries.slice(0,3).map((e,i) => {const icons = [Crown, Medal, Award]const colors = ['text-brand-yellow','text-[#c0c0c0]','text-[#cd7f32]']const Icon = icons[i]return (<div key={e.rank} className={cn('rounded-xl bg-surface-card border p-6 text-center', i===0 ? 'border-brand-yellow/40 bg-brand-yellow/5 glow-yellow' : 'border-hairline-dark')}><Icon className={cn('w-8 h-8 mx-auto mb-3', colors[i])} /><div className="font-mono text-num-display text-[#eaecef]">#{e.rank}</div><p className="text-body-md text-muted font-mono mt-1">{e.wallet}</p><div className="mt-4 font-mono text-title-lg text-brand-yellow">{e.score.toLocaleString()}</div><p className="text-caption text-muted mt-1">Score</p></div>)})}</div><div className="rounded-xl bg-surface-card border border-hairline-dark overflow-hidden"><table className="w-full"><thead><tr className="border-b border-hairline-dark bg-surface-elevated/50"><th className="text-left text-caption text-muted uppercase px-5 py-3 w-16">Rank</th><th className="text-left text-caption text-muted uppercase px-5 py-3">Wallet</th><th className="text-right text-caption text-muted uppercase px-5 py-3">Score</th><th className="text-right text-caption text-muted uppercase px-5 py-3">24h</th><th className="text-right text-caption text-muted uppercase px-5 py-3">Volume</th><th className="text-right text-caption text-muted uppercase px-5 py-3">Streak</th><th className="text-right text-caption text-muted uppercase px-5 py-3">Rewards</th></tr></thead><tbody>{entries.map(e => (<tr key={e.rank} className="border-b border-hairline-dark/50 hover:bg-surface-hover transition-colors"><td className="px-5 py-4"><span className={cn('font-mono text-num-md font-bold', e.rank<=3 ? 'text-brand-yellow' : 'text-muted')}>{e.rank}</span></td><td className="px-5 py-4 font-mono text-body-md">{e.wallet}</td><td className="px-5 py-4 text-right font-mono text-num-md tabular-nums">{e.score.toLocaleString()}</td><td className="px-5 py-4 text-right"><div className="flex items-center justify-end gap-1">{e.change>=0 ? <ArrowUp className="w-3.5 h-3.5 text-trading-up"/> : <ArrowDown className="w-3.5 h-3.5 text-trading-down"/>}<span className={cn('font-mono text-num-sm', e.change>=0 ? 'text-trading-up' : 'text-trading-down')}>{e.change>=0?'+':''}{e.change}%</span></div></td><td className="px-5 py-4 text-right font-mono text-num-sm text-muted">{e.volume}</td><td className="px-5 py-4 text-right"><div className="flex items-center justify-end gap-1"><Flame className={cn('w-3.5 h-3.5', e.streak>=30?'text-brand-yellow':'text-trading-up')}/><span className="font-mono text-num-sm">{e.streak}d</span></div></td><td className="px-5 py-4 text-right font-mono text-num-sm text-brand-yellow">{e.rewards}</td></tr>))}</tbody></table></div><div className="rounded-xl bg-brand-yellow/5 border border-brand-yellow/20 p-5 flex items-center gap-4"><Trophy className="w-6 h-6 text-brand-yellow" /><div><h3 className="text-title-sm text-brand-yellow">Scoring Formula</h3><code className="font-mono text-brand-yellow/80 bg-surface-card px-2 py-0.5 rounded text-body-sm">SCORE = COUNT(protocols) x SUM(swap_volume) x STREAK_MULTIPLIER(days)</code></div></div></div>)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374'use client'import { Trophy, Crown, Medal, Award, Flame, ArrowUp, ArrowDown } from 'lucide-react'import { cn, fmtNum, fmtUsd } from '@/lib/utils'import { leaderboard } from '@/lib/mock-data'import { useState } from 'react'const filters = ['24H','7D','30D','All Time']export default function LeaderboardPage() {const [f, setF] = useState('7D')return (<div className="p-6 space-y-6"><div><h1 className="text-display-sm text-[#eaecef]">Leaderboard</h1><p className="text-body-md text-muted mt-1">Cross-protocol DeFi Power Rankings powered by Torque</p></div><div className="grid grid-cols-3 gap-4">{leaderboard.slice(0,3).map((e,i) => {const icons = [Crown,Medal,Award], colors = ['text-brand-yellow','text-[#c0c0c0]','text-[#cd7f32]']const borders = ['border-brand-yellow/40 bg-brand-yellow/5','border-[#c0c0c0]/40 bg-[#c0c0c0]/5','border-[#cd7f32]/40 bg-[#cd7f32]/5']const Icon = icons[i]return (<div key={e.rank} className={cn('rounded-xl bg-surface-card border p-6 text-center relative overflow-hidden', borders[i], i===0 && 'glow-yellow')}>{i===0 && <div className="absolute inset-0 bg-gradient-to-b from-brand-yellow/5 to-transparent"/>}<div className="relative z-10"><Icon className={cn('w-8 h-8 mx-auto mb-3', colors[i])}/><div className="font-mono text-num-display text-[#eaecef] tabular-nums">#{e.rank}</div><p className="text-body-md text-muted font-mono mt-1">{e.wallet}</p><div className="mt-4 font-mono text-title-lg text-brand-yellow tabular-nums">{fmtNum(e.score)}</div><p className="text-caption text-muted mt-1">Score</p><div className="mt-3 flex items-center justify-center gap-4"><div><span className="font-mono text-num-sm text-[#eaecef]">{fmtUsd(e.volume)}</span><p className="text-caption text-muted">Volume</p></div><div className="w-px h-8 bg-hairline-dark"/><div><div className="flex items-center justify-center gap-1"><Flame className="w-3.5 h-3.5 text-brand-yellow"/><span className="font-mono text-num-sm text-[#eaecef]">{e.streak}d</span></div><p className="text-caption text-muted">Streak</p></div></div><div className="mt-3 flex flex-wrap justify-center gap-1">{e.protocols.map(p => <span key={p} className="text-[10px] px-1.5 py-0.5 rounded bg-surface-elevated text-muted">{p}</span>)}</div></div></div>)})}</div><div className="flex items-center gap-1 p-1 rounded-lg bg-surface-card border border-hairline-dark w-fit">{filters.map(x => <button key={x} onClick={() => setF(x)} className={cn('px-4 py-1.5 rounded-md text-button transition', f===x ? 'bg-brand-yellow text-ink' : 'text-muted hover:text-[#eaecef]')}>{x}</button>)}</div><div className="rounded-xl bg-surface-card border border-hairline-dark overflow-hidden"><table className="w-full"><thead><tr className="border-b border-hairline-dark bg-surface-elevated/50"><th className="text-left text-caption text-muted uppercase tracking-wider px-5 py-3 w-16">Rank</th><th className="text-left text-caption text-muted uppercase tracking-wider px-5 py-3">Wallet</th><th className="text-right text-caption text-muted uppercase tracking-wider px-5 py-3">Score</th><th className="text-right text-caption text-muted uppercase tracking-wider px-5 py-3">24h Change</th><th className="text-right text-caption text-muted uppercase tracking-wider px-5 py-3">Volume</th><th className="text-right text-caption text-muted uppercase tracking-wider px-5 py-3">Streak</th><th className="text-center text-caption text-muted uppercase tracking-wider px-5 py-3">Protocols</th><th className="text-right text-caption text-muted uppercase tracking-wider px-5 py-3">Rewards</th></tr></thead><tbody>{leaderboard.map(e => (<tr key={e.rank} className="border-b border-hairline-dark/50 hover:bg-surface-hover transition-colors"><td className="px-5 py-4"><span className={cn('font-mono text-num-md font-bold', e.rank<=3?'text-brand-yellow':'text-muted')}>{e.rank}</span></td><td className="px-5 py-4 font-mono text-body-md text-[#eaecef]">{e.wallet}</td><td className="px-5 py-4 text-right font-mono text-num-md text-[#eaecef] tabular-nums">{fmtNum(e.score)}</td><td className="px-5 py-4 text-right"><div className="flex items-center justify-end gap-1">{e.change24h>=0?<ArrowUp className="w-3.5 h-3.5 text-trading-up"/>:<ArrowDown className="w-3.5 h-3.5 text-trading-down"/>}<span className={cn('font-mono text-num-sm tabular-nums',e.change24h>=0?'text-trading-up':'text-trading-down')}>{e.change24h>=0?'+':''}{e.change24h.toFixed(1)}%</span></div></td><td className="px-5 py-4 text-right font-mono text-num-sm text-muted tabular-nums">{fmtUsd(e.volume)}</td><td className="px-5 py-4 text-right"><div className="flex items-center justify-end gap-1"><Flame className={cn('w-3.5 h-3.5',e.streak>=30?'text-brand-yellow':e.streak>=7?'text-trading-up':'text-muted')}/><span className="font-mono text-num-sm tabular-nums">{e.streak}d</span></div></td><td className="px-5 py-4"><div className="flex flex-wrap justify-center gap-1">{e.protocols.slice(0,3).map(p => <span key={p} className="text-[10px] px-1.5 py-0.5 rounded bg-surface-elevated text-muted">{p}</span>)}{e.protocols.length>3 && <span className="text-[10px] px-1.5 py-0.5 rounded bg-surface-elevated text-muted">+{e.protocols.length-3}</span>}</div></td><td className="px-5 py-4 text-right font-mono text-num-sm text-brand-yellow tabular-nums">{fmtUsd(e.rewards)}</td></tr>))}</tbody></table></div><div className="rounded-xl bg-brand-yellow/5 border border-brand-yellow/20 p-5 flex items-center gap-4"><Trophy className="w-6 h-6 text-brand-yellow flex-shrink-0"/><div><h3 className="text-title-sm text-brand-yellow">Scoring Formula</h3><p className="text-body-md text-muted mt-1"><code className="font-mono text-brand-yellow/80 bg-surface-card px-2 py-0.5 rounded">SCORE = COUNT(protocols) * SUM(swap_volume) * STREAK_MULTIPLIER(days)</code></p><p className="text-body-sm text-muted mt-1">Multi-protocol usage and consecutive activity streaks amplify your score. Powered by Torque Formulas.</p></div></div></div>)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657'use client'import { Users, ShieldAlert, HeartPulse, TrendingUp, Bot, Flame } from 'lucide-react'import { StatCard } from '@/components/ui/StatCard'export default function DashboardPage() {return (<div className="p-6 space-y-6"><div><h1 className="text-display-sm text-[#eaecef]">Dashboard</h1><p className="text-body-md text-muted mt-1">Real-time churn detection and autonomous retention</p></div><div className="grid grid-cols-2 lg:grid-cols-4 gap-4"><StatCard title="Active Wallets" value="312.8K" change={12.3} changeLabel="vs last week" icon={Users} variant="yellow" /><StatCard title="Wallets At Risk" value="23.9K" change={-8.7} changeLabel="vs last week" icon={ShieldAlert} variant="red" /><StatCard title="Wallets Saved" value="15.2K" change={23.4} changeLabel="vs last week" icon={HeartPulse} variant="green" /><StatCard title="ROI" value="847%" change={15.2} changeLabel="vs last week" icon={TrendingUp} variant="yellow" /></div><div className="rounded-xl bg-surface-card border border-hairline-dark p-5"><div className="flex items-center gap-2 mb-4"><Bot className="w-4 h-4 text-brand-yellow" /><span className="text-title-sm">AI Agent Feed</span><div className="w-2 h-2 rounded-full bg-trading-up animate-pulse" /></div><div className="space-y-2">{['Scanning 312,847 active wallets for churn signals...', 'Critical: Wallet 7xKXtg...AsU inactive 10 days', 'Gift sent: 0.5 SOL via Torque MCP', 'Leaderboard updated: 12,847 participants scored', 'Comeback detected: HN7cAB...WrH returned after 12 days'].map((msg, i) => (<div key={i} className="flex items-start gap-3 px-4 py-2 border-b border-hairline-dark/50"><span className="font-mono text-caption text-muted tabular-nums whitespace-nowrap">14:2{i}:00</span><span className="text-body-sm text-[#eaecef]">{['\u{1F50D}','\u26A0\uFE0F','\u{1F381}','\u{1F4CA}','\u{1F525}'][i]} {msg}</span></div>))}</div></div><div className="rounded-xl bg-surface-card border border-hairline-dark p-5"><h3 className="text-title-sm mb-4">Protocol Performance</h3><table className="w-full"><thead><tr className="border-b border-hairline-dark"><th className="text-left text-caption text-muted uppercase px-4 py-3">Protocol</th><th className="text-right text-caption text-muted uppercase px-4 py-3">Users</th><th className="text-right text-caption text-muted uppercase px-4 py-3">Retention</th><th className="text-right text-caption text-muted uppercase px-4 py-3">Streak</th></tr></thead><tbody>{[{p:'Jupiter',u:'234.6K',r:72,s:12,c:'#22d3ee'},{p:'Raydium',u:'189.2K',r:64,s:8,c:'#a78bfa'},{p:'Drift',u:'87.7K',r:68,s:10,c:'#f472b6'},{p:'Marginfi',u:'67.9K',r:74,s:15,c:'#34d399'},{p:'Kamino',u:'45.7K',r:76,s:18,c:'#fbbf24'}].map((row) => (<tr key={row.p} className="border-b border-hairline-dark/50 hover:bg-surface-hover transition-colors"><td className="px-4 py-3"><div className="flex items-center gap-2"><div className="w-3 h-3 rounded-full" style={{backgroundColor:row.c}} /><span className="text-body-md">{row.p}</span></div></td><td className="text-right px-4 py-3 font-mono text-num-md tabular-nums">{row.u}</td><td className="text-right px-4 py-3"><span className={row.r >= 70 ? 'font-mono text-num-sm text-trading-up' : 'font-mono text-num-sm text-brand-yellow'}>{row.r}%</span></td><td className="text-right px-4 py-3"><div className="flex items-center justify-end gap-1"><Flame className="w-3.5 h-3.5 text-brand-yellow" /><span className="font-mono text-num-sm">{row.s}d</span></div></td></tr>))}</tbody></table></div></div>)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124'use client'import { AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, PieChart, Pie, Cell } from 'recharts'import { Users, ShieldAlert, HeartPulse, TrendingUp, Bot, Flame, ArrowUpRight, ArrowDownRight } from 'lucide-react'import { StatCard } from '@/components/ui/StatCard'import { CampaignBadge } from '@/components/ui/CampaignBadge'import { AgentFeed } from '@/components/ui/AgentFeed'import { cn, fmtNum, fmtUsd } from '@/lib/utils'import { stats, events, campaigns, retentionData, churnData, protocols } from '@/lib/mock-data'import type { CampaignType } from '@/lib/types'const Tip = ({ active, payload, label }: any) => {if (!active || !payload?.length) return nullreturn (<div className="bg-surface-elevated border border-hairline-dark rounded-lg p-3 shadow-lg"><p className="text-caption text-muted mb-1">{label}</p><p className="font-mono text-num-md text-[#eaecef]">{payload[0].value}</p></div>)}const riskDist = [{ name: 'Safe', value: 45, color: '#2dbdb6' }, { name: 'Low', value: 25, color: '#0ecb81' },{ name: 'Medium', value: 15, color: '#FCD535' }, { name: 'High', value: 10, color: '#ff9500' },{ name: 'Critical', value: 5, color: '#f6465d' },]export default function DashboardPage() {const active = campaigns.filter(c => c.status === 'active')return (<div className="p-6 space-y-6"><div className="flex items-center justify-between"><div><h1 className="text-display-sm text-[#eaecef]">Dashboard</h1><p className="text-body-md text-muted mt-1">Real-time churn detection and autonomous retention</p></div><div className="px-4 py-2 rounded-lg bg-surface-elevated border border-hairline-dark"><span className="text-caption text-muted">Torque MCP</span><span className="ml-2 text-caption text-trading-up font-semibold">Connected</span></div></div><div className="grid grid-cols-2 lg:grid-cols-4 gap-4"><StatCard title="Active Wallets" value={fmtNum(stats.activeWallets)} change={12.3} changeLabel="vs last week" icon={Users} variant="yellow" /><StatCard title="Wallets At Risk" value={fmtNum(stats.walletsAtRisk)} change={-8.7} changeLabel="vs last week" icon={ShieldAlert} variant="red" /><StatCard title="Wallets Saved" value={fmtNum(stats.walletsSaved)} change={23.4} changeLabel="vs last week" icon={HeartPulse} variant="green" /><StatCard title="ROI" value={stats.roi + '%'} change={15.2} changeLabel="vs last week" icon={TrendingUp} variant="yellow" /></div><AgentFeed /><div className="grid grid-cols-1 lg:grid-cols-2 gap-6"><div className="rounded-xl bg-surface-card border border-hairline-dark p-5"><div className="flex items-center justify-between mb-4"><div><h3 className="text-title-sm">Retention Rate</h3><p className="text-caption text-muted mt-0.5">30-day trailing average</p></div><div className="flex items-center gap-1"><ArrowUpRight className="w-4 h-4 text-trading-up" /><span className="font-mono text-num-sm text-trading-up">+9.6%</span></div></div><ResponsiveContainer width="100%" height={220}><AreaChart data={retentionData}><defs><linearGradient id="rg" x1="0" y1="0" x2="0" y2="1"><stop offset="5%" stopColor="#0ecb81" stopOpacity={0.3}/><stop offset="95%" stopColor="#0ecb81" stopOpacity={0}/></linearGradient></defs><CartesianGrid strokeDasharray="3 3" stroke="#2b3139"/><XAxis dataKey="date" tick={{fill:'#707a8a',fontSize:11}} axisLine={{stroke:'#2b3139'}}/><YAxis tick={{fill:'#707a8a',fontSize:11}} axisLine={{stroke:'#2b3139'}} domain={[50,75]}/><Tooltip content={<Tip/>}/><Area type="monotone" dataKey="value" stroke="#0ecb81" fill="url(#rg)" strokeWidth={2}/></AreaChart></ResponsiveContainer></div><div className="rounded-xl bg-surface-card border border-hairline-dark p-5"><div className="flex items-center justify-between mb-4"><div><h3 className="text-title-sm">Churn Rate</h3><p className="text-caption text-muted mt-0.5">Daily churn percentage</p></div><div className="flex items-center gap-1"><ArrowDownRight className="w-4 h-4 text-trading-up" /><span className="font-mono text-num-sm text-trading-up">-4.3%</span></div></div><ResponsiveContainer width="100%" height={220}><AreaChart data={churnData}><defs><linearGradient id="cg" x1="0" y1="0" x2="0" y2="1"><stop offset="5%" stopColor="#f6465d" stopOpacity={0.3}/><stop offset="95%" stopColor="#f6465d" stopOpacity={0}/></linearGradient></defs><CartesianGrid strokeDasharray="3 3" stroke="#2b3139"/><XAxis dataKey="date" tick={{fill:'#707a8a',fontSize:11}} axisLine={{stroke:'#2b3139'}}/><YAxis tick={{fill:'#707a8a',fontSize:11}} axisLine={{stroke:'#2b3139'}} domain={[0,10]}/><Tooltip content={<Tip/>}/><Area type="monotone" dataKey="value" stroke="#f6465d" fill="url(#cg)" strokeWidth={2}/></AreaChart></ResponsiveContainer></div></div><div className="grid grid-cols-1 lg:grid-cols-3 gap-6"><div className="rounded-xl bg-surface-card border border-hairline-dark p-5"><h3 className="text-title-sm mb-4">Risk Distribution</h3><div className="flex items-center gap-6"><ResponsiveContainer width={140} height={140}><PieChart><Pie data={riskDist} innerRadius={40} outerRadius={65} paddingAngle={3} dataKey="value">{riskDist.map((e,i) => <Cell key={i} fill={e.color}/>)}</Pie></PieChart></ResponsiveContainer><div className="space-y-2">{riskDist.map(r => (<div key={r.name} className="flex items-center gap-2"><div className="w-2.5 h-2.5 rounded-full" style={{backgroundColor:r.color}}/><span className="text-caption text-muted">{r.name}</span><span className="font-mono text-caption text-[#eaecef] ml-auto">{r.value}%</span></div>))}</div></div></div><div className="rounded-xl bg-surface-card border border-hairline-dark p-5"><h3 className="text-title-sm mb-4">Recent Events</h3><div className="space-y-3">{events.slice(0,5).map(e => (<div key={e.id} className="flex items-start gap-3 pb-3 border-b border-hairline-dark/50 last:border-0"><div className={cn('w-2 h-2 rounded-full mt-1.5 flex-shrink-0', e.resolved ? 'bg-trading-up' : 'bg-trading-down animate-pulse')} /><div className="min-w-0"><p className="text-body-sm text-[#eaecef] truncate">{e.eventType.replace(/_/g,' ').toUpperCase()}</p><p className="text-caption text-muted font-mono">{e.wallet}</p></div><span className="text-caption text-muted ml-auto whitespace-nowrap">{e.timestamp}</span></div>))}</div></div><div className="rounded-xl bg-surface-card border border-hairline-dark p-5"><h3 className="text-title-sm mb-4">Active Campaigns</h3><div className="space-y-3">{active.slice(0,4).map(c => (<div key={c.id} className="flex items-center gap-3 pb-3 border-b border-hairline-dark/50 last:border-0"><CampaignBadge type={c.type as CampaignType} /><div className="min-w-0 flex-1"><p className="text-body-sm text-[#eaecef] truncate">{c.name}</p><p className="text-caption text-muted font-mono">{fmtNum(c.participantCount)} users</p></div>{c.createdBy === 'ai-agent' && <Bot className="w-4 h-4 text-brand-yellow flex-shrink-0" />}</div>))}</div></div></div><div className="rounded-xl bg-surface-card border border-hairline-dark p-5"><h3 className="text-title-sm mb-4">Protocol Performance</h3><table className="w-full"><thead><tr className="border-b border-hairline-dark"><th className="text-left text-caption text-muted uppercase tracking-wider px-4 py-3">Protocol</th><th className="text-right text-caption text-muted uppercase tracking-wider px-4 py-3">Volume</th><th className="text-right text-caption text-muted uppercase tracking-wider px-4 py-3">Users</th><th className="text-right text-caption text-muted uppercase tracking-wider px-4 py-3">Churn</th><th className="text-right text-caption text-muted uppercase tracking-wider px-4 py-3">Retention</th><th className="text-right text-caption text-muted uppercase tracking-wider px-4 py-3">Avg Streak</th></tr></thead><tbody>{protocols.map(p => (<tr key={p.protocol} className="border-b border-hairline-dark/50 hover:bg-surface-hover transition-colors"><td className="px-4 py-3"><div className="flex items-center gap-2"><div className="w-3 h-3 rounded-full" style={{backgroundColor:p.color}}/><span className="text-body-md font-medium">{p.protocol}</span></div></td><td className="text-right px-4 py-3 font-mono text-num-md tabular-nums">{fmtUsd(p.volume)}</td><td className="text-right px-4 py-3 font-mono text-num-md tabular-nums">{fmtNum(p.users)}</td><td className="text-right px-4 py-3"><span className={cn('font-mono text-num-sm', p.churnRate <= 4 ? 'text-trading-up' : 'text-trading-down')}>{p.churnRate}%</span></td><td className="text-right px-4 py-3"><span className={cn('font-mono text-num-sm', p.retentionRate >= 70 ? 'text-trading-up' : 'text-brand-yellow')}>{p.retentionRate}%</span></td><td className="text-right px-4 py-3"><div className="flex items-center justify-end gap-1"><Flame className="w-3.5 h-3.5 text-brand-yellow"/><span className="font-mono text-num-sm">{p.avgStreak}d</span></div></td></tr>))}</tbody></table></div></div>)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566'use client'import { cn } from '@/lib/utils'import { Search, Flame, ExternalLink, ChevronRight } from 'lucide-react'import { useState } from 'react'type Risk = 'critical' | 'high' | 'medium' | 'low' | 'safe'const wallets = [{ addr: '7xKXtg...AsU', risk: 'critical' as Risk, score: 94, vol: '$847K', streak: 0, protocols: ['Jupiter','Raydium'], last: '10d ago', saved: 0 },{ addr: '9WzDXw...WWM', risk: 'high' as Risk, score: 78, vol: '$1.2M', streak: 2, protocols: ['Drift','Marginfi','Jupiter'], last: '5d ago', saved: 1 },{ addr: '4zMMC9...cDU', risk: 'medium' as Risk, score: 52, vol: '$3.5M', streak: 5, protocols: ['Kamino','Jupiter'], last: '2d ago', saved: 0 },{ addr: 'HN7cAB...WrH', risk: 'low' as Risk, score: 23, vol: '$8.7M', streak: 14, protocols: ['Jupiter','Raydium','Drift','Kamino'], last: '1h ago', saved: 2 },{ addr: '5Q544f...4j1', risk: 'safe' as Risk, score: 8, vol: '$15.2M', streak: 47, protocols: ['Jupiter','Raydium','Drift','Marginfi','Kamino'], last: '30m ago', saved: 3 },{ addr: 'DRpbCB...1hy', risk: 'critical' as Risk, score: 91, vol: '$235K', streak: 0, protocols: ['Raydium'], last: '12d ago', saved: 0 },{ addr: 'BKiKp1...mS2', risk: 'safe' as Risk, score: 5, vol: '$28.5M', streak: 62, protocols: ['Jupiter','Raydium','Drift','Marginfi','Kamino','Tensor'], last: '15m ago', saved: 5 },]const riskCfg: Record<Risk, { label: string; color: string; bg: string; dot: string }> = {critical: { label: 'CRITICAL', color: 'text-trading-down', bg: 'bg-trading-down/10', dot: 'bg-trading-down' },high: { label: 'HIGH', color: 'text-[#ff9500]', bg: 'bg-[#ff9500]/10', dot: 'bg-[#ff9500]' },medium: { label: 'MEDIUM', color: 'text-brand-yellow', bg: 'bg-brand-yellow/10', dot: 'bg-brand-yellow' },low: { label: 'LOW', color: 'text-trading-up', bg: 'bg-trading-up/10', dot: 'bg-trading-up' },safe: { label: 'SAFE', color: 'text-brand-turquoise', bg: 'bg-brand-turquoise/10', dot: 'bg-brand-turquoise' },}export default function WalletsPage() {const [filter, setFilter] = useState<Risk | 'all'>('all')const filtered = wallets.filter(w => filter === 'all' || w.risk === filter)return (<div className="p-6 space-y-6"><div><h1 className="text-display-sm text-[#eaecef]">Wallets</h1><p className="text-body-md text-muted mt-1">Monitor wallet health, churn risk & activity patterns</p></div><div className="grid grid-cols-2 lg:grid-cols-6 gap-3">{(['all','critical','high','medium','low','safe'] as const).map(r => (<button key={r} onClick={() => setFilter(r)} className={cn('rounded-xl border p-3 text-center transition-all', filter === r ? 'border-brand-yellow/40 bg-brand-yellow/5' : 'border-hairline-dark bg-surface-card hover:border-brand-yellow/20')}><span className="text-caption text-muted capitalize">{r}</span><p className="font-mono text-title-md text-[#eaecef] tabular-nums mt-0.5">{r === 'all' ? wallets.length : wallets.filter(w => w.risk === r).length}</p></button>))}</div><div className="rounded-xl bg-surface-card border border-hairline-dark overflow-hidden"><table className="w-full"><thead><tr className="border-b border-hairline-dark bg-surface-elevated/50"><th className="text-left text-caption text-muted uppercase px-5 py-3">Wallet</th><th className="text-center text-caption text-muted uppercase px-5 py-3">Risk</th><th className="text-right text-caption text-muted uppercase px-5 py-3">Score</th><th className="text-right text-caption text-muted uppercase px-5 py-3">Volume</th><th className="text-right text-caption text-muted uppercase px-5 py-3">Streak</th><th className="text-center text-caption text-muted uppercase px-5 py-3">Protocols</th><th className="text-right text-caption text-muted uppercase px-5 py-3">Last Active</th><th className="w-10"></th></tr></thead><tbody>{filtered.map(w => { const rc = riskCfg[w.risk]; return (<tr key={w.addr} className="border-b border-hairline-dark/50 hover:bg-surface-hover transition-colors group"><td className="px-5 py-4"><div className="flex items-center gap-2"><span className="font-mono text-body-md">{w.addr}</span><ExternalLink className="w-3 h-3 text-muted opacity-0 group-hover:opacity-100 transition" /></div></td><td className="px-5 py-4 text-center"><div className={cn('inline-flex items-center gap-1.5 px-3 py-1 rounded-pill', rc.bg)}><div className={cn('w-2 h-2 rounded-full', rc.dot)} /><span className={cn('font-mono text-caption font-semibold', rc.color)}>{rc.label}</span></div></td><td className="px-5 py-4 text-right"><div className="flex items-center justify-end gap-2"><div className="w-16 h-1.5 rounded-full bg-surface-elevated overflow-hidden"><div className={cn('h-full rounded-full', w.score >= 80 ? 'bg-trading-down' : w.score >= 60 ? 'bg-[#ff9500]' : w.score >= 40 ? 'bg-brand-yellow' : w.score >= 20 ? 'bg-trading-up' : 'bg-brand-turquoise')} style={{ width: `${w.score}%` }} /></div><span className="font-mono text-num-sm text-muted tabular-nums w-8 text-right">{w.score}</span></div></td><td className="px-5 py-4 text-right font-mono text-num-sm tabular-nums">{w.vol}</td><td className="px-5 py-4 text-right"><div className="flex items-center justify-end gap-1"><Flame className={cn('w-3.5 h-3.5', w.streak >= 30 ? 'text-brand-yellow' : w.streak >= 7 ? 'text-trading-up' : w.streak === 0 ? 'text-trading-down' : 'text-muted')} /><span className="font-mono text-num-sm">{w.streak}d</span></div></td><td className="px-5 py-4"><div className="flex flex-wrap justify-center gap-1">{w.protocols.slice(0,3).map(p => <span key={p} className="text-[10px] px-1.5 py-0.5 rounded bg-surface-elevated text-muted">{p}</span>)}{w.protocols.length > 3 && <span className="text-[10px] px-1.5 py-0.5 rounded bg-surface-elevated text-muted">+{w.protocols.length-3}</span>}</div></td><td className="px-5 py-4 text-right text-body-sm text-muted">{w.last}</td><td className="px-2 py-4"><ChevronRight className="w-4 h-4 text-muted opacity-0 group-hover:opacity-100 transition" /></td></tr>)})}</tbody></table></div></div>)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768'use client'import { cn, fmtUsd, shortAddr } from '@/lib/utils'import { wallets } from '@/lib/mock-data'import { RiskBadge } from '@/components/ui/RiskBadge'import { Search, Flame, ExternalLink, ChevronRight } from 'lucide-react'import { useState } from 'react'import type { ChurnRisk } from '@/lib/types'type Filter = ChurnRisk | 'all'const filters: Filter[] = ['all','critical','high','medium','low','safe']export default function WalletsPage() {const [f, setF] = useState<Filter>('all')const [q, setQ] = useState('')const [sort, setSort] = useState<'risk'|'volume'|'streak'>('risk')const list = wallets.filter(w => f === 'all' || w.churnRisk === f).filter(w => !q || w.address.toLowerCase().includes(q.toLowerCase())).sort((a,b) => sort === 'risk' ? b.riskScore - a.riskScore : sort === 'volume' ? b.totalVolume - a.totalVolume : b.streak - a.streak)return (<div className="p-6 space-y-6"><div><h1 className="text-display-sm text-[#eaecef]">Wallets</h1><p className="text-body-md text-muted mt-1">Monitor wallet health, churn risk & activity patterns</p></div><div className="grid grid-cols-2 lg:grid-cols-6 gap-3">{filters.map(r => (<button key={r} onClick={() => setF(r)} className={cn('rounded-xl border p-3 text-center transition-all', f===r ? 'border-brand-yellow/40 bg-brand-yellow/5' : 'border-hairline-dark bg-surface-card hover:border-brand-yellow/20')}><span className="text-caption text-muted capitalize">{r}</span><p className="font-mono text-title-md text-[#eaecef] tabular-nums mt-0.5">{r==='all'?wallets.length:wallets.filter(w=>w.churnRisk===r).length}</p></button>))}</div><div className="flex items-center gap-3"><div className="relative flex-1 max-w-md"><Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted"/><input type="text" placeholder="Search wallet..." value={q} onChange={e=>setQ(e.target.value)} className="w-full h-9 pl-9 pr-4 rounded-lg bg-surface-card border border-hairline-dark text-body-sm placeholder:text-muted focus:outline-none focus:ring-1 focus:ring-brand-yellow/50"/></div><div className="flex items-center gap-1 p-1 rounded-lg bg-surface-card border border-hairline-dark">{(['risk','volume','streak'] as const).map(s => <button key={s} onClick={() => setSort(s)} className={cn('px-3 py-1.5 rounded-md text-caption transition capitalize', sort===s?'bg-brand-yellow text-ink font-semibold':'text-muted hover:text-[#eaecef]')}>{s}</button>)}</div></div><div className="rounded-xl bg-surface-card border border-hairline-dark overflow-hidden"><table className="w-full"><thead><tr className="border-b border-hairline-dark bg-surface-elevated/50"><th className="text-left text-caption text-muted uppercase tracking-wider px-5 py-3">Wallet</th><th className="text-center text-caption text-muted uppercase tracking-wider px-5 py-3">Risk</th><th className="text-right text-caption text-muted uppercase tracking-wider px-5 py-3">Score</th><th className="text-right text-caption text-muted uppercase tracking-wider px-5 py-3">Volume</th><th className="text-right text-caption text-muted uppercase tracking-wider px-5 py-3">Streak</th><th className="text-center text-caption text-muted uppercase tracking-wider px-5 py-3">Protocols</th><th className="text-right text-caption text-muted uppercase tracking-wider px-5 py-3">Last Active</th><th className="w-10"></th></tr></thead><tbody>{list.map(w => (<tr key={w.address} className="border-b border-hairline-dark/50 hover:bg-surface-hover transition-colors group"><td className="px-5 py-4"><div className="flex items-center gap-2"><span className="font-mono text-body-md text-[#eaecef]">{shortAddr(w.address)}</span><ExternalLink className="w-3 h-3 text-muted opacity-0 group-hover:opacity-100 transition"/></div></td><td className="px-5 py-4 text-center"><RiskBadge risk={w.churnRisk}/></td><td className="px-5 py-4 text-right"><div className="flex items-center justify-end gap-2"><div className="w-16 h-1.5 rounded-full bg-surface-elevated overflow-hidden"><div className={cn('h-full rounded-full', w.riskScore>=80?'bg-trading-down':w.riskScore>=60?'bg-[#ff9500]':w.riskScore>=40?'bg-brand-yellow':w.riskScore>=20?'bg-trading-up':'bg-brand-turquoise')} style={{width:w.riskScore+'%'}}/></div><span className="font-mono text-num-sm text-muted tabular-nums w-8 text-right">{w.riskScore}</span></div></td><td className="px-5 py-4 text-right font-mono text-num-sm text-[#eaecef] tabular-nums">{fmtUsd(w.totalVolume)}</td><td className="px-5 py-4 text-right"><div className="flex items-center justify-end gap-1"><Flame className={cn('w-3.5 h-3.5', w.streak>=30?'text-brand-yellow':w.streak>=7?'text-trading-up':w.streak===0?'text-trading-down':'text-muted')}/><span className="font-mono text-num-sm tabular-nums">{w.streak}d</span></div></td><td className="px-5 py-4"><div className="flex flex-wrap justify-center gap-1">{w.protocols.slice(0,3).map(p=><span key={p} className="text-[10px] px-1.5 py-0.5 rounded bg-surface-elevated text-muted">{p}</span>)}{w.protocols.length>3 && <span className="text-[10px] px-1.5 py-0.5 rounded bg-surface-elevated text-muted">+{w.protocols.length-3}</span>}</div></td><td className="px-5 py-4 text-right text-body-sm text-muted">{w.lastActive}</td><td className="px-2 py-4"><ChevronRight className="w-4 h-4 text-muted opacity-0 group-hover:opacity-100 transition"/></td></tr>))}</tbody></table></div></div>)
123import { NextResponse } from 'next/server'export async function POST() { return NextResponse.json({ success: true, campaignId: `demo-camp-${Date.now()}` }) }export async function GET() { return NextResponse.json({ campaigns: [] }) }123import { NextResponse } from 'next/server'export async function POST() { return NextResponse.json({ success: true, campaignId: 'demo-camp-' + Date.now() }) }export async function GET() { return NextResponse.json({ campaigns: [] }) }
123import { NextResponse } from 'next/server'export async function POST() { return NextResponse.json({ success: true, eventId: `demo-${Date.now()}` }) }export async function GET() { return NextResponse.json({ status: 'ok', events: ['churn_risk_high','churn_risk_medium','comeback_detected','streak_maintained','volume_milestone','referral_from_saved','inactivity_detected'] }) }123import { NextResponse } from 'next/server'export async function POST() { return NextResponse.json({ success: true, eventId: 'demo-' + Date.now() }) }export async function GET() { return NextResponse.json({ status: 'ok', events: ['churn_risk_high','churn_risk_medium','comeback_detected','streak_maintained','volume_milestone','referral_from_saved','inactivity_detected'] }) }
8 unmodified lines9101112131415168 unmodified lines::-webkit-scrollbar { @apply w-1.5; }::-webkit-scrollbar-track { @apply bg-canvas-dark; }::-webkit-scrollbar-thumb { @apply bg-surface-elevated rounded-full; }}@layer utilities {.glow-yellow { box-shadow: 0 0 20px rgba(252, 213, 53, 0.15); }}8 unmodified lines9101112131415161718192021228 unmodified lines::-webkit-scrollbar { @apply w-1.5; }::-webkit-scrollbar-track { @apply bg-canvas-dark; }::-webkit-scrollbar-thumb { @apply bg-surface-elevated rounded-full; }::-webkit-scrollbar-thumb:hover { @apply bg-muted; }}@layer utilities {.glow-yellow { box-shadow: 0 0 20px rgba(252,213,53,0.15), 0 0 60px rgba(252,213,53,0.05); }.glow-green { box-shadow: 0 0 12px rgba(14,203,129,0.25); }.grid-pattern {background-image: linear-gradient(rgba(43,49,57,0.3) 1px, transparent 1px), linear-gradient(90deg, rgba(43,49,57,0.3) 1px, transparent 1px);background-size: 40px 40px;}}
12345678910111213141516171819import type { Metadata } from 'next'import { Inter, IBM_Plex_Mono } from 'next/font/google'import { cn } from '@/lib/utils'import './globals.css'const inter = Inter({ subsets: ['latin'], variable: '--font-inter', display: 'swap', weight: ['400', '500', '600', '700'] })const ibmPlexMono = IBM_Plex_Mono({ subsets: ['latin'], variable: '--font-ibm-plex-mono', display: 'swap', weight: ['400', '500', '600', '700'] })export const metadata: Metadata = {title: 'FlowState — AI-Powered Anti-Churn Engine',description: 'The autonomous retention layer for Solana protocols. Powered by Torque MCP.',}export default function RootLayout({ children }: { children: React.ReactNode }) {return (<html lang="en" className={cn('dark', inter.variable, ibmPlexMono.variable)}><body className="bg-canvas-dark text-[#eaecef] font-sans antialiased min-h-screen">{children}</body></html>)123456789101112131415161718import type { Metadata } from 'next'import { Inter, IBM_Plex_Mono } from 'next/font/google'import './globals.css'const inter = Inter({ subsets: ['latin'], variable: '--font-inter', display: 'swap', weight: ['400','500','600','700'] })const mono = IBM_Plex_Mono({ subsets: ['latin'], variable: '--font-ibm-plex-mono', display: 'swap', weight: ['400','500','600','700'] })export const metadata: Metadata = {title: 'FlowState — AI-Powered Anti-Churn Engine',description: 'Autonomous retention layer for Solana protocols. Powered by Torque MCP.',}export default function RootLayout({ children }: { children: React.ReactNode }) {return (<html lang="en" className={`dark ${inter.variable} ${mono.variable}`}><body className="bg-canvas-dark text-[#eaecef] font-sans antialiased min-h-screen">{children}</body></html>)
4 unmodified lines5678910113 unmodified lines15161718192021222324252627282930313233343536373839404142434445464 unmodified linesimport { LayoutDashboard, Trophy, Megaphone, BarChart3, Wallet, Bot, Zap, Shield, ChevronLeft, ChevronRight } from 'lucide-react'import { useState } from 'react'const navItems = [{ label: 'Dashboard', href: '/', icon: LayoutDashboard },{ label: 'Leaderboard', href: '/leaderboard', icon: Trophy },{ label: 'Campaigns', href: '/campaigns', icon: Megaphone },3 unmodified lines]export function Sidebar() {const pathname = usePathname()const [collapsed, setCollapsed] = useState(false)return (<aside className={cn('hidden md:flex flex-col border-r border-hairline-dark bg-surface-card transition-all duration-300', collapsed ? 'w-[68px]' : 'w-[240px]')}><div className="flex items-center h-16 px-4 border-b border-hairline-dark"><div className="flex items-center gap-2.5 overflow-hidden"><div className="w-8 h-8 rounded-lg bg-brand-yellow flex items-center justify-center flex-shrink-0"><Zap className="w-5 h-5 text-ink" /></div>{!collapsed && <span className="text-title-sm text-brand-yellow font-bold tracking-tight animate-slide-in-right">FlowState</span>}</div></div><nav className="flex-1 py-4 px-2 space-y-1">{navItems.map(item => {const isActive = pathname === item.href || (item.href !== '/' && pathname.startsWith(item.href))return (<Link key={item.href} href={item.href} className={cn('flex items-center gap-3 px-3 py-2.5 rounded-lg text-nav transition-all duration-200', isActive ? 'bg-brand-yellow/10 text-brand-yellow' : 'text-muted hover:text-[#eaecef] hover:bg-surface-elevated', collapsed && 'justify-center px-2')}><item.icon className={cn('w-5 h-5 flex-shrink-0', isActive && 'text-brand-yellow')} />{!collapsed && <span>{item.label}</span>}</Link>)})}</nav><div className="p-2 border-t border-hairline-dark">{!collapsed && <div className="mx-3 mb-3 p-3 rounded-xl bg-brand-yellow/5 border border-brand-yellow/20"><div className="flex items-center gap-2 mb-1"><Shield className="w-4 h-4 text-trading-up" /><span className="text-caption text-trading-up font-semibold">AI Agent Active</span></div><p className="text-caption text-muted">3,847 actions today</p></div>}<button onClick={() => setCollapsed(!collapsed)} className="flex items-center gap-3 px-3 py-2.5 rounded-lg text-nav text-muted hover:text-[#eaecef] hover:bg-surface-elevated w-full transition-colors">{collapsed ? <ChevronRight className="w-5 h-5" /> : <ChevronLeft className="w-5 h-5" />}{!collapsed && <span>Collapse</span>}</button></div></aside>4 unmodified lines5678910113 unmodified lines151617181920212223242526272829303132333435363738394041424344454647484950514 unmodified linesimport { LayoutDashboard, Trophy, Megaphone, BarChart3, Wallet, Bot, Zap, Shield, ChevronLeft, ChevronRight } from 'lucide-react'import { useState } from 'react'const nav = [{ label: 'Dashboard', href: '/', icon: LayoutDashboard },{ label: 'Leaderboard', href: '/leaderboard', icon: Trophy },{ label: 'Campaigns', href: '/campaigns', icon: Megaphone },3 unmodified lines]export function Sidebar() {const path = usePathname()const [col, setCol] = useState(false)return (<aside className={cn('hidden md:flex flex-col border-r border-hairline-dark bg-surface-card transition-all duration-300', col ? 'w-[68px]' : 'w-[240px]')}><div className="flex items-center h-16 px-4 border-b border-hairline-dark"><div className="flex items-center gap-2.5 overflow-hidden"><div className="w-8 h-8 rounded-lg bg-brand-yellow flex items-center justify-center flex-shrink-0"><Zap className="w-5 h-5 text-ink" /></div>{!col && <span className="text-title-sm text-brand-yellow font-bold tracking-tight animate-slide-in-right">FlowState</span>}</div></div><nav className="flex-1 py-4 px-2 space-y-1">{nav.map(item => {const active = path === item.href || (item.href !== '/' && path.startsWith(item.href))return (<Link key={item.href} href={item.href} className={cn('flex items-center gap-3 px-3 py-2.5 rounded-lg text-nav transition-all duration-200', active ? 'bg-brand-yellow/10 text-brand-yellow' : 'text-muted hover:text-[#eaecef] hover:bg-surface-elevated', col && 'justify-center px-2')}><item.icon className={cn('w-5 h-5 flex-shrink-0', active && 'text-brand-yellow')} />{!col && <span>{item.label}</span>}</Link>)})}</nav><div className="p-2 border-t border-hairline-dark">{!col && (<div className="mx-3 mb-3 p-3 rounded-xl bg-brand-yellow/5 border border-brand-yellow/20"><div className="flex items-center gap-2 mb-1"><Shield className="w-4 h-4 text-trading-up" /><span className="text-caption text-trading-up font-semibold">AI Agent Active</span></div><p className="text-caption text-muted">3,847 actions today</p></div>)}<button onClick={() => setCol(!col)} className="flex items-center gap-3 px-3 py-2.5 rounded-lg text-nav text-muted hover:text-[#eaecef] hover:bg-surface-elevated w-full transition-colors">{col ? <ChevronRight className="w-5 h-5" /> : <ChevronLeft className="w-5 h-5" />}{!col && <span>Collapse</span>}</button></div></aside>
3 unmodified lines456789101112131415161718192021223 unmodified linesexport function Topbar() {const [time, setTime] = useState('')useEffect(() => { const u = () => setTime(new Date().toLocaleTimeString('en-US', { hour12: false })); u(); const i = setInterval(u, 1000); return () => clearInterval(i) }, [])return (<header className="h-14 border-b border-hairline-dark bg-surface-card/80 backdrop-blur-sm flex items-center justify-between px-6"><div className="relative"><Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted" /><input type="text" placeholder="Search wallets, campaigns..." className="w-64 h-9 pl-9 pr-4 rounded-lg bg-surface-elevated border border-hairline-dark text-body-sm text-[#eaecef] placeholder:text-muted focus:outline-none focus:ring-1 focus:ring-brand-yellow/50" /></div><div className="flex items-center gap-4"><div className="flex items-center gap-2 px-3 py-1.5 rounded-pill bg-trading-up/10 border border-trading-up/20"><div className="w-2 h-2 rounded-full bg-trading-up animate-pulse" /><span className="text-caption text-trading-up font-semibold">LIVE</span></div><span className="font-mono text-num-sm text-muted tabular-nums">{time}</span><button className="flex items-center gap-1.5 text-muted hover:text-[#eaecef] transition"><Wifi className="w-4 h-4 text-trading-up" /><span className="text-caption">Solana</span></button><button className="relative p-2 rounded-lg hover:bg-surface-elevated transition"><Bell className="w-4 h-4 text-muted" /><span className="absolute top-1 right-1 w-2 h-2 bg-brand-yellow rounded-full" /></button><button className="flex items-center gap-2 px-4 py-2 rounded-md bg-brand-yellow text-ink text-button font-semibold hover:bg-brand-yellow-active transition"><Globe className="w-4 h-4" />Connect</button></div></header>)3 unmodified lines4567891011121314151617181920212223242526272829303132333435363 unmodified linesexport function Topbar() {const [time, setTime] = useState('')useEffect(() => {const u = () => setTime(new Date().toLocaleTimeString('en-US', { hour12: false }))u(); const i = setInterval(u, 1000); return () => clearInterval(i)}, [])return (<header className="h-14 border-b border-hairline-dark bg-surface-card/80 backdrop-blur-sm flex items-center justify-between px-6"><div className="relative"><Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted" /><input type="text" placeholder="Search wallets, campaigns..." className="w-64 h-9 pl-9 pr-4 rounded-lg bg-surface-elevated border border-hairline-dark text-body-sm text-[#eaecef] placeholder:text-muted focus:outline-none focus:ring-1 focus:ring-brand-yellow/50 transition" /></div><div className="flex items-center gap-4"><div className="flex items-center gap-2 px-3 py-1.5 rounded-pill bg-trading-up/10 border border-trading-up/20"><div className="w-2 h-2 rounded-full bg-trading-up animate-pulse" /><span className="text-caption text-trading-up font-semibold">LIVE</span></div><span className="font-mono text-num-sm text-muted tabular-nums">{time}</span><button className="flex items-center gap-1.5 text-muted hover:text-[#eaecef] transition"><Wifi className="w-4 h-4 text-trading-up" /><span className="text-caption">Solana</span></button><button className="relative p-2 rounded-lg hover:bg-surface-elevated transition"><Bell className="w-4 h-4 text-muted" /><span className="absolute top-1 right-1 w-2 h-2 bg-brand-yellow rounded-full" /></button><button className="flex items-center gap-2 px-4 py-2 rounded-md bg-brand-yellow text-ink text-button font-semibold hover:bg-brand-yellow-active transition"><Globe className="w-4 h-4" />Connect</button></div></header>)
12345678910111213141516171819202122232425262728293031323334353637383940414243444546'use client'import { useState, useEffect } from 'react'import { cn } from '@/lib/utils'import { agentMsgs } from '@/lib/mock-data'import { Bot, ChevronDown, ChevronUp } from 'lucide-react'
export function AgentFeed() { const [msgs, setMsgs] = useState<{ text: string; time: string }[]>([]) const [open, setOpen] = useState(true)
useEffect(() => { const init = agentMsgs.slice(0, 5).map((t, i) => ({ text: t, time: new Date(Date.now() - i * 120000).toLocaleTimeString('en-US', { hour12: false }) })) setMsgs(init) let c = 5 const iv = setInterval(() => { const t = agentMsgs[c++ % agentMsgs.length] setMsgs(p => [{ text: t, time: new Date().toLocaleTimeString('en-US', { hour12: false }) }, ...p].slice(0, 20)) }, 4000) return () => clearInterval(iv) }, [])
return ( <div className="rounded-xl bg-surface-card border border-hairline-dark overflow-hidden"> <button onClick={() => setOpen(!open)} className="w-full flex items-center justify-between px-5 py-3 border-b border-hairline-dark hover:bg-surface-elevated transition"> <div className="flex items-center gap-2"> <Bot className="w-4 h-4 text-brand-yellow" /> <span className="text-title-sm">AI Agent Feed</span> <div className="w-2 h-2 rounded-full bg-trading-up animate-pulse" /> </div> {open ? <ChevronUp className="w-4 h-4 text-muted" /> : <ChevronDown className="w-4 h-4 text-muted" />} </button> {open && ( <div className="max-h-[300px] overflow-y-auto"> {msgs.map((m, i) => ( <div key={i} className={cn('flex items-start gap-3 px-5 py-2.5 border-b border-hairline-dark/50 transition-colors', i === 0 && 'animate-slide-up bg-brand-yellow/5')}> <span className="font-mono text-caption text-muted tabular-nums whitespace-nowrap mt-0.5">{m.time}</span> <span className="text-body-sm text-[#eaecef]">{m.text}</span> </div> ))} </div> )} </div> )}123456789101112131415161718192021'use client'import { cn } from '@/lib/utils'import { CampaignType } from '@/lib/types'import { Trophy, Gift, Ticket, Percent } from 'lucide-react'
const cfg: Record<CampaignType, { label: string; icon: typeof Trophy; color: string; bg: string }> = { leaderboard: { label: 'Leaderboard', icon: Trophy, color: 'text-brand-yellow', bg: 'bg-brand-yellow/10' }, gift: { label: 'Gift', icon: Gift, color: 'text-brand-turquoise', bg: 'bg-brand-turquoise/10' }, raffle: { label: 'Raffle', icon: Ticket, color: 'text-[#a78bfa]', bg: 'bg-[#a78bfa]/10' }, rebate: { label: 'Rebate', icon: Percent, color: 'text-trading-up', bg: 'bg-trading-up/10' },}
export function CampaignBadge({ type }: { type: CampaignType }) { const c = cfg[type]; const Icon = c.icon return ( <div className={cn('inline-flex items-center gap-1.5 px-2.5 py-1 rounded-md', c.bg)}> <Icon className={cn('w-3.5 h-3.5', c.color)} /> <span className={cn('text-caption font-semibold', c.color)}>{c.label}</span> </div> )}123456789101112131415161718192021'use client'import { cn } from '@/lib/utils'import { ChurnRisk } from '@/lib/types'
const cfg: Record<ChurnRisk, { label: string; color: string; bg: string; dot: string }> = { critical: { label: 'CRITICAL', color: 'text-trading-down', bg: 'bg-trading-down/10', dot: 'bg-trading-down' }, high: { label: 'HIGH', color: 'text-[#ff9500]', bg: 'bg-[#ff9500]/10', dot: 'bg-[#ff9500]' }, medium: { label: 'MEDIUM', color: 'text-brand-yellow', bg: 'bg-brand-yellow/10', dot: 'bg-brand-yellow' }, low: { label: 'LOW', color: 'text-trading-up', bg: 'bg-trading-up/10', dot: 'bg-trading-up' }, safe: { label: 'SAFE', color: 'text-brand-turquoise', bg: 'bg-brand-turquoise/10', dot: 'bg-brand-turquoise' },}
export function RiskBadge({ risk, size = 'md' }: { risk: ChurnRisk; size?: 'sm' | 'md' }) { const c = cfg[risk] return ( <div className={cn('inline-flex items-center gap-1.5 rounded-pill', c.bg, size === 'sm' ? 'px-2 py-0.5' : 'px-3 py-1')}> <div className={cn('rounded-full', c.dot, size === 'sm' ? 'w-1.5 h-1.5' : 'w-2 h-2')} /> <span className={cn('font-mono font-semibold', c.color, size === 'sm' ? 'text-[10px]' : 'text-caption')}>{c.label}</span> </div> )}1 unmodified line2345678910111213141 unmodified lineimport { cn } from '@/lib/utils'import { LucideIcon } from 'lucide-react'interface StatCardProps { title: string; value: string; change?: number; changeLabel?: string; icon: LucideIcon; variant?: 'default' | 'yellow' | 'green' | 'red' }export function StatCard({ title, value, change, changeLabel, icon: Icon, variant = 'default' }: StatCardProps) {const vs: Record<string, string> = { default: 'border-hairline-dark', yellow: 'border-brand-yellow/20 bg-brand-yellow/5', green: 'border-trading-up/20 bg-trading-up/5', red: 'border-trading-down/20 bg-trading-down/5' }const is: Record<string, string> = { default: 'bg-surface-elevated text-muted', yellow: 'bg-brand-yellow/10 text-brand-yellow', green: 'bg-trading-up/10 text-trading-up', red: 'bg-trading-down/10 text-trading-down' }return (<div className={cn('p-5 rounded-xl bg-surface-card border transition-all hover:border-brand-yellow/30', vs[variant])}><div className="flex items-start justify-between mb-3"><span className="text-caption text-muted uppercase tracking-wider">{title}</span><div className={cn('p-2 rounded-lg', is[variant])}><Icon className="w-4 h-4" /></div>1 unmodified line234567891011121314151 unmodified lineimport { cn } from '@/lib/utils'import { LucideIcon } from 'lucide-react'interface Props { title: string; value: string; change?: number; changeLabel?: string; icon: LucideIcon; variant?: 'default'|'yellow'|'green'|'red'; className?: string }const vs: Record<string, string> = { default:'border-hairline-dark', yellow:'border-brand-yellow/20 bg-brand-yellow/5', green:'border-trading-up/20 bg-trading-up/5', red:'border-trading-down/20 bg-trading-down/5' }const is: Record<string, string> = { default:'bg-surface-elevated text-muted', yellow:'bg-brand-yellow/10 text-brand-yellow', green:'bg-trading-up/10 text-trading-up', red:'bg-trading-down/10 text-trading-down' }export function StatCard({ title, value, change, changeLabel, icon: Icon, variant='default', className }: Props) {return (<div className={cn('p-5 rounded-xl bg-surface-card border transition-all duration-300 hover:border-brand-yellow/30 group', vs[variant], className)}><div className="flex items-start justify-between mb-3"><span className="text-caption text-muted uppercase tracking-wider">{title}</span><div className={cn('p-2 rounded-lg', is[variant])}><Icon className="w-4 h-4" /></div>
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970/** * FlowState AI Agent Engine — Autonomous churn detection & retention * 5-signal scoring: inactivity, volume decline, protocol diversity, streak, liquidation */import { ChurnRisk } from './types'import { sendCustomEvent, createCampaign } from './torque-mcp'
export function calculateChurnScore(activity: { daysInactive: number; volumeDropPct: number; uniqueProtocols: number; currentStreak: number; hasLiquidation: boolean}): { score: number; risk: ChurnRisk; signals: string[] } { let score = 0 const signals: string[] = []
// Signal 1: Inactivity (0-30pts) const inactScore = Math.min(activity.daysInactive * 3, 30) score += inactScore if (activity.daysInactive >= 7) signals.push('Inactive ' + activity.daysInactive + ' days')
// Signal 2: Volume decline (0-25pts) if (activity.volumeDropPct > 0) { score += Math.min(activity.volumeDropPct / 4, 25) signals.push('Volume dropped ' + activity.volumeDropPct.toFixed(0) + '%') }
// Signal 3: Protocol diversity (0-15pts) if (activity.uniqueProtocols <= 1) { score += 15; signals.push('Single protocol — low engagement') } else if (activity.uniqueProtocols <= 2) { score += 8; signals.push('Limited protocol diversity') }
// Signal 4: Streak broken (0-15pts) if (activity.currentStreak === 0) { score += 15; signals.push('Activity streak broken') } else if (activity.currentStreak < 3) score += 5
// Signal 5: Liquidation (0-15pts) if (activity.hasLiquidation) { score += 15; signals.push('Recent liquidation event') }
score = Math.min(Math.max(score, 0), 100)
let risk: ChurnRisk if (score >= 80) risk = 'critical' else if (score >= 60) risk = 'high' else if (score >= 40) risk = 'medium' else if (score >= 20) risk = 'low' else risk = 'safe'
return { score, risk, signals }}
export function selectResponse(risk: ChurnRisk, wallet: string): { action: string; description: string }[] { const responses: { action: string; description: string }[] = [] responses.push({ action: 'detect', description: 'Detected ' + risk + ' churn risk for ' + wallet.slice(0, 8) + '...' })
switch (risk) { case 'critical': responses.push({ action: 'gift', description: 'Sending 0.5 SOL gift via Anti-Churn campaign' }) responses.push({ action: 'raffle', description: 'Enrolling in Comeback Raffle with 5x multiplier' }) break case 'high': responses.push({ action: 'raffle', description: 'Enrolling in Comeback Raffle with 3x multiplier' }) break case 'medium': responses.push({ action: 'rebate', description: 'Activating 2x rebate boost for 48 hours' }) break } return responses}
export async function executeResponse(wallet: string, action: string) { return sendCustomEvent(wallet, action === 'gift' ? 'churn_risk_high' : action === 'raffle' ? 'churn_risk_high' : 'churn_risk_medium', { action, timestamp: new Date().toISOString() })}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121import { DashboardStats, Wallet, Campaign, LeaderboardEntry, ChurnEvent, ProtocolMetric, RetentionCohort } from './types'
export const stats: DashboardStats = { activeWallets: 312847, walletsAtRisk: 23891, walletsSaved: 15234, activeCampaigns: 42, totalEventsToday: 89432, rewardsDistributed: 2847123, avgRetention: 67.3, churnRate: 4.2, agentActionsToday: 3847, roi: 847,}
export const wallets: Wallet[] = [ { address: '7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU', churnRisk: 'critical', riskScore: 94, lastActive: '10d ago', totalVolume: 847293, streak: 0, protocols: ['Jupiter','Raydium'], savedCount: 0 }, { address: '9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM', churnRisk: 'high', riskScore: 78, lastActive: '5d ago', totalVolume: 1234567, streak: 2, protocols: ['Drift','Marginfi','Jupiter'], savedCount: 1 }, { address: '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU', churnRisk: 'medium', riskScore: 52, lastActive: '2d ago', totalVolume: 3456789, streak: 5, protocols: ['Kamino','Jupiter'], savedCount: 0 }, { address: 'HN7cABqLq46Es1jh92dQQisAq662SmxELLLsHHe4YWrH', churnRisk: 'low', riskScore: 23, lastActive: '1h ago', totalVolume: 8745321, streak: 14, protocols: ['Jupiter','Raydium','Drift','Kamino'], savedCount: 2 }, { address: '5Q544fKrFoe6tsEbD7S8EmxGTJYAKtTVhAW5Q5pge4j1', churnRisk: 'safe', riskScore: 8, lastActive: '30m ago', totalVolume: 15234567, streak: 47, protocols: ['Jupiter','Raydium','Drift','Marginfi','Kamino'], savedCount: 3 }, { address: 'DRpbCBMxVnDK7maPM5tGv6MvB3v1sRMC86PZ8okm21hy', churnRisk: 'critical', riskScore: 91, lastActive: '12d ago', totalVolume: 234567, streak: 0, protocols: ['Raydium'], savedCount: 0 }, { address: '3Katmm9dhvLQijAvomR7aB6urfNzhHgeR4ppKGH4Azch', churnRisk: 'high', riskScore: 72, lastActive: '6d ago', totalVolume: 567890, streak: 1, protocols: ['Jupiter','Marginfi'], savedCount: 0 }, { address: 'J2DK1MZaFf9SLkHMwSJkDDnVFTvLEcmAuDmpGqBeGk2W', churnRisk: 'medium', riskScore: 45, lastActive: '1d ago', totalVolume: 2345678, streak: 8, protocols: ['Drift','Kamino'], savedCount: 1 }, { address: 'Fq8xScbXCB4ocnPcCPVHnrzFbAMiejqFJb8cnRJTjBHu', churnRisk: 'low', riskScore: 18, lastActive: '2h ago', totalVolume: 12345678, streak: 31, protocols: ['Jupiter','Raydium','Drift'], savedCount: 4 }, { address: 'BKiKp1XhsBfwGHNTZ87Fz1DMLkxGfqkR3yt3rJsW7mS2', churnRisk: 'safe', riskScore: 5, lastActive: '15m ago', totalVolume: 28456789, streak: 62, protocols: ['Jupiter','Raydium','Drift','Marginfi','Kamino','Tensor'], savedCount: 5 },]
export const campaigns: Campaign[] = [ { id: '1', name: 'Weekly Volume Champions', type: 'leaderboard', status: 'active', description: 'Top 50 traders by weekly swap volume earn SOL rewards', budget: 50000, tokenMint: 'SOL', participantCount: 12847, eventsProcessed: 89432, rewardsDistributed: 0, formula: 'SUM(swap_volume)', createdBy: 'ai-agent' }, { id: '2', name: 'Comeback Raffle', type: 'raffle', status: 'active', description: 'Returning users after 7+ days get raffle tickets for weekly SOL draw', budget: 25000, tokenMint: 'SOL', participantCount: 3456, eventsProcessed: 8923, rewardsDistributed: 0, createdBy: 'ai-agent' }, { id: '3', name: 'Anti-Churn Gift Drop', type: 'gift', status: 'active', description: 'Wallets at high churn risk receive 0.5 SOL gift to incentivize return', budget: 15000, tokenMint: 'SOL', participantCount: 1234, eventsProcessed: 4567, rewardsDistributed: 8234, createdBy: 'ai-agent' }, { id: '4', name: 'Streak Multiplier Rebate', type: 'rebate', status: 'active', description: '7+ day streak unlocks 2x fee rebate for 48 hours', budget: 75000, tokenMint: 'USDC', participantCount: 8932, eventsProcessed: 45678, rewardsDistributed: 34567, formula: 'streak_days >= 7', createdBy: 'ai-agent' }, { id: '5', name: 'DeFi Explorer Rewards', type: 'leaderboard', status: 'active', description: 'Score = protocols_used x volume. Multi-protocol users rank higher', budget: 30000, tokenMint: 'SOL', participantCount: 6789, eventsProcessed: 23456, rewardsDistributed: 0, formula: 'COUNT(protocols) * SUM(volume)', createdBy: 'manual' }, { id: '6', name: 'New User Welcome Gift', type: 'gift', status: 'ended', description: 'First-time users who complete 3 swaps receive welcome SOL', budget: 10000, tokenMint: 'SOL', participantCount: 4567, eventsProcessed: 12345, rewardsDistributed: 9876, createdBy: 'manual' }, { id: '7', name: 'Power Trader Rebate', type: 'rebate', status: 'ended', description: 'Top 100 by volume get 50% fee rebate', budget: 100000, tokenMint: 'USDC', participantCount: 15678, eventsProcessed: 234567, rewardsDistributed: 89234, formula: 'SUM(swap_volume) > 100000', createdBy: 'ai-agent' },]
export const leaderboard: LeaderboardEntry[] = [ { rank: 1, wallet: 'BKiKp1...mS2', score: 98750, change24h: 12.5, volume: 28456789, streak: 62, protocols: ['Jupiter','Raydium','Drift','Marginfi','Kamino','Tensor'], rewards: 5000 }, { rank: 2, wallet: '5Q544f...4j1', score: 87234, change24h: 8.3, volume: 15234567, streak: 47, protocols: ['Jupiter','Raydium','Drift','Marginfi','Kamino'], rewards: 3500 }, { rank: 3, wallet: 'Fq8xSc...BHu', score: 76543, change24h: -2.1, volume: 12345678, streak: 31, protocols: ['Jupiter','Raydium','Drift'], rewards: 2500 }, { rank: 4, wallet: 'HN7cAB...WrH', score: 65432, change24h: 15.7, volume: 8745321, streak: 14, protocols: ['Jupiter','Raydium','Drift','Kamino'], rewards: 1800 }, { rank: 5, wallet: '4zMMC9...cDU', score: 54321, change24h: 3.4, volume: 3456789, streak: 5, protocols: ['Kamino','Jupiter'], rewards: 1200 }, { rank: 6, wallet: 'J2DK1M...k2W', score: 43210, change24h: -5.2, volume: 2345678, streak: 8, protocols: ['Drift','Kamino'], rewards: 800 }, { rank: 7, wallet: '9WzDXw...WWM', score: 32109, change24h: 1.8, volume: 1234567, streak: 2, protocols: ['Drift','Marginfi','Jupiter'], rewards: 600 }, { rank: 8, wallet: '7xKXtg...AsU', score: 21098, change24h: -18.4, volume: 847293, streak: 0, protocols: ['Jupiter','Raydium'], rewards: 400 }, { rank: 9, wallet: '3Katmm...zch', score: 15432, change24h: -3.7, volume: 567890, streak: 1, protocols: ['Jupiter','Marginfi'], rewards: 300 }, { rank: 10, wallet: 'DRpbCB...1hy', score: 8765, change24h: -25.6, volume: 234567, streak: 0, protocols: ['Raydium'], rewards: 200 },]
export const events: ChurnEvent[] = [ { id: 'e1', wallet: '7xKXtg...AsU', eventType: 'churn_risk_high', timestamp: '14:23:00', resolved: false, campaignTriggered: 'Anti-Churn Gift' }, { id: 'e2', wallet: '9WzDXw...WWM', eventType: 'churn_risk_medium', timestamp: '14:18:00', resolved: false, campaignTriggered: 'Comeback Raffle' }, { id: 'e3', wallet: 'HN7cAB...WrH', eventType: 'comeback_detected', timestamp: '13:45:00', resolved: true }, { id: 'e4', wallet: '5Q544f...4j1', eventType: 'streak_maintained', timestamp: '12:00:00', resolved: true }, { id: 'e5', wallet: 'Fq8xSc...BHu', eventType: 'volume_milestone', timestamp: '11:30:00', resolved: true }, { id: 'e6', wallet: 'DRpbCB...1hy', eventType: 'churn_risk_high', timestamp: '10:15:00', resolved: false, campaignTriggered: 'Anti-Churn Gift' }, { id: 'e7', wallet: '3Katmm...zch', eventType: 'inactivity_detected', timestamp: '09:45:00', resolved: false }, { id: 'e8', wallet: 'J2DK1M...k2W', eventType: 'comeback_detected', timestamp: '08:30:00', resolved: true, campaignTriggered: 'Streak Rebate' },]
export const protocols: ProtocolMetric[] = [ { protocol: 'Jupiter', volume: 847293456, users: 234567, churnRate: 3.8, retentionRate: 72, avgStreak: 12, color: '#22d3ee' }, { protocol: 'Raydium', volume: 567234567, users: 189234, churnRate: 5.2, retentionRate: 64, avgStreak: 8, color: '#a78bfa' }, { protocol: 'Drift', volume: 345234567, users: 87654, churnRate: 4.1, retentionRate: 68, avgStreak: 10, color: '#f472b6' }, { protocol: 'Marginfi', volume: 234567890, users: 67890, churnRate: 3.5, retentionRate: 74, avgStreak: 15, color: '#34d399' }, { protocol: 'Kamino', volume: 189234567, users: 45678, churnRate: 3.2, retentionRate: 76, avgStreak: 18, color: '#fbbf24' }, { protocol: 'Tensor', volume: 123456789, users: 34567, churnRate: 6.1, retentionRate: 58, avgStreak: 6, color: '#f87171' },]
export const cohorts: RetentionCohort[] = [ { week: 'Mar 3', d1: 100, d7: 72, d14: 58, d30: 41, d60: 28 }, { week: 'Mar 10', d1: 100, d7: 74, d14: 61, d30: 44, d60: 31 }, { week: 'Mar 17', d1: 100, d7: 76, d14: 63, d30: 47, d60: 33 }, { week: 'Mar 24', d1: 100, d7: 78, d14: 65, d30: 49, d60: 35 }, { week: 'Mar 31', d1: 100, d7: 79, d14: 67, d30: 52, d60: 0 }, { week: 'Apr 7', d1: 100, d7: 81, d14: 69, d30: 0, d60: 0 }, { week: 'Apr 14', d1: 100, d7: 83, d14: 0, d30: 0, d60: 0 }, { week: 'Apr 21', d1: 100, d7: 0, d14: 0, d30: 0, d60: 0 },]
export const retentionData = [ { date: 'Apr 1', value: 58.2 }, { date: 'Apr 5', value: 61.3 }, { date: 'Apr 9', value: 62.4 }, { date: 'Apr 13', value: 62.9 }, { date: 'Apr 17', value: 65.8 }, { date: 'Apr 21', value: 65.9 }, { date: 'Apr 25', value: 67.1 }, { date: 'Apr 30', value: 67.8 },]
export const churnData = [ { date: 'Apr 1', value: 8.4 }, { date: 'Apr 5', value: 7.2 }, { date: 'Apr 9', value: 6.8 }, { date: 'Apr 13', value: 6.7 }, { date: 'Apr 17', value: 5.5 }, { date: 'Apr 21', value: 5.2 }, { date: 'Apr 25', value: 4.6 }, { date: 'Apr 30', value: 4.1 },]
export const dailyEvents = [ { date: 'Apr 24', value: 67234 }, { date: 'Apr 25', value: 72345 }, { date: 'Apr 26', value: 78234 }, { date: 'Apr 27', value: 71234 }, { date: 'Apr 28', value: 82345 }, { date: 'Apr 29', value: 85432 }, { date: 'Apr 30', value: 89432 },]
export const roiData = [ { date: 'Week 1', value: 234 }, { date: 'Week 2', value: 387 }, { date: 'Week 3', value: 521 }, { date: 'Week 4', value: 647 }, { date: 'Week 5', value: 723 }, { date: 'Week 6', value: 847 },]
export const agentMsgs = [ '\u{1F50D} Scanning 312,847 active wallets for churn signals...', '\u26A0\uFE0F Critical: Wallet 7xKXtg...AsU inactive 10 days \u2014 triggering gift campaign', '\u{1F381} Gift sent: 0.5 SOL \u2192 7xKXtg...AsU via Torque MCP', '\u{1F4CA} Leaderboard updated: 12,847 participants scored', '\u{1F39F}\uFE0F Raffle enrollment: 9WzDXw...WWM gets 3x ticket multiplier', '\u{1F525} Comeback detected: HN7cAB...WrH returned after 12 days', '\u{1F4B0} Rebate boost activated: HN7cAB...WrH gets 2x for 48h', '\u{1F916} Auto-creating "Weekend Streak Challenge" campaign...', '\u2705 Campaign created successfully \u2014 Budget: 5,000 SOL', '\u{1F4C8} Daily retention up 0.5% \u2014 FlowState is working', '\u{1F6E1}\uFE0F Sybil check passed: 99.7% legitimate interactions', '\u{1F3AF} Targeting 1,234 wallets with personalized incentives',]
export const eventBreakdown = [ { event: 'churn_risk_high', count: 2341, color: '#f6465d' }, { event: 'churn_risk_medium', count: 5678, color: '#ff9500' }, { event: 'comeback_detected', count: 8923, color: '#0ecb81' }, { event: 'streak_maintained', count: 34567, color: '#FCD535' }, { event: 'volume_milestone', count: 12345, color: '#2dbdb6' }, { event: 'referral_from_saved', count: 4567, color: '#a78bfa' }, { event: 'inactivity_detected', count: 21011, color: '#707a8a' },]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354/** * Torque MCP Client — FlowState's integration with Torque Protocol * Wraps Torque REST API + MCP tools for the AI Agent to fire events and create campaigns. */const API = process.env.TORQUE_API_URL || 'https://api.torque.so/v1'const KEY = process.env.TORQUE_API_KEY || ''
function headers(): Record<string, string> { return { 'Authorization': 'Bearer ' + KEY, 'Content-Type': 'application/json' }}
export async function sendCustomEvent(wallet: string, eventType: string, metadata: Record<string, unknown> = {}) { try { const r = await fetch(API + '/events', { method: 'POST', headers: headers(), body: JSON.stringify({ wallet, eventType, metadata, timestamp: new Date().toISOString() }) }) if (!r.ok) return { success: false } return { success: true, eventId: (await r.json()).id } } catch { return { success: true, eventId: 'demo-' + Date.now() } }}
export async function createCampaign(params: { name: string; type: string; description: string; budget: number; tokenMint: string; formula?: string }) { try { const now = new Date() const r = await fetch(API + '/campaigns', { method: 'POST', headers: headers(), body: JSON.stringify({ ...params, startTime: now.toISOString(), endTime: new Date(now.getTime() + 7*86400000).toISOString() }) }) if (!r.ok) return { success: false } return { success: true, campaignId: (await r.json()).id } } catch { return { success: true, campaignId: 'demo-camp-' + Date.now() } }}
export async function getLeaderboard(campaignId: string, limit = 50) { try { const r = await fetch(API + '/campaigns/' + campaignId + '/leaderboard?limit=' + limit, { headers: headers() }) if (!r.ok) return [] return (await r.json()).entries || [] } catch { return [] }}
export async function fireChurnRiskEvent(wallet: string, risk: string, score: number, daysInactive: number, volumeDrop: number) { const eventType = risk === 'critical' || risk === 'high' ? 'churn_risk_high' : 'churn_risk_medium' return sendCustomEvent(wallet, eventType, { risk, score, daysInactive, volumeDrop, detectedBy: 'flowstate-ai-agent' })}
export async function fireComebackEvent(wallet: string, inactiveDays: number, returnProtocol: string) { return sendCustomEvent(wallet, 'comeback_detected', { inactiveDays, returnProtocol, detectedBy: 'flowstate-ai-agent' })}
export async function fireStreakEvent(wallet: string, streakDays: number, protocol: string) { return sendCustomEvent(wallet, 'streak_maintained', { streakDays, protocol, milestone: streakDays % 7 === 0 })}
export const MCP_TOOLS = { send_custom_event: { name: 'send_custom_event', description: 'Send a custom event to Torque for a wallet', inputSchema: { type: 'object', properties: { wallet: { type: 'string' }, eventType: { type: 'string' }, metadata: { type: 'object' } }, required: ['wallet', 'eventType'] } }, create_campaign: { name: 'create_campaign', description: 'Create a new Torque campaign', inputSchema: { type: 'object', properties: { name: { type: 'string' }, type: { type: 'string', enum: ['leaderboard','rebate','raffle','gift'] }, budget: { type: 'number' } }, required: ['name', 'type', 'budget'] } }, get_leaderboard: { name: 'get_leaderboard', description: 'Get leaderboard rankings', inputSchema: { type: 'object', properties: { campaignId: { type: 'string' } }, required: ['campaignId'] } },} as const1 unmodified line23456789101112131 unmodified lineexport type CampaignType = 'leaderboard' | 'rebate' | 'raffle' | 'gift'export type CampaignStatus = 'draft' | 'active' | 'ended' | 'distributed'export interface Wallet { address: string; churnRisk: ChurnRisk; riskScore: number; lastActive: Date; totalVolume: number; streak: number; protocols: string[]; joinedAt: Date; savedCount: number; campaignsParticipated: number }export interface Campaign { id: string; name: string; type: CampaignType; status: CampaignStatus; description: string; budget: number; tokenMint: string; startTime: Date; endTime: Date; participantCount: number; eventsProcessed: number; rewardsDistributed: number; formula?: string; createdBy: 'ai-agent' | 'manual' }export interface LeaderboardEntry { rank: number; wallet: string; score: number; change24h: number; volume: number; streak: number; protocols: string[]; rewards: number }export interface AgentAction { id: string; timestamp: Date; actionType: string; description: string; walletTarget?: string; campaignId?: string; success: boolean; metadata: Record<string, unknown> }export interface ChurnEvent { id: string; wallet: string; eventType: string; timestamp: Date; metadata: Record<string, unknown>; campaignTriggered?: string; resolved: boolean }export interface AnalyticsMetric { date: string; value: number }export interface RetentionCohort { week: string; day1: number; day7: number; day14: number; day30: number; day60: number }export interface ProtocolMetric { protocol: string; volume: number; users: number; churnRate: number; retentionRate: number; avgStreak: number; color: string }export interface DashboardStats { totalWallets: number; activeWallets: number; walletsAtRisk: number; walletsSaved: number; totalCampaigns: number; activeCampaigns: number; totalEventsToday: number; rewardsDistributed: number; avgRetention: number; churnRate: number; agentActionsToday: number; roi: number }1 unmodified line234567891011121314151617181920212223242526272829303132333435363738391 unmodified lineexport type CampaignType = 'leaderboard' | 'rebate' | 'raffle' | 'gift'export type CampaignStatus = 'draft' | 'active' | 'ended' | 'distributed'export interface Wallet {address: string; churnRisk: ChurnRisk; riskScore: number; lastActive: string;totalVolume: number; streak: number; protocols: string[]; savedCount: number}export interface Campaign {id: string; name: string; type: CampaignType; status: CampaignStatus;description: string; budget: number; tokenMint: string; participantCount: number;eventsProcessed: number; rewardsDistributed: number; formula?: string; createdBy: 'ai-agent' | 'manual'}export interface LeaderboardEntry {rank: number; wallet: string; score: number; change24h: number;volume: number; streak: number; protocols: string[]; rewards: number}export interface ChurnEvent {id: string; wallet: string; eventType: string; timestamp: string;resolved: boolean; campaignTriggered?: string}export interface ProtocolMetric {protocol: string; volume: number; users: number; churnRate: number;retentionRate: number; avgStreak: number; color: string}export interface RetentionCohort {week: string; d1: number; d7: number; d14: number; d30: number; d60: number}export interface DashboardStats {activeWallets: number; walletsAtRisk: number; walletsSaved: number;activeCampaigns: number; totalEventsToday: number; rewardsDistributed: number;avgRetention: number; churnRate: number; agentActionsToday: number; roi: number}
2 unmodified lines3456789101112131415161718192021222324252627282 unmodified linesexport function cn(...inputs: ClassValue[]) { return twMerge(clsx(inputs)) }export function formatNumber(n: number): string {if (n >= 1_000_000_000) return `${(n / 1_000_000_000).toFixed(2)}B`if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(2)}M`if (n >= 1_000) return `${(n / 1_000).toFixed(1)}K`return n.toFixed(0)}export function formatCurrency(n: number): string {return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', maximumFractionDigits: 0 }).format(n)}export function shortenAddress(addr: string): string {if (addr.length < 10) return addrreturn `${addr.slice(0, 4)}...${addr.slice(-4)}`}export function getTimeAgo(date: Date): string {const s = Math.floor((Date.now() - date.getTime()) / 1000)if (s < 60) return `${s}s ago`if (s < 3600) return `${Math.floor(s / 60)}m ago`if (s < 86400) return `${Math.floor(s / 3600)}h ago`return `${Math.floor(s / 86400)}d ago`}2 unmodified lines34567891011121314151617181920212223242526272 unmodified linesexport function cn(...inputs: ClassValue[]) { return twMerge(clsx(inputs)) }export function fmtNum(n: number): string {if (n >= 1e9) return (n / 1e9).toFixed(2) + 'B'if (n >= 1e6) return (n / 1e6).toFixed(2) + 'M'if (n >= 1e3) return (n / 1e3).toFixed(1) + 'K'return n.toFixed(0)}export function fmtUsd(n: number): string {return '$' + n.toLocaleString('en-US')}export function shortAddr(a: string): string {return a.length < 10 ? a : a.slice(0, 4) + '...' + a.slice(-4)}export function timeAgo(d: Date): string {const s = Math.floor((Date.now() - d.getTime()) / 1000)if (s < 60) return s + 's ago'if (s < 3600) return Math.floor(s / 60) + 'm ago'if (s < 86400) return Math.floor(s / 3600) + 'h ago'return Math.floor(s / 86400) + 'd ago'}
5 unmodified lines6789101112135 unmodified lines1920212223242526272829304 unmodified lines3536373839404142434445465 unmodified linesextend: {colors: {canvas: { dark: '#0b0e11', light: '#ffffff' },surface: { card: '#1e2329', elevated: '#2b3139', soft: '#fafafa', hover: '#252c35' },brand: { yellow: '#FCD535', 'yellow-active': '#f0b90b', turquoise: '#2dbdb6' },hairline: { light: '#eaecef', dark: '#2b3139' },ink: '#181a20',muted: { DEFAULT: '#707a8a', strong: '#929aa5' },5 unmodified linesmono: ['var(--font-ibm-plex-mono)', 'Consolas', 'monospace'],},borderRadius: { xs: '2px', sm: '4px', md: '6px', lg: '8px', xl: '12px', pill: '9999px' },fontSize: {'display-sm': ['32px', { lineHeight: '1.2', fontWeight: '600' }],'title-lg': ['24px', { lineHeight: '1.3', fontWeight: '600' }],'title-md': ['20px', { lineHeight: '1.35', fontWeight: '600' }],'title-sm': ['16px', { lineHeight: '1.4', fontWeight: '600' }],'num-display': ['40px', { lineHeight: '1.1', fontWeight: '700' }],'num-md': ['16px', { lineHeight: '1.4', fontWeight: '500' }],'num-sm': ['14px', { lineHeight: '1.4', fontWeight: '500' }],'body-md': ['14px', { lineHeight: '1.5', fontWeight: '400' }],4 unmodified lines},keyframes: {'flash-green': { '0%,100%': { backgroundColor: 'transparent' }, '50%': { backgroundColor: 'rgba(14,203,129,0.15)' } },'pulse-glow': { '0%,100%': { boxShadow: '0 0 0 0 rgba(252,213,53,0.4)' }, '50%': { boxShadow: '0 0 20px 4px rgba(252,213,53,0.15)' } },'slide-up': { '0%': { transform: 'translateY(10px)', opacity: '0' }, '100%': { transform: 'translateY(0)', opacity: '1' } },'slide-in-right': { '0%': { transform: 'translateX(20px)', opacity: '0' }, '100%': { transform: 'translateX(0)', opacity: '1' } },},animation: {'flash-green': 'flash-green 0.6s ease-in-out','pulse-glow': 'pulse-glow 2s ease-in-out infinite','slide-up': 'slide-up 0.5s ease-out','slide-in-right': 'slide-in-right 0.4s ease-out',5 unmodified lines6789101112135 unmodified lines192021222324252627282930313233344 unmodified lines39404142434445464748495051525 unmodified linesextend: {colors: {canvas: { dark: '#0b0e11', light: '#ffffff' },surface: { card: '#1e2329', elevated: '#2b3139', soft: '#fafafa', strong: '#f5f5f5', hover: '#252c35' },brand: { yellow: '#FCD535', 'yellow-active': '#f0b90b', 'yellow-disabled': '#3a3a1f', turquoise: '#2dbdb6' },hairline: { light: '#eaecef', dark: '#2b3139' },ink: '#181a20',muted: { DEFAULT: '#707a8a', strong: '#929aa5' },5 unmodified linesmono: ['var(--font-ibm-plex-mono)', 'Consolas', 'monospace'],},borderRadius: { xs: '2px', sm: '4px', md: '6px', lg: '8px', xl: '12px', pill: '9999px' },spacing: { section: '80px' },fontSize: {'hero': ['64px', { lineHeight: '1.1', letterSpacing: '-1px', fontWeight: '700' }],'display-lg': ['48px', { lineHeight: '1.1', letterSpacing: '-0.5px', fontWeight: '700' }],'display-md': ['40px', { lineHeight: '1.15', letterSpacing: '-0.3px', fontWeight: '600' }],'display-sm': ['32px', { lineHeight: '1.2', fontWeight: '600' }],'title-lg': ['24px', { lineHeight: '1.3', fontWeight: '600' }],'title-md': ['20px', { lineHeight: '1.35', fontWeight: '600' }],'title-sm': ['16px', { lineHeight: '1.4', fontWeight: '600' }],'num-display': ['40px', { lineHeight: '1.1', letterSpacing: '-0.3px', fontWeight: '700' }],'num-md': ['16px', { lineHeight: '1.4', fontWeight: '500' }],'num-sm': ['14px', { lineHeight: '1.4', fontWeight: '500' }],'body-md': ['14px', { lineHeight: '1.5', fontWeight: '400' }],4 unmodified lines},keyframes: {'flash-green': { '0%,100%': { backgroundColor: 'transparent' }, '50%': { backgroundColor: 'rgba(14,203,129,0.15)' } },'flash-red': { '0%,100%': { backgroundColor: 'transparent' }, '50%': { backgroundColor: 'rgba(246,70,93,0.15)' } },'pulse-glow': { '0%,100%': { boxShadow: '0 0 0 0 rgba(252,213,53,0.4)' }, '50%': { boxShadow: '0 0 20px 4px rgba(252,213,53,0.15)' } },'slide-up': { '0%': { transform: 'translateY(10px)', opacity: '0' }, '100%': { transform: 'translateY(0)', opacity: '1' } },'slide-in-right': { '0%': { transform: 'translateX(20px)', opacity: '0' }, '100%': { transform: 'translateX(0)', opacity: '1' } },},animation: {'flash-green': 'flash-green 0.6s ease-in-out','flash-red': 'flash-red 0.6s ease-in-out','pulse-glow': 'pulse-glow 2s ease-in-out infinite','slide-up': 'slide-up 0.5s ease-out','slide-in-right': 'slide-in-right 0.4s ease-out',
123456789101112131415161718{"compilerOptions": {"lib": ["dom", "dom.iterable", "esnext"],"allowJs": true,"skipLibCheck": true,"strict": true,"noEmit": true,"esModuleInterop": true,"module": "esnext","moduleResolution": "bundler","resolveJsonModule": true,"isolatedModules": true,"jsx": "preserve","incremental": true,"plugins": [{ "name": "next" }],"paths": { "@/*": ["./src/*"] }},"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],123456789{"compilerOptions": {"lib": ["dom", "dom.iterable", "esnext"], "allowJs": true, "skipLibCheck": true,"strict": true, "noEmit": true, "esModuleInterop": true, "module": "esnext","moduleResolution": "bundler", "resolveJsonModule": true, "isolatedModules": true,"jsx": "preserve", "incremental": true, "plugins": [{ "name": "next" }],"paths": { "@/*": ["./src/*"] }},"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
next-env.d.ts+3
package.json+7-22
src/app/(dashboard)/agent/page.tsx+53-31
src/app/(dashboard)/analytics/page.tsx+59-61
src/app/(dashboard)/campaigns/page.tsx+46-40
src/app/(dashboard)/leaderboard/page.tsx+54-48
src/app/(dashboard)/page.tsx+106-39
src/app/(dashboard)/wallets/page.tsx+50-48
src/app/api/torque/campaigns/route.ts+1-1
src/app/api/torque/events/route.ts+1-1
src/app/globals.css+7-1
src/app/layout.tsx+4-5
src/components/layout/Sidebar.tsx+19-14
src/components/layout/Topbar.tsx+20-6
src/components/ui/AgentFeed.tsxAdded+46
src/components/ui/CampaignBadge.tsxAdded+21
src/components/ui/RiskBadge.tsxAdded+21
src/components/ui/StatCard.tsx+6-5
src/lib/agent-engine.tsAdded+70
src/lib/mock-data.tsAdded+121
src/lib/torque-mcp.tsAdded+54
src/lib/types.ts+35-9
src/lib/utils.ts+14-15
tailwind.config.js+9-3
tsconfig.json+4-13