Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.
feat(analytics): rename Reddit score to karma, replace lists with area charts
spacesdrive8d2850eecbb3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d815d75..5a9eeaa 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,40 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).### Changed+**Reddit score renamed to karma across the UI**+- Every user-facing "score" label for a Reddit post now reads "karma", matching the vocabulary Reddit shows its own users+- `RedditAnalytics.jsx`: "Total Score" to "Total Karma", "Score Over Time" to "Karma Over Time", "Score Breakdown" to "Karma Breakdown", "Top Posts by Score" to "Top Posts by Karma", table headers and tooltips updated+- `RedditPosts.jsx`, `RedditPostsAll.jsx`: sort options and table headers now read "Karma"; "Combined Score" to "Combined Karma"+- `TrackedContent.jsx`: "Likes / Score" to "Likes / Karma" in the sort select and table header+- `TrackedCategory.jsx`: "Reddit Score" to "Reddit Karma", "Net Upvotes" to "Post Karma", "Avg Net Upvotes" to "Avg Karma per Post"+- `Overview.jsx`: `categoryStats.rdScore` renamed to `rdKarma`, `trackedStats.rdScore` to `rdKarma`, `cacheTotals.rdScore` to `rdKarma`; chart tooltip now reads "Views + Karma" and the legend "Category (views + karma)"+- Backend field names are unchanged; Reddit's API still returns `score` and it is read as-is+- "Virality Score" and "Consistency Score" keep the word "score" - they are computed indices, not karma++**Overview metric totals corrected**+- Tracked Reddit post karma moved out of Total Audience into Total Likes; a monitored post is content, not owned audience+- Total Comments and Total Likes now sum the analytics cache and tracked content instead of preferring one over the other; tracked items are third-party URLs and never overlap with connected-account content+- Reddit Karma stat now shows account karma plus tracked post karma with both parts in the subtitle++**Overview charts replaced with area charts**+- Audience Share pie chart removed; Audience Comparison now spans the full width+- Comments tab: "Tracked Content by Comments" table replaced with two area charts - "Comments by Tracked Content" and "Comments by Category" - plus a "Comments per Content" stat and per-platform comment share percentages+- Likes tab: "Reddit Accounts by Karma" and "Tracked YouTube by Likes" lists replaced with two area charts - "Karma by Reddit Account" and "Engagement by Tracked Content" - plus an Instagram Likes stat and per-platform like share percentages+- `components/MetricAreaChart.jsx` added: shared single-series area chart with project axis, grid, gradient, and tooltip styling; generates a unique gradient id per instance via `useId()`++**Tracked Category page**+- Horizontal bar charts replaced with area charts for both the YouTube and Reddit sections+- Duplicate value display fixed: the full number below the abbreviated one is now only rendered when `fmtNum` actually abbreviated it (values of 1000 and above)+- Stat card labels now name the metric precisely: "Total Items" to "Total Content", "Total Views" to "YouTube Views" and "Video Views", "Total Likes" to "Video Likes", "Total Comments" to "Video Comments" and "Post Comments"+- Empty state rebuilt on the shadcn `Empty` component++**Sidebar**+- Categories section added below Accounts, listing every tracked-content category with a link to its analytics page++### Removed++- `features/analytics/reddit/RedditTracked.jsx` deleted; superseded by `features/analytics/tracked/TrackedContent.jsx` and unreferenced since the Tracked Content rename+**Tracked Content (expanded from Tracked Reddit Posts)**- Renamed feature from "Tracked Posts" / "Tracked Reddit Posts" to "Tracked Content" throughout the UI, routing, and API- Route changed from `/reddit-tracked` to `/tracked-content` (old route redirects to new)diff --git a/docs/architecture/data-flows/ANALYTICS.md b/docs/architecture/data-flows/ANALYTICS.mdindex 4fda2a8..518d41c 100644--- a/docs/architecture/data-flows/ANALYTICS.md+++ b/docs/architecture/data-flows/ANALYTICS.md@@ -211,10 +211,35 @@ User navigates to /▼Overview.jsx uses accounts from AppContext-> Combined totals computed from account.subscriberCount, viewCount, etc.- -> api.getComparison() -> GET /api/comparison- -> returns all accounts sorted by view count, subscriber count+ -> api.getOverview() -> GET /api/overview+ -> returns { tracked: [...], analyticsCache: { [accountId]: {...} } }```-The Overview doesn't fetch fresh analytics - it uses the cached account metadata (subscriber counts, view counts) already in `AppContext.accounts`. Deep per-account analytics (video lists, engagement rates) are only fetched when the user navigates to a specific account page.+The Overview does not fetch fresh per-account analytics. It combines account metadata already+in `AppContext.accounts` with whatever each account's Redis analytics cache holds. When any+account's cache is cold the backend fires a background warm-up and returns `cacheWarmed: false`,+and the page re-fetches once after 6 seconds.-Reddit accounts are excluded from the audience totals, audience comparison chart, and audience share pie chart. Karma is not equivalent to subscribers or followers - it is an engagement/reputation metric. Reddit accounts get their own karma summary card in the Overview showing totalKarma, postKarma, and commentKarma. The audience charts and leaderboard tables only include YouTube and Instagram accounts.+### Metric definitions++| Metric | Formula |+|---|---|+| Total Audience | YouTube subscribers + Instagram followers + Reddit account karma |+| Total Views | YouTube channel view counts |+| Total Content | YouTube videos + Instagram posts + Reddit account posts (cache) + tracked items |+| Total Comments | cache comments (YouTube + Instagram + Reddit) + tracked item comments |+| Total Likes | Reddit karma (account + tracked) + YouTube likes (cache + tracked) + Instagram likes |++Tracked items are third-party URLs the user monitors, never their own connected-account+content, so cache totals and tracked totals are disjoint and are summed rather than+one taking precedence over the other.++Tracked Reddit post karma counts toward Total Likes, not Total Audience - a monitored post is+content, not an audience the user owns. Connected-account karma does count toward Total+Audience as that account's reputation.++### Naming++Reddit's API returns a post's net upvotes as `score`. Every aggregate the frontend derives from+it is named and labelled **karma**. The word "score" is reserved for the computed Virality Score+and Consistency Score indices, which are unrelated to karma.diff --git a/docs/architecture/frontend/FEATURES.md b/docs/architecture/frontend/FEATURES.mdindex bf41da1..3f6d8fe 100644--- a/docs/architecture/frontend/FEATURES.md+++ b/docs/architecture/frontend/FEATURES.md@@ -4,6 +4,9 @@```frontend/src/+├── components/+│ ├── MainCard.jsx <- Card wrapper with optional title/subheader/separator+│ └── MetricAreaChart.jsx <- Shared Recharts area chart for single-metric comparisons├── features/│ ├── analytics/│ │ ├── channel/@@ -12,11 +15,13 @@ frontend/src/│ │ │ └── InstagramAnalytics.jsx <- Instagram account analytics│ │ ├── overview/│ │ │ └── Overview.jsx <- Cross-platform aggregate dashboard-│ │ └── reddit/-│ │ ├── RedditAnalytics.jsx <- Reddit account analytics (karma, scores, subreddits)-│ │ ├── RedditPosts.jsx <- Per-account post explorer-│ │ ├── RedditPostsAll.jsx <- Global post explorer (all Reddit accounts)-│ │ └── RedditTracked.jsx <- Tracked post monitor (URL-based, live score/comments)+│ │ ├── reddit/+│ │ │ ├── RedditAnalytics.jsx <- Reddit account analytics (karma, subreddits)+│ │ │ ├── RedditPosts.jsx <- Per-account post explorer+│ │ │ └── RedditPostsAll.jsx <- Global post explorer (all Reddit accounts)+│ │ └── tracked/+│ │ ├── TrackedContent.jsx <- Tracked Reddit posts and YouTube videos+│ │ └── TrackedCategory.jsx <- Per-category analytics for tracked content│ ├── accounts/│ │ └── AccountManager.jsx <- Add/remove connected accounts│ ├── publishing/@@ -29,6 +34,34 @@ frontend/src/│ └── ReelsExplorer.jsx <- Instagram Reels-filtered view```+## Metric Naming++Reddit exposes a post's net upvotes as `score` in its JSON API. In the UI this is always+labelled **karma**, never "score", so it matches the vocabulary Reddit shows its own users.+The raw `score` field name is kept when reading API responses; every aggregate derived from+it is named `karma` (`rdKarma`, `avgKarma`, `redditKarma`).++"Virality Score" and "Consistency Score" are separate computed indices, not karma, and keep+the word "score".++## Shared Chart Component++`components/MetricAreaChart.jsx` renders a single-series area chart with the project's axis,+grid, gradient, and tooltip styling. Use it instead of hand-rolling a Recharts `AreaChart`:++```jsx+<MetricAreaChart+ data={[{ name: 'Item', karma: 42 }]}+ dataKey="karma"+ label="Karma"+ color="#f97316"+ emptyMessage="Track content to compare karma"+/>+```++Each instance generates its own gradient id via `useId()`, so multiple charts on one page+never collide.+## Feature Conventions### One directory per feature domain@@ -72,7 +105,7 @@ Each page manages its own loading/data/error state. Pages do not write to `AppCo| Feature | Path | Description ||---|---|---|-| Overview | `/` | Aggregate KPIs across all connected accounts (YouTube, Instagram, Reddit) |+| Overview | `/` | Aggregate KPIs across all connected accounts (YouTube, Instagram, Reddit); six metric tabs, each with area charts || Accounts | `/accounts` | Connect/disconnect accounts (YouTube, Instagram, Reddit) || Channel Analytics | `/channel/:id` | YouTube analytics for one channel || Instagram Analytics | `/instagram/:id` | Instagram analytics for one account |diff --git a/frontend/src/components/MetricAreaChart.jsx b/frontend/src/components/MetricAreaChart.jsxnew file mode 100644index 0000000..f7ef4c0--- /dev/null+++ b/frontend/src/components/MetricAreaChart.jsx@@ -0,0 +1,64 @@+import React, { useId } from 'react';+import {+ AreaChart, Area, XAxis, YAxis, CartesianGrid,+ Tooltip as ReTooltip, ResponsiveContainer,+} from 'recharts';+import { fmtNum, fmtNumFull } from '../utils/formatters';++export default function MetricAreaChart({+ data,+ dataKey,+ label,+ color = 'var(--primary)',+ height = 240,+ emptyMessage = 'No data to display',+}) {+ // useId keeps each instance's gradient unique; colons are invalid inside a url() reference+ const gradientId = `metric-area-${useId().replace(/:/g, '')}`;++ if (!data || data.length === 0) {+ return <p className="text-sm text-muted-foreground py-8 text-center">{emptyMessage}</p>;+ }++ return (+ <ResponsiveContainer width="100%" height={height} debounce={200}>+ <AreaChart data={data} margin={{ top: 8, right: 8, left: 0, bottom: 0 }}>+ <defs>+ <linearGradient id={gradientId} x1="0" y1="0" x2="0" y2="1">+ <stop offset="5%" stopColor={color} stopOpacity={0.28} />+ <stop offset="95%" stopColor={color} stopOpacity={0} />+ </linearGradient>+ </defs>+ <CartesianGrid strokeDasharray="3 3" stroke="var(--border)" vertical={false} />+ <XAxis+ dataKey="name"+ tick={{ fill: 'var(--muted-foreground)', fontSize: 11 }}+ axisLine={false}+ tickLine={false}+ interval="preserveStartEnd"+ />+ <YAxis+ tick={{ fill: 'var(--muted-foreground)', fontSize: 11 }}+ tickFormatter={fmtNum}+ axisLine={false}+ tickLine={false}+ width={48}+ allowDecimals={false}+ />+ <ReTooltip+ contentStyle={{ background: 'var(--card)', border: '1px solid var(--border)', borderRadius: 8, fontSize: 12 }}+ formatter={(v) => [fmtNumFull(v), label]}+ />+ <Area+ type="monotone"+ dataKey={dataKey}+ stroke={color}+ strokeWidth={2}+ fill={`url(#${gradientId})`}+ dot={{ r: 3, fill: color, stroke: 'var(--card)', strokeWidth: 2 }}+ activeDot={{ r: 6 }}+ />+ </AreaChart>+ </ResponsiveContainer>+ );+}diff --git a/frontend/src/features/analytics/overview/Overview.jsx b/frontend/src/features/analytics/overview/Overview.jsxindex 658092a..6502206 100644--- a/frontend/src/features/analytics/overview/Overview.jsx+++ b/frontend/src/features/analytics/overview/Overview.jsx@@ -4,21 +4,24 @@ import { Button } from '@/components/ui/button';import { Badge } from '@/components/ui/badge';import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';import { Progress } from '@/components/ui/progress';-import { Skeleton } from '@/components/ui/skeleton';import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';+import {+ Empty, EmptyHeader, EmptyMedia, EmptyTitle, EmptyDescription, EmptyContent,+} from '@/components/ui/empty';import {AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip as ReTooltip,- ResponsiveContainer, PieChart, Pie, Cell, Legend,+ ResponsiveContainer,} from 'recharts';import StatCard from '../../../components/ui/StatCard';import MainCard from '../../../components/MainCard';+import MetricAreaChart from '../../../components/MetricAreaChart';import { useAppContext } from '../../../context/AppContext';import { api } from '../../../services/api';-import { fmtNum, fmtNumFull, timeAgo } from '../../../utils/formatters';+import { fmtNum, fmtNumFull, fmtPercent, timeAgo } from '../../../utils/formatters';import {- RefreshCw, Users, VideoIcon, ExternalLink,+ RefreshCw, Users, VideoIcon, ExternalLink, Camera, BarChart2,Tag, ThumbsUp, MessageSquare, CirclePlay, Flame, BookmarkCheck,} from 'lucide-react';@@ -29,11 +32,6 @@ const PLATFORM_COLORS = {category: '#a855f7',};-const CHART_COLORS = [- '#ef4444', '#ec4899', '#f97316', '#a855f7',- '#06b6d4', '#22c55e', '#6366f1', '#eab308',-];-function PlatformBadge({ platform }) {const map = {youtube: 'border-red-200 bg-red-50 text-red-700 dark:border-red-900 dark:bg-red-950 dark:text-red-400',@@ -81,9 +79,11 @@ export default function Overview() {return () => clearTimeout(timer);}, [isSyncing]);- const loading = accountsLoading || overviewLoading;- const trackedContent = overviewData.tracked ?? [];- const analyticsCache = overviewData.analyticsCache ?? {};+ const loading = accountsLoading || overviewLoading;++ // Memoized so the ?? fallbacks keep a stable identity and the derived useMemos below actually cache+ const trackedContent = useMemo(() => overviewData.tracked ?? [], [overviewData.tracked]);+ const analyticsCache = useMemo(() => overviewData.analyticsCache ?? {}, [overviewData.analyticsCache]);const ytAccounts = accounts.filter(a => a.platform !== 'instagram' && a.platform !== 'reddit');const igAccounts = accounts.filter(a => a.platform === 'instagram');@@ -112,7 +112,7 @@ export default function Overview() {// Per-account analytics from Redis cache (populated when user visits individual analytics pages)const cacheTotals = useMemo(() => {- const result = { ytLikes: 0, ytComments: 0, igLikes: 0, igComments: 0, rdPosts: 0, rdScore: 0, rdComments: 0 };+ const result = { ytLikes: 0, ytComments: 0, igLikes: 0, igComments: 0, rdPosts: 0, rdKarma: 0, rdComments: 0 };accounts.forEach(a => {const c = analyticsCache[a.id];if (!c) return;@@ -124,14 +124,14 @@ export default function Overview() {result.igComments += c.totalComments ?? 0;} else if (a.platform === 'reddit') {result.rdPosts += c.fetchedPosts ?? 0;- result.rdScore += c.totalScore ?? 0;+ result.rdKarma += c.totalScore ?? 0;result.rdComments += c.totalComments ?? 0;}});return result;}, [accounts, analyticsCache]);- // Tracked content aggregates+ // Tracked content aggregates. Reddit post score is karma, so it rolls into karma totals.const trackedStats = useMemo(() => {const ytItems = trackedContent.filter(p => p.contentType === 'youtube');const rdItems = trackedContent.filter(p => (p.contentType || 'reddit') === 'reddit');@@ -139,29 +139,43 @@ export default function Overview() {total: trackedContent.length,ytItems,rdItems,- ytLikes: ytItems.reduce((s, p) => s + (p.likeCount ?? 0), 0),+ ytLikes: ytItems.reduce((s, p) => s + (p.likeCount ?? 0), 0),ytComments: ytItems.reduce((s, p) => s + (p.commentCount ?? 0), 0),- rdScore: rdItems.reduce((s, p) => s + (p.score ?? 0), 0),- rdComments: rdItems.reduce((s, p) => s + (p.numComments ?? 0), 0),+ rdKarma: rdItems.reduce((s, p) => s + (p.score ?? 0), 0),+ rdComments: rdItems.reduce((s, p) => s + (p.numComments ?? 0), 0),};}, [trackedContent]);// ── Metric totals ──────────────────────────────────────────────────────────────- // Total Audience = subs + followers + karma + tracked Reddit scores- const totalAudience = totals.subscribers + totals.followers + totals.karma + trackedStats.rdScore;+ // Total Audience = subs + followers + account karma. Tracked posts are content, not audience.+ const totalAudience = totals.subscribers + totals.followers + totals.karma;// Total Content = YT videos + IG posts + Reddit account posts (from cache) + tracked itemsconst totalContent = totals.videos + totals.posts + cacheTotals.rdPosts + trackedStats.total;- // Total Comments: prefer cache (complete) over tracked subset to avoid double-counting- const ytComments = cacheTotals.ytComments > 0 ? cacheTotals.ytComments : trackedStats.ytComments;- const rdComments = cacheTotals.rdComments > 0 ? cacheTotals.rdComments : trackedStats.rdComments;+ // Tracked items are third-party URLs the user monitors, never their own account content,+ // so cache totals and tracked totals are disjoint and sum without double-counting.+ const ytComments = cacheTotals.ytComments + trackedStats.ytComments;+ const rdComments = cacheTotals.rdComments + trackedStats.rdComments;const totalComments = ytComments + cacheTotals.igComments + rdComments;- // Total Likes: prefer cache for YouTube; include IG; Reddit postKarma covers account posts- const ytLikes = cacheTotals.ytLikes > 0 ? cacheTotals.ytLikes : trackedStats.ytLikes;- const totalLikes = totals.postKarma + ytLikes + cacheTotals.igLikes;+ // Reddit karma = account post karma + tracked post karma+ const redditKarma = totals.postKarma + trackedStats.rdKarma;+ const ytLikes = cacheTotals.ytLikes + trackedStats.ytLikes;+ const totalLikes = redditKarma + ytLikes + cacheTotals.igLikes;++ const avgCommentsPerContent = totalContent > 0 ? Math.round(totalComments / totalContent) : 0;++ const commentShare = {+ youtube: totalComments > 0 ? (ytComments / totalComments) * 100 : 0,+ reddit: totalComments > 0 ? (rdComments / totalComments) * 100 : 0,+ };++ const likeShare = {+ youtube: totalLikes > 0 ? (ytLikes / totalLikes) * 100 : 0,+ instagram: totalLikes > 0 ? (cacheTotals.igLikes / totalLikes) * 100 : 0,+ };// ── Category stats for tracked content ────────────────────────────────────────const categoryStats = useMemo(() => {@@ -174,7 +188,7 @@ export default function Overview() {category: p.category,count: 0, ytCount: 0, rdCount: 0,ytViews: 0, ytLikes: 0, ytComments: 0,- rdScore: 0, rdComments: 0,+ rdKarma: 0, rdComments: 0,};}const c = map[p.category];@@ -186,12 +200,12 @@ export default function Overview() {c.ytComments += p.commentCount ?? 0;} else {c.rdCount++;- c.rdScore += p.score ?? 0;+ c.rdKarma += p.score ?? 0;c.rdComments += p.numComments ?? 0;}});return Object.values(map).sort((a, b) =>- (b.rdScore + b.ytViews) - (a.rdScore + a.ytViews)+ (b.rdKarma + b.ytViews) - (a.rdKarma + a.ytViews));}, [trackedContent]);@@ -230,26 +244,47 @@ export default function Overview() {})),...categoryStats.map(c => ({name: c.category.slice(0, 12) + (c.category.length > 12 ? '…' : ''),- value: c.rdScore + c.ytViews,+ value: c.rdKarma + c.ytViews,type: 'category',})),], [ytAccounts, igAccounts, redditAccounts, categoryStats]);- const pieData = useMemo(() => {- const entries = [- ...accounts.map((a, i) => ({- name: (a.title || a.username || '?').slice(0, 14),- value: audienceMetric(a),- color: CHART_COLORS[i % CHART_COLORS.length],- })),- ...categoryStats.map((c, i) => ({- name: c.category.slice(0, 14),- value: c.rdScore + c.ytViews,- color: CHART_COLORS[(accounts.length + i) % CHART_COLORS.length],- })),- ].filter(e => e.value > 0);- return entries;- }, [accounts, categoryStats]);+ // ── Comment and engagement chart data ─────────────────────────────────────────+ const commentByContentData = useMemo(() =>+ trackedContent+ .map(p => ({+ name: (p.title || p.label || p.url || '').slice(0, 16),+ comments: p.contentType === 'youtube' ? (p.commentCount ?? 0) : (p.numComments ?? 0),+ }))+ .sort((a, b) => b.comments - a.comments)+ .slice(0, 12),+ [trackedContent]+ );++ const commentByCategoryData = useMemo(() =>+ categoryStats+ .map(c => ({ name: c.category.slice(0, 16), comments: c.ytComments + c.rdComments }))+ .sort((a, b) => b.comments - a.comments),+ [categoryStats]+ );++ const karmaByAccountData = useMemo(() =>+ [...redditAccounts]+ .sort((a, b) => (b.postKarma || 0) - (a.postKarma || 0))+ .map(a => ({ name: `u/${a.username || ''}`.slice(0, 16), karma: a.postKarma || 0 })),+ [redditAccounts]+ );++ const engagementByContentData = useMemo(() =>+ trackedContent+ .map(p => ({+ name: (p.title || p.label || p.url || '').slice(0, 16),+ engagement: p.contentType === 'youtube' ? (p.likeCount ?? 0) : (p.score ?? 0),+ }))+ .sort((a, b) => b.engagement - a.engagement)+ .slice(0, 12),+ [trackedContent]+ );function handleViewChannel(acc) {if (acc.platform === 'instagram') navigate(`/instagram/${acc.id}`);@@ -384,87 +419,67 @@ export default function Overview() {{/* ── AUDIENCE TAB ──────────────────────────────────────────────── */}<TabsContent value="audience" className="space-y-4">- <div className="grid grid-cols-1 xl:grid-cols-3 gap-4">- <MainCard title="Audience Comparison" className="xl:col-span-2">- <p className="text-xs text-muted-foreground mb-3">- YouTube = subscribers · Instagram = followers · Reddit = karma · Categories = total score- </p>- {audienceChartData.length === 0 ? (- <p className="text-sm text-muted-foreground py-8 text-center">No data to display</p>- ) : (- <ResponsiveContainer width="100%" height={240} debounce={200}>- <AreaChart data={audienceChartData} margin={{ top: 8, right: 4, left: 0, bottom: 0 }}>- <defs>- <linearGradient id="audienceAreaGrad" x1="0" y1="0" x2="0" y2="1">- <stop offset="5%" stopColor="var(--primary)" stopOpacity={0.15} />- <stop offset="95%" stopColor="var(--primary)" stopOpacity={0} />- </linearGradient>- </defs>- <CartesianGrid strokeDasharray="3 3" stroke="var(--border)" vertical={false} />- <XAxis dataKey="name" tick={{ fill: 'var(--muted-foreground)', fontSize: 11 }} axisLine={false} tickLine={false} />- <YAxis tick={{ fill: 'var(--muted-foreground)', fontSize: 11 }} tickFormatter={fmtNum} axisLine={false} tickLine={false} width={48} />- <ReTooltip- contentStyle={{ background: 'var(--card)', border: '1px solid var(--border)', borderRadius: 8, fontSize: 12 }}- formatter={(v, name, props) => [fmtNumFull(v), props.payload.type === 'category' ? 'Views + Score' : 'Audience']}- />- <Area- type="monotone"- dataKey="value"- stroke="var(--primary)"- strokeWidth={2}- fill="url(#audienceAreaGrad)"- dot={(props) => {- const { cx, cy, payload, index } = props;- return (- <circle- key={`dot-${index}`}- cx={cx}- cy={cy}- r={5}- fill={PLATFORM_COLORS[payload.type] || '#6366f1'}- stroke="var(--card)"- strokeWidth={2}- />- );- }}- activeDot={{ r: 7 }}- />- </AreaChart>- </ResponsiveContainer>- )}- <div className="flex flex-wrap gap-3 mt-2">- {[- ytAccounts.length ? { color: PLATFORM_COLORS.youtube, label: 'YouTube (subs)' } : null,- igAccounts.length ? { color: PLATFORM_COLORS.instagram, label: 'Instagram (followers)' } : null,- redditAccounts.length ? { color: PLATFORM_COLORS.reddit, label: 'Reddit (karma)' } : null,- categoryStats.length ? { color: PLATFORM_COLORS.category, label: 'Category (views + score)' } : null,- ].filter(Boolean).map(({ color, label }) => (- <div key={label} className="flex items-center gap-1.5 text-xs text-muted-foreground">- <span className="h-2.5 w-2.5 rounded-full flex-shrink-0" style={{ background: color }} />- {label}- </div>- ))}- </div>- </MainCard>-- <MainCard title="Audience Share">- {pieData.length === 0 ? (- <p className="text-sm text-muted-foreground py-8 text-center">No data to display</p>- ) : (- <ResponsiveContainer width="100%" height={260} debounce={200}>- <PieChart>- <Pie data={pieData} dataKey="value" nameKey="name" cx="50%" cy="44%" outerRadius={85} innerRadius={48} paddingAngle={3} strokeWidth={0}>- {pieData.map((entry, i) => (- <Cell key={i} fill={entry.color} />- ))}- </Pie>- <ReTooltip contentStyle={{ background: 'var(--card)', border: '1px solid var(--border)', borderRadius: 8, fontSize: 12 }} formatter={(v) => fmtNumFull(v)} />- <Legend iconType="circle" iconSize={8} wrapperStyle={{ fontSize: 11, paddingTop: 8 }} />- </PieChart>- </ResponsiveContainer>- )}- </MainCard>- </div>+ <MainCard title="Audience Comparison">+ <p className="text-xs text-muted-foreground mb-3">+ YouTube = subscribers · Instagram = followers · Reddit = karma · Categories = views + karma+ </p>+ {audienceChartData.length === 0 ? (+ <p className="text-sm text-muted-foreground py-8 text-center">No data to display</p>+ ) : (+ <ResponsiveContainer width="100%" height={260} debounce={200}>+ <AreaChart data={audienceChartData} margin={{ top: 8, right: 8, left: 0, bottom: 0 }}>+ <defs>+ <linearGradient id="audienceAreaGrad" x1="0" y1="0" x2="0" y2="1">+ <stop offset="5%" stopColor="var(--primary)" stopOpacity={0.28} />+ <stop offset="95%" stopColor="var(--primary)" stopOpacity={0} />+ </linearGradient>+ </defs>+ <CartesianGrid strokeDasharray="3 3" stroke="var(--border)" vertical={false} />+ <XAxis dataKey="name" tick={{ fill: 'var(--muted-foreground)', fontSize: 11 }} axisLine={false} tickLine={false} />+ <YAxis tick={{ fill: 'var(--muted-foreground)', fontSize: 11 }} tickFormatter={fmtNum} axisLine={false} tickLine={false} width={48} />+ <ReTooltip+ contentStyle={{ background: 'var(--card)', border: '1px solid var(--border)', borderRadius: 8, fontSize: 12 }}+ formatter={(v, name, props) => [fmtNumFull(v), props.payload.type === 'category' ? 'Views + Karma' : 'Audience']}+ />+ <Area+ type="monotone"+ dataKey="value"+ stroke="var(--primary)"+ strokeWidth={2}+ fill="url(#audienceAreaGrad)"+ dot={(props) => {+ const { cx, cy, payload, index } = props;+ return (+ <circle+ key={`dot-${index}`}+ cx={cx}+ cy={cy}+ r={5}+ fill={PLATFORM_COLORS[payload.type] || '#6366f1'}+ stroke="var(--card)"+ strokeWidth={2}+ />+ );+ }}+ activeDot={{ r: 7 }}+ />+ </AreaChart>+ </ResponsiveContainer>+ )}+ <div className="flex flex-wrap gap-3 mt-2">+ {[+ ytAccounts.length ? { color: PLATFORM_COLORS.youtube, label: 'YouTube (subs)' } : null,+ igAccounts.length ? { color: PLATFORM_COLORS.instagram, label: 'Instagram (followers)' } : null,+ redditAccounts.length ? { color: PLATFORM_COLORS.reddit, label: 'Reddit (karma)' } : null,+ categoryStats.length ? { color: PLATFORM_COLORS.category, label: 'Category (views + karma)' } : null,+ ].filter(Boolean).map(({ color, label }) => (+ <div key={label} className="flex items-center gap-1.5 text-xs text-muted-foreground">+ <span className="h-2.5 w-2.5 rounded-full flex-shrink-0" style={{ background: color }} />+ {label}+ </div>+ ))}+ </div>+ </MainCard>{/* Top by Audience - accounts only, no metric label */}<MainCard title="Top by Audience">@@ -649,7 +664,7 @@ export default function Overview() {)}{stat.rdCount > 0 && (<p className="text-xs font-semibold tabular-nums text-orange-500 leading-none mt-0.5">- {fmtNum(stat.rdScore)} score+ {fmtNum(stat.rdKarma)} karma</p>)}</div>@@ -737,161 +752,116 @@ export default function Overview() {{/* ── COMMENTS TAB ──────────────────────────────────────────────── */}<TabsContent value="comments" className="space-y-4">- <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">- <StatCard icon={<MessageSquare />} label="Total Comments" value={fmtNum(totalComments)} subtitle={totalComments > 0 ? 'across all platforms' : 'visit analytics pages to load'} gradient="blue" />- <StatCard icon={<CirclePlay />} label="YouTube Comments" value={fmtNum(ytComments)} subtitle={cacheTotals.ytComments > 0 ? 'from video cache' : `${trackedStats.ytItems.length} tracked videos`} gradient="red" />- <StatCard icon={<Flame />} label="Reddit Comments" value={fmtNum(rdComments)} subtitle={cacheTotals.rdComments > 0 ? 'from analytics cache' : `${trackedStats.rdItems.length} tracked posts`} gradient="orange" />+ <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-4">+ <StatCard icon={<MessageSquare />} label="Total Comments" value={fmtNum(totalComments)} subtitle={totalComments > 0 ? 'across all platforms' : 'visit analytics pages to load'} gradient="blue" />+ <StatCard icon={<CirclePlay />} label="YouTube Comments" value={fmtNum(ytComments)} subtitle={`${fmtPercent(commentShare.youtube)} of all comments`} gradient="red" />+ <StatCard icon={<Flame />} label="Reddit Comments" value={fmtNum(rdComments)} subtitle={`${fmtPercent(commentShare.reddit)} of all comments`} gradient="orange" />+ <StatCard icon={<BarChart2 />} label="Comments per Content" value={fmtNum(avgCommentsPerContent)} subtitle={`average across ${fmtNum(totalContent)} item${totalContent !== 1 ? 's' : ''}`} gradient="purple" /></div>- {trackedContent.length === 0 && totalComments === 0 ? (+ {totalComments === 0 ? (<MainCard>- <div className="flex flex-col items-center text-center py-10 gap-3">- <MessageSquare className="h-8 w-8 text-muted-foreground" />- <div>- <p className="text-sm font-semibold">No comment data available yet</p>- <p className="text-xs text-muted-foreground mt-1">- Visit Reddit Analytics or YouTube Analytics pages to load data, or track content via Tracked Content- </p>- </div>- <Button size="sm" onClick={() => navigate('/tracked-content')}>Track Content</Button>- </div>+ <Empty>+ <EmptyHeader>+ <EmptyMedia variant="icon">+ <MessageSquare />+ </EmptyMedia>+ <EmptyTitle>No comment data yet</EmptyTitle>+ <EmptyDescription>+ Open a channel or account analytics page to load its comment data, or track individual posts and videos.+ </EmptyDescription>+ </EmptyHeader>+ <EmptyContent>+ <Button size="sm" onClick={() => navigate('/tracked-content')}>Track Content</Button>+ </EmptyContent>+ </Empty></MainCard>- ) : trackedContent.length > 0 ? (- <MainCard title="Tracked Content by Comments" content={false}>- <Table>- <TableHeader>- <TableRow>- <TableHead>Title</TableHead>- <TableHead className="w-28">Category</TableHead>- <TableHead className="text-right w-28">Comments</TableHead>- <TableHead className="text-right w-28">Likes / Score</TableHead>- </TableRow>- </TableHeader>- <TableBody>- {[...trackedContent]- .sort((a, b) => {- const ca = a.contentType === 'youtube' ? (a.commentCount ?? 0) : (a.numComments ?? 0);- const cb = b.contentType === 'youtube' ? (b.commentCount ?? 0) : (b.numComments ?? 0);- return cb - ca;- })- .map(item => {- const isYT = item.contentType === 'youtube';- const comments = isYT ? (item.commentCount ?? 0) : (item.numComments ?? 0);- const engagement = isYT ? (item.likeCount ?? 0) : (item.score ?? 0);- return (- <TableRow key={item.id}>- <TableCell>- <div className="flex items-center gap-2">- {isYT- ? <CirclePlay className="h-3.5 w-3.5 text-red-500 flex-shrink-0" />- : <Flame className="h-3.5 w-3.5 text-orange-500 flex-shrink-0" />- }- <span className="text-sm font-medium truncate max-w-xs">- {item.title || item.label || item.url}- </span>- </div>- <p className="text-xs text-muted-foreground ml-5 mt-0.5">- {isYT ? item.channelTitle : item.subredditPrefixed}- </p>- </TableCell>- <TableCell>- {item.category- ? <Badge variant="outline" className="text-xs">{item.category}</Badge>- : <span className="text-xs text-muted-foreground">-</span>}- </TableCell>- <TableCell className="text-right text-sm font-semibold tabular-nums">- {fmtNum(comments)}- </TableCell>- <TableCell className={`text-right text-sm font-semibold tabular-nums ${isYT ? 'text-red-500' : 'text-orange-500'}`}>- {fmtNum(engagement)}- </TableCell>- </TableRow>- );- })}- </TableBody>- </Table>- </MainCard>- ) : null}+ ) : (+ <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">+ <MainCard+ title="Comments by Tracked Content"+ subheader="Top 12 tracked items ranked by comment count"+ >+ <MetricAreaChart+ data={commentByContentData}+ dataKey="comments"+ label="Comments"+ color="#06b6d4"+ emptyMessage="Track content to compare comment volume"+ />+ </MainCard>++ <MainCard+ title="Comments by Category"+ subheader="Total comments across every item in each category"+ >+ <MetricAreaChart+ data={commentByCategoryData}+ dataKey="comments"+ label="Comments"+ color="#a855f7"+ emptyMessage="Assign categories to tracked content to see this breakdown"+ />+ </MainCard>+ </div>+ )}</TabsContent>{/* ── LIKES TAB ──────────────────────────────────────────────────── */}<TabsContent value="likes" className="space-y-4">- <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">- <StatCard icon={<ThumbsUp />} label="Total Likes" value={fmtNum(totalLikes)} subtitle={totalLikes > 0 ? 'across all platforms' : 'visit analytics pages to load'} gradient="purple" />- <StatCard icon={<Flame />} label="Reddit Karma" value={fmtNum(totals.postKarma)} subtitle="post upvotes across accounts" gradient="orange" />- <StatCard icon={<CirclePlay />} label="YouTube Likes" value={fmtNum(ytLikes)} subtitle={cacheTotals.ytLikes > 0 ? 'from video cache' : `${trackedStats.ytItems.length} tracked videos`} gradient="red" />+ <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-4">+ <StatCard icon={<ThumbsUp />} label="Total Likes" value={fmtNum(totalLikes)} subtitle={totalLikes > 0 ? 'YouTube likes, Instagram likes, Reddit karma' : 'visit analytics pages to load'} gradient="purple" />+ <StatCard icon={<Flame />} label="Reddit Karma" value={fmtNum(redditKarma)} subtitle={`${fmtNum(totals.postKarma)} account · ${fmtNum(trackedStats.rdKarma)} tracked`} gradient="orange" />+ <StatCard icon={<CirclePlay />} label="YouTube Likes" value={fmtNum(ytLikes)} subtitle={`${fmtPercent(likeShare.youtube)} of all likes`} gradient="red" />+ <StatCard icon={<Camera />} label="Instagram Likes" value={fmtNum(cacheTotals.igLikes)} subtitle={igAccounts.length > 0 ? `${fmtPercent(likeShare.instagram)} of all likes` : 'no Instagram accounts'} gradient="pink" /></div>- <div className="grid grid-cols-1 md:grid-cols-2 gap-4">- {redditAccounts.length > 0 && (- <MainCard title="Reddit Accounts by Karma">- <div className="space-y-1">- {[...redditAccounts]- .sort((a, b) => (b.postKarma || 0) - (a.postKarma || 0))- .map(a => (- <button- key={a.id}- onClick={() => navigate(`/reddit/${a.id}`)}- className="w-full flex items-center gap-2.5 px-2 py-1.5 rounded-lg hover:bg-muted/60 transition-colors text-left"- >- <Avatar className="h-6 w-6 flex-shrink-0">- <AvatarImage src={a.iconUrl} />- <AvatarFallback className="bg-orange-500 text-white text-[0.5rem] font-bold">- {(a.username || '?').slice(0, 2).toUpperCase()}- </AvatarFallback>- </Avatar>- <span className="flex-1 text-sm font-medium">u/{a.username}</span>- <div className="text-right">- <p className="text-sm font-bold tabular-nums text-orange-500">{fmtNum(a.postKarma || 0)}</p>- <p className="text-[10px] text-muted-foreground">post karma</p>- </div>- </button>- ))}- </div>+ {totalLikes === 0 ? (+ <MainCard>+ <Empty>+ <EmptyHeader>+ <EmptyMedia variant="icon">+ <ThumbsUp />+ </EmptyMedia>+ <EmptyTitle>No engagement data yet</EmptyTitle>+ <EmptyDescription>+ Open a channel or account analytics page to load its like data, or track individual posts and videos.+ </EmptyDescription>+ </EmptyHeader>+ <EmptyContent>+ <Button size="sm" onClick={() => navigate('/tracked-content')}>Track Content</Button>+ </EmptyContent>+ </Empty>+ </MainCard>+ ) : (+ <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">+ <MainCard+ title="Karma by Reddit Account"+ subheader="Post karma earned by each connected account"+ >+ <MetricAreaChart+ data={karmaByAccountData}+ dataKey="karma"+ label="Post karma"+ color="#f97316"+ emptyMessage="Connect a Reddit account to see karma"+ /></MainCard>- )}- <MainCard title="Tracked YouTube by Likes">- {trackedStats.ytItems.length === 0 ? (- <div className="flex flex-col items-center text-center py-8 gap-3">- <CirclePlay className="h-7 w-7 text-muted-foreground" />- <div>- <p className="text-sm font-medium">No YouTube videos tracked</p>- <p className="text-xs text-muted-foreground mt-1">Track YouTube videos to see their like counts</p>- </div>- <Button size="sm" variant="outline" onClick={() => navigate('/tracked-content')}>Track Videos</Button>- </div>- ) : (- <div className="space-y-1">- {[...trackedStats.ytItems]- .sort((a, b) => (b.likeCount ?? 0) - (a.likeCount ?? 0))- .map(item => (- <button- key={item.id}- onClick={() => window.open(item.permalink || item.url, '_blank')}- className="w-full flex items-center gap-2.5 px-2 py-1.5 rounded-lg hover:bg-muted/60 transition-colors text-left"- >- {item.thumbnail ? (- <img src={item.thumbnail} alt="" className="h-9 w-14 rounded object-cover flex-shrink-0" />- ) : (- <div className="h-9 w-14 rounded bg-red-500/10 flex items-center justify-center flex-shrink-0">- <CirclePlay className="h-4 w-4 text-red-500" />- </div>- )}- <div className="flex-1 min-w-0">- <p className="text-sm font-medium truncate">{item.title || item.url}</p>- <p className="text-xs text-muted-foreground">{item.channelTitle}</p>- </div>- <div className="text-right flex-shrink-0">- <p className="text-sm font-bold tabular-nums text-red-500">{fmtNum(item.likeCount ?? 0)}</p>- <p className="text-[10px] text-muted-foreground">likes</p>- </div>- </button>- ))}- </div>- )}- </MainCard>- </div>+ <MainCard+ title="Engagement by Tracked Content"+ subheader="YouTube likes and Reddit karma for the top 12 tracked items"+ >+ <MetricAreaChart+ data={engagementByContentData}+ dataKey="engagement"+ label="Likes / karma"+ color="#a855f7"+ emptyMessage="Track content to compare engagement"+ />+ </MainCard>+ </div>+ )}</TabsContent></Tabs>)}diff --git a/frontend/src/features/analytics/reddit/RedditAnalytics.jsx b/frontend/src/features/analytics/reddit/RedditAnalytics.jsxindex dac1057..6d2f1f3 100644--- a/frontend/src/features/analytics/reddit/RedditAnalytics.jsx+++ b/frontend/src/features/analytics/reddit/RedditAnalytics.jsx@@ -184,15 +184,15 @@ export default function RedditAnalytics() {{/* KPI cards */}<div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-4"><StatCard icon={<TrendingUp />} label="Posts Fetched" value={fmtNum(a.fetchedPosts)} subtitle={`${a.postsLast30Days ?? 0} in the last 30 days`} gradient="orange" />- <StatCard icon={<Award />} label="Total Score" value={fmtNum(a.totalScore)} subtitle={`Avg ${fmtNum(a.avgScore)} per post`} gradient="red" />+ <StatCard icon={<Award />} label="Total Karma" value={fmtNum(a.totalScore)} subtitle={`Avg ${fmtNum(a.avgScore)} per post`} gradient="red" /><StatCard icon={<MessageSquare />} label="Total Comments" value={fmtNum(a.totalComments)} subtitle={`Avg ${fmtNum(a.avgComments)} per post`} gradient="blue" /><StatCard icon={<Star />} label="Awards Received" value={fmtNum(a.totalAwards ?? 0)} subtitle={`Avg ${a.avgAwards ?? 0} per post`} gradient="purple" /></div>- {/* Score timeline + media type pie */}+ {/* Karma timeline + media type pie */}{a.monthlyBreakdown?.length > 0 && (<div className="grid grid-cols-1 xl:grid-cols-3 gap-4">- <MainCard title="Score Over Time" className="xl:col-span-2">+ <MainCard title="Karma Over Time" className="xl:col-span-2"><ResponsiveContainer width="100%" height={240} debounce={200}><AreaChart data={a.monthlyBreakdown} margin={{ top: 4, right: 4, left: 0, bottom: 0 }}><defs>@@ -204,7 +204,7 @@ export default function RedditAnalytics() {<CartesianGrid strokeDasharray="3 3" stroke="var(--border)" vertical={false} /><XAxis dataKey="month" tick={{ fill: 'var(--muted-foreground)', fontSize: 11 }} axisLine={false} tickLine={false} /><YAxis tick={{ fill: 'var(--muted-foreground)', fontSize: 11 }} tickFormatter={fmtNum} axisLine={false} tickLine={false} width={48} />- <ReTooltip contentStyle={TS} formatter={(v, n) => [fmtNumFull(v), n === 'score' ? 'Total Score' : 'Posts']} />+ <ReTooltip contentStyle={TS} formatter={(v, n) => [fmtNumFull(v), n === 'score' ? 'Total Karma' : 'Posts']} /><Area type="monotone" dataKey="score" stroke="#FF4500" strokeWidth={2} fill="url(#redditGrad)" dot={{ fill: '#FF4500', r: 3, strokeWidth: 0 }} /></AreaChart></ResponsiveContainer>@@ -252,11 +252,11 @@ export default function RedditAnalytics() {</div></MainCard>- <MainCard title="Score Breakdown">+ <MainCard title="Karma Breakdown"><div className="space-y-3">{[- { label: 'Average score', value: fmtNum(a.avgScore) },- { label: 'Median score', value: fmtNum(a.medianScore) },+ { 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: 'Avg upvote ratio', value: `${a.avgUpvoteRatio ?? 0}%` },{ label: 'Total comments', value: fmtNum(a.totalComments) },@@ -273,8 +273,8 @@ export default function RedditAnalytics() {<MainCard title="Performance Indicators"><div className="space-y-4">{[- { label: 'Virality Score', value: a.viralityScore, max: Math.max(10, a.viralityScore), desc: 'Ratio of peak post score to average - higher means bigger outlier hits' },- { label: 'Consistency', value: a.consistencyScore, max: 100, desc: 'Score reliability across posts - 100 means very uniform performance' },+ { label: 'Virality Score', value: a.viralityScore, max: Math.max(10, a.viralityScore), desc: 'Ratio of peak post karma to average - higher means bigger outlier hits' },+ { label: 'Consistency', value: a.consistencyScore, max: 100, desc: 'Karma reliability across posts - 100 means very uniform performance' },].map(item => (<div key={item.label} className="space-y-1.5"><div className="flex items-center justify-between text-sm">@@ -298,7 +298,7 @@ export default function RedditAnalytics() {<CartesianGrid strokeDasharray="3 3" stroke="var(--border)" vertical={false} /><XAxis dataKey="shortDay" tick={{ fill: 'var(--muted-foreground)', fontSize: 11 }} axisLine={false} tickLine={false} /><YAxis tick={{ fill: 'var(--muted-foreground)', fontSize: 11 }} tickFormatter={fmtNum} axisLine={false} tickLine={false} width={36} />- <ReTooltip contentStyle={TS} formatter={(v, n) => [fmtNumFull(v), n === 'avgScore' ? 'Avg Score' : 'Posts']} />+ <ReTooltip contentStyle={TS} formatter={(v, n) => [fmtNumFull(v), n === 'avgScore' ? 'Avg Karma' : 'Posts']} /><Bar dataKey="posts" fill="#FF4500" opacity={0.35} radius={[3, 3, 0, 0]} /><Bar dataKey="avgScore" fill="#FF4500" radius={[3, 3, 0, 0]} /></BarChart>@@ -316,7 +316,7 @@ export default function RedditAnalytics() {<CartesianGrid strokeDasharray="3 3" stroke="var(--border)" vertical={false} /><XAxis dataKey="hour" tickFormatter={h => `${h}h`} tick={{ fill: 'var(--muted-foreground)', fontSize: 10 }} axisLine={false} tickLine={false} interval={3} /><YAxis tick={{ fill: 'var(--muted-foreground)', fontSize: 11 }} tickFormatter={fmtNum} axisLine={false} tickLine={false} width={36} />- <ReTooltip contentStyle={TS} formatter={(v, n) => [fmtNumFull(v), n === 'avgScore' ? 'Avg Score' : 'Posts']} />+ <ReTooltip contentStyle={TS} formatter={(v, n) => [fmtNumFull(v), n === 'avgScore' ? 'Avg Karma' : 'Posts']} /><Bar dataKey="avgScore" fill="#FF6534" radius={[3, 3, 0, 0]} /></BarChart></ResponsiveContainer>@@ -338,8 +338,8 @@ export default function RedditAnalytics() {<TableHead className="w-8">#</TableHead><TableHead>Subreddit</TableHead><TableHead className="text-right">Posts</TableHead>- <TableHead className="text-right">Total Score</TableHead>- <TableHead className="text-right">Avg Score</TableHead>+ <TableHead className="text-right">Total Karma</TableHead>+ <TableHead className="text-right">Avg Karma</TableHead><TableHead className="text-right">Avg Comments</TableHead></TableRow></TableHeader>@@ -371,13 +371,13 @@ export default function RedditAnalytics() {{/* Top posts */}{a.topPosts?.length > 0 && (- <MainCard title="Top Posts by Score" content={false}>+ <MainCard title="Top Posts by Karma" content={false}><Table><TableHeader><TableRow><TableHead className="w-8">#</TableHead><TableHead>Post</TableHead>- <TableHead className="text-right">Score</TableHead>+ <TableHead className="text-right">Karma</TableHead><TableHead className="text-right">Comments</TableHead><TableHead className="text-right">Upvote %</TableHead><TableHead className="text-right">Posted</TableHead>diff --git a/frontend/src/features/analytics/reddit/RedditPosts.jsx b/frontend/src/features/analytics/reddit/RedditPosts.jsxindex 5d8e71c..429fa64 100644--- a/frontend/src/features/analytics/reddit/RedditPosts.jsx+++ b/frontend/src/features/analytics/reddit/RedditPosts.jsx@@ -15,8 +15,8 @@ import { ArrowLeft, Search, ExternalLink, TrendingUp, MessageSquare, FileText, Iconst MEDIA_TYPE_LABELS = { text: 'Text', image: 'Image', video: 'Video', link: 'Link' };const SORT_OPTIONS = [- { value: 'score-desc', label: 'Score (high to low)' },- { value: 'score-asc', label: 'Score (low to high)' },+ { value: 'score-desc', label: 'Karma (high to low)' },+ { value: 'score-asc', label: 'Karma (low to high)' },{ value: 'comments-desc', label: 'Comments (most)' },{ value: 'date-desc', label: 'Newest first' },{ value: 'date-asc', label: 'Oldest first' },@@ -156,7 +156,7 @@ export default function RedditPosts() {<TableHead className="w-8">#</TableHead><TableHead>Post</TableHead><TableHead className="w-24">Type</TableHead>- <TableHead className="text-right w-24">Score</TableHead>+ <TableHead className="text-right w-24">Karma</TableHead><TableHead className="text-right w-28">Comments</TableHead><TableHead className="text-right w-20">Upvote %</TableHead><TableHead className="text-right w-28">Date</TableHead>diff --git a/frontend/src/features/analytics/reddit/RedditPostsAll.jsx b/frontend/src/features/analytics/reddit/RedditPostsAll.jsxindex e2cd14d..fb73d59 100644--- a/frontend/src/features/analytics/reddit/RedditPostsAll.jsx+++ b/frontend/src/features/analytics/reddit/RedditPostsAll.jsx@@ -19,8 +19,8 @@ import {const MEDIA_TYPE_LABELS = { text: 'Text', image: 'Image', video: 'Video', link: 'Link' };const SORT_OPTIONS = [- { value: 'score-desc', label: 'Score (high to low)' },- { value: 'score-asc', label: 'Score (low to high)' },+ { value: 'score-desc', label: 'Karma (high to low)' },+ { value: 'score-asc', label: 'Karma (low to high)' },{ value: 'comments-desc', label: 'Comments (most)' },{ value: 'date-desc', label: 'Newest first' },{ value: 'date-asc', label: 'Oldest first' },@@ -174,7 +174,7 @@ export default function RedditPostsAll() {{/* Summary stats */}<div className="grid grid-cols-1 sm:grid-cols-3 gap-4"><StatCard icon={<TrendingUp />} label="Posts Shown" value={fmtNum(totals.posts)} subtitle={`${posts.length} total fetched`} gradient="orange" />- <StatCard icon={<Award />} label="Combined Score" value={fmtNum(totals.score)} subtitle={filtered.length > 0 ? `Avg ${fmtNum(Math.round(totals.score / filtered.length))} per post` : ''} gradient="red" />+ <StatCard icon={<Award />} label="Combined Karma" value={fmtNum(totals.score)} subtitle={filtered.length > 0 ? `Avg ${fmtNum(Math.round(totals.score / filtered.length))} per post` : ''} gradient="red" /><StatCard icon={<MessageSquare />} label="Total Comments" value={fmtNum(totals.comments)} subtitle={filtered.length > 0 ? `Avg ${fmtNum(Math.round(totals.comments / filtered.length))} per post` : ''} gradient="blue" /></div>@@ -253,7 +253,7 @@ export default function RedditPostsAll() {<TableHead>Post</TableHead>{redditAccounts.length > 1 && <TableHead className="w-36">Account</TableHead>}<TableHead className="w-24">Type</TableHead>- <TableHead className="text-right w-24">Score</TableHead>+ <TableHead className="text-right w-24">Karma</TableHead><TableHead className="text-right w-28">Comments</TableHead><TableHead className="text-right w-20">Upvote %</TableHead><TableHead className="text-right w-28">Date</TableHead>diff --git a/frontend/src/features/analytics/reddit/RedditTracked.jsx b/frontend/src/features/analytics/reddit/RedditTracked.jsxdeleted file mode 100644index eb2fa45..0000000--- a/frontend/src/features/analytics/reddit/RedditTracked.jsx+++ /dev/null@@ -1,558 +0,0 @@-import React, { useState, useEffect, useMemo, useCallback } from 'react';-import { Button } from '@/components/ui/button';-import { Input } from '@/components/ui/input';-import { Badge } from '@/components/ui/badge';-import { Checkbox } from '@/components/ui/checkbox';-import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';-import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';-import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';-import { Skeleton } from '@/components/ui/skeleton';-import {- Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter,-} from '@/components/ui/dialog';-import StatCard from '../../../components/ui/StatCard';-import MainCard from '../../../components/MainCard';-import { useAppContext } from '../../../context/AppContext';-import { api } from '../../../services/api';-import { fmtNum, fmtDate } from '../../../utils/formatters';-import {- Plus, RefreshCw, Trash2, Pencil, ExternalLink,- Tag, Bookmark, TrendingUp, BookmarkCheck,-} from 'lucide-react';--export default function RedditTracked() {- const { accounts, showToast } = useAppContext();- const redditAccounts = accounts.filter(a => a.platform === 'reddit');-- const [posts, setPosts] = useState([]);- const [loading, setLoading] = useState(true);- const [addOpen, setAddOpen] = useState(false);- const [editPost, setEditPost] = useState(null);- const [selected, setSelected] = useState(new Set());- const [bulkCategory, setBulkCategory] = useState('');- const [query, setQuery] = useState('');- const [categoryFilter, setCategoryFilter] = useState('all');- const [sort, setSort] = useState('date-desc');- const [refreshingIds, setRefreshingIds] = useState(new Set());-- // Add dialog state- const [addUrl, setAddUrl] = useState('');- const [addAccountId, setAddAccountId] = useState(redditAccounts[0]?.id ?? 'none');- const [addLabel, setAddLabel] = useState('');- const [addCategory, setAddCategory] = useState('');- const [adding, setAdding] = useState(false);-- // Edit dialog state- const [editLabel, setEditLabel] = useState('');- const [editCategory, setEditCategory] = useState('');- const [saving, setSaving] = useState(false);-- const load = useCallback(async () => {- try {- const data = await api.getTrackedPosts();- setPosts(Array.isArray(data) ? data : []);- } catch (err) {- showToast(err.message, 'error');- } finally {- setLoading(false);- }- }, [showToast]);-- useEffect(() => { load(); }, [load]);-- const categories = useMemo(() => {- const seen = new Set(posts.map(p => p.category).filter(Boolean));- return Array.from(seen).sort();- }, [posts]);-- const filtered = useMemo(() => {- let result = posts;- if (categoryFilter !== 'all') result = result.filter(p => p.category === categoryFilter);- if (query.trim()) {- const q = query.toLowerCase();- result = result.filter(p =>- (p.title || '').toLowerCase().includes(q) ||- (p.subreddit || '').toLowerCase().includes(q) ||- (p.label || '').toLowerCase().includes(q) ||- (p.category || '').toLowerCase().includes(q)- );- }- return [...result].sort((a, b) => {- if (sort === 'score-desc') return (b.score ?? 0) - (a.score ?? 0);- if (sort === 'comments-desc') return (b.numComments ?? 0) - (a.numComments ?? 0);- return new Date(b.createdAt || 0) - new Date(a.createdAt || 0);- });- }, [posts, query, categoryFilter, sort]);-- const totals = useMemo(() => ({- tracked: posts.length,- categories: categories.length,- avgScore: posts.length > 0 ? Math.round(posts.reduce((s, p) => s + (p.score ?? 0), 0) / posts.length) : 0,- }), [posts, categories]);-- const allSelected = filtered.length > 0 && filtered.every(p => selected.has(p.id));- const someSelected = selected.size > 0;-- function toggleAll() {- if (allSelected) {- setSelected(prev => { const n = new Set(prev); filtered.forEach(p => n.delete(p.id)); return n; });- } else {- setSelected(prev => { const n = new Set(prev); filtered.forEach(p => n.add(p.id)); return n; });- }- }-- function toggleOne(id) {- setSelected(prev => { const n = new Set(prev); n.has(id) ? n.delete(id) : n.add(id); return n; });- }-- async function handleAdd() {- if (!addUrl.trim()) { showToast('Paste a Reddit post URL', 'error'); return; }- setAdding(true);- try {- const accountId = addAccountId === 'none' ? null : addAccountId;- const post = await api.addTrackedPost(addUrl.trim(), accountId, addLabel.trim(), addCategory.trim());- setPosts(prev => [post, ...prev]);- setAddOpen(false);- setAddUrl(''); setAddLabel(''); setAddCategory('');- showToast('Post is now tracked');- } catch (err) {- showToast(err.message, 'error');- } finally {- setAdding(false);- }- }-- function openEdit(post) {- setEditPost(post);- setEditLabel(post.label || '');- setEditCategory(post.category || '');- }-- async function handleSaveEdit() {- if (!editPost) return;- setSaving(true);- try {- const updated = await api.updateTrackedPost(editPost.id, { label: editLabel, category: editCategory });- setPosts(prev => prev.map(p => p.id === editPost.id ? updated : p));- setEditPost(null);- showToast('Post updated');- } catch (err) {- showToast(err.message, 'error');- } finally {- setSaving(false);- }- }-- async function handleDelete(id) {- try {- await api.deleteTrackedPost(id);- setPosts(prev => prev.filter(p => p.id !== id));- setSelected(prev => { const n = new Set(prev); n.delete(id); return n; });- } catch (err) {- showToast(err.message, 'error');- }- }-- async function handleRefresh(id) {- setRefreshingIds(prev => new Set(prev).add(id));- try {- const updated = await api.refreshTrackedPost(id);- setPosts(prev => prev.map(p => p.id === id ? updated : p));- } catch (err) {- showToast(err.message, 'error');- } finally {- setRefreshingIds(prev => { const n = new Set(prev); n.delete(id); return n; });- }- }-- async function handleBulkCategory() {- if (!bulkCategory.trim() || selected.size === 0) return;- try {- const updates = await Promise.allSettled(- [...selected].map(id => api.updateTrackedPost(id, { category: bulkCategory.trim() }))- );- const succeeded = updates- .map((r, i) => r.status === 'fulfilled' ? { id: [...selected][i], data: r.value } : null)- .filter(Boolean);- setPosts(prev => prev.map(p => {- const hit = succeeded.find(s => s.id === p.id);- return hit ? hit.data : p;- }));- setSelected(new Set());- setBulkCategory('');- showToast(`Category assigned to ${succeeded.length} post${succeeded.length !== 1 ? 's' : ''}`);- } catch (err) {- showToast(err.message, 'error');- }- }-- if (loading) {- return (- <div className="space-y-6">- <Skeleton className="h-8 w-48" />- <div className="grid grid-cols-3 gap-4">- <Skeleton className="h-28" />- <Skeleton className="h-28" />- <Skeleton className="h-28" />- </div>- <Skeleton className="h-64" />- </div>- );- }-- return (- <div className="space-y-6">- {/* Header */}- <div className="flex items-start justify-between gap-4">- <div>- <h1 className="text-2xl font-bold tracking-tight">Tracked Posts</h1>- <p className="text-sm text-muted-foreground mt-0.5">- Monitor score and comments on specific Reddit posts using your account cookies- </p>- </div>- <Button size="sm" className="gap-2 shrink-0" onClick={() => setAddOpen(true)}>- <Plus className="h-3.5 w-3.5" />- Track Post- </Button>- </div>-- {/* Stat cards */}- <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">- <StatCard icon={<BookmarkCheck />} label="Tracked Posts" value={totals.tracked} subtitle="across all categories" gradient="orange" />- <StatCard icon={<Tag />} label="Categories" value={totals.categories} subtitle={totals.categories === 0 ? 'none assigned yet' : `${totals.categories} group${totals.categories !== 1 ? 's' : ''}`} gradient="blue" />- <StatCard icon={<TrendingUp />} label="Avg Score" value={fmtNum(totals.avgScore)} subtitle="across all tracked posts" gradient="red" />- </div>-- {/* Bulk category bar */}- {someSelected && (- <MainCard>- <div className="flex items-center gap-3">- <span className="text-sm font-medium text-muted-foreground">{selected.size} selected</span>- <div className="flex-1 flex items-center gap-2">- <Tag className="h-4 w-4 text-muted-foreground shrink-0" />- <Input- placeholder="Category name"- value={bulkCategory}- onChange={e => setBulkCategory(e.target.value)}- className="h-8 max-w-xs"- onKeyDown={e => e.key === 'Enter' && handleBulkCategory()}- />- <Button size="sm" onClick={handleBulkCategory} disabled={!bulkCategory.trim()}>- Assign- </Button>- </div>- <Button size="sm" variant="ghost" onClick={() => setSelected(new Set())}>- Clear- </Button>- </div>- </MainCard>- )}-- {/* Filters */}- <MainCard>- <div className="flex flex-col sm:flex-row gap-3">- <Input- placeholder="Search posts..."- value={query}- onChange={e => setQuery(e.target.value)}- className="flex-1"- />- {categories.length > 0 && (- <Select- value={categoryFilter}- onValueChange={setCategoryFilter}- items={[{ value: 'all', label: 'All categories' }, ...categories.map(c => ({ value: c, label: c }))]}- >- <SelectTrigger className="w-full sm:w-48">- <SelectValue placeholder="All categories" />- </SelectTrigger>- <SelectContent>- <SelectItem value="all">All categories</SelectItem>- {categories.map(c => <SelectItem key={c} value={c}>{c}</SelectItem>)}- </SelectContent>- </Select>- )}- <Select- value={sort}- onValueChange={setSort}- items={[- { value: 'date-desc', label: 'Newest first' },- { value: 'score-desc', label: 'Score (high to low)' },- { value: 'comments-desc', label: 'Comments (most)' },- ]}- >- <SelectTrigger className="w-full sm:w-52">- <SelectValue />- </SelectTrigger>- <SelectContent>- <SelectItem value="date-desc">Newest first</SelectItem>- <SelectItem value="score-desc">Score (high to low)</SelectItem>- <SelectItem value="comments-desc">Comments (most)</SelectItem>- </SelectContent>- </Select>- </div>- </MainCard>-- {/* Table */}- <MainCard content={false}>- {posts.length === 0 ? (- <div className="flex flex-col items-center text-center py-16 gap-4">- <div className="h-14 w-14 rounded-full bg-orange-500/10 flex items-center justify-center">- <Bookmark className="h-7 w-7 text-orange-500" />- </div>- <div>- <p className="text-sm font-semibold">No posts tracked yet</p>- <p className="text-xs text-muted-foreground mt-1">- Paste a Reddit post URL and pick which account cookie to use for fetching- </p>- </div>- <Button size="sm" onClick={() => setAddOpen(true)}>- <Plus className="h-3.5 w-3.5 mr-1.5" />- Track your first post- </Button>- </div>- ) : (- <Table>- <TableHeader>- <TableRow>- <TableHead className="w-10">- <Checkbox- checked={allSelected}- onCheckedChange={toggleAll}- aria-label="Select all"- />- </TableHead>- <TableHead>Post</TableHead>- <TableHead className="w-32">Account</TableHead>- <TableHead className="w-28">Category</TableHead>- <TableHead className="text-right w-20">Score</TableHead>- <TableHead className="text-right w-24">Comments</TableHead>- <TableHead className="text-right w-20">Upvote %</TableHead>- <TableHead className="text-right w-28">Fetched</TableHead>- <TableHead className="w-24" />- </TableRow>- </TableHeader>- <TableBody>- {filtered.length === 0 ? (- <TableRow>- <TableCell colSpan={9} className="text-center text-muted-foreground py-10">- No posts match the current filters- </TableCell>- </TableRow>- ) : (- filtered.map(post => {- const acc = accounts.find(a => a.id === post.accountId);- const isRefreshing = refreshingIds.has(post.id);- return (- <TableRow key={post.id} className={selected.has(post.id) ? 'bg-muted/30' : ''}>- <TableCell>- <Checkbox- checked={selected.has(post.id)}- onCheckedChange={() => toggleOne(post.id)}- aria-label={`Select ${post.title}`}- />- </TableCell>- <TableCell>- <div className="max-w-sm">- <p className="text-sm font-medium leading-snug line-clamp-2">- {post.title || post.label || post.url}- </p>- <div className="flex items-center gap-2 mt-0.5">- {post.subredditPrefixed && (- <span className="text-xs text-muted-foreground">{post.subredditPrefixed}</span>- )}- {post.label && (- <span className="text-xs text-muted-foreground italic">{post.label}</span>- )}- </div>- </div>- </TableCell>- <TableCell>- {acc ? (- <div className="flex items-center gap-1.5">- <Avatar className="h-5 w-5 flex-shrink-0">- <AvatarImage src={acc.iconUrl} />- <AvatarFallback className="bg-orange-500 text-white text-[0.5rem] font-bold">- {(acc.username || '?').slice(0, 2).toUpperCase()}- </AvatarFallback>- </Avatar>- <span className="text-xs text-muted-foreground">u/{acc.username}</span>- </div>- ) : (- <span className="text-xs text-muted-foreground">Public</span>- )}- </TableCell>- <TableCell>- {post.category ? (- <Badge variant="outline" className="text-xs font-medium">- {post.category}- </Badge>- ) : (- <span className="text-xs text-muted-foreground">-</span>- )}- </TableCell>- <TableCell className="text-right text-sm font-semibold tabular-nums text-orange-500">- {post.score !== undefined ? fmtNum(post.score) : '-'}- </TableCell>- <TableCell className="text-right text-sm tabular-nums">- {post.numComments !== undefined ? fmtNum(post.numComments) : '-'}- </TableCell>- <TableCell className="text-right text-sm tabular-nums text-muted-foreground">- {post.upvoteRatio !== undefined && (post.score ?? 0) >= 10- ? `${Math.round(post.upvoteRatio * 100)}%`- : '-'}- </TableCell>- <TableCell className="text-right text-xs text-muted-foreground">- {post.lastFetchedAt ? fmtDate(post.lastFetchedAt) : '-'}- </TableCell>- <TableCell>- <div className="flex items-center gap-0.5 justify-end">- <Button- variant="ghost"- size="icon"- className="size-7"- onClick={() => handleRefresh(post.id)}- disabled={isRefreshing}- title="Refresh live data"- >- <RefreshCw className={`h-3.5 w-3.5 ${isRefreshing ? 'animate-spin' : ''}`} />- </Button>- <Button- variant="ghost"- size="icon"- className="size-7"- onClick={() => openEdit(post)}- title="Edit label or category"- >- <Pencil className="h-3.5 w-3.5" />- </Button>- <a href={post.permalink} target="_blank" rel="noopener noreferrer">- <Button variant="ghost" size="icon" className="size-7" title="Open on Reddit">- <ExternalLink className="h-3.5 w-3.5" />- </Button>- </a>- <Button- variant="ghost"- size="icon"- className="size-7 text-destructive hover:text-destructive"- onClick={() => handleDelete(post.id)}- title="Stop tracking"- >- <Trash2 className="h-3.5 w-3.5" />- </Button>- </div>- </TableCell>- </TableRow>- );- })- )}- </TableBody>- </Table>- )}- </MainCard>-- {/* Add post dialog */}- <Dialog open={addOpen} onOpenChange={setAddOpen}>- <DialogContent className="max-w-md">- <DialogHeader>- <DialogTitle>Track a Reddit post</DialogTitle>- </DialogHeader>- <div className="space-y-4 py-2">- <div className="space-y-1.5">- <label className="text-sm font-medium">Post URL</label>- <Input- placeholder="https://www.reddit.com/r/.../comments/..."- value={addUrl}- onChange={e => setAddUrl(e.target.value)}- autoFocus- />- <p className="text-xs text-muted-foreground">- Paste the full URL of the Reddit post you want to track- </p>- </div>- <div className="space-y-1.5">- <label className="text-sm font-medium">Account cookie</label>- <Select- value={addAccountId}- onValueChange={setAddAccountId}- items={[- { value: 'none', label: 'No cookie (public posts only)' },- ...redditAccounts.map(a => ({ value: a.id, label: `u/${a.username}` })),- ]}- >- <SelectTrigger>- <SelectValue />- </SelectTrigger>- <SelectContent>- <SelectItem value="none">No cookie (public posts only)</SelectItem>- {redditAccounts.map(a => (- <SelectItem key={a.id} value={a.id} textValue={`u/${a.username}`}>- u/{a.username}- </SelectItem>- ))}- </SelectContent>- </Select>- <p className="text-xs text-muted-foreground">- Using a session cookie improves access from datacenter IPs- </p>- </div>- <div className="grid grid-cols-2 gap-3">- <div className="space-y-1.5">- <label className="text-sm font-medium">Label <span className="text-muted-foreground font-normal">(optional)</span></label>- <Input placeholder="My post" value={addLabel} onChange={e => setAddLabel(e.target.value)} />- </div>- <div className="space-y-1.5">- <label className="text-sm font-medium">Category <span className="text-muted-foreground font-normal">(optional)</span></label>- <Input placeholder="Campaign A" value={addCategory} onChange={e => setAddCategory(e.target.value)} />- </div>- </div>- </div>- <DialogFooter>- <Button variant="outline" onClick={() => setAddOpen(false)} disabled={adding}>Cancel</Button>- <Button onClick={handleAdd} disabled={adding || !addUrl.trim()}>- {adding ? 'Fetching...' : 'Track Post'}- </Button>- </DialogFooter>- </DialogContent>- </Dialog>-- {/* Edit dialog */}- <Dialog open={!!editPost} onOpenChange={v => !v && setEditPost(null)}>- <DialogContent className="max-w-sm">- <DialogHeader>- <DialogTitle>Edit tracked post</DialogTitle>- </DialogHeader>- <div className="space-y-4 py-2">- <div className="space-y-1.5">- <label className="text-sm font-medium">Label</label>- <Input value={editLabel} onChange={e => setEditLabel(e.target.value)} placeholder="My post" />- </div>- <div className="space-y-1.5">- <label className="text-sm font-medium">Category</label>- <Input value={editCategory} onChange={e => setEditCategory(e.target.value)} placeholder="Campaign A" />- {categories.length > 0 && (- <div className="flex flex-wrap gap-1.5 pt-1">- {categories.map(c => (- <button- key={c}- onClick={() => setEditCategory(c)}- className="text-xs px-2 py-0.5 rounded-full border border-border hover:bg-muted transition-colors"- >- {c}- </button>- ))}- </div>- )}- </div>- </div>- <DialogFooter>- <Button variant="outline" onClick={() => setEditPost(null)} disabled={saving}>Cancel</Button>- <Button onClick={handleSaveEdit} disabled={saving}>- {saving ? 'Saving...' : 'Save'}- </Button>- </DialogFooter>- </DialogContent>- </Dialog>- </div>- );-}diff --git a/frontend/src/features/analytics/tracked/TrackedCategory.jsx b/frontend/src/features/analytics/tracked/TrackedCategory.jsxindex 243ca38..dae1e8d 100644--- a/frontend/src/features/analytics/tracked/TrackedCategory.jsx+++ b/frontend/src/features/analytics/tracked/TrackedCategory.jsx@@ -6,11 +6,11 @@ import { Separator } from '@/components/ui/separator';import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';import { Skeleton } from '@/components/ui/skeleton';import {- BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip as ReTooltip,- ResponsiveContainer, Cell,-} from 'recharts';+ Empty, EmptyHeader, EmptyMedia, EmptyTitle, EmptyDescription, EmptyContent,+} from '@/components/ui/empty';import StatCard from '../../../components/ui/StatCard';import MainCard from '../../../components/MainCard';+import MetricAreaChart from '../../../components/MetricAreaChart';import { useAppContext } from '../../../context/AppContext';import { api } from '../../../services/api';import { fmtNum, fmtNumFull, fmtDate } from '../../../utils/formatters';@@ -19,21 +19,9 @@ import {ThumbsUp, MessageSquare, Tag, TrendingUp, BarChart2,} from 'lucide-react';-function ContentTypeBadge({ type }) {- if (type === 'youtube') {- return (- <Badge variant="outline" className="text-[10px] border-red-200 bg-red-50 text-red-700 dark:border-red-900 dark:bg-red-950 dark:text-red-400 gap-1 px-1.5 py-0">- <CirclePlay className="h-2.5 w-2.5" />- YouTube- </Badge>- );- }- return (- <Badge variant="outline" className="text-[10px] border-orange-200 bg-orange-50 text-orange-700 dark:border-orange-900 dark:bg-orange-950 dark:text-orange-400 gap-1 px-1.5 py-0">- <Flame className="h-2.5 w-2.5" />- </Badge>- );+// fmtNum abbreviates only at 1000 and above, so the full value is redundant below that+function showsFullValue(n) {+ return Math.abs(Number(n) || 0) >= 1000;}export default function TrackedCategory() {@@ -69,32 +57,35 @@ export default function TrackedCategory() {views,likes,comments,- avgViews: count ? Math.round(views / count) : 0,- avgLikes: count ? Math.round(likes / count) : 0,+ avgViews: count ? Math.round(views / count) : 0,+ avgLikes: count ? Math.round(likes / count) : 0,+ avgComments: count ? Math.round(comments / count) : 0,likeRatio: views > 0 ? ((likes / views) * 100).toFixed(2) : '0',};}, [ytItems]);+ // Reddit post score is karma, so it is named and labelled as karma throughoutconst rdStats = useMemo(() => {const count = rdItems.length;- const score = rdItems.reduce((s, p) => s + (p.score ?? 0), 0);+ const karma = rdItems.reduce((s, p) => s + (p.score ?? 0), 0);const comments = rdItems.reduce((s, p) => s + (p.numComments ?? 0), 0);const ratioSum = rdItems.reduce((s, p) => s + (p.upvoteRatio ?? 0), 0);return {count,- score,+ karma,comments,- avgScore: count ? Math.round(score / count) : 0,- avgRatio: count ? ratioSum / count : 0,+ avgKarma: count ? Math.round(karma / count) : 0,+ avgComments: count ? Math.round(comments / count) : 0,+ avgRatio: count ? ratioSum / count : 0,};}, [rdItems]);const ytChartData = useMemo(() =>[...ytItems].sort((a, b) => (b.viewCount ?? 0) - (a.viewCount ?? 0))- .slice(0, 10)+ .slice(0, 12).map(p => ({- name: (p.title || p.url || '').slice(0, 30),+ name: (p.title || p.url || '').slice(0, 16),views: p.viewCount ?? 0,})),[ytItems]@@ -103,10 +94,10 @@ export default function TrackedCategory() {const rdChartData = useMemo(() =>[...rdItems].sort((a, b) => (b.score ?? 0) - (a.score ?? 0))- .slice(0, 10)+ .slice(0, 12).map(p => ({- name: (p.title || p.url || '').slice(0, 30),- score: p.score ?? 0,+ name: (p.title || p.url || '').slice(0, 16),+ karma: p.score ?? 0,})),[rdItems]);@@ -146,18 +137,20 @@ export default function TrackedCategory() {</div></div><MainCard>- <div className="flex flex-col items-center text-center py-12 gap-3">- <div className="h-14 w-14 rounded-full bg-purple-500/10 flex items-center justify-center">- <Tag className="h-7 w-7 text-purple-500" />- </div>- <div>- <p className="text-sm font-semibold">No tracked items in "{categoryName}"</p>- <p className="text-xs text-muted-foreground mt-1">- Add content and assign this category in Tracked Content to see analytics here- </p>- </div>- <Button size="sm" onClick={() => navigate('/tracked-content')}>Manage Tracked Content</Button>- </div>+ <Empty className="py-8">+ <EmptyHeader>+ <EmptyMedia variant="icon">+ <Tag />+ </EmptyMedia>+ <EmptyTitle>Nothing tracked in {categoryName}</EmptyTitle>+ <EmptyDescription>+ Assign this category to a Reddit post or YouTube video in Tracked Content and its analytics will appear here.+ </EmptyDescription>+ </EmptyHeader>+ <EmptyContent>+ <Button size="sm" onClick={() => navigate('/tracked-content')}>Manage Tracked Content</Button>+ </EmptyContent>+ </Empty></MainCard></div>);@@ -193,26 +186,26 @@ export default function TrackedCategory() {<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4"><StatCardicon={<Tag />}- label="Total Items"+ label="Total Content"value={items.length}subtitle={[- ytItems.length > 0 ? `${ytItems.length} YouTube` : null,- rdItems.length > 0 ? `${rdItems.length} Reddit` : null,+ ytItems.length > 0 ? `${ytItems.length} YouTube video${ytItems.length !== 1 ? 's' : ''}` : null,+ rdItems.length > 0 ? `${rdItems.length} Reddit post${rdItems.length !== 1 ? 's' : ''}` : null,].filter(Boolean).join(' · ')}gradient="purple"/><StatCardicon={<Eye />}- label="Total Views"+ label="YouTube Views"value={ytItems.length > 0 ? fmtNum(ytStats.views) : '-'}- subtitle={ytItems.length > 0 ? `avg ${fmtNum(ytStats.avgViews)} per video` : 'no YouTube videos'}+ subtitle={ytItems.length > 0 ? `avg ${fmtNum(ytStats.avgViews)} per video` : 'no YouTube videos in this category'}gradient="red"/><StatCardicon={<Flame />}- label="Reddit Score"- value={rdItems.length > 0 ? fmtNum(rdStats.score) : '-'}- subtitle={rdItems.length > 0 ? `avg ${fmtNum(rdStats.avgScore)} per post` : 'no Reddit posts'}+ label="Reddit Karma"+ value={rdItems.length > 0 ? fmtNum(rdStats.karma) : '-'}+ subtitle={rdItems.length > 0 ? `avg ${fmtNum(rdStats.avgKarma)} per post` : 'no Reddit posts in this category'}gradient="orange"/><StatCard@@ -220,9 +213,9 @@ export default function TrackedCategory() {label="Total Comments"value={fmtNum(ytStats.comments + rdStats.comments)}subtitle={[- ytItems.length > 0 ? 'YouTube' : null,- rdItems.length > 0 ? 'Reddit' : null,- ].filter(Boolean).join(' + ') + ' combined'}+ ytItems.length > 0 ? `${fmtNum(ytStats.comments)} YouTube` : null,+ rdItems.length > 0 ? `${fmtNum(rdStats.comments)} Reddit` : null,+ ].filter(Boolean).join(' · ')}gradient="blue"/></div>@@ -242,23 +235,23 @@ export default function TrackedCategory() {<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4"><StatCardicon={<Eye />}- label="Total Views"+ label="Video Views"value={fmtNum(ytStats.views)}subtitle={`avg ${fmtNum(ytStats.avgViews)} per video`}gradient="red"/><StatCardicon={<ThumbsUp />}- label="Total Likes"+ label="Video Likes"value={fmtNum(ytStats.likes)}subtitle={`avg ${fmtNum(ytStats.avgLikes)} per video`}gradient="orange"/><StatCardicon={<MessageSquare />}- label="Total Comments"+ label="Video Comments"value={fmtNum(ytStats.comments)}- subtitle="across all videos"+ subtitle={`avg ${fmtNum(ytStats.avgComments)} per video`}gradient="blue"/><StatCard@@ -271,44 +264,17 @@ export default function TrackedCategory() {</div>{ytChartData.length > 1 && (- <MainCard title="Top Videos by Views">- <ResponsiveContainer- width="100%"- height={Math.max(ytChartData.length * 44, 200)}- debounce={200}- >- <BarChart- data={ytChartData}- layout="vertical"- margin={{ top: 0, right: 56, left: 0, bottom: 0 }}- >- <CartesianGrid strokeDasharray="3 3" stroke="var(--border)" horizontal={false} />- <XAxis- type="number"- tick={{ fill: 'var(--muted-foreground)', fontSize: 11 }}- tickFormatter={fmtNum}- axisLine={false}- tickLine={false}- />- <YAxis- type="category"- dataKey="name"- width={196}- tick={{ fill: 'var(--muted-foreground)', fontSize: 11 }}- axisLine={false}- tickLine={false}- />- <ReTooltip- contentStyle={{ background: 'var(--card)', border: '1px solid var(--border)', borderRadius: 8, fontSize: 12 }}- formatter={(v) => [fmtNumFull(v), 'Views']}- />- <Bar dataKey="views" radius={[0, 4, 4, 0]} maxBarSize={22}>- {ytChartData.map((_, i) => (- <Cell key={i} fill="#ef4444" fillOpacity={Math.max(1 - i * 0.07, 0.4)} />- ))}- </Bar>- </BarChart>- </ResponsiveContainer>+ <MainCard+ title="Video Views"+ subheader={`Top ${ytChartData.length} video${ytChartData.length !== 1 ? 's' : ''} in this category ranked by views`}+ >+ <MetricAreaChart+ data={ytChartData}+ dataKey="views"+ label="Views"+ color="#ef4444"+ height={260}+ /></MainCard>)}@@ -366,7 +332,9 @@ export default function TrackedCategory() {</TableCell><TableCell className="text-right"><p className="text-sm font-bold tabular-nums">{fmtNum(item.viewCount ?? 0)}</p>- <p className="text-xs text-muted-foreground">{fmtNumFull(item.viewCount ?? 0)}</p>+ {showsFullValue(item.viewCount) && (+ <p className="text-xs text-muted-foreground tabular-nums">{fmtNumFull(item.viewCount)}</p>+ )}</TableCell><TableCell className="text-right text-sm font-semibold tabular-nums text-red-500">{fmtNum(item.likeCount ?? 0)}@@ -407,16 +375,16 @@ export default function TrackedCategory() {<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4"><StatCardicon={<Flame />}- label="Net Upvotes"- value={fmtNum(rdStats.score)}+ label="Post Karma"+ value={fmtNum(rdStats.karma)}subtitle="upvotes minus downvotes"gradient="orange"/><StatCardicon={<MessageSquare />}- label="Total Comments"+ label="Post Comments"value={fmtNum(rdStats.comments)}- subtitle="across all posts"+ subtitle={`avg ${fmtNum(rdStats.avgComments)} per post`}gradient="blue"/><StatCard@@ -428,52 +396,25 @@ export default function TrackedCategory() {/><StatCardicon={<BarChart2 />}- label="Avg Net Upvotes"- value={fmtNum(rdStats.avgScore)}- subtitle={`${rdItems.length} post${rdItems.length !== 1 ? 's' : ''} tracked`}+ label="Avg Karma per Post"+ value={fmtNum(rdStats.avgKarma)}+ subtitle={`across ${rdItems.length} post${rdItems.length !== 1 ? 's' : ''}`}gradient="purple"/></div>{rdChartData.length > 1 && (- <MainCard title="Top Posts by Score">- <ResponsiveContainer- width="100%"- height={Math.max(rdChartData.length * 44, 200)}- debounce={200}- >- <BarChart- data={rdChartData}- layout="vertical"- margin={{ top: 0, right: 56, left: 0, bottom: 0 }}- >- <CartesianGrid strokeDasharray="3 3" stroke="var(--border)" horizontal={false} />- <XAxis- type="number"- tick={{ fill: 'var(--muted-foreground)', fontSize: 11 }}- tickFormatter={fmtNum}- axisLine={false}- tickLine={false}- />- <YAxis- type="category"- dataKey="name"- width={196}- tick={{ fill: 'var(--muted-foreground)', fontSize: 11 }}- axisLine={false}- tickLine={false}- />- <ReTooltip- contentStyle={{ background: 'var(--card)', border: '1px solid var(--border)', borderRadius: 8, fontSize: 12 }}- formatter={(v) => [fmtNumFull(v), 'Score']}- />- <Bar dataKey="score" radius={[0, 4, 4, 0]} maxBarSize={22}>- {rdChartData.map((_, i) => (- <Cell key={i} fill="#f97316" fillOpacity={Math.max(1 - i * 0.07, 0.4)} />- ))}- </Bar>- </BarChart>- </ResponsiveContainer>+ <MainCard+ title="Post Karma"+ subheader={`Top ${rdChartData.length} post${rdChartData.length !== 1 ? 's' : ''} in this category ranked by karma`}+ >+ <MetricAreaChart+ data={rdChartData}+ dataKey="karma"+ label="Karma"+ color="#f97316"+ height={260}+ /></MainCard>)}@@ -483,7 +424,7 @@ export default function TrackedCategory() {<TableRow><TableHead className="w-8">#</TableHead><TableHead>Post</TableHead>- <TableHead className="text-right w-28">Score</TableHead>+ <TableHead className="text-right w-28">Karma</TableHead><TableHead className="text-right w-20">Upvote %</TableHead><TableHead className="text-right w-24">Comments</TableHead><TableHead className="text-right w-28">Fetched</TableHead>@@ -517,7 +458,9 @@ export default function TrackedCategory() {<p className="text-sm font-bold tabular-nums text-orange-500">{fmtNum(item.score ?? 0)}</p>- <p className="text-xs text-muted-foreground">{fmtNumFull(item.score ?? 0)}</p>+ {showsFullValue(item.score) && (+ <p className="text-xs text-muted-foreground tabular-nums">{fmtNumFull(item.score)}</p>+ )}</TableCell><TableCell className="text-right text-sm tabular-nums text-muted-foreground">{(item.upvoteRatio != null && (item.score ?? 0) >= 10)diff --git a/frontend/src/features/analytics/tracked/TrackedContent.jsx b/frontend/src/features/analytics/tracked/TrackedContent.jsxindex 846c2f7..aad502f 100644--- a/frontend/src/features/analytics/tracked/TrackedContent.jsx+++ b/frontend/src/features/analytics/tracked/TrackedContent.jsx@@ -254,7 +254,7 @@ export default function TrackedContent() {<div><h1 className="text-2xl font-bold tracking-tight">Tracked Content</h1><p className="text-sm text-muted-foreground mt-0.5">- Monitor Reddit posts and YouTube videos - track scores, likes, and comments over time+ Monitor Reddit posts and YouTube videos - track karma, likes, and comments over time</p></div><Button size="sm" className="gap-2 shrink-0" onClick={() => setAddOpen(true)}>@@ -343,7 +343,7 @@ export default function TrackedContent() {onValueChange={setSort}items={[{ value: 'date-desc', label: 'Newest first' },- { value: 'engagement-desc', label: 'Likes / Score' },+ { value: 'engagement-desc', label: 'Likes / Karma' },{ value: 'comments-desc', label: 'Most comments' },{ value: 'views-desc', label: 'Most views' },]}@@ -353,7 +353,7 @@ export default function TrackedContent() {</SelectTrigger><SelectContent><SelectItem value="date-desc">Newest first</SelectItem>- <SelectItem value="engagement-desc">Likes / Score</SelectItem>+ <SelectItem value="engagement-desc">Likes / Karma</SelectItem><SelectItem value="comments-desc">Most comments</SelectItem><SelectItem value="views-desc">Most views (YouTube)</SelectItem></SelectContent>@@ -389,7 +389,7 @@ export default function TrackedContent() {<TableHead>Title</TableHead><TableHead className="w-28">Category</TableHead><TableHead className="text-right w-24">Views</TableHead>- <TableHead className="text-right w-24">Likes / Score</TableHead>+ <TableHead className="text-right w-24">Likes / Karma</TableHead><TableHead className="text-right w-24">Comments</TableHead><TableHead className="text-right w-20">Ratio</TableHead><TableHead className="text-right w-28">Fetched</TableHead>