'use client'; import { useAuth } from '@/lib/hooks/useAuth'; import { useRealtimeContext } from '@/components/realtime/RealtimeProvider'; import { useEffect, useState } from 'react'; import Link from 'next/link'; import { Users, MessageSquare, TrendingUp, DollarSign, Target, UserPlus, Mail, CheckCircle2, Circle, Zap, Building2, ArrowUpRight, Clock, Rocket, Activity, Sparkles, Settings, BarChart3, Wifi, WifiOff, AlertCircle, PhoneCall, Megaphone, UserCheck } from 'lucide-react'; interface DashboardStats { totalContacts: number; activeConversations: number; openOpportunities: number; pipelineValue: number; } export default function DashboardPage() { const { user } = useAuth(); const { isConnected } = useRealtimeContext(); const [stats, setStats] = useState({ totalContacts: 0, activeConversations: 0, openOpportunities: 0, pipelineValue: 0, }); const [loading, setLoading] = useState(true); useEffect(() => { async function fetchStats() { try { const response = await fetch('/api/v1/dashboard/stats'); if (response.ok) { const data = await response.json(); setStats(data); } } catch (error) { console.error('Failed to fetch stats:', error); } finally { setLoading(false); } } fetchStats(); }, []); const quickActions = [ { name: 'Add Contact', href: '/contacts', icon: UserPlus, description: 'Import or create new contacts' }, { name: 'Send Message', href: '/conversations', icon: Mail, description: 'Start a conversation' }, { name: 'View Pipeline', href: '/opportunities', icon: Target, description: 'Track your deals' }, { name: 'Get Leads', href: '/leads', icon: TrendingUp, description: 'Find new opportunities' }, ]; return (
{/* Header Section - Level 1 (subtle) since it's a page header, not main content */}

Welcome back{user?.firstName && , {user.firstName}}

Here's what's happening with your portfolio today

{isConnected ? ( <> Connected ) : ( <> Connecting... )}
{/* Stats Grid */}
{/* Section header - Level 1 (subtle) */}

Overview

Your key metrics at a glance

0 ? "+12%" : undefined} trendUp emptyMessage="No contacts yet" emptyAction={{ label: "Import contacts", href: "/contacts" }} /> 0 ? "+5%" : undefined} trendUp emptyMessage="No active chats" emptyAction={{ label: "Start a conversation", href: "/conversations" }} /> 0 ? "+8%" : undefined} trendUp emptyMessage="No opportunities" emptyAction={{ label: "Create opportunity", href: "/opportunities" }} /> 0 ? "+23%" : undefined} trendUp highlight isCurrency emptyMessage="No pipeline value" emptyAction={{ label: "Add a deal", href: "/opportunities" }} />
{/* Quick Actions */}
{/* Section header - Level 1 (subtle) */}

Quick Actions

Jump right into common tasks

