import Head from "next/head"; import { useEffect, useState, useRef } from "react"; import { FiUserPlus, FiMessageSquare, FiEye, FiRepeat, FiUsers, FiRefreshCw } from "react-icons/fi"; import { RiMailSendLine, RiReplyLine, RiRobot2Line, RiLinkedinBoxLine, RiFilterLine } from "react-icons/ri"; interface DashboardStats { totals: { total_targets: number; connections_requested: number; connected: number; messages_sent: number; inmails_sent: number; replies_received: number; active_runs: number; total_lists: number; total_workflows: number; emails_sent: number; email_replies: number; }; today: { visits_today: number; connections_today: number; messages_today: number; inmails_today: number; }; activity: { day: string; visits: number; connections: number; messages: number; inmails: number; emails: number }[]; lists: { id: string; name: string }[]; workflows: { id: string; name: string }[]; } interface AgentStats { daily: { day: string; cost_usd: number; input_tokens: number; output_tokens: number }[]; } interface AccountRow { id: string; is_authenticated: number; li_connections: number | null; li_pending: number | null; li_profile_views: number | null; li_stats_synced_at: string | null; } // ── Animated counter ────────────────────────────────────────────────────────── function Counter({ value, duration = 800 }: { value: number; duration?: number }) { const [display, setDisplay] = useState(0); const raf = useRef(0); const start = useRef(0); const from = useRef(0); useEffect(() => { from.current = display; start.current = 0; cancelAnimationFrame(raf.current); function step(ts: number) { if (!start.current) start.current = ts; const p = Math.min((ts - start.current) / duration, 1); const ease = 1 - Math.pow(1 - p, 3); setDisplay(Math.round(from.current + (value - from.current) * ease)); if (p < 1) raf.current = requestAnimationFrame(step); } raf.current = requestAnimationFrame(step); return () => cancelAnimationFrame(raf.current); }, [value]); // eslint-disable-line return <>{display.toLocaleString()}; } // ── Channel section header ───────────────────────────────────────────────────── function ChannelHeader({ icon, label, color }: { icon: React.ReactNode; label: string; color: string }) { return (
{icon} {label}
); } // ── KPI card ───────────────────────────────────────────────────────────────── function KpiCard({ label, value, sub, color, icon, pulse, }: { label: string; value: number; sub?: string; color: string; icon: React.ReactNode; pulse?: boolean; }) { return (
{icon} {pulse && ( )}
{label}
{sub &&
{sub}
}
); } // ── Funnel bar row ───────────────────────────────────────────────────────────── function FunnelRow({ icon, color, label, value, max, }: { icon: React.ReactNode; color: string; label: string; value: number; max: number; }) { const pct = max > 0 ? Math.max(2, (value / max) * 100) : 0; return (
{icon} {label}
); } // ── Activity chart ──────────────────────────────────────────────────────────── const SERIES = [ { key: "visits" as const, color: "#5aa2ff", label: "Visits" }, { key: "connections" as const, color: "#32d583", label: "Connects" }, { key: "messages" as const, color: "#f4b740", label: "Messages" }, { key: "inmails" as const, color: "#e879f9", label: "InMails" }, { key: "emails" as const, color: "#fb923c", label: "Emails" }, ]; const DAY_OPTIONS = [7, 14, 30, 90]; function ActivityChart({ data, days, onDaysChange, }: { data: DashboardStats["activity"]; days: number; onDaysChange: (d: number) => void; }) { const [activeSeries, setActiveSeries] = useState>(new Set(SERIES.map(s => s.key))); const maxVal = Math.max( ...data.flatMap(d => SERIES.filter(s => activeSeries.has(s.key)).map(s => d[s.key])), 1 ); const labelEvery = days <= 7 ? 1 : days <= 14 ? 2 : days <= 30 ? 5 : 15; const gridLines = [0.25, 0.5, 0.75, 1]; function toggleSeries(key: string) { setActiveSeries(prev => { const next = new Set(prev); if (next.has(key) && next.size > 1) next.delete(key); else next.add(key); return next; }); } return (
{/* Header */}
Activity
{SERIES.map(s => ( ))}
{DAY_OPTIONS.map(d => ( ))}
{/* Chart */}
{gridLines.map(g => (
))}
{data.map((d, i) => { const showLabel = i % labelEvery === 0; return (
{/* Tooltip */}
{d.day}
{SERIES.filter(s => activeSeries.has(s.key)).map(s => (
{d[s.key]} {s.label.toLowerCase()}
))}
{/* Bars */}
{SERIES.filter(s => activeSeries.has(s.key)).map(s => (
))}
{showLabel && ( {d.day.slice(5)} )}
); })}
); } // ── LinkedIn stats card ─────────────────────────────────────────────────────── interface LiStats { connections: number; pending: number; profile_views: number } function LinkedInCard({ accountId, cachedStats, cachedSyncedAt, }: { accountId?: string; cachedStats?: LiStats | null; cachedSyncedAt?: string | null; }) { const [syncing, setSyncing] = useState(false); const [liStats, setLiStats] = useState(cachedStats ?? null); const [syncedAt, setSyncedAt] = useState(cachedSyncedAt ?? null); const [syncError, setSyncError] = useState(null); async function handleSync() { if (!accountId) return; setSyncing(true); setSyncError(null); try { const res = await fetch(`/api/accounts/${accountId}/li-stats`, { method: "POST" }); const data = await res.json(); if (!res.ok) throw new Error(data.error ?? "Sync failed"); setLiStats(data); setSyncedAt(new Date().toISOString()); } catch (e) { setSyncError(e instanceof Error ? e.message : "Sync failed"); } finally { setSyncing(false); } } const items = [ { label: "Connections", value: liStats?.connections ?? null, color: "#32d583" }, { label: "Pending sent", value: liStats?.pending ?? null, color: "#f4b740" }, { label: "Profile views", value: liStats?.profile_views ?? null, color: "#5aa2ff" }, ]; return (
LinkedIn
{syncedAt && ( {new Date(syncedAt).toLocaleString(undefined, { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" })} )} {accountId && ( )}
{items.map(s => (
{s.value !== null ? : — } {s.label}
))}
{syncError &&

{syncError}

} {!accountId &&

No authenticated account.

}
); } // ── AI usage panel ──────────────────────────────────────────────────────────── function AiUsagePanel({ data, days }: { data: AgentStats["daily"]; days: number }) { const totalCost = data.reduce((s, d) => s + (d.cost_usd ?? 0), 0); const totalTokens = data.reduce((s, d) => s + (d.input_tokens ?? 0) + (d.output_tokens ?? 0), 0); const hasData = totalCost > 0 || totalTokens > 0; const maxCost = Math.max(...data.map(d => d.cost_usd ?? 0), 0.000001); const labelEvery = days <= 7 ? 1 : days <= 14 ? 2 : days <= 30 ? 5 : 15; return (
AI Usage
{hasData && (
{totalTokens.toLocaleString()} tokens ${totalCost.toFixed(4)}
)}
{!hasData ? (

No AI usage in this period.

) : (
{data.map((d, i) => { const showLabel = i % labelEvery === 0; const height = Math.max(2, ((d.cost_usd ?? 0) / maxCost) * 44); return (
{d.day}
${(d.cost_usd ?? 0).toFixed(5)}
{((d.input_tokens ?? 0) + (d.output_tokens ?? 0)).toLocaleString()} tok
{showLabel && ( {d.day.slice(5)} )}
); })}
)}
); } // ── Filter bar ──────────────────────────────────────────────────────────────── function FilterBar({ lists, workflows, listId, workflowId, onListChange, onWorkflowChange, }: { lists: { id: string; name: string }[]; workflows: { id: string; name: string }[]; listId: string; workflowId: string; onListChange: (id: string) => void; onWorkflowChange: (id: string) => void; }) { const hasFilter = listId || workflowId; return (
{hasFilter && ( )}
); } // ── Page ───────────────────────────────────────────────────────────────────── export default function Dashboard() { const [stats, setStats] = useState(null); const [agentStats, setAgentStats] = useState(null); // Open-core: the AI usage panel reflects the premium AI writer — hidden in the public build. const [hasPremium, setHasPremium] = useState(true); const [error, setError] = useState(false); const [days, setDays] = useState(7); const [account, setAccount] = useState(null); const [listId, setListId] = useState(""); const [workflowId, setWorkflowId] = useState(""); useEffect(() => { fetch("/api/accounts") .then(r => r.json()) .then((accounts: AccountRow[]) => { const auth = accounts.find(a => a.is_authenticated === 1); if (auth) setAccount(auth); }) .catch(() => {}); }, []); useEffect(() => { fetch("/api/premium-status").then((r) => r.ok ? r.json() : null) .then((d) => { if (d) setHasPremium(!!d.hasPremium); }).catch(() => {}); }, []); useEffect(() => { let cancelled = false; const params = new URLSearchParams({ days: String(days) }); if (listId) params.set("list_id", listId); if (workflowId) params.set("workflow_id", workflowId); Promise.all([ fetch(`/api/dashboard/stats?${params}`).then(r => r.json()), fetch(`/api/dashboard/agent-stats?days=${days}`).then(r => r.json()), ]) .then(([s, a]) => { if (!cancelled) { setStats(s); setAgentStats(a); } }) .catch(() => { if (!cancelled) setError(true); }); return () => { cancelled = true; }; }, [days, listId, workflowId]); if (error) return
Failed to load dashboard.
; if (!stats) { return (
Loading…
); } const { totals, today } = stats; const acceptanceRate = totals.connections_requested > 0 ? Math.round((totals.connected / totals.connections_requested) * 100) : 0; const replyRate = totals.messages_sent > 0 ? Math.round((totals.replies_received / totals.messages_sent) * 100) : 0; const emailReplyRate = totals.emails_sent > 0 ? Math.round((totals.email_replies / totals.emails_sent) * 100) : 0; const maxFunnelValue = totals.total_targets; return ( <> Dashboard — Linki
{/* ── Header ── */}

Dashboard

Your outreach at a glance.

{/* Filters */} {/* Today pills */}
Today {[ { label: `${today.visits_today} visits`, color: "#5aa2ff" }, { label: `${today.connections_today} connects`, color: "#32d583" }, { label: `${today.messages_today} messages`, color: "#f4b740" }, { label: `${today.inmails_today} inmails`, color: "#c084fc" }, ].map(p => ( {p.label} ))}
{/* ── KPI rows — LinkedIn then Email ── */}
{/* LinkedIn */}
} label="LinkedIn" color="#5aa2ff" />
} /> 0 ? `${acceptanceRate}% accepted` : undefined} color="#32d583" icon={} pulse={totals.active_runs > 0} /> 0 ? `${replyRate}% replied` : undefined} color="#f4b740" icon={} /> } /> } />
{/* Email */}
} label="Email" color="#fb923c" />
0 ? `${emailReplyRate}% replied` : undefined} color="#fb923c" icon={} /> } /> } /> } />
{/* ── Second row: funnel left, chart right ── */}
{/* Left: funnel + LinkedIn + AI */}
{/* Funnel */}
Funnel
} color="#808080" label="Targets" value={totals.total_targets} max={maxFunnelValue} /> } color="#32d583" label="Connected" value={totals.connected} max={maxFunnelValue} /> } color="#c084fc" label="LI replies" value={totals.replies_received} max={maxFunnelValue} /> } color="#fb923c" label="Emails sent" value={totals.emails_sent} max={maxFunnelValue} /> } color="#32d583" label="Email replies" value={totals.email_replies} max={maxFunnelValue} />
{/* LinkedIn account card */} {/* AI usage mini */} {hasPremium && agentStats && }
{/* Right: activity chart */}
); }