'use client' import { useState, useEffect, useCallback, useRef } from 'react' import { useRouter } from 'next/navigation' import api from '@/services/api' import { getErrorMessage } from '@/utils/error' // ============================================ // TYPES // ============================================ type Period = '7d' | '30d' | '90d' type SortKey = 'views' | 'likes' | 'comments' | 'shares' | 'date' type SortDir = 'asc' | 'desc' interface StatSummary { current: number previous: number changePercent: number } interface ImpressionsPoint { date: string views: number } interface TopPost { id: string title: string views: number likes: number comments: number shares: number date: string } interface LanguageStat { language: string count: number percentage: number } interface LocationStat { country: string count: number } interface ReferralStat { source: 'direct' | 'search' | 'social' | string count: number percentage: number } interface DashboardData { stats: { views: StatSummary likes: StatSummary comments: StatSummary followersGained: StatSummary } impressions: ImpressionsPoint[] topPosts: TopPost[] languages: LanguageStat[] audience: { locations: LocationStat[] referrals: ReferralStat[] } } // ============================================ // HELPERS // ============================================ function formatNum(n: number): string { if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M` if (n >= 1_000) return `${(n / 1_000).toFixed(1)}K` return n.toLocaleString() } function formatDate(iso: string, short = false): string { const d = new Date(iso) if (short) return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' }) return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' }) } // ============================================ // STAT CARD // ============================================ interface StatCardProps { title: string value: number changePercent: number } function StatCard({ title, value, changePercent }: StatCardProps) { const positive = changePercent >= 0 const arrow = positive ? '↑' : '↓' const colorClass = positive ? 'text-[var(--accent)]' : 'text-[var(--error)]' const absChange = Math.abs(changePercent).toFixed(1) return (

{title}

{formatNum(value)}

{arrow} {absChange}% vs prior period

) } // ============================================ // SVG LINE CHART // ============================================ interface TooltipState { x: number y: number date: string value: number } interface LineChartProps { data: ImpressionsPoint[] } function LineChart({ data }: LineChartProps) { const [tooltip, setTooltip] = useState(null) const svgRef = useRef(null) const W = 800 const H = 200 const PAD_LEFT = 50 const PAD_RIGHT = 20 const PAD_TOP = 16 const PAD_BOTTOM = 30 if (data.length === 0) { return (
No impression data available
) } const maxVal = Math.max(...data.map((d) => d.views), 1) const minVal = 0 const chartW = W - PAD_LEFT - PAD_RIGHT const chartH = H - PAD_TOP - PAD_BOTTOM const toX = (i: number) => PAD_LEFT + (i / Math.max(data.length - 1, 1)) * chartW const toY = (v: number) => PAD_TOP + chartH - ((v - minVal) / (maxVal - minVal)) * chartH const linePath = data .map((d, i) => `${i === 0 ? 'M' : 'L'} ${toX(i)} ${toY(d.views)}`) .join(' ') const areaPath = linePath + ` L ${toX(data.length - 1)} ${PAD_TOP + chartH} L ${toX(0)} ${PAD_TOP + chartH} Z` // Y-axis labels (4 ticks) const ticks = [0, 0.25, 0.5, 0.75, 1].map((t) => Math.round(minVal + t * maxVal)) // X-axis: show up to 7 evenly-spaced labels const xLabelIndices: number[] = [] const step = Math.max(1, Math.floor((data.length - 1) / 6)) for (let i = 0; i < data.length; i += step) xLabelIndices.push(i) if (xLabelIndices[xLabelIndices.length - 1] !== data.length - 1) xLabelIndices.push(data.length - 1) const handleMouseMove = (e: React.MouseEvent) => { if (!svgRef.current) return const rect = svgRef.current.getBoundingClientRect() const relX = ((e.clientX - rect.left) / rect.width) * W const chartRelX = relX - PAD_LEFT const index = Math.round( (chartRelX / chartW) * (data.length - 1) ) const clamped = Math.max(0, Math.min(data.length - 1, index)) const point = data[clamped] setTooltip({ x: toX(clamped), y: toY(point.views), date: point.date, value: point.views, }) } const handleMouseLeave = () => setTooltip(null) return (
{/* Grid lines */} {ticks.map((tick) => ( {formatNum(tick)} ))} {/* X-axis labels */} {xLabelIndices.map((idx) => ( {formatDate(data[idx].date, true)} ))} {/* Area fill */} {/* Line */} {/* Tooltip dot */} {tooltip && ( <> )} {/* Floating tooltip box */} {tooltip && (

{formatDate(tooltip.date, true)}

{tooltip.value.toLocaleString()} views

)}
) } // ============================================ // LANGUAGE BAR CHART // ============================================ interface LanguageBarChartProps { data: LanguageStat[] } const LANG_COLORS = [ '#7C3AED', '#2563EB', '#059669', '#D97706', '#DC2626', '#0891B2', '#7C3AED', ] function LanguageBarChart({ data }: LanguageBarChartProps) { if (data.length === 0) { return (