{quickActions.map((action) => { const Icon = action.icon; return (

{action.name}

{action.description}

); })}
{/* Bottom Section */}
); } function StatCard({ title, value, icon: Icon, loading, trend, trendUp, highlight, isCurrency, emptyMessage, emptyAction }: { title: string; value: string | number; icon: React.ComponentType<{ className?: string }>; loading: boolean; trend?: string; trendUp?: boolean; highlight?: boolean; isCurrency?: boolean; emptyMessage?: string; emptyAction?: { label: string; href: string }; }) { const numericValue = typeof value === 'number' ? value : parseFloat(value) || 0; const isEmpty = numericValue === 0; const displayValue = isCurrency ? `$${numericValue.toLocaleString()}` : value; return (
{trend ? ( {trend} ) : !loading && isEmpty ? ( -- ) : null}
{loading ? (
) : isEmpty ? (

{isCurrency ? '$0' : '0'}

{emptyMessage && (

{emptyMessage}

)} {emptyAction && ( {emptyAction.label} )}
) : (

{displayValue}

)}

{title}

); } function SetupProgress() { const [progress, setProgress] = useState({ smsConfigured: false, emailConfigured: false, contactsImported: false, campaignsSetup: false, }); useEffect(() => { fetch('/api/v1/onboarding/status') .then(res => res.json()) .then(data => { if (data.setupStatus) { setProgress(data.setupStatus); } }) .catch(() => {}); }, []); const steps = [ { key: 'smsConfigured', label: 'Configure SMS', description: 'Set up two-way texting', done: progress.smsConfigured, href: '/settings/sms', icon: MessageSquare }, { key: 'emailConfigured', label: 'Set up Email', description: 'Connect your email account', done: progress.emailConfigured, href: '/settings/email', icon: Mail }, { key: 'contactsImported', label: 'Import Contacts', description: 'Bring in your database', done: progress.contactsImported, href: '/contacts', icon: Users }, { key: 'campaignsSetup', label: 'Create Campaigns', description: 'Automate your follow-ups', done: progress.campaignsSetup, href: '/campaigns', icon: Zap }, ]; const completedCount = steps.filter(s => s.done).length; const progressPercent = (completedCount / steps.length) * 100; const isComplete = progressPercent === 100; return (
{/* Header */}
{isComplete ? ( ) : ( )}

Setup Progress

{isComplete ? 'All set! You\'re ready to go' : 'Complete these steps to unlock all features'}

{completedCount} / {steps.length} complete
{/* Progress Bar */}
{isComplete ? 'Setup Complete!' : `${completedCount} of ${steps.length} steps completed`} {Math.round(progressPercent)}%
{/* Steps List */}
{steps.map((step, index) => { const StepIcon = step.icon; return (
{/* Step Number/Check */}
{step.done ? ( ) : ( {index + 1} )}
{/* Step Icon */}
{/* Step Content */}

{step.label}

{step.description}

{/* Action Button */} {step.done ? ( Done ) : ( Start )}
); })}
); } interface Recommendation { id: string; type: 'follow_up' | 'stale_lead' | 'pipeline_stuck' | 'campaign_response' | 'no_response'; priority: 'high' | 'medium' | 'low'; title: string; description: string; actionLabel: string; actionUrl: string; contactId?: string; contactName?: string; daysOverdue?: number; pipelineStage?: string; } function RecommendedTasks() { const [recommendations, setRecommendations] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { async function fetchRecommendations() { try { const response = await fetch('/api/v1/dashboard/recommendations'); if (response.ok) { const data = await response.json(); setRecommendations(data.recommendations || []); } else { setError('Failed to load recommendations'); } } catch (err) { console.error('Failed to fetch recommendations:', err); setError('Failed to load recommendations'); } finally { setLoading(false); } } fetchRecommendations(); }, []); const getIconForType = (type: Recommendation['type']) => { switch (type) { case 'follow_up': return UserCheck; case 'no_response': return PhoneCall; case 'pipeline_stuck': return Target; case 'campaign_response': return Megaphone; case 'stale_lead': return AlertCircle; default: return Zap; } }; const getColorForPriority = (priority: Recommendation['priority']) => { switch (priority) { case 'high': return { bg: 'bg-red-100', icon: 'text-red-600', border: 'border-red-200 hover:border-red-300' }; case 'medium': return { bg: 'bg-amber-100', icon: 'text-amber-600', border: 'border-amber-200 hover:border-amber-300' }; case 'low': return { bg: 'bg-blue-100', icon: 'text-blue-600', border: 'border-blue-200 hover:border-blue-300' }; } }; return (
{/* Header */}

Recommended Tasks

AI-powered suggestions based on your CRM

{loading ? (
{[1, 2, 3, 4].map((i) => (
))}
) : error ? (

Unable to load recommendations

Make sure your MCP server is running

) : recommendations.length > 0 ? (
{recommendations.map((rec) => { const Icon = getIconForType(rec.type); const colors = getColorForPriority(rec.priority); return (

{rec.title}

{rec.description}

{rec.actionLabel}
); })}
) : ( /* Empty State - All caught up */

You're all caught up!

No urgent tasks right now. Keep up the great work with your leads and deals.

Ask AI for Insights Add More Contacts
)} {/* Footer link to Control Center for more insights */} {recommendations.length > 0 && (
Get more insights with AI
)}
); }