Skip to content

Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.

refactor(analytics): share account analytics loading and split pages

spacesdrive2e11a483f0cf
diff --git a/docs/architecture/frontend/CONTEXTS.md b/docs/architecture/frontend/CONTEXTS.md
index 7691edc..467a993 100644
--- a/docs/architecture/frontend/CONTEXTS.md
+++ b/docs/architecture/frontend/CONTEXTS.md
@@ -111,9 +111,12 @@ Hooks used by more than one feature. Hooks used by a single feature live in that
| `useCommandPaletteShortcut(setOpen)` | `use-command-palette-shortcut.js` | Ctrl+K / Cmd+K toggle for the command palette |
| `useSmoothTheme()` | `use-smooth-theme.js` | Theme switch as one cross-fade |
| `useCloudinaryConfig(reloadKey)` | `use-cloudinary-config.js` | Loads `api.getCloudinaryConfig()`; returns the config or `null` |
+| `useAccountAnalytics(account, fetchAnalytics, label)` | `use-account-analytics.js` | Loads one account's analytics and refreshes it; used by Instagram and Reddit analytics |
`useCloudinaryConfig` sets the config only when the response has `success: true`. A failed request keeps the previous value (initially `null`), and pages show a missing config as an alert or a disabled upload field. The request runs again whenever `reloadKey` changes: the Publish page passes `accounts`, Tracked Content passes nothing and loads once.
+`useAccountAnalytics` returns `{ loading, profile, analytics, refreshing, handleRefresh }`. Pass a stable `api` method (`api.getIGAnalytics`, `api.getRedditAnalytics`), never an inline arrow: the load is keyed on the account id and that method, so a background account refresh does not refetch analytics. `label` names the platform in the toasts (`Couldn't load Instagram analytics.`, `Instagram account refreshed`). `handleRefresh` calls `api.refreshAccount()` and then loads the analytics again.
+
---
## Context Rules
diff --git a/docs/architecture/frontend/FEATURES.md b/docs/architecture/frontend/FEATURES.md
index d351cc6..6076aa4 100644
--- a/docs/architecture/frontend/FEATURES.md
+++ b/docs/architecture/frontend/FEATURES.md
@@ -20,7 +20,11 @@ frontend/src/
│ │ ├── channel/
│ │ │ └── ChannelAnalytics.jsx <- YouTube channel analytics
│ │ ├── instagram/
-│ │ │ └── InstagramAnalytics.jsx <- Instagram account analytics
+│ │ │ ├── InstagramAnalytics.jsx <- Page: Instagram account analytics (loads through useAccountAnalytics)
+│ │ │ ├── InstagramHeader.jsx, InstagramMetrics.jsx, InstagramInsightChips.jsx, TypeBadge.jsx
+│ │ │ ├── InstagramEngagementCharts.jsx, InstagramPostCharts.jsx, InstagramHashtags.jsx, InstagramRecentGrid.jsx
+│ │ │ ├── InstagramTopPostsTable.jsx, InstagramTypeSummaryTable.jsx
+│ │ │ └── instagramAnalyticsData.js <- Pure chart rows and labels (instagramAnalyticsData.test.js)
│ │ ├── overview/
│ │ │ ├── Overview.jsx <- Page: cross-platform aggregate dashboard with six metric tabs
│ │ │ ├── OverviewHeader.jsx, QuickActions.jsx, GettingStarted.jsx, MetricTabsList.jsx
@@ -30,7 +34,10 @@ frontend/src/
│ │ │ ├── useOverviewStats.js <- Memoized totals, rankings and chart rows
│ │ │ └── overviewStats.js, overviewCharts.js, overviewLabels.js, greeting.js <- Pure helpers with *.test.js
│ │ ├── reddit/
-│ │ │ ├── RedditAnalytics.jsx <- Reddit account analytics (karma, subreddits)
+│ │ │ ├── RedditAnalytics.jsx <- Page: Reddit account analytics (loads through useAccountAnalytics)
+│ │ │ ├── RedditHeader.jsx, RedditKarmaSummary.jsx, RedditKarmaCharts.jsx, RedditStatPanels.jsx
+│ │ │ ├── RedditTimingCharts.jsx, RedditSubredditTable.jsx, RedditTopPostsTable.jsx
+│ │ │ ├── redditAnalyticsData.js <- Pure chart rows and stat lists (redditAnalyticsData.test.js)
│ │ │ ├── RedditPosts.jsx <- Per-account post explorer
│ │ │ ├── RedditPostsAll.jsx <- Global post explorer (all Reddit accounts)
│ │ │ ├── redditPostTable.jsx <- Filters and table shared by both post explorers
diff --git a/docs/architecture/frontend/REACT_ARCHITECTURE.md b/docs/architecture/frontend/REACT_ARCHITECTURE.md
index b55a329..92c05e8 100644
--- a/docs/architecture/frontend/REACT_ARCHITECTURE.md
+++ b/docs/architecture/frontend/REACT_ARCHITECTURE.md
@@ -98,11 +98,11 @@ frontend/src/
analytics/
overview/ Overview.jsx - all-accounts dashboard (page; tabs, hooks and helpers beside it)
channel/ ChannelAnalytics.jsx - per-channel YouTube
- instagram/ InstagramAnalytics.jsx - per-account Instagram
+ instagram/ InstagramAnalytics.jsx - per-account Instagram (page; sections and helpers beside it)
videos/ VideoExplorer.jsx - all videos table
shorts/ ShortsExplorer.jsx - shorts-filtered table
reels/ ReelsExplorer.jsx - Instagram media grid
- reddit/ RedditAnalytics, RedditPosts, RedditPostsAll, shared post table
+ reddit/ RedditAnalytics (page; sections and helpers beside it), RedditPosts, RedditPostsAll, shared post table
tracked/ TrackedContent.jsx, TrackedCategory.jsx (pages; components, hooks and helpers beside them)
publishing/
UploadContent.jsx Instagram publishing + schedule queue (page; components, hooks and helpers beside it)
diff --git a/frontend/src/features/analytics/instagram/InstagramAnalytics.jsx b/frontend/src/features/analytics/instagram/InstagramAnalytics.jsx
index c80bd36..afc7ce3 100644
--- a/frontend/src/features/analytics/instagram/InstagramAnalytics.jsx
+++ b/frontend/src/features/analytics/instagram/InstagramAnalytics.jsx
@@ -1,101 +1,36 @@
-import React, { useCallback, useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
-import {
- BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip as ReTooltip, PieChart, Pie, Cell, Legend,
- AreaChart, Area,
-} from 'recharts';
-import {
- RefreshCw, Heart, MessageCircle, Users, UserPlus, Image, TrendingUp, Calendar, Clock, Zap, Flame,
- Trophy, Star, ExternalLink, BarChart2, Hash, Eye, Clapperboard, Film, UserX,
-} from 'lucide-react';
-import { Button } from '@/components/ui/button';
-import { Badge } from '@/components/ui/badge';
+import { UserX } from 'lucide-react';
import { Progress } from '@/components/ui/progress';
-import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
-import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import PageHeader from '@/components/PageHeader';
-import MetricBox from '@/components/MetricBox';
import SurfaceBox from '@/components/SurfaceBox';
-import ChartPanel from '@/components/ChartPanel';
-import { MediaChip } from '@/components/MediaCard';
import { EmptyState, PageSkeleton } from '@/components/StateViews';
-import { AccountAvatar } from '@/components/platform';
-import { SERIES, axisProps, gridProps, legendStyle, tooltipCursor, tooltipStyle } from '@/lib/chart';
import { useAppContext } from '../../../context/AppContext';
+import { useAccountAnalytics } from '../../../hooks/use-account-analytics';
import { api } from '../../../services/api';
-import { fmtNum, fmtNumFull, fmtDate, timeAgo } from '../../../utils/formatters';
-import { IG_CONTENT_TYPES, IG_CONTENT_TYPE_META, igContentTypeMeta, fmtIGViews } from '../../../utils/instagramContent';
-import { cn } from '@/lib/utils';
-
-const CONTENT_TYPE_ICONS = { reel: Clapperboard, post: Image, video: Film };
-
-function TypeBadge({ type }) {
- const meta = igContentTypeMeta(type);
- return (
- <span className="inline-flex h-5 items-center gap-1.5 rounded-pill border border-line px-2 text-caption font-medium text-ink-muted">
- <span className="size-2 rounded-full" style={{ background: meta.color }} />
- {meta.label}
- </span>
- );
-}
-
-function InsightChip({ icon, children }) {
- const Icon = icon;
- return (
- <span className="inline-flex h-8 items-center gap-1.5 rounded-field border border-line bg-surface px-3 text-small font-medium text-ink">
- <Icon className="size-3.5 stroke-[1.75] text-ink-faint" />
- {children}
- </span>
- );
-}
+import { timeAgo } from '../../../utils/formatters';
+import { instagramChartsOf } from './instagramAnalyticsData.js';
+import InstagramHeader from './InstagramHeader';
+import InstagramMetrics from './InstagramMetrics';
+import InstagramInsightChips from './InstagramInsightChips';
+import InstagramEngagementCharts from './InstagramEngagementCharts';
+import InstagramPostCharts from './InstagramPostCharts';
+import InstagramHashtags from './InstagramHashtags';
+import InstagramRecentGrid from './InstagramRecentGrid';
+import InstagramTopPostsTable from './InstagramTopPostsTable';
+import InstagramTypeSummaryTable from './InstagramTypeSummaryTable';
+
+const BACK = { to: '/', label: 'Overview' };
export default function InstagramAnalytics() {
const { id } = useParams();
- const { accounts, showToast } = useAppContext();
- const account = accounts.find(a => a.id === id);
-
- const [loading, setLoading] = useState(true);
- const [profile, setProfile] = useState(null);
- const [analytics, setAnalytics] = useState(null);
- const [refreshing, setRefreshing] = useState(false);
-
- const loadAnalytics = useCallback(async () => {
- if (!account) return;
- setLoading(true);
- try {
- const data = await api.getIGAnalytics(account.id);
- setProfile(data.profile);
- setAnalytics(data.analytics);
- } catch (err) {
- showToast(`Couldn't load Instagram analytics. ${err.message}`, 'error');
- } finally {
- setLoading(false);
- }
- // Keyed on the account id so a background account refresh does not refetch analytics
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [account?.id, showToast]);
-
- useEffect(() => { loadAnalytics(); }, [id, loadAnalytics]);
-
- const handleRefresh = async () => {
- setRefreshing(true);
- try {
- await api.refreshAccount(account.id);
- await loadAnalytics();
- showToast('Instagram account refreshed');
- } catch (err) {
- showToast(`Refresh failed. ${err.message}`, 'error');
- } finally {
- setRefreshing(false);
- }
- };
-
- const back = { to: '/', label: 'Overview' };
+ const { accounts } = useAppContext();
+ const account = accounts.find(item => item.id === id);
+ const { loading, profile, analytics, refreshing, handleRefresh } = useAccountAnalytics(account, api.getIGAnalytics, 'Instagram');
if (!account) {
return (
<div className="flex flex-col gap-6">
- <PageHeader title="Instagram account" back={back} />
+ <PageHeader title="Instagram account" back={BACK} />
<SurfaceBox>
<EmptyState icon={<UserX />} title="Account not found" description="It may have been removed. Choose another account from the sidebar." />
</SurfaceBox>
@@ -105,299 +40,30 @@ export default function InstagramAnalytics() {
if (loading) return <PageSkeleton metrics={6} />;
- const p = profile || account;
- const a = analytics || {};
-
- const typeStats = a.contentTypeStats || {};
- const typeRows = IG_CONTENT_TYPES
- .filter(type => typeStats[type]?.count > 0)
- .map(type => ({ type, ...typeStats[type], name: IG_CONTENT_TYPE_META[type].plural, color: IG_CONTENT_TYPE_META[type].color }));
- const contentMixData = typeRows.map(row => ({ name: row.name, value: row.count, color: row.color }));
- const topPostsData = (a.topPosts || []).slice(0, 8).map((post, i) => ({ name: `#${i + 1}`, likes: post.likeCount, comments: post.commentsCount }));
- const dayOfWeekData = (a.postsByDayOfWeek || []).map(d => ({ name: d.shortDay, posts: d.posts, avgEngagement: d.avgEngagement, avgLikes: d.avgLikes }));
- const timelineData = (a.engagementTimeline || []).map(m => ({ name: m.month, posts: m.posts, likes: m.likes, comments: m.comments, avgLikes: m.avgLikes }));
- const captionData = a.captionLengthCorrelation || [];
+ const profileData = profile || account;
+ const analyticsData = analytics || {};
+ const charts = instagramChartsOf(analyticsData);
+ const hashtags = analyticsData.hashtagAnalysis || [];
+ const topPosts = analyticsData.topPosts || [];
return (
<div className="flex flex-col gap-6">
- <PageHeader
- back={back}
- media={<AccountAvatar account={{ ...account, profilePictureUrl: p.profilePictureUrl || account.profilePictureUrl }} size="xl" showPlatform />}
- title={p.name || p.username}
- description={
- <span className="flex flex-col gap-1">
- <span>@{p.username}</span>
- {p.biography && <span className="line-clamp-2 max-w-xl text-small text-ink-faint">{p.biography}</span>}
- </span>
- }
- actions={
- <Button variant="outline" size="sm" onClick={handleRefresh} disabled={refreshing}>
- <RefreshCw data-icon="inline-start" className={cn(refreshing && 'animate-spin')} />
- {refreshing ? 'Refreshing' : 'Refresh'}
- </Button>
- }
- />
+ <InstagramHeader account={account} profile={profileData} back={BACK} refreshing={refreshing} onRefresh={handleRefresh} />
{refreshing && <Progress value={null} aria-label="Refreshing account" />}
- <div className="flex flex-col gap-3">
- <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 xl:grid-cols-6">
- <MetricBox small icon={<Users />} label="Followers" value={fmtNum(p.followersCount)} subtitle={fmtNumFull(p.followersCount)} highlight />
- <MetricBox small icon={<UserPlus />} label="Following" value={fmtNum(p.followsCount)} subtitle={fmtNumFull(p.followsCount)} />
- <MetricBox small icon={<Image />} label="Total posts" value={fmtNum(a.totalPosts || p.mediaCount)} subtitle={`${a.fetchedPosts || 0} analyzed`} />
- <MetricBox small icon={<Heart />} label="Total likes" value={fmtNum(a.totalLikes)} subtitle={fmtNumFull(a.totalLikes)} />
- <MetricBox small icon={<MessageCircle />} label="Total comments" value={fmtNum(a.totalComments)} subtitle={fmtNumFull(a.totalComments)} />
- <MetricBox small icon={<TrendingUp />} label="Engagement rate" value={`${a.engagementRate || 0}%`} subtitle={`${fmtNum(a.avgLikes)} likes per post on average`} />
- </div>
- <div className="grid grid-cols-2 gap-3 xl:grid-cols-4">
- <MetricBox small icon={<Eye />} label="Total views" value={fmtNum(a.totalViews)} subtitle={`${a.mediaWithViews || 0} of ${a.fetchedPosts || 0} items report views`} />
- {IG_CONTENT_TYPES.map(type => {
- const stats = typeStats[type] || {};
- const Icon = CONTENT_TYPE_ICONS[type];
- return (
- <MetricBox
- key={type}
- small
- icon={<Icon />}
- label={IG_CONTENT_TYPE_META[type].plural}
- value={fmtNum(stats.count)}
- subtitle={stats.viewsReported > 0 ? `${fmtNum(stats.totalViews)} views, ${fmtNum(stats.avgViews)} on average` : 'No views reported'}
- />
- );
- })}
- </div>
- <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 xl:grid-cols-6">
- <MetricBox small icon={<Zap />} label="Likes per post" value={fmtNum(a.avgLikes)} />
- <MetricBox small icon={<MessageCircle />} label="Comments per post" value={fmtNum(a.avgComments)} />
- <MetricBox small icon={<BarChart2 />} label="Median likes" value={fmtNum(a.medianLikes)} />
- <MetricBox small icon={<Users />} label="Follower ratio" value={p.followersCount > 0 ? (p.followersCount / Math.max(1, p.followsCount)).toFixed(1) : '0'} subtitle="Followers per account followed" />
- <MetricBox small icon={<Heart />} label="Likes per follower" value={`${a.likesPerFollower || 0}%`} subtitle="Per post, on average" />
- <MetricBox small icon={<TrendingUp />} label="Likes per comment" value={`${a.likesToCommentsRatio || 0}:1`} />
- </div>
- <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 xl:grid-cols-6">
- <MetricBox small icon={<Calendar />} label="Posts per week" value={a.postFrequency?.perWeek || 0} subtitle={`${a.postFrequency?.perMonth || 0} per month`} />
- <MetricBox small icon={<Calendar />} label="Last 7 days" value={a.postsLast7Days || 0} subtitle="Posts" />
- <MetricBox small icon={<Calendar />} label="Last 30 days" value={a.postsLast30Days || 0} subtitle="Posts" />
- <MetricBox small icon={<Calendar />} label="Last 90 days" value={a.postsLast90Days || 0} subtitle="Posts" />
- <MetricBox small icon={<Flame />} label="Virality" value={`${a.viralityScore || 0}x`} subtitle="Best post against the average" />
- <MetricBox small icon={<Trophy />} label="Consistency" value={`${a.consistencyScore || 0}/100`} subtitle="Engagement stability" />
- </div>
- </div>
-
- <div className="flex flex-wrap items-center gap-2">
- {a.bestPostingDay && <InsightChip icon={Star}>Best day: {a.bestPostingDay}</InsightChip>}
- {a.bestPostingHour && <InsightChip icon={Clock}>Best hour: {a.bestPostingHour}</InsightChip>}
- <InsightChip icon={TrendingUp}>Average engagement: {fmtNum(a.avgEngagement || 0)} per post</InsightChip>
- <InsightChip icon={Trophy}>Consistency: {a.consistencyScore || 0}/100</InsightChip>
- </div>
-
- <div className="grid grid-cols-1 gap-4 xl:grid-cols-3">
- <ChartPanel title="Engagement over time" className="xl:col-span-2" empty={timelineData.length === 0} emptyMessage="Not enough posts to chart a timeline">
- <AreaChart data={timelineData}>
- <defs>
- <linearGradient id="igLikesGrad" x1="0" y1="0" x2="0" y2="1">
- <stop offset="5%" stopColor={SERIES.primary} stopOpacity={0.2} />
- <stop offset="95%" stopColor={SERIES.primary} stopOpacity={0} />
- </linearGradient>
- </defs>
- <CartesianGrid {...gridProps} vertical={false} />
- <XAxis dataKey="name" {...axisProps} />
- <YAxis {...axisProps} width={44} tickFormatter={fmtNum} />
- <ReTooltip contentStyle={tooltipStyle} cursor={{ stroke: 'var(--line-strong)' }} />
- <Area type="monotone" dataKey="likes" name="Likes" stroke={SERIES.primary} strokeWidth={2} fill="url(#igLikesGrad)" />
- <Area type="monotone" dataKey="comments" name="Comments" stroke={SERIES.cool} strokeWidth={2} fill="transparent" />
- <Legend wrapperStyle={legendStyle} />
- </AreaChart>
- </ChartPanel>
- <ChartPanel title="Content type mix" empty={contentMixData.length === 0}>
- <PieChart>
- <Pie data={contentMixData} dataKey="value" nameKey="name" cx="50%" cy="44%" outerRadius={80} innerRadius={48} paddingAngle={2} strokeWidth={0}>
- {contentMixData.map(entry => <Cell key={entry.name} fill={entry.color} />)}
- </Pie>
- <ReTooltip contentStyle={tooltipStyle} formatter={(v, n) => [`${v} items`, n]} />
- <Legend iconType="circle" iconSize={8} wrapperStyle={{ ...legendStyle, paddingTop: 8 }} />
- </PieChart>
- </ChartPanel>
- </div>
-
- <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
- <ChartPanel title="Performance by content type" height={260} empty={typeRows.length === 0}>
- <BarChart data={typeRows}>
- <CartesianGrid {...gridProps} vertical={false} />
- <XAxis dataKey="name" {...axisProps} />
- <YAxis {...axisProps} width={44} tickFormatter={fmtNum} />
- <ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} />
- <Bar dataKey="avgLikes" name="Average likes" fill={SERIES.primary} radius={[4, 4, 0, 0]} />
- <Bar dataKey="avgComments" name="Average comments" fill={SERIES.neutral} radius={[4, 4, 0, 0]} />
- <Legend wrapperStyle={legendStyle} />
- </BarChart>
- </ChartPanel>
- <ChartPanel title="Best days to post" height={260} empty={dayOfWeekData.length === 0}>
- <BarChart data={dayOfWeekData}>
- <CartesianGrid {...gridProps} vertical={false} />
- <XAxis dataKey="name" {...axisProps} />
- <YAxis {...axisProps} width={44} tickFormatter={fmtNum} />
- <ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} />
- <Bar dataKey="avgEngagement" name="Average engagement" fill={SERIES.warm} radius={[4, 4, 0, 0]} />
- <Bar dataKey="posts" name="Posts" fill={SERIES.neutral} radius={[4, 4, 0, 0]} />
- <Legend wrapperStyle={legendStyle} />
- </BarChart>
- </ChartPanel>
- </div>
-
- <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
- <ChartPanel title="Top posts by engagement" height={260} empty={topPostsData.length === 0}>
- <BarChart data={topPostsData}>
- <CartesianGrid {...gridProps} vertical={false} />
- <XAxis dataKey="name" {...axisProps} />
- <YAxis {...axisProps} width={44} tickFormatter={fmtNum} />
- <ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} />
- <Bar dataKey="likes" name="Likes" fill={SERIES.primary} radius={[4, 4, 0, 0]} />
- <Bar dataKey="comments" name="Comments" fill={SERIES.neutral} radius={[4, 4, 0, 0]} />
- <Legend wrapperStyle={legendStyle} />
- </BarChart>
- </ChartPanel>
- <ChartPanel title="Caption length and engagement" height={260} empty={captionData.length === 0}>
- <BarChart data={captionData}>
- <CartesianGrid {...gridProps} vertical={false} />
- <XAxis dataKey="label" {...axisProps} />
- <YAxis {...axisProps} width={44} tickFormatter={fmtNum} />
- <ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} />
- <Bar dataKey="avgEngagement" name="Average engagement" fill={SERIES.cool} radius={[4, 4, 0, 0]} />
- </BarChart>
- </ChartPanel>
- </div>
+ <InstagramMetrics profile={profileData} analytics={analyticsData} />
+ <InstagramInsightChips analytics={analyticsData} />
+ <InstagramEngagementCharts charts={charts} />
+ <InstagramPostCharts charts={charts} />
- {timelineData.length > 1 && (
- <ChartPanel title="Posts per month" height={220}>
- <BarChart data={timelineData}>
- <CartesianGrid {...gridProps} vertical={false} />
- <XAxis dataKey="name" {...axisProps} />
- <YAxis {...axisProps} width={44} />
- <ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} />
- <Bar dataKey="posts" name="Posts" fill={SERIES.warm} radius={[4, 4, 0, 0]} />
- </BarChart>
- </ChartPanel>
- )}
+ {hashtags.length > 0 && <InstagramHashtags hashtags={hashtags} />}
- {(a.hashtagAnalysis || []).length > 0 && (
- <SurfaceBox title="Top hashtags">
- <div className="flex flex-wrap gap-1.5">
- {a.hashtagAnalysis.slice(0, 20).map((h, i) => (
- <Tooltip key={h.tag}>
- <TooltipTrigger render={<Badge variant={i < 5 ? 'default' : 'outline'} className="h-6 cursor-default px-2.5" />}>
- <Hash />{h.tag}<span className="opacity-70">{h.count}</span>
- </TooltipTrigger>
- <TooltipContent>Used {h.count} times, {fmtNum(h.avgEngagement)} average engagement</TooltipContent>
- </Tooltip>
- ))}
- </div>
- </SurfaceBox>
- )}
+ <InstagramRecentGrid posts={analyticsData.recentMedia || []} fetchedPosts={analyticsData.fetchedPosts} />
- <SurfaceBox title="Recent posts" subheader={`${a.fetchedPosts || 0} loaded`}>
- {(a.recentMedia || []).length > 0 ? (
- <div className="grid grid-cols-3 gap-2 sm:grid-cols-4 md:grid-cols-6 xl:grid-cols-8">
- {a.recentMedia.map(post => {
- const thumb = post.contentType === 'post' ? (post.thumbnailUrl || post.mediaUrl) : post.thumbnailUrl;
- return (
- <a
- key={post.id}
- href={post.permalink}
- target="_blank"
- rel="noopener noreferrer"
- aria-label={`Open ${igContentTypeMeta(post.contentType).label.toLowerCase()} on Instagram`}
- className="group relative aspect-square overflow-hidden rounded-control border border-line bg-surface-sunken focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring"
- >
- {thumb && <img src={thumb} alt="" loading="lazy" className="size-full object-cover" onError={e => { e.currentTarget.style.display = 'none'; }} />}
- {post.contentType !== 'post' && (
- <span className="absolute top-1 right-1"><MediaChip className="px-1.5 text-[0.625rem]">{igContentTypeMeta(post.contentType).label}</MediaChip></span>
- )}
- <span className="absolute inset-x-0 bottom-0 flex justify-center gap-2 bg-gradient-to-t from-[#0C0809]/80 to-transparent pt-4 pb-1 text-[0.625rem] font-semibold text-white opacity-0 transition-opacity duration-(--duration-base) group-hover:opacity-100 group-focus-visible:opacity-100 [&_svg]:size-2.5">
- <span className="flex items-center gap-0.5"><Eye />{fmtIGViews(post.viewCount)}</span>
- <span className="flex items-center gap-0.5"><Heart />{fmtNum(post.likeCount)}</span>
- <span className="flex items-center gap-0.5"><MessageCircle />{fmtNum(post.commentsCount)}</span>
- </span>
- </a>
- );
- })}
- </div>
- ) : (
- <EmptyState compact icon={<Image />} title="No posts yet" description="This account has not published anything we can read." />
- )}
- </SurfaceBox>
+ {topPosts.length > 0 && <InstagramTopPostsTable posts={topPosts} />}
- {(a.topPosts || []).length > 0 && (
- <SurfaceBox title="Top performing posts" content={false} className="overflow-hidden">
- <Table>
- <TableHeader>
- <TableRow>
- <TableHead className="w-10 text-right">#</TableHead>
- <TableHead>Caption</TableHead>
- <TableHead>Type</TableHead>
- <TableHead className="text-right">Views</TableHead>
- <TableHead className="text-right">Likes</TableHead>
- <TableHead className="text-right">Comments</TableHead>
- <TableHead className="text-right">Engagement</TableHead>
- <TableHead>Posted</TableHead>
- <TableHead className="w-10"><span className="sr-only">Open</span></TableHead>
- </TableRow>
- </TableHeader>
- <TableBody>
- {a.topPosts.slice(0, 10).map((post, i) => (
- <TableRow key={post.id}>
- <TableCell className="text-right font-mono text-caption text-ink-faint">{i + 1}</TableCell>
- <TableCell className="max-w-[220px]"><p className="truncate text-sm text-ink">{post.caption || 'No caption'}</p></TableCell>
- <TableCell><TypeBadge type={post.contentType} /></TableCell>
- <TableCell className="text-right text-ink-muted">{fmtIGViews(post.viewCount)}</TableCell>
- <TableCell className="text-right font-semibold text-ink">{fmtNum(post.likeCount)}</TableCell>
- <TableCell className="text-right text-ink-muted">{fmtNum(post.commentsCount)}</TableCell>
- <TableCell className="text-right text-ink-muted">{fmtNum(post.engagement)}</TableCell>
- <TableCell className="text-small text-ink-faint">{fmtDate(post.timestamp)}</TableCell>
- <TableCell>
- {post.permalink && (
- <Button variant="ghost" size="icon-xs" render={<a href={post.permalink} target="_blank" rel="noopener noreferrer" aria-label="Open post on Instagram" />}>
- <ExternalLink />
- </Button>
- )}
- </TableCell>
- </TableRow>
- ))}
- </TableBody>
- </Table>
- </SurfaceBox>
- )}
-
- {typeRows.length > 0 && (
- <SurfaceBox title="Summary by content type" content={false} className="overflow-hidden">
- <Table>
- <TableHeader>
- <TableRow>
- <TableHead>Type</TableHead>
- <TableHead className="text-right">Count</TableHead>
- <TableHead className="text-right">Total views</TableHead>
- <TableHead className="text-right">Average views</TableHead>
- <TableHead className="text-right">Average likes</TableHead>
- <TableHead className="text-right">Average comments</TableHead>
- <TableHead className="text-right">Average engagement</TableHead>
- </TableRow>
- </TableHeader>
- <TableBody>
- {typeRows.map(row => (
- <TableRow key={row.type}>
- <TableCell><TypeBadge type={row.type} /></TableCell>
- <TableCell className="text-right text-ink">{row.count}</TableCell>
- <TableCell className="text-right text-ink-muted">{row.viewsReported > 0 ? fmtNum(row.totalViews) : '-'}</TableCell>
- <TableCell className="text-right text-ink-muted">{row.viewsReported > 0 ? fmtNum(row.avgViews) : '-'}</TableCell>
- <TableCell className="text-right text-ink-muted">{fmtNum(row.avgLikes)}</TableCell>
- <TableCell className="text-right text-ink-muted">{fmtNum(row.avgComments)}</TableCell>
- <TableCell className="text-right font-semibold text-ink">{fmtNum(row.avgEngagement)}</TableCell>
- </TableRow>
- ))}
- </TableBody>
- </Table>
- </SurfaceBox>
- )}
+ {charts.typeRows.length > 0 && <InstagramTypeSummaryTable rows={charts.typeRows} />}
<p className="text-center text-caption text-ink-faint">Last updated {timeAgo(account.lastUpdated).toLowerCase()}</p>
</div>
diff --git a/frontend/src/features/analytics/instagram/InstagramEngagementCharts.jsx b/frontend/src/features/analytics/instagram/InstagramEngagementCharts.jsx
new file mode 100644
index 0000000..e88f609
--- /dev/null
+++ b/frontend/src/features/analytics/instagram/InstagramEngagementCharts.jsx
@@ -0,0 +1,71 @@
+import {
+ AreaChart, Area, BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip as ReTooltip, PieChart, Pie, Cell, Legend,
+} from 'recharts';
+import ChartPanel from '@/components/ChartPanel';
+import { SERIES, axisProps, gridProps, legendStyle, tooltipCursor, tooltipStyle } from '@/lib/chart';
+import { fmtNum } from '../../../utils/formatters';
+
+function formatItems(value, name) {
+ return [`${value} items`, name];
+}
+
+export default function InstagramEngagementCharts({ charts }) {
+ const { timeline, contentMix, typeRows, dayOfWeek } = charts;
+ return (
+ <>
+ <div className="grid grid-cols-1 gap-4 xl:grid-cols-3">
+ <ChartPanel title="Engagement over time" className="xl:col-span-2" empty={timeline.length === 0} emptyMessage="Not enough posts to chart a timeline">
+ <AreaChart data={timeline}>
+ <defs>
+ <linearGradient id="igLikesGrad" x1="0" y1="0" x2="0" y2="1">
+ <stop offset="5%" stopColor={SERIES.primary} stopOpacity={0.2} />
+ <stop offset="95%" stopColor={SERIES.primary} stopOpacity={0} />
+ </linearGradient>
+ </defs>
+ <CartesianGrid {...gridProps} vertical={false} />
+ <XAxis dataKey="name" {...axisProps} />
+ <YAxis {...axisProps} width={44} tickFormatter={fmtNum} />
+ <ReTooltip contentStyle={tooltipStyle} cursor={{ stroke: 'var(--line-strong)' }} />
+ <Area type="monotone" dataKey="likes" name="Likes" stroke={SERIES.primary} strokeWidth={2} fill="url(#igLikesGrad)" />
+ <Area type="monotone" dataKey="comments" name="Comments" stroke={SERIES.cool} strokeWidth={2} fill="transparent" />
+ <Legend wrapperStyle={legendStyle} />
+ </AreaChart>
+ </ChartPanel>
+ <ChartPanel title="Content type mix" empty={contentMix.length === 0}>
+ <PieChart>
+ <Pie data={contentMix} dataKey="value" nameKey="name" cx="50%" cy="44%" outerRadius={80} innerRadius={48} paddingAngle={2} strokeWidth={0}>
+ {contentMix.map(entry => <Cell key={entry.name} fill={entry.color} />)}
+ </Pie>
+ <ReTooltip contentStyle={tooltipStyle} formatter={formatItems} />
+ <Legend iconType="circle" iconSize={8} wrapperStyle={{ ...legendStyle, paddingTop: 8 }} />
+ </PieChart>
+ </ChartPanel>
+ </div>
+
+ <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
+ <ChartPanel title="Performance by content type" height={260} empty={typeRows.length === 0}>
+ <BarChart data={typeRows}>
+ <CartesianGrid {...gridProps} vertical={false} />
+ <XAxis dataKey="name" {...axisProps} />
+ <YAxis {...axisProps} width={44} tickFormatter={fmtNum} />
+ <ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} />
+ <Bar dataKey="avgLikes" name="Average likes" fill={SERIES.primary} radius={[4, 4, 0, 0]} />
+ <Bar dataKey="avgComments" name="Average comments" fill={SERIES.neutral} radius={[4, 4, 0, 0]} />
+ <Legend wrapperStyle={legendStyle} />
+ </BarChart>
+ </ChartPanel>
+ <ChartPanel title="Best days to post" height={260} empty={dayOfWeek.length === 0}>
+ <BarChart data={dayOfWeek}>
+ <CartesianGrid {...gridProps} vertical={false} />
+ <XAxis dataKey="name" {...axisProps} />
+ <YAxis {...axisProps} width={44} tickFormatter={fmtNum} />
+ <ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} />
+ <Bar dataKey="avgEngagement" name="Average engagement" fill={SERIES.warm} radius={[4, 4, 0, 0]} />
+ <Bar dataKey="posts" name="Posts" fill={SERIES.neutral} radius={[4, 4, 0, 0]} />
+ <Legend wrapperStyle={legendStyle} />
+ </BarChart>
+ </ChartPanel>
+ </div>
+ </>
+ );
+}
diff --git a/frontend/src/features/analytics/instagram/InstagramHashtags.jsx b/frontend/src/features/analytics/instagram/InstagramHashtags.jsx
new file mode 100644
index 0000000..5fc0cc1
--- /dev/null
+++ b/frontend/src/features/analytics/instagram/InstagramHashtags.jsx
@@ -0,0 +1,22 @@
+import { Hash } from 'lucide-react';
+import { Badge } from '@/components/ui/badge';
+import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
+import SurfaceBox from '@/components/SurfaceBox';
+import { fmtNum } from '../../../utils/formatters';
+
+export default function InstagramHashtags({ hashtags }) {
+ return (
+ <SurfaceBox title="Top hashtags">
+ <div className="flex flex-wrap gap-1.5">
+ {hashtags.slice(0, 20).map((hashtag, i) => (
+ <Tooltip key={hashtag.tag}>
+ <TooltipTrigger render={<Badge variant={i < 5 ? 'default' : 'outline'} className="h-6 cursor-default px-2.5" />}>
+ <Hash />{hashtag.tag}<span className="opacity-70">{hashtag.count}</span>
+ </TooltipTrigger>
+ <TooltipContent>Used {hashtag.count} times, {fmtNum(hashtag.avgEngagement)} average engagement</TooltipContent>
+ </Tooltip>
+ ))}
+ </div>
+ </SurfaceBox>
+ );
+}
diff --git a/frontend/src/features/analytics/instagram/InstagramHeader.jsx b/frontend/src/features/analytics/instagram/InstagramHeader.jsx
new file mode 100644
index 0000000..3f4f252
--- /dev/null
+++ b/frontend/src/features/analytics/instagram/InstagramHeader.jsx
@@ -0,0 +1,27 @@
+import { RefreshCw } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import PageHeader from '@/components/PageHeader';
+import { AccountAvatar } from '@/components/platform';
+import { cn } from '@/lib/utils';
+
+export default function InstagramHeader({ account, profile, back, refreshing, onRefresh }) {
+ return (
+ <PageHeader
+ back={back}
+ media={<AccountAvatar account={{ ...account, profilePictureUrl: profile.profilePictureUrl || account.profilePictureUrl }} size="xl" showPlatform />}
+ title={profile.name || profile.username}
+ description={
+ <span className="flex flex-col gap-1">
+ <span>@{profile.username}</span>
+ {profile.biography && <span className="line-clamp-2 max-w-xl text-small text-ink-faint">{profile.biography}</span>}
+ </span>
+ }
+ actions={
+ <Button variant="outline" size="sm" onClick={onRefresh} disabled={refreshing}>
+ <RefreshCw data-icon="inline-start" className={cn(refreshing && 'animate-spin')} />
+ {refreshing ? 'Refreshing' : 'Refresh'}
+ </Button>
+ }
+ />
+ );
+}
diff --git a/frontend/src/features/analytics/instagram/InstagramInsightChips.jsx b/frontend/src/features/analytics/instagram/InstagramInsightChips.jsx
new file mode 100644
index 0000000..a7d1e24
--- /dev/null
+++ b/frontend/src/features/analytics/instagram/InstagramInsightChips.jsx
@@ -0,0 +1,23 @@
+import { Clock, Star, TrendingUp, Trophy } from 'lucide-react';
+import { fmtNum } from '../../../utils/formatters';
+
+function InsightChip({ icon, children }) {
+ const Icon = icon;
+ return (
+ <span className="inline-flex h-8 items-center gap-1.5 rounded-field border border-line bg-surface px-3 text-small font-medium text-ink">
+ <Icon className="size-3.5 stroke-[1.75] text-ink-faint" />
+ {children}
+ </span>
+ );
+}
+
+export default function InstagramInsightChips({ analytics }) {
+ return (
+ <div className="flex flex-wrap items-center gap-2">
+ {analytics.bestPostingDay && <InsightChip icon={Star}>Best day: {analytics.bestPostingDay}</InsightChip>}
+ {analytics.bestPostingHour && <InsightChip icon={Clock}>Best hour: {analytics.bestPostingHour}</InsightChip>}
+ <InsightChip icon={TrendingUp}>Average engagement: {fmtNum(analytics.avgEngagement || 0)} per post</InsightChip>
+ <InsightChip icon={Trophy}>Consistency: {analytics.consistencyScore || 0}/100</InsightChip>
+ </div>
+ );
+}
diff --git a/frontend/src/features/analytics/instagram/InstagramMetrics.jsx b/frontend/src/features/analytics/instagram/InstagramMetrics.jsx
new file mode 100644
index 0000000..3953952
--- /dev/null
+++ b/frontend/src/features/analytics/instagram/InstagramMetrics.jsx
@@ -0,0 +1,58 @@
+import {
+ BarChart2, Calendar, Clapperboard, Eye, Film, Flame, Heart, Image, MessageCircle, TrendingUp, Trophy, UserPlus, Users, Zap,
+} from 'lucide-react';
+import MetricBox from '@/components/MetricBox';
+import { fmtNum, fmtNumFull } from '../../../utils/formatters';
+import { IG_CONTENT_TYPES, IG_CONTENT_TYPE_META } from '../../../utils/instagramContent';
+import { followerRatio, typeViewsSubtitle } from './instagramAnalyticsData.js';
+
+const CONTENT_TYPE_ICONS = { reel: Clapperboard, post: Image, video: Film };
+
+function ContentTypeMetric({ type, stats }) {
+ const Icon = CONTENT_TYPE_ICONS[type];
+ return (
+ <MetricBox
+ small
+ icon={<Icon />}
+ label={IG_CONTENT_TYPE_META[type].plural}
+ value={fmtNum(stats.count)}
+ subtitle={typeViewsSubtitle(stats)}
+ />
+ );
+}
+
+export default function InstagramMetrics({ profile, analytics }) {
+ const typeStats = analytics.contentTypeStats || {};
+ return (
+ <div className="flex flex-col gap-3">
+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 xl:grid-cols-6">
+ <MetricBox small icon={<Users />} label="Followers" value={fmtNum(profile.followersCount)} subtitle={fmtNumFull(profile.followersCount)} highlight />
+ <MetricBox small icon={<UserPlus />} label="Following" value={fmtNum(profile.followsCount)} subtitle={fmtNumFull(profile.followsCount)} />
+ <MetricBox small icon={<Image />} label="Total posts" value={fmtNum(analytics.totalPosts || profile.mediaCount)} subtitle={`${analytics.fetchedPosts || 0} analyzed`} />
+ <MetricBox small icon={<Heart />} label="Total likes" value={fmtNum(analytics.totalLikes)} subtitle={fmtNumFull(analytics.totalLikes)} />
+ <MetricBox small icon={<MessageCircle />} label="Total comments" value={fmtNum(analytics.totalComments)} subtitle={fmtNumFull(analytics.totalComments)} />
+ <MetricBox small icon={<TrendingUp />} label="Engagement rate" value={`${analytics.engagementRate || 0}%`} subtitle={`${fmtNum(analytics.avgLikes)} likes per post on average`} />
+ </div>
+ <div className="grid grid-cols-2 gap-3 xl:grid-cols-4">
+ <MetricBox small icon={<Eye />} label="Total views" value={fmtNum(analytics.totalViews)} subtitle={`${analytics.mediaWithViews || 0} of ${analytics.fetchedPosts || 0} items report views`} />
+ {IG_CONTENT_TYPES.map(type => <ContentTypeMetric key={type} type={type} stats={typeStats[type] || {}} />)}
+ </div>
+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 xl:grid-cols-6">
+ <MetricBox small icon={<Zap />} label="Likes per post" value={fmtNum(analytics.avgLikes)} />
+ <MetricBox small icon={<MessageCircle />} label="Comments per post" value={fmtNum(analytics.avgComments)} />
+ <MetricBox small icon={<BarChart2 />} label="Median likes" value={fmtNum(analytics.medianLikes)} />
+ <MetricBox small icon={<Users />} label="Follower ratio" value={followerRatio(profile)} subtitle="Followers per account followed" />
+ <MetricBox small icon={<Heart />} label="Likes per follower" value={`${analytics.likesPerFollower || 0}%`} subtitle="Per post, on average" />
+ <MetricBox small icon={<TrendingUp />} label="Likes per comment" value={`${analytics.likesToCommentsRatio || 0}:1`} />
+ </div>
+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 xl:grid-cols-6">
+ <MetricBox small icon={<Calendar />} label="Posts per week" value={analytics.postFrequency?.perWeek || 0} subtitle={`${analytics.postFrequency?.perMonth || 0} per month`} />
+ <MetricBox small icon={<Calendar />} label="Last 7 days" value={analytics.postsLast7Days || 0} subtitle="Posts" />
+ <MetricBox small icon={<Calendar />} label="Last 30 days" value={analytics.postsLast30Days || 0} subtitle="Posts" />
+ <MetricBox small icon={<Calendar />} label="Last 90 days" value={analytics.postsLast90Days || 0} subtitle="Posts" />
+ <MetricBox small icon={<Flame />} label="Virality" value={`${analytics.viralityScore || 0}x`} subtitle="Best post against the average" />
+ <MetricBox small icon={<Trophy />} label="Consistency" value={`${analytics.consistencyScore || 0}/100`} subtitle="Engagement stability" />
+ </div>
+ </div>
+ );
+}
diff --git a/frontend/src/features/analytics/instagram/InstagramPostCharts.jsx b/frontend/src/features/analytics/instagram/InstagramPostCharts.jsx
new file mode 100644
index 0000000..2fb3ebb
--- /dev/null
+++ b/frontend/src/features/analytics/instagram/InstagramPostCharts.jsx
@@ -0,0 +1,46 @@
+import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip as ReTooltip, Legend } from 'recharts';
+import ChartPanel from '@/components/ChartPanel';
+import { SERIES, axisProps, gridProps, legendStyle, tooltipCursor, tooltipStyle } from '@/lib/chart';
+import { fmtNum } from '../../../utils/formatters';
+
+export default function InstagramPostCharts({ charts }) {
+ const { topPosts, caption, timeline } = charts;
+ return (
+ <>
+ <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
+ <ChartPanel title="Top posts by engagement" height={260} empty={topPosts.length === 0}>
+ <BarChart data={topPosts}>
+ <CartesianGrid {...gridProps} vertical={false} />
+ <XAxis dataKey="name" {...axisProps} />
+ <YAxis {...axisProps} width={44} tickFormatter={fmtNum} />
+ <ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} />
+ <Bar dataKey="likes" name="Likes" fill={SERIES.primary} radius={[4, 4, 0, 0]} />
+ <Bar dataKey="comments" name="Comments" fill={SERIES.neutral} radius={[4, 4, 0, 0]} />
+ <Legend wrapperStyle={legendStyle} />
+ </BarChart>
+ </ChartPanel>
+ <ChartPanel title="Caption length and engagement" height={260} empty={caption.length === 0}>
+ <BarChart data={caption}>
+ <CartesianGrid {...gridProps} vertical={false} />
+ <XAxis dataKey="label" {...axisProps} />
+ <YAxis {...axisProps} width={44} tickFormatter={fmtNum} />
+ <ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} />
+ <Bar dataKey="avgEngagement" name="Average engagement" fill={SERIES.cool} radius={[4, 4, 0, 0]} />
+ </BarChart>
+ </ChartPanel>
+ </div>
+
+ {timeline.length > 1 && (
+ <ChartPanel title="Posts per month" height={220}>
+ <BarChart data={timeline}>
+ <CartesianGrid {...gridProps} vertical={false} />
+ <XAxis dataKey="name" {...axisProps} />
+ <YAxis {...axisProps} width={44} />
+ <ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} />
+ <Bar dataKey="posts" name="Posts" fill={SERIES.warm} radius={[4, 4, 0, 0]} />
+ </BarChart>
+ </ChartPanel>
+ )}
+ </>
+ );
+}
diff --git a/frontend/src/features/analytics/instagram/InstagramRecentGrid.jsx b/frontend/src/features/analytics/instagram/InstagramRecentGrid.jsx
new file mode 100644
index 0000000..8c10b3e
--- /dev/null
+++ b/frontend/src/features/analytics/instagram/InstagramRecentGrid.jsx
@@ -0,0 +1,47 @@
+import { Eye, Heart, Image, MessageCircle } from 'lucide-react';
+import SurfaceBox from '@/components/SurfaceBox';
+import { MediaChip } from '@/components/MediaCard';
+import { EmptyState } from '@/components/StateViews';
+import { fmtNum } from '../../../utils/formatters';
+import { fmtIGViews, igContentTypeMeta, igThumbnail } from '../../../utils/instagramContent';
+
+function hideBrokenImage(e) {
+ e.currentTarget.style.display = 'none';
+}
+
+function RecentPost({ post }) {
+ const thumb = igThumbnail(post);
+ return (
+ <a
+ href={post.permalink}
+ target="_blank"
+ rel="noopener noreferrer"
+ aria-label={`Open ${igContentTypeMeta(post.contentType).label.toLowerCase()} on Instagram`}
+ className="group relative aspect-square overflow-hidden rounded-control border border-line bg-surface-sunken focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring"
+ >
+ {thumb && <img src={thumb} alt="" loading="lazy" className="size-full object-cover" onError={hideBrokenImage} />}
+ {post.contentType !== 'post' && (
+ <span className="absolute top-1 right-1"><MediaChip className="px-1.5 text-[0.625rem]">{igContentTypeMeta(post.contentType).label}</MediaChip></span>
+ )}
+ <span className="absolute inset-x-0 bottom-0 flex justify-center gap-2 bg-gradient-to-t from-[#0C0809]/80 to-transparent pt-4 pb-1 text-[0.625rem] font-semibold text-white opacity-0 transition-opacity duration-(--duration-base) group-hover:opacity-100 group-focus-visible:opacity-100 [&_svg]:size-2.5">
+ <span className="flex items-center gap-0.5"><Eye />{fmtIGViews(post.viewCount)}</span>
+ <span className="flex items-center gap-0.5"><Heart />{fmtNum(post.likeCount)}</span>
+ <span className="flex items-center gap-0.5"><MessageCircle />{fmtNum(post.commentsCount)}</span>
+ </span>
+ </a>
+ );
+}
+
+export default function InstagramRecentGrid({ posts, fetchedPosts }) {
+ return (
+ <SurfaceBox title="Recent posts" subheader={`${fetchedPosts || 0} loaded`}>
+ {posts.length > 0 ? (
+ <div className="grid grid-cols-3 gap-2 sm:grid-cols-4 md:grid-cols-6 xl:grid-cols-8">
+ {posts.map(post => <RecentPost key={post.id} post={post} />)}
+ </div>
+ ) : (
+ <EmptyState compact icon={<Image />} title="No posts yet" description="This account has not published anything we can read." />
+ )}
+ </SurfaceBox>
+ );
+}
diff --git a/frontend/src/features/analytics/instagram/InstagramTopPostsTable.jsx b/frontend/src/features/analytics/instagram/InstagramTopPostsTable.jsx
new file mode 100644
index 0000000..fce7f23
--- /dev/null
+++ b/frontend/src/features/analytics/instagram/InstagramTopPostsTable.jsx
@@ -0,0 +1,50 @@
+import { ExternalLink } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
+import SurfaceBox from '@/components/SurfaceBox';
+import { fmtDate, fmtNum } from '../../../utils/formatters';
+import { fmtIGViews } from '../../../utils/instagramContent';
+import TypeBadge from './TypeBadge';
+
+export default function InstagramTopPostsTable({ posts }) {
+ return (
+ <SurfaceBox title="Top performing posts" content={false} className="overflow-hidden">
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead className="w-10 text-right">#</TableHead>
+ <TableHead>Caption</TableHead>
+ <TableHead>Type</TableHead>
+ <TableHead className="text-right">Views</TableHead>
+ <TableHead className="text-right">Likes</TableHead>
+ <TableHead className="text-right">Comments</TableHead>
+ <TableHead className="text-right">Engagement</TableHead>
+ <TableHead>Posted</TableHead>
+ <TableHead className="w-10"><span className="sr-only">Open</span></TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {posts.slice(0, 10).map((post, i) => (
+ <TableRow key={post.id}>
+ <TableCell className="text-right font-mono text-caption text-ink-faint">{i + 1}</TableCell>
+ <TableCell className="max-w-[220px]"><p className="truncate text-sm text-ink">{post.caption || 'No caption'}</p></TableCell>
+ <TableCell><TypeBadge type={post.contentType} /></TableCell>
+ <TableCell className="text-right text-ink-muted">{fmtIGViews(post.viewCount)}</TableCell>
+ <TableCell className="text-right font-semibold text-ink">{fmtNum(post.likeCount)}</TableCell>
+ <TableCell className="text-right text-ink-muted">{fmtNum(post.commentsCount)}</TableCell>
+ <TableCell className="text-right text-ink-muted">{fmtNum(post.engagement)}</TableCell>
+ <TableCell className="text-small text-ink-faint">{fmtDate(post.timestamp)}</TableCell>
+ <TableCell>
+ {post.permalink && (
+ <Button variant="ghost" size="icon-xs" render={<a href={post.permalink} target="_blank" rel="noopener noreferrer" aria-label="Open post on Instagram" />}>
+ <ExternalLink />
+ </Button>
+ )}
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ </SurfaceBox>
+ );
+}
diff --git a/frontend/src/features/analytics/instagram/InstagramTypeSummaryTable.jsx b/frontend/src/features/analytics/instagram/InstagramTypeSummaryTable.jsx
new file mode 100644
index 0000000..ea9d0a7
--- /dev/null
+++ b/frontend/src/features/analytics/instagram/InstagramTypeSummaryTable.jsx
@@ -0,0 +1,38 @@
+import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
+import SurfaceBox from '@/components/SurfaceBox';
+import { fmtNum } from '../../../utils/formatters';
+import { reportedViews } from './instagramAnalyticsData.js';
+import TypeBadge from './TypeBadge';
+
+export default function InstagramTypeSummaryTable({ rows }) {
+ return (
+ <SurfaceBox title="Summary by content type" content={false} className="overflow-hidden">
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead>Type</TableHead>
+ <TableHead className="text-right">Count</TableHead>
+ <TableHead className="text-right">Total views</TableHead>
+ <TableHead className="text-right">Average views</TableHead>
+ <TableHead className="text-right">Average likes</TableHead>
+ <TableHead className="text-right">Average comments</TableHead>
+ <TableHead className="text-right">Average engagement</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {rows.map(row => (
+ <TableRow key={row.type}>
+ <TableCell><TypeBadge type={row.type} /></TableCell>
+ <TableCell className="text-right text-ink">{row.count}</TableCell>
+ <TableCell className="text-right text-ink-muted">{reportedViews(row, 'totalViews')}</TableCell>
+ <TableCell className="text-right text-ink-muted">{reportedViews(row, 'avgViews')}</TableCell>
+ <TableCell className="text-right text-ink-muted">{fmtNum(row.avgLikes)}</TableCell>
+ <TableCell className="text-right text-ink-muted">{fmtNum(row.avgComments)}</TableCell>
+ <TableCell className="text-right font-semibold text-ink">{fmtNum(row.avgEngagement)}</TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ </SurfaceBox>
+ );
+}
diff --git a/frontend/src/features/analytics/instagram/TypeBadge.jsx b/frontend/src/features/analytics/instagram/TypeBadge.jsx
new file mode 100644
index 0000000..e006fc0
--- /dev/null
+++ b/frontend/src/features/analytics/instagram/TypeBadge.jsx
@@ -0,0 +1,11 @@
+import { igContentTypeMeta } from '../../../utils/instagramContent';
+
+export default function TypeBadge({ type }) {
+ const meta = igContentTypeMeta(type);
+ return (
+ <span className="inline-flex h-5 items-center gap-1.5 rounded-pill border border-line px-2 text-caption font-medium text-ink-muted">
+ <span className="size-2 rounded-full" style={{ background: meta.color }} />
+ {meta.label}
+ </span>
+ );
+}
diff --git a/frontend/src/features/analytics/instagram/instagramAnalyticsData.js b/frontend/src/features/analytics/instagram/instagramAnalyticsData.js
new file mode 100644
index 0000000..a62218c
--- /dev/null
+++ b/frontend/src/features/analytics/instagram/instagramAnalyticsData.js
@@ -0,0 +1,57 @@
+// chart rows and labels for Instagram analytics; no JSX or path aliases so node --test can import it
+
+import { fmtNum } from '../../../utils/formatters.js';
+import { IG_CONTENT_TYPES, IG_CONTENT_TYPE_META } from '../../../utils/instagramContent.js';
+
+export function typeRowsOf(typeStats) {
+ return IG_CONTENT_TYPES
+ .filter(type => typeStats[type]?.count > 0)
+ .map(type => ({ type, ...typeStats[type], name: IG_CONTENT_TYPE_META[type].plural, color: IG_CONTENT_TYPE_META[type].color }));
+}
+
+export function contentMixOf(typeRows) {
+ return typeRows.map(row => ({ name: row.name, value: row.count, color: row.color }));
+}
+
+export function topPostsChartOf(topPosts) {
+ return (topPosts || []).slice(0, 8).map((post, i) => ({ name: `#${i + 1}`, likes: post.likeCount, comments: post.commentsCount }));
+}
+
+export function dayOfWeekDataOf(postsByDayOfWeek) {
+ return (postsByDayOfWeek || []).map(day => ({
+ name: day.shortDay, posts: day.posts, avgEngagement: day.avgEngagement, avgLikes: day.avgLikes,
+ }));
+}
+
+export function timelineDataOf(engagementTimeline) {
+ return (engagementTimeline || []).map(month => ({
+ name: month.month, posts: month.posts, likes: month.likes, comments: month.comments, avgLikes: month.avgLikes,
+ }));
+}
+
+export function instagramChartsOf(analytics) {
+ const typeRows = typeRowsOf(analytics.contentTypeStats || {});
+ return {
+ typeRows,
+ contentMix: contentMixOf(typeRows),
+ topPosts: topPostsChartOf(analytics.topPosts),
+ dayOfWeek: dayOfWeekDataOf(analytics.postsByDayOfWeek),
+ timeline: timelineDataOf(analytics.engagementTimeline),
+ caption: analytics.captionLengthCorrelation || [],
+ };
+}
+
+export function followerRatio(profile) {
+ if (profile.followersCount > 0) return (profile.followersCount / Math.max(1, profile.followsCount)).toFixed(1);
+ return '0';
+}
+
+export function typeViewsSubtitle(stats) {
+ if (stats.viewsReported > 0) return `${fmtNum(stats.totalViews)} views, ${fmtNum(stats.avgViews)} on average`;
+ return 'No views reported';
+}
+
+export function reportedViews(row, field) {
+ if (row.viewsReported > 0) return fmtNum(row[field]);
+ return '-';
+}
diff --git a/frontend/src/features/analytics/instagram/instagramAnalyticsData.test.js b/frontend/src/features/analytics/instagram/instagramAnalyticsData.test.js
new file mode 100644
index 0000000..e8e2794
--- /dev/null
+++ b/frontend/src/features/analytics/instagram/instagramAnalyticsData.test.js
@@ -0,0 +1,57 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import {
+ typeRowsOf, contentMixOf, topPostsChartOf, dayOfWeekDataOf, timelineDataOf, instagramChartsOf, followerRatio,
+ typeViewsSubtitle, reportedViews,
+} from './instagramAnalyticsData.js';
+
+const typeStats = {
+ reel: { count: 3, avgLikes: 10, viewsReported: 3, totalViews: 4500, avgViews: 1500 },
+ post: { count: 0 },
+ video: { count: 1, avgLikes: 2, viewsReported: 0 },
+};
+
+test('type rows keep content types with posts, in display order', () => {
+ const rows = typeRowsOf(typeStats);
+ assert.deepEqual(rows.map(row => row.type), ['reel', 'video']);
+ assert.equal(rows[0].name, 'Reels');
+ assert.equal(rows[0].color, 'var(--chart-1)');
+ assert.equal(rows[0].avgLikes, 10);
+ assert.deepEqual(contentMixOf(rows), [
+ { name: 'Reels', value: 3, color: 'var(--chart-1)' },
+ { name: 'Videos', value: 1, color: 'var(--chart-4)' },
+ ]);
+});
+
+test('chart rows map the analytics fields', () => {
+ const posts = Array.from({ length: 10 }, (_, i) => ({ likeCount: i, commentsCount: i * 2 }));
+ const top = topPostsChartOf(posts);
+ assert.equal(top.length, 8);
+ assert.deepEqual(top[1], { name: '#2', likes: 1, comments: 2 });
+ assert.deepEqual(topPostsChartOf(undefined), []);
+ assert.deepEqual(dayOfWeekDataOf([{ shortDay: 'Mon', posts: 2, avgEngagement: 5, avgLikes: 4, extra: 1 }]), [
+ { name: 'Mon', posts: 2, avgEngagement: 5, avgLikes: 4 },
+ ]);
+ assert.deepEqual(timelineDataOf([{ month: 'Jan', posts: 1, likes: 2, comments: 3, avgLikes: 2 }]), [
+ { name: 'Jan', posts: 1, likes: 2, comments: 3, avgLikes: 2 },
+ ]);
+});
+
+test('empty analytics give empty charts', () => {
+ assert.deepEqual(instagramChartsOf({}), {
+ typeRows: [], contentMix: [], topPosts: [], dayOfWeek: [], timeline: [], caption: [],
+ });
+});
+
+test('follower ratio guards against zero', () => {
+ assert.equal(followerRatio({ followersCount: 300, followsCount: 120 }), '2.5');
+ assert.equal(followerRatio({ followersCount: 300, followsCount: 0 }), '300.0');
+ assert.equal(followerRatio({ followersCount: 0, followsCount: 10 }), '0');
+});
+
+test('views show only when Instagram reported them', () => {
+ assert.equal(typeViewsSubtitle(typeStats.reel), '4.5K views, 1.5K on average');
+ assert.equal(typeViewsSubtitle({}), 'No views reported');
+ assert.equal(reportedViews(typeStats.reel, 'avgViews'), '1.5K');
+ assert.equal(reportedViews(typeStats.video, 'totalViews'), '-');
+});
diff --git a/frontend/src/features/analytics/reddit/RedditAnalytics.jsx b/frontend/src/features/analytics/reddit/RedditAnalytics.jsx
index 1ef6b51..ab64e71 100644
--- a/frontend/src/features/analytics/reddit/RedditAnalytics.jsx
+++ b/frontend/src/features/analytics/reddit/RedditAnalytics.jsx
@@ -1,91 +1,36 @@
-import React, { useCallback, useEffect, useState } from 'react';
-import { Link, useParams } from 'react-router-dom';
-import {
- BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip as ReTooltip, AreaChart, Area, PieChart, Pie,
- Cell, Legend,
-} from 'recharts';
-import { RefreshCw, TrendingUp, MessageSquare, Award, Star, ExternalLink, FileText, UserX } from 'lucide-react';
-import { Button } from '@/components/ui/button';
-import { Badge } from '@/components/ui/badge';
+import { useParams } from 'react-router-dom';
+import { Award, MessageSquare, Star, TrendingUp, UserX } from 'lucide-react';
import { Progress } from '@/components/ui/progress';
-import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import PageHeader from '@/components/PageHeader';
import MetricBox from '@/components/MetricBox';
import SurfaceBox from '@/components/SurfaceBox';
-import ChartPanel from '@/components/ChartPanel';
-import { RankNumber } from '@/components/ListRow';
import { EmptyState, PageSkeleton } from '@/components/StateViews';
-import { AccountAvatar } from '@/components/platform';
-import { SERIES, axisProps, axisTick, gridProps, legendStyle, seriesAt, tooltipCursor, tooltipStyle } from '@/lib/chart';
import { useAppContext } from '../../../context/AppContext';
+import { useAccountAnalytics } from '../../../hooks/use-account-analytics';
import { api } from '../../../services/api';
-import { fmtNum, fmtNumFull, fmtDate, timeAgo } from '../../../utils/formatters';
+import { fmtNum } from '../../../utils/formatters';
import { MEDIA_TYPE_LABELS } from './redditPostUtils';
-import { cn } from '@/lib/utils';
-import ColumnHint from '@/components/ColumnHint';
+import { mediaTypeDataOf } from './redditAnalyticsData.js';
+import RedditHeader from './RedditHeader';
+import RedditKarmaSummary from './RedditKarmaSummary';
+import RedditKarmaCharts from './RedditKarmaCharts';
+import RedditStatPanels from './RedditStatPanels';
+import RedditTimingCharts from './RedditTimingCharts';
+import RedditSubredditTable from './RedditSubredditTable';
+import RedditTopPostsTable from './RedditTopPostsTable';
-const MEDIA_TYPE_ORDER = ['text', 'image', 'video', 'link'];
-
-function StatList({ rows }) {
- return (
- <dl className="flex flex-col divide-y divide-divider">
- {rows.map(row => (
- <div key={row.label} className="flex items-center justify-between gap-4 py-2.5 first:pt-0 last:pb-0">
- <dt className="text-sm text-ink-muted">{row.label}</dt>
- <dd className="text-sm font-semibold text-ink tabular-nums">{row.value}</dd>
- </div>
- ))}
- </dl>
- );
-}
+const BACK = { to: '/', label: 'Overview' };
export default function RedditAnalytics() {
const { id } = useParams();
- const { accounts, showToast } = useAppContext();
- const account = accounts.find(a => a.id === id);
-
- const [loading, setLoading] = useState(true);
- const [profile, setProfile] = useState(null);
- const [analytics, setAnalytics] = useState(null);
- const [refreshing, setRefreshing] = useState(false);
-
- const loadAnalytics = useCallback(async () => {
- if (!account) return;
- setLoading(true);
- try {
- const data = await api.getRedditAnalytics(account.id);
- setProfile(data.profile);
- setAnalytics(data.analytics);
- } catch (err) {
- showToast(`Couldn't load Reddit analytics. ${err.message}`, 'error');
- } finally {
- setLoading(false);
- }
- // Keyed on the account id so a background account refresh does not refetch analytics
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [account?.id, showToast]);
-
- useEffect(() => { loadAnalytics(); }, [id, loadAnalytics]);
-
- const handleRefresh = async () => {
- setRefreshing(true);
- try {
- await api.refreshAccount(account.id);
- await loadAnalytics();
- showToast('Reddit account refreshed');
- } catch (err) {
- showToast(`Refresh failed. ${err.message}`, 'error');
- } finally {
- setRefreshing(false);
- }
- };
-
- const back = { to: '/', label: 'Overview' };
+ const { accounts } = useAppContext();
+ const account = accounts.find(item => item.id === id);
+ const { loading, profile, analytics, refreshing, handleRefresh } = useAccountAnalytics(account, api.getRedditAnalytics, 'Reddit');
if (!account) {
return (
<div className="flex flex-col gap-6">
- <PageHeader title="Reddit account" back={back} />
+ <PageHeader title="Reddit account" back={BACK} />
<SurfaceBox>
<EmptyState icon={<UserX />} title="Account not found" description="It may have been removed. Choose another account from the sidebar." />
</SurfaceBox>
@@ -95,247 +40,38 @@ export default function RedditAnalytics() {
if (loading) return <PageSkeleton metrics={4} />;
- const p = profile || account;
- const a = analytics || {};
-
- const mediaTypeData = a.mediaTypeDistribution
- ? Object.entries(a.mediaTypeDistribution).map(([key, value]) => ({
- name: MEDIA_TYPE_LABELS[key] || key,
- value,
- color: seriesAt(Math.max(0, MEDIA_TYPE_ORDER.indexOf(key))),
- }))
- : [];
+ const profileData = profile || account;
+ const analyticsData = analytics || {};
return (
<div className="flex flex-col gap-6">
- <PageHeader
- back={back}
- media={<AccountAvatar account={{ ...account, iconUrl: p.iconUrl || account.iconUrl }} size="xl" showPlatform />}
- title={`u/${p.username || account.username}`}
- description={
- <span className="flex flex-wrap items-center gap-1.5">
- {p.isGold && <Badge variant="warning">Gold</Badge>}
- {p.verified && <Badge variant="info">Verified</Badge>}
- {p.isMod && <Badge variant="outline">Moderator</Badge>}
- <span>
- {p.createdAt ? `Joined ${fmtDate(p.createdAt)}. ` : ''}Refreshed {timeAgo(account.lastUpdated).toLowerCase()}.
- </span>
- </span>
- }
- actions={
- <>
- <Button variant="outline" size="sm" render={<Link to={`/reddit-posts/${account.id}`} />}>
- <FileText data-icon="inline-start" />
- View posts
- </Button>
- <Button variant="outline" size="sm" onClick={handleRefresh} disabled={refreshing}>
- <RefreshCw data-icon="inline-start" className={cn(refreshing && 'animate-spin')} />
- {refreshing ? 'Refreshing' : 'Refresh'}
- </Button>
- </>
- }
- />
+ <RedditHeader account={account} profile={profileData} back={BACK} refreshing={refreshing} onRefresh={handleRefresh} />
{refreshing && <Progress value={null} aria-label="Refreshing account" />}
- <SurfaceBox title="Karma" subheader="Earned across posts and comments">
- <div className="grid grid-cols-2 gap-x-6 gap-y-5 sm:grid-cols-4">
- {[
- { label: 'Total karma', value: fmtNum(p.totalKarma), sub: fmtNumFull(p.totalKarma), lead: true },
- { label: 'Post karma', value: fmtNum(p.postKarma), sub: 'From submitted posts' },
- { label: 'Comment karma', value: fmtNum(p.commentKarma), sub: 'From comments' },
- { label: 'Awardee karma', value: fmtNum(p.awardeeKarma ?? 0), sub: 'From awards received' },
- ].map(item => (
- <div key={item.label} className="flex flex-col gap-1">
- <span className="text-small font-medium text-ink-muted">{item.label}</span>
- <span className={cn('font-heading text-2xl font-semibold tracking-[-0.02em] tabular-nums', item.lead ? 'text-brand-text' : 'text-ink')}>{item.value}</span>
- <span className="text-caption text-ink-faint">{item.sub}</span>
- </div>
- ))}
- </div>
- </SurfaceBox>
+ <RedditKarmaSummary profile={profileData} />
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-4">
- <MetricBox icon={<TrendingUp />} label="Posts fetched" value={fmtNum(a.fetchedPosts)} subtitle={`${a.postsLast30Days ?? 0} in the last 30 days`} />
- <MetricBox icon={<Award />} label="Karma from posts" value={fmtNum(a.totalScore)} subtitle={`${fmtNum(a.avgScore)} per post on average`} highlight />
- <MetricBox icon={<MessageSquare />} label="Comments" value={fmtNum(a.totalComments)} subtitle={`${fmtNum(a.avgComments)} per post on average`} />
- <MetricBox icon={<Star />} label="Awards received" value={fmtNum(a.totalAwards ?? 0)} subtitle={`${a.avgAwards ?? 0} per post on average`} />
+ <MetricBox icon={<TrendingUp />} label="Posts fetched" value={fmtNum(analyticsData.fetchedPosts)} subtitle={`${analyticsData.postsLast30Days ?? 0} in the last 30 days`} />
+ <MetricBox icon={<Award />} label="Karma from posts" value={fmtNum(analyticsData.totalScore)} subtitle={`${fmtNum(analyticsData.avgScore)} per post on average`} highlight />
+ <MetricBox icon={<MessageSquare />} label="Comments" value={fmtNum(analyticsData.totalComments)} subtitle={`${fmtNum(analyticsData.avgComments)} per post on average`} />
+ <MetricBox icon={<Star />} label="Awards received" value={fmtNum(analyticsData.totalAwards ?? 0)} subtitle={`${analyticsData.avgAwards ?? 0} per post on average`} />
</div>
- {a.monthlyBreakdown?.length > 0 && (
- <div className="grid grid-cols-1 gap-4 xl:grid-cols-3">
- <ChartPanel title="Karma over time" height={240} className="xl:col-span-2">
- <AreaChart data={a.monthlyBreakdown} margin={{ top: 4, right: 4, left: 0, bottom: 0 }}>
- <defs>
- <linearGradient id="redditGrad" x1="0" y1="0" x2="0" y2="1">
- <stop offset="5%" stopColor={SERIES.primary} stopOpacity={0.2} />
- <stop offset="95%" stopColor={SERIES.primary} stopOpacity={0} />
- </linearGradient>
- </defs>
- <CartesianGrid {...gridProps} vertical={false} />
- <XAxis dataKey="month" {...axisProps} />
- <YAxis {...axisProps} tickFormatter={fmtNum} width={48} />
- <ReTooltip contentStyle={tooltipStyle} cursor={{ stroke: 'var(--line-strong)' }} formatter={(v, n) => [fmtNumFull(v), n === 'score' ? 'Karma' : 'Posts']} />
- <Area type="monotone" dataKey="score" stroke={SERIES.primary} strokeWidth={2} fill="url(#redditGrad)" dot={{ fill: SERIES.primary, r: 3, strokeWidth: 0 }} />
- </AreaChart>
- </ChartPanel>
-
- {mediaTypeData.length > 0 && (
- <ChartPanel title="Post types" height={240}>
- <PieChart>
- <Pie data={mediaTypeData} dataKey="value" nameKey="name" cx="50%" cy="44%" outerRadius={80} innerRadius={48} paddingAngle={2} strokeWidth={0}>
- {mediaTypeData.map(entry => <Cell key={entry.name} fill={entry.color} />)}
- </Pie>
- <ReTooltip contentStyle={tooltipStyle} formatter={v => [fmtNumFull(v), 'Posts']} />
- <Legend iconType="circle" iconSize={8} wrapperStyle={{ ...legendStyle, paddingTop: 8 }} />
- </PieChart>
- </ChartPanel>
- )}
- </div>
+ {analyticsData.monthlyBreakdown?.length > 0 && (
+ <RedditKarmaCharts
+ monthlyBreakdown={analyticsData.monthlyBreakdown}
+ mediaTypeData={mediaTypeDataOf(analyticsData.mediaTypeDistribution, MEDIA_TYPE_LABELS)}
+ />
)}
- <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-3">
- <SurfaceBox title="Posting frequency">
- <StatList rows={[
- { label: 'Last 7 days', value: `${a.postsLast7Days ?? 0} posts` },
- { label: 'Last 30 days', value: `${a.postsLast30Days ?? 0} posts` },
- { label: 'Last 90 days', value: `${a.postsLast90Days ?? 0} posts` },
- { label: 'Per week', value: a.postFrequency?.perWeek ?? 0 },
- { label: 'Per month', value: a.postFrequency?.perMonth ?? 0 },
- ]} />
- </SurfaceBox>
+ <RedditStatPanels analytics={analyticsData} />
- <SurfaceBox title="Karma breakdown">
- <StatList rows={[
- { label: 'Average karma', value: fmtNum(a.avgScore) },
- { label: 'Median karma', value: fmtNum(a.medianScore) },
- { label: 'Best single post', value: fmtNum(a.topPosts?.[0]?.score) },
- { label: 'Average upvote ratio', value: `${a.avgUpvoteRatio ?? 0}%` },
- { label: 'Total comments', value: fmtNum(a.totalComments) },
- { label: 'Average comments', value: fmtNum(a.avgComments) },
- ]} />
- </SurfaceBox>
-
- <SurfaceBox title="Performance indicators">
- <div className="flex flex-col gap-5">
- {[
- { label: 'Virality score', value: a.viralityScore ?? 0, max: Math.max(10, a.viralityScore ?? 0), desc: 'Best post karma against the average. Higher means bigger outlier hits.' },
- { label: 'Consistency', value: a.consistencyScore ?? 0, max: 100, desc: 'How evenly karma spreads across posts. 100 means every post performs alike.' },
- ].map(item => (
- <div key={item.label} className="flex flex-col gap-2">
- <div className="flex items-center justify-between text-sm">
- <span className="font-medium text-ink">{item.label}</span>
- <span className="text-ink-muted tabular-nums">{item.value}</span>
- </div>
- <Progress value={(item.value / item.max) * 100} aria-label={item.label} />
- <p className="text-caption text-ink-faint">{item.desc}</p>
- </div>
- ))}
- </div>
- </SurfaceBox>
- </div>
-
- {a.postsByDayOfWeek?.length > 0 && (
- <div className="grid grid-cols-1 gap-4 xl:grid-cols-2">
- <ChartPanel title="Posts by day of week" subheader={a.bestPostingDay ? `Best day: ${a.bestPostingDay}` : undefined} height={220}>
- <BarChart data={a.postsByDayOfWeek} margin={{ top: 4, right: 4, left: 0, bottom: 0 }}>
- <CartesianGrid {...gridProps} vertical={false} />
- <XAxis dataKey="shortDay" {...axisProps} />
- <YAxis {...axisProps} tickFormatter={fmtNum} width={36} />
- <ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} formatter={(v, n) => [fmtNumFull(v), n === 'avgScore' ? 'Average karma' : 'Posts']} />
- <Bar dataKey="posts" fill={SERIES.neutral} radius={[3, 3, 0, 0]} />
- <Bar dataKey="avgScore" fill={SERIES.primary} radius={[3, 3, 0, 0]} />
- </BarChart>
- </ChartPanel>
+ {analyticsData.postsByDayOfWeek?.length > 0 && <RedditTimingCharts analytics={analyticsData} />}
- <ChartPanel title="Average karma by hour" subheader={a.bestPostingHour ? `Best hour: ${a.bestPostingHour}` : undefined} height={220}>
- <BarChart data={a.postsByHour} margin={{ top: 4, right: 4, left: 0, bottom: 0 }}>
- <CartesianGrid {...gridProps} vertical={false} />
- <XAxis dataKey="hour" tickFormatter={h => `${h}h`} tick={{ ...axisTick, fontSize: 10 }} axisLine={false} tickLine={false} interval={3} />
- <YAxis {...axisProps} tickFormatter={fmtNum} width={36} />
- <ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} formatter={(v, n) => [fmtNumFull(v), n === 'avgScore' ? 'Average karma' : 'Posts']} />
- <Bar dataKey="avgScore" fill={SERIES.warm} radius={[3, 3, 0, 0]} />
- </BarChart>
- </ChartPanel>
- </div>
- )}
+ {analyticsData.subredditBreakdown?.length > 0 && <RedditSubredditTable subreddits={analyticsData.subredditBreakdown} />}
- {a.subredditBreakdown?.length > 0 && (
- <SurfaceBox title="Top subreddits" content={false} className="overflow-hidden">
- <Table>
- <TableHeader>
- <TableRow>
- <TableHead className="w-10 text-right">#</TableHead>
- <TableHead>Subreddit</TableHead>
- <TableHead className="text-right">Posts</TableHead>
- <TableHead className="text-right">Total karma</TableHead>
- <TableHead className="text-right">Average karma</TableHead>
- <TableHead className="text-right">Average comments</TableHead>
- </TableRow>
- </TableHeader>
- <TableBody>
- {a.subredditBreakdown.map((sub, i) => (
- <TableRow key={sub.subreddit}>
- <TableCell className="text-right font-mono text-caption text-ink-faint">{i + 1}</TableCell>
- <TableCell>
- <a href={`https://reddit.com/r/${sub.subreddit}`} target="_blank" rel="noopener noreferrer" className="flex items-center gap-1 text-sm font-medium text-ink hover:underline">
- r/{sub.subreddit}
- <ExternalLink className="size-3 text-ink-faint" />
- </a>
- </TableCell>
- <TableCell className="text-right text-ink-muted">{sub.posts}</TableCell>
- <TableCell className="text-right font-semibold text-ink">{fmtNum(sub.totalScore)}</TableCell>
- <TableCell className="text-right text-ink-muted">{fmtNum(sub.avgScore)}</TableCell>
- <TableCell className="text-right text-ink-muted">{fmtNum(sub.avgComments)}</TableCell>
- </TableRow>
- ))}
- </TableBody>
- </Table>
- </SurfaceBox>
- )}
-
- {a.topPosts?.length > 0 && (
- <SurfaceBox title="Top posts by karma" content={false} className="overflow-hidden">
- <Table>
- <TableHeader>
- <TableRow>
- <TableHead className="w-10 text-right">#</TableHead>
- <TableHead>Post</TableHead>
- <TableHead className="text-right">Karma</TableHead>
- <TableHead className="text-right">Comments</TableHead>
- <TableHead className="text-right"><ColumnHint label="Upvote rate" hint="Share of votes on the post that are upvotes. 96% means 96 of every 100 votes were up." /></TableHead>
- <TableHead className="text-right">Posted</TableHead>
- <TableHead className="w-10"><span className="sr-only">Open</span></TableHead>
- </TableRow>
- </TableHeader>
- <TableBody>
- {a.topPosts.map((post, i) => (
- <TableRow key={post.id}>
- <TableCell className="text-right"><RankNumber rank={i + 1} className="w-auto" /></TableCell>
- <TableCell className="whitespace-normal">
- <div className="max-w-sm">
- <p className="line-clamp-2 text-sm font-medium leading-snug text-ink">{post.title}</p>
- <div className="mt-1 flex items-center gap-1.5">
- <span className="text-caption text-ink-faint">{post.subredditPrefixed}</span>
- {post.flair && <Badge variant="outline">{post.flair}</Badge>}
- </div>
- </div>
- </TableCell>
- <TableCell className="text-right font-semibold text-ink">{fmtNum(post.score)}</TableCell>
- <TableCell className="text-right text-ink-muted">{fmtNum(post.numComments)}</TableCell>
- <TableCell className="text-right text-ink-muted">{Math.round((post.upvoteRatio ?? 0) * 100)}%</TableCell>
- <TableCell className="text-right text-small text-ink-faint">{fmtDate(post.createdAt)}</TableCell>
- <TableCell>
- <Button variant="ghost" size="icon-xs" render={<a href={post.permalink} target="_blank" rel="noopener noreferrer" aria-label={`Open "${post.title}" on Reddit`} />}>
- <ExternalLink />
- </Button>
- </TableCell>
- </TableRow>
- ))}
- </TableBody>
- </Table>
- </SurfaceBox>
- )}
+ {analyticsData.topPosts?.length > 0 && <RedditTopPostsTable posts={analyticsData.topPosts} />}
</div>
);
}
diff --git a/frontend/src/features/analytics/reddit/RedditHeader.jsx b/frontend/src/features/analytics/reddit/RedditHeader.jsx
new file mode 100644
index 0000000..6c57fbd
--- /dev/null
+++ b/frontend/src/features/analytics/reddit/RedditHeader.jsx
@@ -0,0 +1,40 @@
+import { Link } from 'react-router-dom';
+import { FileText, RefreshCw } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import { Badge } from '@/components/ui/badge';
+import PageHeader from '@/components/PageHeader';
+import { AccountAvatar } from '@/components/platform';
+import { cn } from '@/lib/utils';
+import { fmtDate, timeAgo } from '../../../utils/formatters';
+
+export default function RedditHeader({ account, profile, back, refreshing, onRefresh }) {
+ return (
+ <PageHeader
+ back={back}
+ media={<AccountAvatar account={{ ...account, iconUrl: profile.iconUrl || account.iconUrl }} size="xl" showPlatform />}
+ title={`u/${profile.username || account.username}`}
+ description={
+ <span className="flex flex-wrap items-center gap-1.5">
+ {profile.isGold && <Badge variant="warning">Gold</Badge>}
+ {profile.verified && <Badge variant="info">Verified</Badge>}
+ {profile.isMod && <Badge variant="outline">Moderator</Badge>}
+ <span>
+ {profile.createdAt ? `Joined ${fmtDate(profile.createdAt)}. ` : ''}Refreshed {timeAgo(account.lastUpdated).toLowerCase()}.
+ </span>
+ </span>
+ }
+ actions={
+ <>
+ <Button variant="outline" size="sm" render={<Link to={`/reddit-posts/${account.id}`} />}>
+ <FileText data-icon="inline-start" />
+ View posts
+ </Button>
+ <Button variant="outline" size="sm" onClick={onRefresh} disabled={refreshing}>
+ <RefreshCw data-icon="inline-start" className={cn(refreshing && 'animate-spin')} />
+ {refreshing ? 'Refreshing' : 'Refresh'}
+ </Button>
+ </>
+ }
+ />
+ );
+}
diff --git a/frontend/src/features/analytics/reddit/RedditKarmaCharts.jsx b/frontend/src/features/analytics/reddit/RedditKarmaCharts.jsx
new file mode 100644
index 0000000..d39a5c2
--- /dev/null
+++ b/frontend/src/features/analytics/reddit/RedditKarmaCharts.jsx
@@ -0,0 +1,48 @@
+import {
+ XAxis, YAxis, CartesianGrid, Tooltip as ReTooltip, AreaChart, Area, PieChart, Pie, Cell, Legend,
+} from 'recharts';
+import ChartPanel from '@/components/ChartPanel';
+import { SERIES, axisProps, gridProps, legendStyle, tooltipStyle } from '@/lib/chart';
+import { fmtNum, fmtNumFull } from '../../../utils/formatters';
+
+function formatKarmaTooltip(value, name) {
+ return [fmtNumFull(value), name === 'score' ? 'Karma' : 'Posts'];
+}
+
+function formatPostsTooltip(value) {
+ return [fmtNumFull(value), 'Posts'];
+}
+
+export default function RedditKarmaCharts({ monthlyBreakdown, mediaTypeData }) {
+ return (
+ <div className="grid grid-cols-1 gap-4 xl:grid-cols-3">
+ <ChartPanel title="Karma over time" height={240} className="xl:col-span-2">
+ <AreaChart data={monthlyBreakdown} margin={{ top: 4, right: 4, left: 0, bottom: 0 }}>
+ <defs>
+ <linearGradient id="redditGrad" x1="0" y1="0" x2="0" y2="1">
+ <stop offset="5%" stopColor={SERIES.primary} stopOpacity={0.2} />
+ <stop offset="95%" stopColor={SERIES.primary} stopOpacity={0} />
+ </linearGradient>
+ </defs>
+ <CartesianGrid {...gridProps} vertical={false} />
+ <XAxis dataKey="month" {...axisProps} />
+ <YAxis {...axisProps} tickFormatter={fmtNum} width={48} />
+ <ReTooltip contentStyle={tooltipStyle} cursor={{ stroke: 'var(--line-strong)' }} formatter={formatKarmaTooltip} />
+ <Area type="monotone" dataKey="score" stroke={SERIES.primary} strokeWidth={2} fill="url(#redditGrad)" dot={{ fill: SERIES.primary, r: 3, strokeWidth: 0 }} />
+ </AreaChart>
+ </ChartPanel>
+
+ {mediaTypeData.length > 0 && (
+ <ChartPanel title="Post types" height={240}>
+ <PieChart>
+ <Pie data={mediaTypeData} dataKey="value" nameKey="name" cx="50%" cy="44%" outerRadius={80} innerRadius={48} paddingAngle={2} strokeWidth={0}>
+ {mediaTypeData.map(entry => <Cell key={entry.name} fill={entry.color} />)}
+ </Pie>
+ <ReTooltip contentStyle={tooltipStyle} formatter={formatPostsTooltip} />
+ <Legend iconType="circle" iconSize={8} wrapperStyle={{ ...legendStyle, paddingTop: 8 }} />
+ </PieChart>
+ </ChartPanel>
+ )}
+ </div>
+ );
+}
diff --git a/frontend/src/features/analytics/reddit/RedditKarmaSummary.jsx b/frontend/src/features/analytics/reddit/RedditKarmaSummary.jsx
new file mode 100644
index 0000000..b8b6995
--- /dev/null
+++ b/frontend/src/features/analytics/reddit/RedditKarmaSummary.jsx
@@ -0,0 +1,19 @@
+import SurfaceBox from '@/components/SurfaceBox';
+import { cn } from '@/lib/utils';
+import { karmaSummaryOf } from './redditAnalyticsData.js';
+
+export default function RedditKarmaSummary({ profile }) {
+ return (
+ <SurfaceBox title="Karma" subheader="Earned across posts and comments">
+ <div className="grid grid-cols-2 gap-x-6 gap-y-5 sm:grid-cols-4">
+ {karmaSummaryOf(profile).map(item => (
+ <div key={item.label} className="flex flex-col gap-1">
+ <span className="text-small font-medium text-ink-muted">{item.label}</span>
+ <span className={cn('font-heading text-2xl font-semibold tracking-[-0.02em] tabular-nums', item.lead ? 'text-brand-text' : 'text-ink')}>{item.value}</span>
+ <span className="text-caption text-ink-faint">{item.sub}</span>
+ </div>
+ ))}
+ </div>
+ </SurfaceBox>
+ );
+}
diff --git a/frontend/src/features/analytics/reddit/RedditStatPanels.jsx b/frontend/src/features/analytics/reddit/RedditStatPanels.jsx
new file mode 100644
index 0000000..cccdeda
--- /dev/null
+++ b/frontend/src/features/analytics/reddit/RedditStatPanels.jsx
@@ -0,0 +1,45 @@
+import { Progress } from '@/components/ui/progress';
+import SurfaceBox from '@/components/SurfaceBox';
+import { karmaBreakdownRows, performanceIndicators, postingFrequencyRows } from './redditAnalyticsData.js';
+
+function StatList({ rows }) {
+ return (
+ <dl className="flex flex-col divide-y divide-divider">
+ {rows.map(row => (
+ <div key={row.label} className="flex items-center justify-between gap-4 py-2.5 first:pt-0 last:pb-0">
+ <dt className="text-sm text-ink-muted">{row.label}</dt>
+ <dd className="text-sm font-semibold text-ink tabular-nums">{row.value}</dd>
+ </div>
+ ))}
+ </dl>
+ );
+}
+
+export default function RedditStatPanels({ analytics }) {
+ return (
+ <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-3">
+ <SurfaceBox title="Posting frequency">
+ <StatList rows={postingFrequencyRows(analytics)} />
+ </SurfaceBox>
+
+ <SurfaceBox title="Karma breakdown">
+ <StatList rows={karmaBreakdownRows(analytics)} />
+ </SurfaceBox>
+
+ <SurfaceBox title="Performance indicators">
+ <div className="flex flex-col gap-5">
+ {performanceIndicators(analytics).map(item => (
+ <div key={item.label} className="flex flex-col gap-2">
+ <div className="flex items-center justify-between text-sm">
+ <span className="font-medium text-ink">{item.label}</span>
+ <span className="text-ink-muted tabular-nums">{item.value}</span>
+ </div>
+ <Progress value={(item.value / item.max) * 100} aria-label={item.label} />
+ <p className="text-caption text-ink-faint">{item.desc}</p>
+ </div>
+ ))}
+ </div>
+ </SurfaceBox>
+ </div>
+ );
+}
diff --git a/frontend/src/features/analytics/reddit/RedditSubredditTable.jsx b/frontend/src/features/analytics/reddit/RedditSubredditTable.jsx
new file mode 100644
index 0000000..1a1c8a1
--- /dev/null
+++ b/frontend/src/features/analytics/reddit/RedditSubredditTable.jsx
@@ -0,0 +1,40 @@
+import { ExternalLink } from 'lucide-react';
+import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
+import SurfaceBox from '@/components/SurfaceBox';
+import { fmtNum } from '../../../utils/formatters';
+
+export default function RedditSubredditTable({ subreddits }) {
+ return (
+ <SurfaceBox title="Top subreddits" content={false} className="overflow-hidden">
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead className="w-10 text-right">#</TableHead>
+ <TableHead>Subreddit</TableHead>
+ <TableHead className="text-right">Posts</TableHead>
+ <TableHead className="text-right">Total karma</TableHead>
+ <TableHead className="text-right">Average karma</TableHead>
+ <TableHead className="text-right">Average comments</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {subreddits.map((sub, i) => (
+ <TableRow key={sub.subreddit}>
+ <TableCell className="text-right font-mono text-caption text-ink-faint">{i + 1}</TableCell>
+ <TableCell>
+ <a href={`https://reddit.com/r/${sub.subreddit}`} target="_blank" rel="noopener noreferrer" className="flex items-center gap-1 text-sm font-medium text-ink hover:underline">
+ r/{sub.subreddit}
+ <ExternalLink className="size-3 text-ink-faint" />
+ </a>
+ </TableCell>
+ <TableCell className="text-right text-ink-muted">{sub.posts}</TableCell>
+ <TableCell className="text-right font-semibold text-ink">{fmtNum(sub.totalScore)}</TableCell>
+ <TableCell className="text-right text-ink-muted">{fmtNum(sub.avgScore)}</TableCell>
+ <TableCell className="text-right text-ink-muted">{fmtNum(sub.avgComments)}</TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ </SurfaceBox>
+ );
+}
diff --git a/frontend/src/features/analytics/reddit/RedditTimingCharts.jsx b/frontend/src/features/analytics/reddit/RedditTimingCharts.jsx
new file mode 100644
index 0000000..17841a6
--- /dev/null
+++ b/frontend/src/features/analytics/reddit/RedditTimingCharts.jsx
@@ -0,0 +1,43 @@
+import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip as ReTooltip } from 'recharts';
+import ChartPanel from '@/components/ChartPanel';
+import { SERIES, axisProps, axisTick, gridProps, tooltipCursor, tooltipStyle } from '@/lib/chart';
+import { fmtNum, fmtNumFull } from '../../../utils/formatters';
+
+function formatTimingTooltip(value, name) {
+ return [fmtNumFull(value), name === 'avgScore' ? 'Average karma' : 'Posts'];
+}
+
+function formatHour(hour) {
+ return `${hour}h`;
+}
+
+function bestLabel(prefix, value) {
+ return value ? `${prefix}: ${value}` : undefined;
+}
+
+export default function RedditTimingCharts({ analytics }) {
+ return (
+ <div className="grid grid-cols-1 gap-4 xl:grid-cols-2">
+ <ChartPanel title="Posts by day of week" subheader={bestLabel('Best day', analytics.bestPostingDay)} height={220}>
+ <BarChart data={analytics.postsByDayOfWeek} margin={{ top: 4, right: 4, left: 0, bottom: 0 }}>
+ <CartesianGrid {...gridProps} vertical={false} />
+ <XAxis dataKey="shortDay" {...axisProps} />
+ <YAxis {...axisProps} tickFormatter={fmtNum} width={36} />
+ <ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} formatter={formatTimingTooltip} />
+ <Bar dataKey="posts" fill={SERIES.neutral} radius={[3, 3, 0, 0]} />
+ <Bar dataKey="avgScore" fill={SERIES.primary} radius={[3, 3, 0, 0]} />
+ </BarChart>
+ </ChartPanel>
+
+ <ChartPanel title="Average karma by hour" subheader={bestLabel('Best hour', analytics.bestPostingHour)} height={220}>
+ <BarChart data={analytics.postsByHour} margin={{ top: 4, right: 4, left: 0, bottom: 0 }}>
+ <CartesianGrid {...gridProps} vertical={false} />
+ <XAxis dataKey="hour" tickFormatter={formatHour} tick={{ ...axisTick, fontSize: 10 }} axisLine={false} tickLine={false} interval={3} />
+ <YAxis {...axisProps} tickFormatter={fmtNum} width={36} />
+ <ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} formatter={formatTimingTooltip} />
+ <Bar dataKey="avgScore" fill={SERIES.warm} radius={[3, 3, 0, 0]} />
+ </BarChart>
+ </ChartPanel>
+ </div>
+ );
+}
diff --git a/frontend/src/features/analytics/reddit/RedditTopPostsTable.jsx b/frontend/src/features/analytics/reddit/RedditTopPostsTable.jsx
new file mode 100644
index 0000000..cc4b400
--- /dev/null
+++ b/frontend/src/features/analytics/reddit/RedditTopPostsTable.jsx
@@ -0,0 +1,53 @@
+import { ExternalLink } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import { Badge } from '@/components/ui/badge';
+import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
+import SurfaceBox from '@/components/SurfaceBox';
+import ColumnHint from '@/components/ColumnHint';
+import { RankNumber } from '@/components/ListRow';
+import { fmtDate, fmtNum } from '../../../utils/formatters';
+
+export default function RedditTopPostsTable({ posts }) {
+ return (
+ <SurfaceBox title="Top posts by karma" content={false} className="overflow-hidden">
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead className="w-10 text-right">#</TableHead>
+ <TableHead>Post</TableHead>
+ <TableHead className="text-right">Karma</TableHead>
+ <TableHead className="text-right">Comments</TableHead>
+ <TableHead className="text-right"><ColumnHint label="Upvote rate" hint="Share of votes on the post that are upvotes. 96% means 96 of every 100 votes were up." /></TableHead>
+ <TableHead className="text-right">Posted</TableHead>
+ <TableHead className="w-10"><span className="sr-only">Open</span></TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {posts.map((post, i) => (
+ <TableRow key={post.id}>
+ <TableCell className="text-right"><RankNumber rank={i + 1} className="w-auto" /></TableCell>
+ <TableCell className="whitespace-normal">
+ <div className="max-w-sm">
+ <p className="line-clamp-2 text-sm font-medium leading-snug text-ink">{post.title}</p>
+ <div className="mt-1 flex items-center gap-1.5">
+ <span className="text-caption text-ink-faint">{post.subredditPrefixed}</span>
+ {post.flair && <Badge variant="outline">{post.flair}</Badge>}
+ </div>
+ </div>
+ </TableCell>
+ <TableCell className="text-right font-semibold text-ink">{fmtNum(post.score)}</TableCell>
+ <TableCell className="text-right text-ink-muted">{fmtNum(post.numComments)}</TableCell>
+ <TableCell className="text-right text-ink-muted">{Math.round((post.upvoteRatio ?? 0) * 100)}%</TableCell>
+ <TableCell className="text-right text-small text-ink-faint">{fmtDate(post.createdAt)}</TableCell>
+ <TableCell>
+ <Button variant="ghost" size="icon-xs" render={<a href={post.permalink} target="_blank" rel="noopener noreferrer" aria-label={`Open "${post.title}" on Reddit`} />}>
+ <ExternalLink />
+ </Button>
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ </SurfaceBox>
+ );
+}
diff --git a/frontend/src/features/analytics/reddit/redditAnalyticsData.js b/frontend/src/features/analytics/reddit/redditAnalyticsData.js
new file mode 100644
index 0000000..b0d8040
--- /dev/null
+++ b/frontend/src/features/analytics/reddit/redditAnalyticsData.js
@@ -0,0 +1,54 @@
+// chart rows and stat lists for Reddit analytics; no JSX or path aliases so node --test can import it
+
+import { seriesAt } from '../../../lib/chart.js';
+import { fmtNum, fmtNumFull } from '../../../utils/formatters.js';
+
+const MEDIA_TYPE_ORDER = ['text', 'image', 'video', 'link'];
+
+// labels come in as an argument because redditPostUtils.js imports through a path alias
+export function mediaTypeDataOf(distribution, labels) {
+ if (!distribution) return [];
+ return Object.entries(distribution).map(([key, value]) => ({
+ name: labels[key] || key,
+ value,
+ color: seriesAt(Math.max(0, MEDIA_TYPE_ORDER.indexOf(key))),
+ }));
+}
+
+export function karmaSummaryOf(profile) {
+ return [
+ { label: 'Total karma', value: fmtNum(profile.totalKarma), sub: fmtNumFull(profile.totalKarma), lead: true },
+ { label: 'Post karma', value: fmtNum(profile.postKarma), sub: 'From submitted posts' },
+ { label: 'Comment karma', value: fmtNum(profile.commentKarma), sub: 'From comments' },
+ { label: 'Awardee karma', value: fmtNum(profile.awardeeKarma ?? 0), sub: 'From awards received' },
+ ];
+}
+
+export function postingFrequencyRows(analytics) {
+ return [
+ { label: 'Last 7 days', value: `${analytics.postsLast7Days ?? 0} posts` },
+ { label: 'Last 30 days', value: `${analytics.postsLast30Days ?? 0} posts` },
+ { label: 'Last 90 days', value: `${analytics.postsLast90Days ?? 0} posts` },
+ { label: 'Per week', value: analytics.postFrequency?.perWeek ?? 0 },
+ { label: 'Per month', value: analytics.postFrequency?.perMonth ?? 0 },
+ ];
+}
+
+export function karmaBreakdownRows(analytics) {
+ return [
+ { label: 'Average karma', value: fmtNum(analytics.avgScore) },
+ { label: 'Median karma', value: fmtNum(analytics.medianScore) },
+ { label: 'Best single post', value: fmtNum(analytics.topPosts?.[0]?.score) },
+ { label: 'Average upvote ratio', value: `${analytics.avgUpvoteRatio ?? 0}%` },
+ { label: 'Total comments', value: fmtNum(analytics.totalComments) },
+ { label: 'Average comments', value: fmtNum(analytics.avgComments) },
+ ];
+}
+
+export function performanceIndicators(analytics) {
+ const virality = analytics.viralityScore ?? 0;
+ return [
+ { label: 'Virality score', value: virality, max: Math.max(10, virality), desc: 'Best post karma against the average. Higher means bigger outlier hits.' },
+ { label: 'Consistency', value: analytics.consistencyScore ?? 0, max: 100, desc: 'How evenly karma spreads across posts. 100 means every post performs alike.' },
+ ];
+}
diff --git a/frontend/src/features/analytics/reddit/redditAnalyticsData.test.js b/frontend/src/features/analytics/reddit/redditAnalyticsData.test.js
new file mode 100644
index 0000000..31d8f99
--- /dev/null
+++ b/frontend/src/features/analytics/reddit/redditAnalyticsData.test.js
@@ -0,0 +1,36 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import {
+ mediaTypeDataOf, karmaSummaryOf, postingFrequencyRows, karmaBreakdownRows, performanceIndicators,
+} from './redditAnalyticsData.js';
+
+const labels = { text: 'Text', image: 'Image', video: 'Video', link: 'Link' };
+
+test('media types use their label and a fixed colour per type', () => {
+ assert.deepEqual(mediaTypeDataOf({ image: 4, gallery: 1 }, labels), [
+ { name: 'Image', value: 4, color: 'var(--chart-2)' },
+ { name: 'gallery', value: 1, color: 'var(--chart-1)' },
+ ]);
+ assert.deepEqual(mediaTypeDataOf(undefined, labels), []);
+});
+
+test('karma summary leads with total karma', () => {
+ const items = karmaSummaryOf({ totalKarma: 1500, postKarma: 1000, commentKarma: 500 });
+ assert.deepEqual(items.map(item => item.value), ['1.5K', '1.0K', '500', '0']);
+ assert.equal(items[0].sub, '1,500');
+ assert.equal(items[0].lead, true);
+});
+
+test('stat lists fall back to zero', () => {
+ assert.deepEqual(postingFrequencyRows({}).map(row => row.value), ['0 posts', '0 posts', '0 posts', 0, 0]);
+ const breakdown = karmaBreakdownRows({ avgScore: 12, topPosts: [{ score: 2400 }], avgUpvoteRatio: 93 });
+ assert.equal(breakdown[0].value, '12');
+ assert.equal(breakdown[2].value, '2.4K');
+ assert.equal(breakdown[3].value, '93%');
+});
+
+test('virality scale grows past ten', () => {
+ assert.equal(performanceIndicators({}).at(0).max, 10);
+ assert.equal(performanceIndicators({ viralityScore: 25 }).at(0).max, 25);
+ assert.equal(performanceIndicators({ consistencyScore: 80 }).at(1).value, 80);
+});
diff --git a/frontend/src/hooks/use-account-analytics.js b/frontend/src/hooks/use-account-analytics.js
new file mode 100644
index 0000000..a0f7ff1
--- /dev/null
+++ b/frontend/src/hooks/use-account-analytics.js
@@ -0,0 +1,45 @@
+import { useCallback, useEffect, useState } from 'react';
+import { useAppContext } from '../context/AppContext';
+import { api } from '../services/api';
+
+// pass a stable api method such as api.getIGAnalytics so the load runs once per account
+export function useAccountAnalytics(account, fetchAnalytics, label) {
+ const { showToast } = useAppContext();
+ const [loading, setLoading] = useState(true);
+ const [profile, setProfile] = useState(null);
+ const [analytics, setAnalytics] = useState(null);
+ const [refreshing, setRefreshing] = useState(false);
+
+ // keyed on the account id so a background account refresh does not refetch analytics
+ const accountId = account?.id;
+ const loadAnalytics = useCallback(async () => {
+ if (!accountId) return;
+ setLoading(true);
+ try {
+ const data = await fetchAnalytics(accountId);
+ setProfile(data.profile);
+ setAnalytics(data.analytics);
+ } catch (err) {
+ showToast(`Couldn't load ${label} analytics. ${err.message}`, 'error');
+ } finally {
+ setLoading(false);
+ }
+ }, [accountId, fetchAnalytics, label, showToast]);
+
+ useEffect(() => { loadAnalytics(); }, [loadAnalytics]);
+
+ const handleRefresh = async () => {
+ setRefreshing(true);
+ try {
+ await api.refreshAccount(accountId);
+ await loadAnalytics();
+ showToast(`${label} account refreshed`);
+ } catch (err) {
+ showToast(`Refresh failed. ${err.message}`, 'error');
+ } finally {
+ setRefreshing(false);
+ }
+ };
+
+ return { loading, profile, analytics, refreshing, handleRefresh };
+}
diff --git a/frontend/src/utils/instagramContent.js b/frontend/src/utils/instagramContent.js
index 010d26d..f2371d7 100644
--- a/frontend/src/utils/instagramContent.js
+++ b/frontend/src/utils/instagramContent.js
@@ -17,3 +17,9 @@ export function igContentTypeMeta(type) {
export function fmtIGViews(views) {
return typeof views === 'number' ? fmtNum(views) : '-';
}
+
+// image posts can lack a thumbnail url, so they fall back to the image itself
+export function igThumbnail(item) {
+ if (item.contentType === 'post') return item.thumbnailUrl || item.mediaUrl;
+ return item.thumbnailUrl;
+}
diff --git a/frontend/src/utils/instagramContent.test.js b/frontend/src/utils/instagramContent.test.js
new file mode 100644
index 0000000..1bddd8a
--- /dev/null
+++ b/frontend/src/utils/instagramContent.test.js
@@ -0,0 +1,13 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { igThumbnail } from './instagramContent.js';
+
+test('image posts fall back to the media url', () => {
+ assert.equal(igThumbnail({ contentType: 'post', mediaUrl: 'image.jpg' }), 'image.jpg');
+ assert.equal(igThumbnail({ contentType: 'post', thumbnailUrl: 'thumb.jpg', mediaUrl: 'image.jpg' }), 'thumb.jpg');
+});
+
+test('reels and videos only use their thumbnail', () => {
+ assert.equal(igThumbnail({ contentType: 'reel', mediaUrl: 'video.mp4' }), undefined);
+ assert.equal(igThumbnail({ contentType: 'video', thumbnailUrl: 'cover.jpg', mediaUrl: 'video.mp4' }), 'cover.jpg');
+});