No language data available

) } const maxCount = Math.max(...data.map((d) => d.count), 1) return (
    {data.map((lang, i) => (
  • {lang.language} {lang.count.toLocaleString()} · {lang.percentage.toFixed(1)}%
  • ))}
) } // ============================================ // TOP POSTS TABLE // ============================================ interface TopPostsTableProps { posts: TopPost[] } function TopPostsTable({ posts }: TopPostsTableProps) { const router = useRouter() const [sortKey, setSortKey] = useState('views') const [sortDir, setSortDir] = useState('desc') const handleSort = (key: SortKey) => { if (key === sortKey) { setSortDir((d) => (d === 'asc' ? 'desc' : 'asc')) } else { setSortKey(key) setSortDir('desc') } } const sorted = [...posts].sort((a, b) => { let av: number | string = a[sortKey] let bv: number | string = b[sortKey] if (sortKey === 'date') { av = new Date(a.date).getTime() bv = new Date(b.date).getTime() } if (av < bv) return sortDir === 'asc' ? -1 : 1 if (av > bv) return sortDir === 'asc' ? 1 : -1 return 0 }) const colClass = 'py-3 px-3 text-xs font-semibold uppercase tracking-wider text-[var(--foreground-secondary)] select-none cursor-pointer hover:text-[var(--foreground)] transition-colors' const indicator = (key: SortKey) => { if (key !== sortKey) return ↕ return ( {sortDir === 'asc' ? '↑' : '↓'} ) } if (posts.length === 0) { return (

No posts to display

) } return (
{sorted.map((post) => ( router.push(`/posts/${post.id}`)} > ))}
Post handleSort('views')} > Views{indicator('views')} handleSort('likes')} > Likes{indicator('likes')} handleSort('comments')} > Comments{indicator('comments')} handleSort('shares')} > Shares{indicator('shares')} handleSort('date')} > Date{indicator('date')}

{post.title || 'Untitled post'}

{formatNum(post.views)} {formatNum(post.likes)} {formatNum(post.comments)} {formatNum(post.shares)} {formatDate(post.date, true)}
) } // ============================================ // AUDIENCE SECTION // ============================================ interface AudienceProps { locations: LocationStat[] referrals: ReferralStat[] } function AudienceSection({ locations, referrals }: AudienceProps) { const maxLoc = Math.max(...locations.map((l) => l.count), 1) const maxRef = Math.max(...referrals.map((r) => r.count), 1) const referralColor = (source: string) => { if (source === 'direct') return '#7C3AED' if (source === 'search') return '#2563EB' if (source === 'social') return '#059669' return '#6B7280' } return (
{/* Top locations */}

Top Locations

{locations.length === 0 ? (

No location data yet

) : (
    {locations.map((loc) => (
  • {loc.country}
    {formatNum(loc.count)}
  • ))}
)}
{/* Referral sources */}

Referral Sources

{referrals.length === 0 ? (

No referral data yet

) : (
    {referrals.map((ref) => (
  • {ref.source}
    {formatNum(ref.count)} · {ref.percentage.toFixed(0)}%
  • ))}
)}
) } // ============================================ // MAIN PAGE // ============================================ export default function AnalyticsDashboardPage() { const [period, setPeriod] = useState('7d') const [data, setData] = useState(null) const [loading, setLoading] = useState(true) const [error, setError] = useState(null) const fetchDashboard = useCallback(async (p: Period) => { setLoading(true) setError(null) try { const res = await api.get(`/v1/analytics/dashboard?period=${p}`) setData(res.data) } catch (err: unknown) { setError(getErrorMessage(err)) } finally { setLoading(false) } }, []) useEffect(() => { fetchDashboard(period) }, [fetchDashboard, period]) const handlePeriodChange = (p: Period) => { setPeriod(p) } const periods: { value: Period; label: string }[] = [ { value: '7d', label: '7d' }, { value: '30d', label: '30d' }, { value: '90d', label: '90d' }, ] return (
{/* ── Header ── */}

Analytics

Post performance and audience insights

{/* Period selector */}
{periods.map(({ value, label }) => ( ))}
{/* ── Loading ── */} {loading && (
)} {/* ── Error ── */} {!loading && error && (

{error}

)} {/* ── Content ── */} {!loading && !error && data && ( <> {/* Stats cards */}
{/* Impressions chart */}

Impressions Over Time

{/* Top posts table */}

Top Posts

{/* Language breakdown */}

Language Breakdown

{/* Audience */}

Audience

)} {/* ── Empty state ── */} {!loading && !error && !data && (

No analytics data available yet. Start posting to see your stats.

)}
) }