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(overview): split Overview into small modules
spacesdrivee5bbf1d6b631
diff --git a/docs/architecture/data-flows/ANALYTICS.md b/docs/architecture/data-flows/ANALYTICS.mdindex f16175d..0850f32 100644--- a/docs/architecture/data-flows/ANALYTICS.md+++ b/docs/architecture/data-flows/ANALYTICS.md@@ -211,7 +211,7 @@ Note: Reddit disabled `view_count` from their API in December 2018. The field alUser navigates to /│▼-Overview.jsx uses accounts from AppContext+Overview.jsx uses accounts from AppContext (data loaded by useOverviewData.js)-> Combined totals computed from account.subscriberCount, viewCount, etc.-> api.getOverview() -> GET /api/overview-> returns { tracked: [...], analyticsCache: { [accountId]: {...} } }@@ -219,8 +219,9 @@ Overview.jsx uses accounts from AppContextThe Overview does not fetch fresh per-account analytics. It combines account metadata alreadyin `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.+account's cache is cold the backend fires a background warm-up and returns `cacheWarmed: false`+with `syncing: true`. While any account is syncing, the page fetches the overview again after 4,+8 and 16 seconds, then stops so the syncing label never hangs.### Metric definitionsdiff --git a/docs/architecture/frontend/FEATURES.md b/docs/architecture/frontend/FEATURES.mdindex ac29c99..d351cc6 100644--- a/docs/architecture/frontend/FEATURES.md+++ b/docs/architecture/frontend/FEATURES.md@@ -22,7 +22,13 @@ frontend/src/│ │ ├── instagram/│ │ │ └── InstagramAnalytics.jsx <- Instagram account analytics│ │ ├── overview/-│ │ │ └── Overview.jsx <- Cross-platform aggregate dashboard+│ │ │ ├── Overview.jsx <- Page: cross-platform aggregate dashboard with six metric tabs+│ │ │ ├── OverviewHeader.jsx, QuickActions.jsx, GettingStarted.jsx, MetricTabsList.jsx+│ │ │ ├── AudienceTab.jsx, AudienceChart.jsx, ViewsTab.jsx, ContentTab.jsx, AccountsTab.jsx, CommentsTab.jsx, LikesTab.jsx+│ │ │ ├── InstagramViewsTable.jsx, YouTubeViewsTable.jsx, AccountCell.jsx, AccountRankRow.jsx, CategoryRow.jsx, OpenAnalytics.jsx+│ │ │ ├── useOverviewData.js <- Loads api.getOverview() and re-polls while accounts are syncing+│ │ │ ├── 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)│ │ │ ├── RedditPosts.jsx <- Per-account post explorerdiff --git a/docs/architecture/frontend/REACT_ARCHITECTURE.md b/docs/architecture/frontend/REACT_ARCHITECTURE.mdindex 6a9316d..b55a329 100644--- a/docs/architecture/frontend/REACT_ARCHITECTURE.md+++ b/docs/architecture/frontend/REACT_ARCHITECTURE.md@@ -96,7 +96,7 @@ frontend/src/Login.jsx Auth page (not lazy-loaded, always small)features/analytics/- overview/ Overview.jsx - all-accounts dashboard+ overview/ Overview.jsx - all-accounts dashboard (page; tabs, hooks and helpers beside it)channel/ ChannelAnalytics.jsx - per-channel YouTubeinstagram/ InstagramAnalytics.jsx - per-account Instagramvideos/ VideoExplorer.jsx - all videos tablediff --git a/frontend/src/features/analytics/overview/AccountCell.jsx b/frontend/src/features/analytics/overview/AccountCell.jsxnew file mode 100644index 0000000..3fd757f--- /dev/null+++ b/frontend/src/features/analytics/overview/AccountCell.jsx@@ -0,0 +1,17 @@+import { TableCell } from '@/components/ui/table';+import { AccountAvatar } from '@/components/platform';+import { accountHandle } from '@/lib/accounts';++export default function AccountCell({ account, name }) {+ return (+ <TableCell>+ <div className="flex items-center gap-2.5">+ <AccountAvatar account={account} />+ <div>+ <p className="text-sm font-medium text-ink">{name}</p>+ <p className="text-caption text-ink-faint">{accountHandle(account)}</p>+ </div>+ </div>+ </TableCell>+ );+}diff --git a/frontend/src/features/analytics/overview/AccountRankRow.jsx b/frontend/src/features/analytics/overview/AccountRankRow.jsxnew file mode 100644index 0000000..1f09a86--- /dev/null+++ b/frontend/src/features/analytics/overview/AccountRankRow.jsx@@ -0,0 +1,17 @@+import { useNavigate } from 'react-router-dom';+import ListRow, { RankNumber } from '@/components/ListRow';+import { AccountAvatar } from '@/components/platform';+import { accountHandle, accountName, accountPath } from '@/lib/accounts';++export default function AccountRankRow({ account, rank, trailing }) {+ const navigate = useNavigate();+ return (+ <ListRow+ onClick={() => navigate(accountPath(account))}+ leading={<><RankNumber rank={rank} /><AccountAvatar account={account} showPlatform /></>}+ title={accountName(account)}+ meta={accountHandle(account)}+ trailing={trailing}+ />+ );+}diff --git a/frontend/src/features/analytics/overview/AccountsTab.jsx b/frontend/src/features/analytics/overview/AccountsTab.jsxnew file mode 100644index 0000000..0e43a16--- /dev/null+++ b/frontend/src/features/analytics/overview/AccountsTab.jsx@@ -0,0 +1,42 @@+import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';+import SurfaceBox from '@/components/SurfaceBox';+import { RankNumber } from '@/components/ListRow';+import { PlatformBadge } from '@/components/platform';+import { accountName, platformOf } from '@/lib/accounts';+import { timeAgo } from '../../../utils/formatters';+import { accountAudienceLabel, accountContentLabel } from './overviewLabels.js';+import AccountCell from './AccountCell';+import OpenAnalytics from './OpenAnalytics';++export default function AccountsTab({ accounts }) {+ return (+ <SurfaceBox content={false} className="overflow-hidden">+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead className="w-10 text-right">#</TableHead>+ <TableHead>Account</TableHead>+ <TableHead>Platform</TableHead>+ <TableHead className="text-right">Audience</TableHead>+ <TableHead className="text-right">Content</TableHead>+ <TableHead className="text-right">Updated</TableHead>+ <TableHead className="w-10"><span className="sr-only">Open</span></TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {accounts.map((account, i) => (+ <TableRow key={account.id}>+ <TableCell className="text-right"><RankNumber rank={i + 1} className="w-auto" /></TableCell>+ <AccountCell account={account} name={accountName(account)} />+ <TableCell><PlatformBadge platform={platformOf(account)} /></TableCell>+ <TableCell className="text-right text-ink">{accountAudienceLabel(account)}</TableCell>+ <TableCell className="text-right text-ink-muted">{accountContentLabel(account)}</TableCell>+ <TableCell className="text-right text-small text-ink-faint">{timeAgo(account.lastUpdated)}</TableCell>+ <TableCell><OpenAnalytics account={account} name={accountName(account)} /></TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>+ </SurfaceBox>+ );+}diff --git a/frontend/src/features/analytics/overview/AudienceChart.jsx b/frontend/src/features/analytics/overview/AudienceChart.jsxnew file mode 100644index 0000000..19d9b0b--- /dev/null+++ b/frontend/src/features/analytics/overview/AudienceChart.jsx@@ -0,0 +1,62 @@+import {+ AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip as ReTooltip, ResponsiveContainer,+} from 'recharts';+import { axisProps, gridProps, tooltipStyle } from '@/lib/chart';+import { fmtNum, fmtNumFull } from '../../../utils/formatters';+import { audienceDotColor } from './overviewCharts.js';++function formatAudienceTooltip(value, name, props) {+ return [fmtNumFull(value), props.payload.type === 'category' ? 'Karma' : 'Audience'];+}++function renderAudienceDot({ cx, cy, payload, index }) {+ return (+ <circle+ key={`dot-${index}`}+ cx={cx}+ cy={cy}+ r={4.5}+ fill={audienceDotColor(payload.type)}+ stroke="var(--surface-raised)"+ strokeWidth={2}+ />+ );+}++export default function AudienceChart({ data, legend }) {+ return (+ <>+ <ResponsiveContainer width="100%" height={260} debounce={200}>+ <AreaChart data={data} 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(--chart-1)" stopOpacity={0.22} />+ <stop offset="95%" stopColor="var(--chart-1)" stopOpacity={0} />+ </linearGradient>+ </defs>+ <CartesianGrid {...gridProps} vertical={false} />+ <XAxis dataKey="name" {...axisProps} />+ <YAxis {...axisProps} tickFormatter={fmtNum} width={48} />+ <ReTooltip contentStyle={tooltipStyle} cursor={{ stroke: 'var(--line-strong)' }} formatter={formatAudienceTooltip} />+ <Area+ type="monotone"+ dataKey="value"+ stroke="var(--chart-1)"+ strokeWidth={2}+ fill="url(#audienceAreaGrad)"+ dot={renderAudienceDot}+ activeDot={{ r: 6 }}+ />+ </AreaChart>+ </ResponsiveContainer>+ <ul className="mt-3 flex flex-wrap gap-x-4 gap-y-1.5">+ {legend.map(({ color, label }) => (+ <li key={label} className="flex items-center gap-1.5 text-caption text-ink-muted">+ <span className="size-2.5 shrink-0 rounded-full" style={{ background: color }} />+ {label}+ </li>+ ))}+ </ul>+ </>+ );+}diff --git a/frontend/src/features/analytics/overview/AudienceTab.jsx b/frontend/src/features/analytics/overview/AudienceTab.jsxnew file mode 100644index 0000000..88db7d9--- /dev/null+++ b/frontend/src/features/analytics/overview/AudienceTab.jsx@@ -0,0 +1,35 @@+import { Users } from 'lucide-react';+import { Badge } from '@/components/ui/badge';+import SurfaceBox from '@/components/SurfaceBox';+import { EmptyState } from '@/components/StateViews';+import { PlatformBadge } from '@/components/platform';+import { platformOf } from '@/lib/accounts';+import AudienceChart from './AudienceChart';+import AccountRankRow from './AccountRankRow';+import CategoryRow from './CategoryRow';++export default function AudienceTab({ stats }) {+ const audienceData = stats.charts.audience;+ return (+ <>+ <SurfaceBox title="Audience by account" subheader="Subscribers, followers and karma, plus karma earned by each tracked category">+ {audienceData.length === 0 ? (+ <EmptyState compact icon={<Users />} title="No audience data yet" description="Refresh your accounts to load subscriber and follower counts." />+ ) : (+ <AudienceChart data={audienceData} legend={stats.legend} />+ )}+ </SurfaceBox>++ <SurfaceBox title="Top by audience" contentClassName="px-2 py-2">+ <div className="flex flex-col">+ {stats.byAudience.map((account, i) => (+ <AccountRankRow key={account.id} account={account} rank={i + 1} trailing={<PlatformBadge platform={platformOf(account)} />} />+ ))}+ {stats.categoryStats.map(stat => (+ <CategoryRow key={stat.category} stat={stat} trailing={<Badge variant="outline">Category</Badge>} />+ ))}+ </div>+ </SurfaceBox>+ </>+ );+}diff --git a/frontend/src/features/analytics/overview/CategoryRow.jsx b/frontend/src/features/analytics/overview/CategoryRow.jsxnew file mode 100644index 0000000..6fdffa7--- /dev/null+++ b/frontend/src/features/analytics/overview/CategoryRow.jsx@@ -0,0 +1,17 @@+import { useNavigate } from 'react-router-dom';+import { Tag } from 'lucide-react';+import ListRow from '@/components/ListRow';+import { categoryMeta } from './overviewLabels.js';++export default function CategoryRow({ stat, trailing }) {+ const navigate = useNavigate();+ return (+ <ListRow+ onClick={() => navigate(`/tracked-content/category/${encodeURIComponent(stat.category)}`)}+ leading={<><span className="w-5 shrink-0" /><span className="flex size-8 items-center justify-center rounded-control bg-surface-sunken text-ink-muted"><Tag className="size-4 stroke-[1.75]" /></span></>}+ title={stat.category}+ meta={categoryMeta(stat)}+ trailing={trailing}+ />+ );+}diff --git a/frontend/src/features/analytics/overview/CommentsTab.jsx b/frontend/src/features/analytics/overview/CommentsTab.jsxnew file mode 100644index 0000000..42f26c3--- /dev/null+++ b/frontend/src/features/analytics/overview/CommentsTab.jsx@@ -0,0 +1,45 @@+import { Link } from 'react-router-dom';+import { BarChart2, CirclePlay, MessageSquare, MessagesSquare } from 'lucide-react';+import { Button } from '@/components/ui/button';+import SurfaceBox from '@/components/SurfaceBox';+import MetricBox from '@/components/MetricBox';+import MetricAreaChart from '@/components/MetricAreaChart';+import { EmptyState } from '@/components/StateViews';+import { SERIES } from '@/lib/chart';+import { fmtNum, fmtPercent } from '../../../utils/formatters';+import { pluralWord } from './overviewLabels.js';++export default function CommentsTab({ stats }) {+ const { summary, charts } = stats;+ const { totalComments, totalContent } = summary;+ return (+ <>+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-4">+ <MetricBox icon={<MessageSquare />} label="Total comments" value={fmtNum(totalComments)} subtitle={totalComments > 0 ? 'Across all platforms' : 'Open an analytics page to load'} highlight />+ <MetricBox icon={<CirclePlay />} label="YouTube comments" value={fmtNum(summary.ytComments)} subtitle={`${fmtPercent(summary.commentShare.youtube)} of all comments`} />+ <MetricBox icon={<MessagesSquare />} label="Reddit comments" value={fmtNum(summary.rdComments)} subtitle={`${fmtPercent(summary.commentShare.reddit)} of all comments`} />+ <MetricBox icon={<BarChart2 />} label="Comments per item" value={fmtNum(summary.avgCommentsPerContent)} subtitle={`Average across ${fmtNum(totalContent)} ${pluralWord(totalContent, 'item')}`} />+ </div>++ {totalComments === 0 ? (+ <SurfaceBox>+ <EmptyState+ icon={<MessageSquare />}+ title="No comment data yet"+ description="Open a channel or account analytics page to load its comments, or track individual posts and videos."+ action={<Button size="sm" render={<Link to="/tracked-content" />}>Track content</Button>}+ />+ </SurfaceBox>+ ) : (+ <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">+ <SurfaceBox title="Comments by tracked content" subheader="Top 12 tracked items ranked by comments">+ <MetricAreaChart data={charts.commentByContent} dataKey="comments" label="Comments" color={SERIES.cool} emptyMessage="Track content to compare comment volume" />+ </SurfaceBox>+ <SurfaceBox title="Comments by category" subheader="Total comments across every item in each category">+ <MetricAreaChart data={charts.commentByCategory} dataKey="comments" label="Comments" color={SERIES.warm} emptyMessage="Assign categories to tracked content to see this breakdown" />+ </SurfaceBox>+ </div>+ )}+ </>+ );+}diff --git a/frontend/src/features/analytics/overview/ContentTab.jsx b/frontend/src/features/analytics/overview/ContentTab.jsxnew file mode 100644index 0000000..2d570e8--- /dev/null+++ b/frontend/src/features/analytics/overview/ContentTab.jsx@@ -0,0 +1,71 @@+import { Link } from 'react-router-dom';+import { BookmarkCheck, CirclePlay, MessagesSquare, Tag, VideoIcon } from 'lucide-react';+import { Button } from '@/components/ui/button';+import SurfaceBox from '@/components/SurfaceBox';+import MetricBox from '@/components/MetricBox';+import { EmptyState } from '@/components/StateViews';+import { fmtNum } from '../../../utils/formatters';+import { IG_CONTENT_TYPES } from '../../../utils/instagramContent';+import { countLabel, igTypeSummary, topContentLabel } from './overviewLabels.js';+import AccountRankRow from './AccountRankRow';+import CategoryRow from './CategoryRow';++function instagramContentSubtitle(stats) {+ const { igTypes } = stats.cacheTotals;+ if (IG_CONTENT_TYPES.some(type => igTypes[type].count > 0)) return igTypeSummary(igTypes, 'count');+ return countLabel(stats.groups.instagram.length, 'account');+}++function CategoryTrailing({ stat }) {+ return (+ <span className="flex flex-col items-end gap-0.5 text-caption">+ {stat.views > 0 && <span className="font-medium text-ink">{fmtNum(stat.views)} views</span>}+ {stat.rdCount > 0 && <span className="text-ink-faint">{fmtNum(stat.rdKarma)} karma</span>}+ </span>+ );+}++export default function ContentTab({ stats }) {+ const { groups, totals, cacheTotals, trackedStats, categoryStats } = stats;+ return (+ <>+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">+ <MetricBox icon={<CirclePlay />} label="YouTube videos" value={fmtNum(totals.videos)} subtitle={countLabel(groups.youtube.length, 'channel')} />+ <MetricBox icon={<VideoIcon />} label="Instagram content" value={fmtNum(totals.posts)} subtitle={instagramContentSubtitle(stats)} />+ <MetricBox icon={<MessagesSquare />} label="Reddit posts" value={fmtNum(cacheTotals.rdPosts)} subtitle={cacheTotals.rdPosts > 0 ? 'From the analytics cache' : 'Open Reddit analytics to load'} />+ <MetricBox icon={<BookmarkCheck />} label="Tracked content" value={fmtNum(trackedStats.total)} subtitle={`${trackedStats.ytItems.length} YouTube, ${trackedStats.rdItems.length} Reddit`} />+ </div>++ <div className="grid grid-cols-1 gap-4 md:grid-cols-2">+ <SurfaceBox title="Top by content" contentClassName="px-2 py-2">+ <div className="flex flex-col">+ {stats.byContent.map((account, i) => (+ <AccountRankRow+ key={account.id}+ account={account}+ rank={i + 1}+ trailing={<span className="font-medium text-ink-muted">{topContentLabel(account)}</span>}+ />+ ))}+ </div>+ </SurfaceBox>++ <SurfaceBox title="Tracked categories" contentClassName="px-2 py-2">+ {categoryStats.length === 0 ? (+ <EmptyState+ compact+ icon={<Tag />}+ title="No categories yet"+ description="Assign categories to tracked content to see this breakdown."+ action={<Button size="sm" variant="outline" render={<Link to="/tracked-content" />}>Open tracked content</Button>}+ />+ ) : (+ <div className="flex flex-col">+ {categoryStats.map(stat => <CategoryRow key={stat.category} stat={stat} trailing={<CategoryTrailing stat={stat} />} />)}+ </div>+ )}+ </SurfaceBox>+ </div>+ </>+ );+}diff --git a/frontend/src/features/analytics/overview/GettingStarted.jsx b/frontend/src/features/analytics/overview/GettingStarted.jsxnew file mode 100644index 0000000..e208244--- /dev/null+++ b/frontend/src/features/analytics/overview/GettingStarted.jsx@@ -0,0 +1,17 @@+import { Link } from 'react-router-dom';+import { Plus } from 'lucide-react';+import { Button } from '@/components/ui/button';++export default function GettingStarted() {+ return (+ <section className="relative overflow-hidden rounded-panel border border-line bg-surface-raised">+ <div aria-hidden="true" className="fold-band absolute inset-y-0 right-0 hidden w-2/5 [clip-path:polygon(35%_0,100%_0,100%_100%,0_100%)] md:block" />+ <div className="relative flex max-w-xl flex-col gap-4 p-8">+ <p className="eyebrow text-brand-text">Getting started</p>+ <h2 className="font-heading text-page-title font-semibold text-ink">Bring your channels into one picture.</h2>+ <p className="text-sm text-ink-muted">Add a YouTube channel, connect an Instagram Business or Creator account, or add a Reddit profile. Analytics start filling in as soon as an account is added.</p>+ <div><Button render={<Link to="/accounts?add=1" />}><Plus data-icon="inline-start" />Add an account</Button></div>+ </div>+ </section>+ );+}diff --git a/frontend/src/features/analytics/overview/InstagramViewsTable.jsx b/frontend/src/features/analytics/overview/InstagramViewsTable.jsxnew file mode 100644index 0000000..e5c03b2--- /dev/null+++ b/frontend/src/features/analytics/overview/InstagramViewsTable.jsx@@ -0,0 +1,57 @@+import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';+import SurfaceBox from '@/components/SurfaceBox';+import { accountName } from '@/lib/accounts';+import { fmtNum } from '../../../utils/formatters';+import { IG_CONTENT_TYPES, IG_CONTENT_TYPE_META } from '../../../utils/instagramContent';+import AccountCell from './AccountCell';+import OpenAnalytics from './OpenAnalytics';++function InstagramViewsRow({ account, cache, isSyncing }) {+ const warmed = cache?.cacheWarmed;+ const pendingLabel = isSyncing ? 'Syncing' : '-';+ return (+ <TableRow>+ <AccountCell account={account} name={accountName(account)} />+ {IG_CONTENT_TYPES.map(type => (+ <TableCell key={type} className="text-right">+ {warmed ? (+ <>+ <p className="text-sm font-medium text-ink">{fmtNum(cache.contentTypes?.[type]?.views)}</p>+ <p className="text-caption text-ink-faint">{fmtNum(cache.contentTypes?.[type]?.count)} {IG_CONTENT_TYPE_META[type].plural.toLowerCase()}</p>+ </>+ ) : <span className="text-ink-faint">-</span>}+ </TableCell>+ ))}+ <TableCell className="text-right font-semibold text-ink">+ {warmed ? fmtNum(cache.totalViews) : <span className="font-normal text-ink-faint">{pendingLabel}</span>}+ </TableCell>+ <TableCell>+ <OpenAnalytics account={account} name={accountName(account)} />+ </TableCell>+ </TableRow>+ );+}++export default function InstagramViewsTable({ rows, isSyncing }) {+ return (+ <SurfaceBox title="Instagram views by content type" content={false} className="overflow-hidden">+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead>Account</TableHead>+ {IG_CONTENT_TYPES.map(type => (+ <TableHead key={type} className="text-right">{IG_CONTENT_TYPE_META[type].plural}</TableHead>+ ))}+ <TableHead className="text-right">Total views</TableHead>+ <TableHead className="w-10"><span className="sr-only">Open</span></TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {rows.map(({ account, cache }) => (+ <InstagramViewsRow key={account.id} account={account} cache={cache} isSyncing={isSyncing} />+ ))}+ </TableBody>+ </Table>+ </SurfaceBox>+ );+}diff --git a/frontend/src/features/analytics/overview/LikesTab.jsx b/frontend/src/features/analytics/overview/LikesTab.jsxnew file mode 100644index 0000000..8b8deb0--- /dev/null+++ b/frontend/src/features/analytics/overview/LikesTab.jsx@@ -0,0 +1,50 @@+import { Link } from 'react-router-dom';+import { Camera, CirclePlay, MessagesSquare, ThumbsUp } from 'lucide-react';+import { Button } from '@/components/ui/button';+import SurfaceBox from '@/components/SurfaceBox';+import MetricBox from '@/components/MetricBox';+import MetricAreaChart from '@/components/MetricAreaChart';+import { EmptyState } from '@/components/StateViews';+import { PLATFORM_META } from '@/lib/accounts';+import { SERIES } from '@/lib/chart';+import { fmtNum, fmtPercent } from '../../../utils/formatters';++function instagramLikesSubtitle(stats) {+ if (stats.groups.instagram.length > 0) return `${fmtPercent(stats.summary.likeShare.instagram)} of all likes`;+ return 'No Instagram accounts';+}++export default function LikesTab({ stats }) {+ const { totals, cacheTotals, trackedStats, summary, charts } = stats;+ const { totalLikes } = summary;+ return (+ <>+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-4">+ <MetricBox icon={<ThumbsUp />} label="Total likes" value={fmtNum(totalLikes)} subtitle={totalLikes > 0 ? 'YouTube likes, Instagram likes, Reddit karma' : 'Open an analytics page to load'} highlight />+ <MetricBox icon={<MessagesSquare />} label="Reddit karma" value={fmtNum(summary.redditKarma)} subtitle={`${fmtNum(totals.postKarma)} account, ${fmtNum(trackedStats.rdKarma)} tracked`} />+ <MetricBox icon={<CirclePlay />} label="YouTube likes" value={fmtNum(summary.ytLikes)} subtitle={`${fmtPercent(summary.likeShare.youtube)} of all likes`} />+ <MetricBox icon={<Camera />} label="Instagram likes" value={fmtNum(cacheTotals.igLikes)} subtitle={instagramLikesSubtitle(stats)} />+ </div>++ {totalLikes === 0 ? (+ <SurfaceBox>+ <EmptyState+ icon={<ThumbsUp />}+ title="No engagement data yet"+ description="Open a channel or account analytics page to load its likes, or track individual posts and videos."+ action={<Button size="sm" render={<Link to="/tracked-content" />}>Track content</Button>}+ />+ </SurfaceBox>+ ) : (+ <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">+ <SurfaceBox title="Karma by Reddit account" subheader="Post karma earned by each connected account">+ <MetricAreaChart data={charts.karmaByAccount} dataKey="karma" label="Post karma" color={PLATFORM_META.reddit.series} emptyMessage="Connect a Reddit account to see karma" />+ </SurfaceBox>+ <SurfaceBox title="Engagement by tracked content" subheader="YouTube likes and Reddit karma for the top 12 tracked items">+ <MetricAreaChart data={charts.engagementByContent} dataKey="engagement" label="Likes or karma" color={SERIES.primary} emptyMessage="Track content to compare engagement" />+ </SurfaceBox>+ </div>+ )}+ </>+ );+}diff --git a/frontend/src/features/analytics/overview/MetricTabsList.jsx b/frontend/src/features/analytics/overview/MetricTabsList.jsxnew file mode 100644index 0000000..7ba4ad7--- /dev/null+++ b/frontend/src/features/analytics/overview/MetricTabsList.jsx@@ -0,0 +1,23 @@+import { TabsList, TabsTrigger } from '@/components/ui/tabs';++export default function MetricTabsList({ tabs }) {+ return (+ <TabsList+ variant="none"+ aria-label="Overview metrics"+ className="grid w-full grid-cols-2 gap-3 sm:grid-cols-3 xl:grid-cols-6"+ >+ {tabs.map(tab => (+ <TabsTrigger+ key={tab.value}+ value={tab.value}+ className="h-auto min-w-0 flex-col items-start justify-start gap-1 rounded-card border border-line bg-surface-raised p-4 text-left after:hidden hover:border-line-strong/40 data-active:border-brand data-active:bg-brand-soft/40"+ >+ <span className="text-small font-medium text-ink-muted">{tab.label}</span>+ <span className="font-heading text-2xl font-semibold tracking-[-0.02em] text-ink tabular-nums">{tab.figure}</span>+ <span className="w-full truncate text-caption font-normal text-ink-faint">{tab.detail}</span>+ </TabsTrigger>+ ))}+ </TabsList>+ );+}diff --git a/frontend/src/features/analytics/overview/OpenAnalytics.jsx b/frontend/src/features/analytics/overview/OpenAnalytics.jsxnew file mode 100644index 0000000..eb183ad--- /dev/null+++ b/frontend/src/features/analytics/overview/OpenAnalytics.jsx@@ -0,0 +1,17 @@+import { useNavigate } from 'react-router-dom';+import { ArrowUpRight } from 'lucide-react';+import { Button } from '@/components/ui/button';+import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';+import { accountPath } from '@/lib/accounts';++export default function OpenAnalytics({ account, name }) {+ const navigate = useNavigate();+ return (+ <Tooltip>+ <TooltipTrigger render={<Button variant="ghost" size="icon-xs" onClick={() => navigate(accountPath(account))} aria-label={`Open analytics for ${name}`} />}>+ <ArrowUpRight />+ </TooltipTrigger>+ <TooltipContent>Open analytics</TooltipContent>+ </Tooltip>+ );+}diff --git a/frontend/src/features/analytics/overview/Overview.jsx b/frontend/src/features/analytics/overview/Overview.jsxindex d8b6b0d..d9e15e1 100644--- a/frontend/src/features/analytics/overview/Overview.jsx+++ b/frontend/src/features/analytics/overview/Overview.jsx@@ -1,806 +1,63 @@-import React, { useState, useEffect, useMemo } from 'react';-import { Link, useNavigate } from 'react-router-dom';-import {- AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip as ReTooltip, ResponsiveContainer,-} from 'recharts';-import {- RefreshCw, Users, VideoIcon, Camera, BarChart2, Eye, Tag, ThumbsUp, MessageSquare, CirclePlay,- MessagesSquare, BookmarkCheck, Bookmark, Send, Plus, PlaySquare, Scissors, Clapperboard, ArrowUpRight,-} from 'lucide-react';-import { Button } from '@/components/ui/button';-import { Badge } from '@/components/ui/badge';+import { useState } from '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 { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';-import PageHeader from '@/components/PageHeader';-import MetricBox from '@/components/MetricBox';-import SurfaceBox from '@/components/SurfaceBox';-import MetricAreaChart from '@/components/MetricAreaChart';-import ListRow, { RankNumber } from '@/components/ListRow';-import { EmptyState } from '@/components/StateViews';-import { AccountAvatar, PlatformBadge } from '@/components/platform';-import { PLATFORM_META, accountHandle, accountName, accountPath, platformOf, platformSummary } from '@/lib/accounts';-import { SERIES, axisProps, gridProps, tooltipStyle } from '@/lib/chart';+import { Tabs, TabsContent } from '@/components/ui/tabs';import { useAppContext } from '../../../context/AppContext';import { useAuth } from '../../../context/AuthContext';-import { api } from '../../../services/api';-import { fmtNum, fmtNumFull, fmtPercent, timeAgo } from '../../../utils/formatters';-import { trackedViews } from '../../../utils/trackedContent';-import { IG_CONTENT_TYPES, IG_CONTENT_TYPE_META } from '../../../utils/instagramContent';-import { cn } from '@/lib/utils';--const CATEGORY_SERIES = SERIES.neutral;-const SYNC_POLL_DELAYS = [4000, 8000, 16000];--function greeting(date = new Date()) {- const hour = date.getHours();- if (hour < 12) return 'Good morning';- if (hour < 18) return 'Good afternoon';- return 'Good evening';-}+import { metricTabsOf } from './overviewLabels.js';+import { useOverviewData } from './useOverviewData';+import { useOverviewStats } from './useOverviewStats';+import OverviewHeader from './OverviewHeader';+import QuickActions from './QuickActions';+import GettingStarted from './GettingStarted';+import MetricTabsList from './MetricTabsList';+import AudienceTab from './AudienceTab';+import ViewsTab from './ViewsTab';+import ContentTab from './ContentTab';+import AccountsTab from './AccountsTab';+import CommentsTab from './CommentsTab';+import LikesTab from './LikesTab';export default function Overview() {const { accounts, loading: accountsLoading, refreshAll } = useAppContext();const { user } = useAuth();- const navigate = useNavigate();const [activeTab, setActiveTab] = useState('audience');-- const [overviewData, setOverviewData] = useState({ tracked: [], analyticsCache: {} });- const [overviewLoading, setOverviewLoading] = useState(true);-- useEffect(() => {- api.getOverview()- .then(data => {- if (data && !data.error) setOverviewData(data);- })- .catch(() => {})- .finally(() => setOverviewLoading(false));- }, []);-- // The backend reports syncing: true for accounts whose analytics it started fetching in the- // background. Re-poll with backoff, and give up after a few tries so the label never hangs.- const [syncPolls, setSyncPolls] = useState(0);- const isSyncing = !overviewLoading && syncPolls < SYNC_POLL_DELAYS.length && accounts.some(a => {- return overviewData.analyticsCache[a.id]?.syncing === true;- });-- useEffect(() => {- if (!isSyncing) return undefined;- const timer = setTimeout(() => {- api.getOverview()- .then(data => { if (data && !data.error) setOverviewData(data); })- .catch(() => {})- .finally(() => setSyncPolls(n => n + 1));- }, SYNC_POLL_DELAYS[syncPolls]);- return () => clearTimeout(timer);- }, [isSyncing, syncPolls]);-+ const { overviewData, overviewLoading, isSyncing } = useOverviewData(accounts);+ const stats = useOverviewStats(accounts, overviewData);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');- const redditAccounts = accounts.filter(a => a.platform === 'reddit');-- // Account metadata totals- const totals = useMemo(() => accounts.reduce((acc, a) => {- if (a.platform === 'instagram') {- return { ...acc, followers: acc.followers + (a.followersCount || 0), posts: acc.posts + (a.mediaCount || 0) };- }- if (a.platform === 'reddit') {- return {- ...acc,- karma: acc.karma + (a.totalKarma || 0),- postKarma: acc.postKarma + (a.postKarma || 0),- commentKarma: acc.commentKarma + (a.commentKarma || 0),- };- }- return {- ...acc,- subscribers: acc.subscribers + (a.subscriberCount || 0),- views: acc.views + (a.viewCount || 0),- videos: acc.videos + (a.videoCount || 0),- };- }, { subscribers: 0, views: 0, videos: 0, followers: 0, posts: 0, karma: 0, postKarma: 0, commentKarma: 0 }), [accounts]);-- // 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, igViews: 0, rdPosts: 0, rdKarma: 0, rdComments: 0,- igTypes: Object.fromEntries(IG_CONTENT_TYPES.map(t => [t, { count: 0, views: 0 }])),- };- accounts.forEach(a => {- const c = analyticsCache[a.id];- if (!c) return;- if (a.platform === 'youtube') {- result.ytLikes += c.totalLikes ?? 0;- result.ytComments += c.totalComments ?? 0;- } else if (a.platform === 'instagram') {- result.igLikes += c.totalLikes ?? 0;- result.igComments += c.totalComments ?? 0;- result.igViews += c.totalViews ?? 0;- IG_CONTENT_TYPES.forEach(t => {- result.igTypes[t].count += c.contentTypes?.[t]?.count ?? 0;- result.igTypes[t].views += c.contentTypes?.[t]?.views ?? 0;- });- } else if (a.platform === 'reddit') {- result.rdPosts += c.fetchedPosts ?? 0;- result.rdKarma += c.totalScore ?? 0;- result.rdComments += c.totalComments ?? 0;- }- });- return result;- }, [accounts, analyticsCache]);-- // 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');- return {- total: trackedContent.length,- ytItems,- rdItems,- ytViews: ytItems.reduce((s, p) => s + trackedViews(p), 0),- ytLikes: ytItems.reduce((s, p) => s + (p.likeCount ?? 0), 0),- ytComments: ytItems.reduce((s, p) => s + (p.commentCount ?? 0), 0),- rdViews: rdItems.reduce((s, p) => s + trackedViews(p), 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 + 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 items- const totalContent = totals.videos + totals.posts + cacheTotals.rdPosts + trackedStats.total;-- // Total Views = YouTube channel views + Instagram reel, post, and video views + tracked views- const trackedViewTotal = trackedStats.ytViews + trackedStats.rdViews;- const totalViews = totals.views + cacheTotals.igViews + trackedViewTotal;- const igTypeSummary = (field) => IG_CONTENT_TYPES- .map(t => `${fmtNum(cacheTotals.igTypes[t][field])} ${IG_CONTENT_TYPE_META[t].plural.toLowerCase()}`)- .join(', ');- const igAccountRows = igAccounts- .map(a => ({ account: a, cache: analyticsCache[a.id] }))- .sort((x, y) => (y.cache?.totalViews ?? 0) - (x.cache?.totalViews ?? 0));-- // 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;-- // 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(() => {- const withCat = trackedContent.filter(p => p.category);- if (!withCat.length) return [];- const map = {};- withCat.forEach(p => {- if (!map[p.category]) {- map[p.category] = {- category: p.category,- count: 0, ytCount: 0, rdCount: 0,- ytViews: 0, ytLikes: 0, ytComments: 0,- rdViews: 0, rdKarma: 0, rdComments: 0,- };- }- const c = map[p.category];- c.count++;- if (p.contentType === 'youtube') {- c.ytCount++;- c.ytViews += trackedViews(p);- c.ytLikes += p.likeCount ?? 0;- c.ytComments += p.commentCount ?? 0;- } else {- c.rdCount++;- c.rdViews += trackedViews(p);- c.rdKarma += p.score ?? 0;- c.rdComments += p.numComments ?? 0;- }- });- return Object.values(map)- .map(c => ({ ...c, views: c.ytViews + c.rdViews }))- .sort((a, b) => (b.views + b.rdKarma) - (a.views + a.rdKarma));- }, [trackedContent]);-- // ── Audience metric per account ────────────────────────────────────────────────- function audienceMetric(a) {- if (a.platform === 'instagram') return a.followersCount || 0;- if (a.platform === 'reddit') return a.totalKarma || 0;- return a.subscriberCount || 0;- }-- function contentMetric(a) {- if (a.platform === 'instagram') return a.mediaCount || 0;- if (a.platform === 'reddit') return a.totalKarma || 0;- return a.viewCount || 0;- }-- const allSortedByAudience = [...accounts].sort((a, b) => audienceMetric(b) - audienceMetric(a));- const allSortedByContent = [...accounts].sort((a, b) => contentMetric(b) - contentMetric(a));-- // ── Chart data ────────────────────────────────────────────────────────────────- const audienceChartData = useMemo(() => [- ...ytAccounts.map(a => ({- name: (a.title || '').slice(0, 12) + ((a.title || '').length > 12 ? '…' : ''),- value: a.subscriberCount || 0,- type: 'youtube',- })),- ...igAccounts.map(a => ({- name: (a.title || a.username || '').slice(0, 12) + ((a.title || a.username || '').length > 12 ? '…' : ''),- value: a.followersCount || 0,- type: 'instagram',- })),- ...redditAccounts.map(a => ({- name: `u/${(a.username || '')}`.slice(0, 12),- value: a.totalKarma || 0,- type: 'reddit',- })),- // Karma only. Adding views would mix an audience metric with a reach metric and- // inflate the category far above the accounts it sits beside.- ...categoryStats.map(c => ({- name: c.category.slice(0, 12) + (c.category.length > 12 ? '…' : ''),- value: c.rdKarma,- type: 'category',- })),- ], [ytAccounts, igAccounts, redditAccounts, 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 categoryViewData = useMemo(() =>- categoryStats- .map(c => ({ name: c.category.slice(0, 16), views: c.views }))- .sort((a, b) => b.views - a.views),- [categoryStats]- );-- 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) {- navigate(accountPath(acc));- }-- const firstName = (user?.email || '').split('@')[0].split(/[._-]/)[0];- const greetingName = firstName ? firstName[0].toUpperCase() + firstName.slice(1) : '';-- const metricTabs = [- {- value: 'audience', label: 'Audience', value_: fmtNum(totalAudience),- detail: [- totals.subscribers ? `${fmtNum(totals.subscribers)} subscribers` : null,- totals.followers ? `${fmtNum(totals.followers)} followers` : null,- totals.karma ? `${fmtNum(totals.karma)} karma` : null,- ].filter(Boolean).join(', ') || 'No data yet',- },- {- value: 'views', label: 'Views', value_: fmtNum(totalViews),- detail: [- totals.views ? `${fmtNum(totals.views)} YouTube` : null,- cacheTotals.igViews ? `${fmtNum(cacheTotals.igViews)} Instagram` : null,- trackedViewTotal ? `${fmtNum(trackedViewTotal)} tracked` : null,- ].filter(Boolean).join(', ') || 'No views recorded yet',- },- {- value: 'content', label: 'Content', value_: fmtNum(totalContent),- detail: [- totals.videos ? `${fmtNum(totals.videos)} videos` : null,- totals.posts ? `${fmtNum(totals.posts)} Instagram` : null,- cacheTotals.rdPosts ? `${fmtNum(cacheTotals.rdPosts)} Reddit` : null,- trackedStats.total ? `${fmtNum(trackedStats.total)} tracked` : null,- ].filter(Boolean).join(', ') || 'No content yet',- },- { value: 'accounts', label: 'Accounts', value_: accounts.length, detail: platformSummary(accounts) },- {- value: 'comments', label: 'Comments', value_: fmtNum(totalComments),- detail: isSyncing ? 'Syncing analytics' : totalComments > 0 ? 'Across all platforms' : 'Open an analytics page to load',- },- {- value: 'likes', label: 'Likes', value_: fmtNum(totalLikes),- detail: isSyncing ? 'Syncing analytics' : totalLikes > 0 ? 'Across all platforms' : 'Open an analytics page to load',- },- ];-- const quickActions = [- { to: '/upload', label: 'Publish', icon: Send },- { to: '/accounts?add=1', label: 'Add account', icon: Plus },- { to: '/tracked-content', label: 'Track content', icon: Bookmark },- { to: '/videos', label: 'Videos', icon: PlaySquare },- { to: '/shorts', label: 'Shorts', icon: Scissors },- { to: '/reels', label: 'Instagram', icon: Clapperboard },- { to: '/reddit-posts', label: 'Reddit', icon: MessagesSquare },- ];-- const accountRow = (a, i, trailing) => (- <ListRow- key={a.id}- onClick={() => handleViewChannel(a)}- leading={<><RankNumber rank={i + 1} /><AccountAvatar account={a} showPlatform /></>}- title={accountName(a)}- meta={accountHandle(a)}- trailing={trailing}- />- );-- const categoryRow = (stat, trailing) => (- <ListRow- key={stat.category}- onClick={() => navigate(`/tracked-content/category/${encodeURIComponent(stat.category)}`)}- leading={<><span className="w-5 shrink-0" /><span className="flex size-8 items-center justify-center rounded-control bg-surface-sunken text-ink-muted"><Tag className="size-4 stroke-[1.75]" /></span></>}- title={stat.category}- meta={[`${stat.count} item${stat.count !== 1 ? 's' : ''}`, stat.ytCount > 0 && `${stat.ytCount} YouTube`, stat.rdCount > 0 && `${stat.rdCount} Reddit`].filter(Boolean).join(', ')}- trailing={trailing}- />- );-- const legend = [- ytAccounts.length ? { color: PLATFORM_META.youtube.series, label: 'YouTube subscribers' } : null,- igAccounts.length ? { color: PLATFORM_META.instagram.series, label: 'Instagram followers' } : null,- redditAccounts.length ? { color: PLATFORM_META.reddit.series, label: 'Reddit karma' } : null,- categoryStats.length ? { color: CATEGORY_SERIES, label: 'Category karma' } : null,- ].filter(Boolean);-return (<div className="flex flex-col gap-8">- <PageHeader- size="display"- title={greetingName ? `${greeting()}, ${greetingName}` : greeting()}- description={accounts.length === 0- ? 'Add your first account to start tracking.'- : `Tracking ${accounts.length} account${accounts.length !== 1 ? 's' : ''}: ${platformSummary(accounts)}.`}- actions={- <>- {isSyncing && (- <span className="flex items-center gap-1.5 text-small text-ink-muted" role="status">- <RefreshCw className="size-3.5 animate-spin" />- Syncing analytics- </span>- )}- <Button onClick={refreshAll} disabled={loading || accounts.length === 0} variant="outline">- <RefreshCw data-icon="inline-start" className={cn(loading && 'animate-spin')} />- {loading ? 'Refreshing' : 'Refresh all'}- </Button>- </>- }- />+ <OverviewHeader accounts={accounts} email={user?.email} isSyncing={isSyncing} loading={loading} onRefresh={refreshAll} />- <nav aria-label="Quick actions" className="grid grid-cols-4 gap-x-3 gap-y-5 sm:grid-cols-7">- {quickActions.map(action => {- const Icon = action.icon;- return (- <Link- key={action.to}- to={action.to}- className="group flex flex-col items-center gap-2 rounded-card py-2 text-center focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring"- >- <span className="flex size-12 items-center justify-center rounded-card bg-surface-wash text-ink-muted transition-colors duration-(--duration-base) group-hover:bg-surface-selected group-hover:text-ink">- <Icon className="size-5 stroke-[1.75]" />- </span>- <span className="text-small font-medium text-ink">{action.label}</span>- </Link>- );- })}- </nav>+ <QuickActions />{loading && <Progress value={null} aria-label="Loading accounts" />}{accounts.length === 0 ? (- <section className="relative overflow-hidden rounded-panel border border-line bg-surface-raised">- <div aria-hidden="true" className="fold-band absolute inset-y-0 right-0 hidden w-2/5 [clip-path:polygon(35%_0,100%_0,100%_100%,0_100%)] md:block" />- <div className="relative flex max-w-xl flex-col gap-4 p-8">- <p className="eyebrow text-brand-text">Getting started</p>- <h2 className="font-heading text-page-title font-semibold text-ink">Bring your channels into one picture.</h2>- <p className="text-sm text-ink-muted">Add a YouTube channel, connect an Instagram Business or Creator account, or add a Reddit profile. Analytics start filling in as soon as an account is added.</p>- <div><Button render={<Link to="/accounts?add=1" />}><Plus data-icon="inline-start" />Add an account</Button></div>- </div>- </section>+ <GettingStarted />) : (<Tabs value={activeTab} onValueChange={setActiveTab} className="gap-6">- <TabsList- variant="none"- aria-label="Overview metrics"- className="grid w-full grid-cols-2 gap-3 sm:grid-cols-3 xl:grid-cols-6"- >- {metricTabs.map(tab => (- <TabsTrigger- key={tab.value}- value={tab.value}- className="h-auto min-w-0 flex-col items-start justify-start gap-1 rounded-card border border-line bg-surface-raised p-4 text-left after:hidden hover:border-line-strong/40 data-active:border-brand data-active:bg-brand-soft/40"- >- <span className="text-small font-medium text-ink-muted">{tab.label}</span>- <span className="font-heading text-2xl font-semibold tracking-[-0.02em] text-ink tabular-nums">{tab.value_}</span>- <span className="w-full truncate text-caption font-normal text-ink-faint">{tab.detail}</span>- </TabsTrigger>- ))}- </TabsList>-+ <MetricTabsList tabs={metricTabsOf(accounts, stats, isSyncing)} /><TabsContent value="audience" className="flex flex-col gap-4">- <SurfaceBox title="Audience by account" subheader="Subscribers, followers and karma, plus karma earned by each tracked category">- {audienceChartData.length === 0 ? (- <EmptyState compact icon={<Users />} title="No audience data yet" description="Refresh your accounts to load subscriber and follower counts." />- ) : (- <>- <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(--chart-1)" stopOpacity={0.22} />- <stop offset="95%" stopColor="var(--chart-1)" stopOpacity={0} />- </linearGradient>- </defs>- <CartesianGrid {...gridProps} vertical={false} />- <XAxis dataKey="name" {...axisProps} />- <YAxis {...axisProps} tickFormatter={fmtNum} width={48} />- <ReTooltip- contentStyle={tooltipStyle}- cursor={{ stroke: 'var(--line-strong)' }}- formatter={(v, name, props) => [fmtNumFull(v), props.payload.type === 'category' ? 'Karma' : 'Audience']}- />- <Area- type="monotone"- dataKey="value"- stroke="var(--chart-1)"- strokeWidth={2}- fill="url(#audienceAreaGrad)"- dot={({ cx, cy, payload, index }) => (- <circle- key={`dot-${index}`}- cx={cx}- cy={cy}- r={4.5}- fill={payload.type === 'category' ? CATEGORY_SERIES : PLATFORM_META[payload.type]?.series}- stroke="var(--surface-raised)"- strokeWidth={2}- />- )}- activeDot={{ r: 6 }}- />- </AreaChart>- </ResponsiveContainer>- <ul className="mt-3 flex flex-wrap gap-x-4 gap-y-1.5">- {legend.map(({ color, label }) => (- <li key={label} className="flex items-center gap-1.5 text-caption text-ink-muted">- <span className="size-2.5 shrink-0 rounded-full" style={{ background: color }} />- {label}- </li>- ))}- </ul>- </>- )}- </SurfaceBox>-- <SurfaceBox title="Top by audience" contentClassName="px-2 py-2">- <div className="flex flex-col">- {allSortedByAudience.map((a, i) => accountRow(a, i, <PlatformBadge platform={platformOf(a)} />))}- {categoryStats.map(stat => categoryRow(stat, <Badge variant="outline">Category</Badge>))}- </div>- </SurfaceBox>+ <AudienceTab stats={stats} /></TabsContent>-<TabsContent value="views" className="flex flex-col gap-4">- <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-4">- <MetricBox icon={<Eye />} label="Total views" value={fmtNum(totalViews)} subtitle="YouTube, Instagram and tracked content" highlight />- <MetricBox icon={<CirclePlay />} label="Channel views" value={fmtNum(totals.views)} subtitle={`${ytAccounts.length} YouTube channel${ytAccounts.length !== 1 ? 's' : ''}`} />- <MetricBox icon={<Camera />} label="Instagram views" value={fmtNum(cacheTotals.igViews)} subtitle={igAccounts.length > 0 ? igTypeSummary('views') : 'No Instagram accounts'} />- <MetricBox icon={<BookmarkCheck />} label="Tracked views" value={fmtNum(trackedViewTotal)} subtitle={`${fmtNum(trackedStats.ytViews)} YouTube, ${fmtNum(trackedStats.rdViews)} Reddit`} />- </div>-- {igAccounts.length > 0 && (- <SurfaceBox title="Instagram views by content type" content={false} className="overflow-hidden">- <Table>- <TableHeader>- <TableRow>- <TableHead>Account</TableHead>- {IG_CONTENT_TYPES.map(t => (- <TableHead key={t} className="text-right">{IG_CONTENT_TYPE_META[t].plural}</TableHead>- ))}- <TableHead className="text-right">Total views</TableHead>- <TableHead className="w-10"><span className="sr-only">Open</span></TableHead>- </TableRow>- </TableHeader>- <TableBody>- {igAccountRows.map(({ account: a, cache }) => (- <TableRow key={a.id}>- <TableCell>- <div className="flex items-center gap-2.5">- <AccountAvatar account={a} />- <div>- <p className="text-sm font-medium text-ink">{accountName(a)}</p>- <p className="text-caption text-ink-faint">{accountHandle(a)}</p>- </div>- </div>- </TableCell>- {IG_CONTENT_TYPES.map(t => (- <TableCell key={t} className="text-right">- {cache?.cacheWarmed ? (- <>- <p className="text-sm font-medium text-ink">{fmtNum(cache.contentTypes?.[t]?.views)}</p>- <p className="text-caption text-ink-faint">{fmtNum(cache.contentTypes?.[t]?.count)} {IG_CONTENT_TYPE_META[t].plural.toLowerCase()}</p>- </>- ) : <span className="text-ink-faint">-</span>}- </TableCell>- ))}- <TableCell className="text-right font-semibold text-ink">- {cache?.cacheWarmed ? fmtNum(cache.totalViews) : <span className="font-normal text-ink-faint">{isSyncing ? 'Syncing' : '-'}</span>}- </TableCell>- <TableCell>- <OpenAnalytics onClick={() => handleViewChannel(a)} name={accountName(a)} />- </TableCell>- </TableRow>- ))}- </TableBody>- </Table>- </SurfaceBox>- )}-- {categoryStats.length > 0 && (- <SurfaceBox title="Views by category" subheader="YouTube video views plus Reddit post views entered by hand">- <MetricAreaChart data={categoryViewData} dataKey="views" label="Views" color={SERIES.cool} emptyMessage="No views recorded for these categories yet" />- </SurfaceBox>- )}-- {ytAccounts.length > 0 && (- <SurfaceBox title="YouTube views by channel" content={false} className="overflow-hidden">- <Table>- <TableHeader>- <TableRow>- <TableHead className="w-10 text-right">#</TableHead>- <TableHead>Channel</TableHead>- <TableHead className="text-right">Total views</TableHead>- <TableHead className="text-right">Subscribers</TableHead>- <TableHead className="text-right">Videos</TableHead>- <TableHead className="text-right">Updated</TableHead>- <TableHead className="w-10"><span className="sr-only">Open</span></TableHead>- </TableRow>- </TableHeader>- <TableBody>- {[...ytAccounts].sort((a, b) => (b.viewCount || 0) - (a.viewCount || 0)).map((a, i) => (- <TableRow key={a.id}>- <TableCell className="text-right"><RankNumber rank={i + 1} className="w-auto" /></TableCell>- <TableCell>- <div className="flex items-center gap-2.5">- <AccountAvatar account={a} />- <div>- <p className="text-sm font-medium text-ink">{a.title}</p>- <p className="text-caption text-ink-faint">{accountHandle(a)}</p>- </div>- </div>- </TableCell>- <TableCell className="text-right">- <p className="font-semibold text-ink">{fmtNum(a.viewCount)}</p>- <p className="text-caption text-ink-faint">{fmtNumFull(a.viewCount)}</p>- </TableCell>- <TableCell className="text-right text-ink-muted">{fmtNum(a.subscriberCount)}</TableCell>- <TableCell className="text-right text-ink-muted">{fmtNum(a.videoCount)}</TableCell>- <TableCell className="text-right text-small text-ink-faint">{timeAgo(a.lastUpdated)}</TableCell>- <TableCell><OpenAnalytics onClick={() => handleViewChannel(a)} name={a.title} /></TableCell>- </TableRow>- ))}- </TableBody>- </Table>- </SurfaceBox>- )}+ <ViewsTab stats={stats} isSyncing={isSyncing} /></TabsContent>-<TabsContent value="content" className="flex flex-col gap-4">- <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">- <MetricBox icon={<CirclePlay />} label="YouTube videos" value={fmtNum(totals.videos)} subtitle={`${ytAccounts.length} channel${ytAccounts.length !== 1 ? 's' : ''}`} />- <MetricBox icon={<VideoIcon />} label="Instagram content" value={fmtNum(totals.posts)} subtitle={IG_CONTENT_TYPES.some(t => cacheTotals.igTypes[t].count > 0) ? igTypeSummary('count') : `${igAccounts.length} account${igAccounts.length !== 1 ? 's' : ''}`} />- <MetricBox icon={<MessagesSquare />} label="Reddit posts" value={fmtNum(cacheTotals.rdPosts)} subtitle={cacheTotals.rdPosts > 0 ? 'From the analytics cache' : 'Open Reddit analytics to load'} />- <MetricBox icon={<BookmarkCheck />} label="Tracked content" value={fmtNum(trackedStats.total)} subtitle={`${trackedStats.ytItems.length} YouTube, ${trackedStats.rdItems.length} Reddit`} />- </div>-- <div className="grid grid-cols-1 gap-4 md:grid-cols-2">- <SurfaceBox title="Top by content" contentClassName="px-2 py-2">- <div className="flex flex-col">- {allSortedByContent.map((a, i) => accountRow(a, i, (- <span className="font-medium text-ink-muted">- {platformOf(a) === 'instagram' ? `${fmtNum(a.mediaCount)} items`- : platformOf(a) === 'reddit' ? `${fmtNum(a.totalKarma)} karma`- : `${fmtNum(a.viewCount)} views`}- </span>- )))}- </div>- </SurfaceBox>-- <SurfaceBox title="Tracked categories" contentClassName="px-2 py-2">- {categoryStats.length === 0 ? (- <EmptyState- compact- icon={<Tag />}- title="No categories yet"- description="Assign categories to tracked content to see this breakdown."- action={<Button size="sm" variant="outline" render={<Link to="/tracked-content" />}>Open tracked content</Button>}- />- ) : (- <div className="flex flex-col">- {categoryStats.map(stat => categoryRow(stat, (- <span className="flex flex-col items-end gap-0.5 text-caption">- {stat.views > 0 && <span className="font-medium text-ink">{fmtNum(stat.views)} views</span>}- {stat.rdCount > 0 && <span className="text-ink-faint">{fmtNum(stat.rdKarma)} karma</span>}- </span>- )))}- </div>- )}- </SurfaceBox>- </div>+ <ContentTab stats={stats} /></TabsContent>-<TabsContent value="accounts" className="flex flex-col gap-4">- <SurfaceBox content={false} className="overflow-hidden">- <Table>- <TableHeader>- <TableRow>- <TableHead className="w-10 text-right">#</TableHead>- <TableHead>Account</TableHead>- <TableHead>Platform</TableHead>- <TableHead className="text-right">Audience</TableHead>- <TableHead className="text-right">Content</TableHead>- <TableHead className="text-right">Updated</TableHead>- <TableHead className="w-10"><span className="sr-only">Open</span></TableHead>- </TableRow>- </TableHeader>- <TableBody>- {allSortedByAudience.map((a, i) => {- const platform = platformOf(a);- const audience = platform === 'instagram' ? `${fmtNum(a.followersCount)} followers`- : platform === 'reddit' ? `${fmtNum(a.totalKarma)} karma`- : `${fmtNum(a.subscriberCount)} subscribers`;- const content = platform === 'instagram' ? `${fmtNum(a.mediaCount)} items`- : platform === 'reddit' ? `${fmtNum(a.postKarma)} post karma`- : `${fmtNum(a.viewCount)} views, ${fmtNum(a.videoCount)} videos`;- return (- <TableRow key={a.id}>- <TableCell className="text-right"><RankNumber rank={i + 1} className="w-auto" /></TableCell>- <TableCell>- <div className="flex items-center gap-2.5">- <AccountAvatar account={a} />- <div>- <p className="text-sm font-medium text-ink">{accountName(a)}</p>- <p className="text-caption text-ink-faint">{accountHandle(a)}</p>- </div>- </div>- </TableCell>- <TableCell><PlatformBadge platform={platform} /></TableCell>- <TableCell className="text-right text-ink">{audience}</TableCell>- <TableCell className="text-right text-ink-muted">{content}</TableCell>- <TableCell className="text-right text-small text-ink-faint">{timeAgo(a.lastUpdated)}</TableCell>- <TableCell><OpenAnalytics onClick={() => handleViewChannel(a)} name={accountName(a)} /></TableCell>- </TableRow>- );- })}- </TableBody>- </Table>- </SurfaceBox>+ <AccountsTab accounts={stats.byAudience} /></TabsContent>-<TabsContent value="comments" className="flex flex-col gap-4">- <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-4">- <MetricBox icon={<MessageSquare />} label="Total comments" value={fmtNum(totalComments)} subtitle={totalComments > 0 ? 'Across all platforms' : 'Open an analytics page to load'} highlight />- <MetricBox icon={<CirclePlay />} label="YouTube comments" value={fmtNum(ytComments)} subtitle={`${fmtPercent(commentShare.youtube)} of all comments`} />- <MetricBox icon={<MessagesSquare />} label="Reddit comments" value={fmtNum(rdComments)} subtitle={`${fmtPercent(commentShare.reddit)} of all comments`} />- <MetricBox icon={<BarChart2 />} label="Comments per item" value={fmtNum(avgCommentsPerContent)} subtitle={`Average across ${fmtNum(totalContent)} item${totalContent !== 1 ? 's' : ''}`} />- </div>-- {totalComments === 0 ? (- <SurfaceBox>- <EmptyState- icon={<MessageSquare />}- title="No comment data yet"- description="Open a channel or account analytics page to load its comments, or track individual posts and videos."- action={<Button size="sm" render={<Link to="/tracked-content" />}>Track content</Button>}- />- </SurfaceBox>- ) : (- <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">- <SurfaceBox title="Comments by tracked content" subheader="Top 12 tracked items ranked by comments">- <MetricAreaChart data={commentByContentData} dataKey="comments" label="Comments" color={SERIES.cool} emptyMessage="Track content to compare comment volume" />- </SurfaceBox>- <SurfaceBox title="Comments by category" subheader="Total comments across every item in each category">- <MetricAreaChart data={commentByCategoryData} dataKey="comments" label="Comments" color={SERIES.warm} emptyMessage="Assign categories to tracked content to see this breakdown" />- </SurfaceBox>- </div>- )}+ <CommentsTab stats={stats} /></TabsContent>-<TabsContent value="likes" className="flex flex-col gap-4">- <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-4">- <MetricBox icon={<ThumbsUp />} label="Total likes" value={fmtNum(totalLikes)} subtitle={totalLikes > 0 ? 'YouTube likes, Instagram likes, Reddit karma' : 'Open an analytics page to load'} highlight />- <MetricBox icon={<MessagesSquare />} label="Reddit karma" value={fmtNum(redditKarma)} subtitle={`${fmtNum(totals.postKarma)} account, ${fmtNum(trackedStats.rdKarma)} tracked`} />- <MetricBox icon={<CirclePlay />} label="YouTube likes" value={fmtNum(ytLikes)} subtitle={`${fmtPercent(likeShare.youtube)} of all likes`} />- <MetricBox icon={<Camera />} label="Instagram likes" value={fmtNum(cacheTotals.igLikes)} subtitle={igAccounts.length > 0 ? `${fmtPercent(likeShare.instagram)} of all likes` : 'No Instagram accounts'} />- </div>-- {totalLikes === 0 ? (- <SurfaceBox>- <EmptyState- icon={<ThumbsUp />}- title="No engagement data yet"- description="Open a channel or account analytics page to load its likes, or track individual posts and videos."- action={<Button size="sm" render={<Link to="/tracked-content" />}>Track content</Button>}- />- </SurfaceBox>- ) : (- <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">- <SurfaceBox title="Karma by Reddit account" subheader="Post karma earned by each connected account">- <MetricAreaChart data={karmaByAccountData} dataKey="karma" label="Post karma" color={PLATFORM_META.reddit.series} emptyMessage="Connect a Reddit account to see karma" />- </SurfaceBox>- <SurfaceBox title="Engagement by tracked content" subheader="YouTube likes and Reddit karma for the top 12 tracked items">- <MetricAreaChart data={engagementByContentData} dataKey="engagement" label="Likes or karma" color={SERIES.primary} emptyMessage="Track content to compare engagement" />- </SurfaceBox>- </div>- )}+ <LikesTab stats={stats} /></TabsContent></Tabs>)}</div>);}--function OpenAnalytics({ onClick, name }) {- return (- <Tooltip>- <TooltipTrigger render={<Button variant="ghost" size="icon-xs" onClick={onClick} aria-label={`Open analytics for ${name}`} />}>- <ArrowUpRight />- </TooltipTrigger>- <TooltipContent>Open analytics</TooltipContent>- </Tooltip>- );-}diff --git a/frontend/src/features/analytics/overview/OverviewHeader.jsx b/frontend/src/features/analytics/overview/OverviewHeader.jsxnew file mode 100644index 0000000..562be89--- /dev/null+++ b/frontend/src/features/analytics/overview/OverviewHeader.jsx@@ -0,0 +1,30 @@+import { RefreshCw } from 'lucide-react';+import { Button } from '@/components/ui/button';+import PageHeader from '@/components/PageHeader';+import { cn } from '@/lib/utils';+import { greetingTitle } from './greeting.js';+import { overviewDescription } from './overviewLabels.js';++export default function OverviewHeader({ accounts, email, isSyncing, loading, onRefresh }) {+ return (+ <PageHeader+ size="display"+ title={greetingTitle(email)}+ description={overviewDescription(accounts)}+ actions={+ <>+ {isSyncing && (+ <span className="flex items-center gap-1.5 text-small text-ink-muted" role="status">+ <RefreshCw className="size-3.5 animate-spin" />+ Syncing analytics+ </span>+ )}+ <Button onClick={onRefresh} disabled={loading || accounts.length === 0} variant="outline">+ <RefreshCw data-icon="inline-start" className={cn(loading && 'animate-spin')} />+ {loading ? 'Refreshing' : 'Refresh all'}+ </Button>+ </>+ }+ />+ );+}diff --git a/frontend/src/features/analytics/overview/QuickActions.jsx b/frontend/src/features/analytics/overview/QuickActions.jsxnew file mode 100644index 0000000..982bca0--- /dev/null+++ b/frontend/src/features/analytics/overview/QuickActions.jsx@@ -0,0 +1,34 @@+import { Link } from 'react-router-dom';+import { Bookmark, Clapperboard, MessagesSquare, PlaySquare, Plus, Scissors, Send } from 'lucide-react';++const QUICK_ACTIONS = [+ { to: '/upload', label: 'Publish', icon: Send },+ { to: '/accounts?add=1', label: 'Add account', icon: Plus },+ { to: '/tracked-content', label: 'Track content', icon: Bookmark },+ { to: '/videos', label: 'Videos', icon: PlaySquare },+ { to: '/shorts', label: 'Shorts', icon: Scissors },+ { to: '/reels', label: 'Instagram', icon: Clapperboard },+ { to: '/reddit-posts', label: 'Reddit', icon: MessagesSquare },+];++export default function QuickActions() {+ return (+ <nav aria-label="Quick actions" className="grid grid-cols-4 gap-x-3 gap-y-5 sm:grid-cols-7">+ {QUICK_ACTIONS.map(action => {+ const Icon = action.icon;+ return (+ <Link+ key={action.to}+ to={action.to}+ className="group flex flex-col items-center gap-2 rounded-card py-2 text-center focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring"+ >+ <span className="flex size-12 items-center justify-center rounded-card bg-surface-wash text-ink-muted transition-colors duration-(--duration-base) group-hover:bg-surface-selected group-hover:text-ink">+ <Icon className="size-5 stroke-[1.75]" />+ </span>+ <span className="text-small font-medium text-ink">{action.label}</span>+ </Link>+ );+ })}+ </nav>+ );+}diff --git a/frontend/src/features/analytics/overview/ViewsTab.jsx b/frontend/src/features/analytics/overview/ViewsTab.jsxnew file mode 100644index 0000000..483c4f2--- /dev/null+++ b/frontend/src/features/analytics/overview/ViewsTab.jsx@@ -0,0 +1,38 @@+import { BookmarkCheck, Camera, CirclePlay, Eye } from 'lucide-react';+import SurfaceBox from '@/components/SurfaceBox';+import MetricBox from '@/components/MetricBox';+import MetricAreaChart from '@/components/MetricAreaChart';+import { SERIES } from '@/lib/chart';+import { fmtNum } from '../../../utils/formatters';+import { countLabel, igTypeSummary } from './overviewLabels.js';+import InstagramViewsTable from './InstagramViewsTable';+import YouTubeViewsTable from './YouTubeViewsTable';++function instagramViewsSubtitle(stats) {+ if (stats.groups.instagram.length > 0) return igTypeSummary(stats.cacheTotals.igTypes, 'views');+ return 'No Instagram accounts';+}++export default function ViewsTab({ stats, isSyncing }) {+ const { groups, totals, cacheTotals, trackedStats, summary } = stats;+ return (+ <>+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-4">+ <MetricBox icon={<Eye />} label="Total views" value={fmtNum(summary.totalViews)} subtitle="YouTube, Instagram and tracked content" highlight />+ <MetricBox icon={<CirclePlay />} label="Channel views" value={fmtNum(totals.views)} subtitle={countLabel(groups.youtube.length, 'YouTube channel')} />+ <MetricBox icon={<Camera />} label="Instagram views" value={fmtNum(cacheTotals.igViews)} subtitle={instagramViewsSubtitle(stats)} />+ <MetricBox icon={<BookmarkCheck />} label="Tracked views" value={fmtNum(summary.trackedViewTotal)} subtitle={`${fmtNum(trackedStats.ytViews)} YouTube, ${fmtNum(trackedStats.rdViews)} Reddit`} />+ </div>++ {groups.instagram.length > 0 && <InstagramViewsTable rows={stats.igAccountRows} isSyncing={isSyncing} />}++ {stats.categoryStats.length > 0 && (+ <SurfaceBox title="Views by category" subheader="YouTube video views plus Reddit post views entered by hand">+ <MetricAreaChart data={stats.charts.categoryViews} dataKey="views" label="Views" color={SERIES.cool} emptyMessage="No views recorded for these categories yet" />+ </SurfaceBox>+ )}++ {groups.youtube.length > 0 && <YouTubeViewsTable accounts={stats.byChannelViews} />}+ </>+ );+}diff --git a/frontend/src/features/analytics/overview/YouTubeViewsTable.jsx b/frontend/src/features/analytics/overview/YouTubeViewsTable.jsxnew file mode 100644index 0000000..a8eb56f--- /dev/null+++ b/frontend/src/features/analytics/overview/YouTubeViewsTable.jsx@@ -0,0 +1,42 @@+import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';+import SurfaceBox from '@/components/SurfaceBox';+import { RankNumber } from '@/components/ListRow';+import { fmtNum, fmtNumFull, timeAgo } from '../../../utils/formatters';+import AccountCell from './AccountCell';+import OpenAnalytics from './OpenAnalytics';++export default function YouTubeViewsTable({ accounts }) {+ return (+ <SurfaceBox title="YouTube views by channel" content={false} className="overflow-hidden">+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead className="w-10 text-right">#</TableHead>+ <TableHead>Channel</TableHead>+ <TableHead className="text-right">Total views</TableHead>+ <TableHead className="text-right">Subscribers</TableHead>+ <TableHead className="text-right">Videos</TableHead>+ <TableHead className="text-right">Updated</TableHead>+ <TableHead className="w-10"><span className="sr-only">Open</span></TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {accounts.map((account, i) => (+ <TableRow key={account.id}>+ <TableCell className="text-right"><RankNumber rank={i + 1} className="w-auto" /></TableCell>+ <AccountCell account={account} name={account.title} />+ <TableCell className="text-right">+ <p className="font-semibold text-ink">{fmtNum(account.viewCount)}</p>+ <p className="text-caption text-ink-faint">{fmtNumFull(account.viewCount)}</p>+ </TableCell>+ <TableCell className="text-right text-ink-muted">{fmtNum(account.subscriberCount)}</TableCell>+ <TableCell className="text-right text-ink-muted">{fmtNum(account.videoCount)}</TableCell>+ <TableCell className="text-right text-small text-ink-faint">{timeAgo(account.lastUpdated)}</TableCell>+ <TableCell><OpenAnalytics account={account} name={account.title} /></TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>+ </SurfaceBox>+ );+}diff --git a/frontend/src/features/analytics/overview/greeting.js b/frontend/src/features/analytics/overview/greeting.jsnew file mode 100644index 0000000..bd0b95a--- /dev/null+++ b/frontend/src/features/analytics/overview/greeting.js@@ -0,0 +1,21 @@+// overview header greeting; no JSX or path aliases so node --test can import it++export function greeting(date = new Date()) {+ const hour = date.getHours();+ if (hour < 12) return 'Good morning';+ if (hour < 18) return 'Good afternoon';+ return 'Good evening';+}++// first part of the email's local name, so "[email protected]" greets "Jane"+export function greetingName(email) {+ const firstName = (email || '').split('@')[0].split(/[._-]/)[0];+ if (!firstName) return '';+ return firstName[0].toUpperCase() + firstName.slice(1);+}++export function greetingTitle(email, date = new Date()) {+ const name = greetingName(email);+ if (!name) return greeting(date);+ return `${greeting(date)}, ${name}`;+}diff --git a/frontend/src/features/analytics/overview/greeting.test.js b/frontend/src/features/analytics/overview/greeting.test.jsnew file mode 100644index 0000000..905a69c--- /dev/null+++ b/frontend/src/features/analytics/overview/greeting.test.js@@ -0,0 +1,27 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { greeting, greetingName, greetingTitle } from './greeting.js';++const atHour = hour => new Date(2026, 0, 1, hour, 30);++test('greeting follows the time of day', () => {+ assert.equal(greeting(atHour(6)), 'Good morning');+ assert.equal(greeting(atHour(11)), 'Good morning');+ assert.equal(greeting(atHour(12)), 'Good afternoon');+ assert.equal(greeting(atHour(17)), 'Good afternoon');+ assert.equal(greeting(atHour(18)), 'Good evening');+});++test('greeting name is the capitalised first part of the email', () => {+ assert.equal(greetingName('[email protected]'), 'Jane');+ assert.equal(greetingName('[email protected]'), 'Sam');+ assert.equal(greetingName('[email protected]'), 'Ox');+ assert.equal(greetingName(''), '');+ assert.equal(greetingName(undefined), '');+ assert.equal(greetingName('[email protected]'), '');+});++test('greeting title adds the name only when there is one', () => {+ assert.equal(greetingTitle('[email protected]', atHour(9)), 'Good morning, Jane');+ assert.equal(greetingTitle(undefined, atHour(20)), 'Good evening');+});diff --git a/frontend/src/features/analytics/overview/overviewCharts.js b/frontend/src/features/analytics/overview/overviewCharts.jsnew file mode 100644index 0000000..1f3db00--- /dev/null+++ b/frontend/src/features/analytics/overview/overviewCharts.js@@ -0,0 +1,94 @@+// overview chart rows and legend; no JSX or path aliases so node --test can import it++import { PLATFORM_META } from '../../../lib/accounts.js';+import { SERIES } from '../../../lib/chart.js';++export const CATEGORY_SERIES = SERIES.neutral;++const CHART_ITEMS = 12;++function shortName(text, max) {+ return text.slice(0, max) + (text.length > max ? '…' : '');+}++function itemName(item) {+ return (item.title || item.label || item.url || '').slice(0, 16);+}++// karma only for categories: adding views would mix reach into an audience chart+export function audienceChartDataOf(groups, categoryStats) {+ return [+ ...groups.youtube.map(account => ({+ name: shortName(account.title || '', 12),+ value: account.subscriberCount || 0,+ type: 'youtube',+ })),+ ...groups.instagram.map(account => ({+ name: shortName(account.title || account.username || '', 12),+ value: account.followersCount || 0,+ type: 'instagram',+ })),+ ...groups.reddit.map(account => ({+ name: `u/${(account.username || '')}`.slice(0, 12),+ value: account.totalKarma || 0,+ type: 'reddit',+ })),+ ...categoryStats.map(stat => ({+ name: shortName(stat.category, 12),+ value: stat.rdKarma,+ type: 'category',+ })),+ ];+}++export function audienceLegendOf(groups, categoryStats) {+ return [+ groups.youtube.length ? { color: PLATFORM_META.youtube.series, label: 'YouTube subscribers' } : null,+ groups.instagram.length ? { color: PLATFORM_META.instagram.series, label: 'Instagram followers' } : null,+ groups.reddit.length ? { color: PLATFORM_META.reddit.series, label: 'Reddit karma' } : null,+ categoryStats.length ? { color: CATEGORY_SERIES, label: 'Category karma' } : null,+ ].filter(Boolean);+}++export function audienceDotColor(type) {+ if (type === 'category') return CATEGORY_SERIES;+ return PLATFORM_META[type]?.series;+}++export function commentByContentOf(trackedContent) {+ return trackedContent+ .map(item => ({+ name: itemName(item),+ comments: item.contentType === 'youtube' ? (item.commentCount ?? 0) : (item.numComments ?? 0),+ }))+ .sort((a, b) => b.comments - a.comments)+ .slice(0, CHART_ITEMS);+}++export function engagementByContentOf(trackedContent) {+ return trackedContent+ .map(item => ({+ name: itemName(item),+ engagement: item.contentType === 'youtube' ? (item.likeCount ?? 0) : (item.score ?? 0),+ }))+ .sort((a, b) => b.engagement - a.engagement)+ .slice(0, CHART_ITEMS);+}++export function categoryViewDataOf(categoryStats) {+ return categoryStats+ .map(stat => ({ name: stat.category.slice(0, 16), views: stat.views }))+ .sort((a, b) => b.views - a.views);+}++export function commentByCategoryOf(categoryStats) {+ return categoryStats+ .map(stat => ({ name: stat.category.slice(0, 16), comments: stat.ytComments + stat.rdComments }))+ .sort((a, b) => b.comments - a.comments);+}++export function karmaByAccountOf(redditAccounts) {+ return [...redditAccounts]+ .sort((a, b) => (b.postKarma || 0) - (a.postKarma || 0))+ .map(account => ({ name: `u/${account.username || ''}`.slice(0, 16), karma: account.postKarma || 0 }));+}diff --git a/frontend/src/features/analytics/overview/overviewCharts.test.js b/frontend/src/features/analytics/overview/overviewCharts.test.jsnew file mode 100644index 0000000..31a5324--- /dev/null+++ b/frontend/src/features/analytics/overview/overviewCharts.test.js@@ -0,0 +1,50 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import {+ CATEGORY_SERIES, audienceChartDataOf, audienceLegendOf, audienceDotColor, commentByContentOf, engagementByContentOf,+ categoryViewDataOf, commentByCategoryOf, karmaByAccountOf,+} from './overviewCharts.js';++const groups = {+ youtube: [{ title: 'A channel with a long name', subscriberCount: 10 }],+ instagram: [{ username: 'fold', followersCount: 5 }],+ reddit: [{ username: 'averyverylongname', totalKarma: 3, postKarma: 2 }, { username: 'b', postKarma: 9 }],+};+const categoryStats = [{ category: 'Technology news', rdKarma: 4, views: 10, ytComments: 1, rdComments: 2 }];++test('audience chart shortens names and keeps category karma only', () => {+ assert.deepEqual(audienceChartDataOf(groups, categoryStats), [+ { name: 'A channel wi…', value: 10, type: 'youtube' },+ { name: 'fold', value: 5, type: 'instagram' },+ { name: 'u/averyveryl', value: 3, type: 'reddit' },+ { name: 'u/b', value: 0, type: 'reddit' },+ { name: 'Technology n…', value: 4, type: 'category' },+ ]);+});++test('legend lists only platforms with data', () => {+ const labels = audienceLegendOf({ youtube: [], instagram: [{}], reddit: [] }, []).map(item => item.label);+ assert.deepEqual(labels, ['Instagram followers']);+ assert.equal(audienceDotColor('category'), CATEGORY_SERIES);+ assert.equal(audienceDotColor('reddit'), 'var(--chart-4)');+});++test('tracked content charts rank the top items', () => {+ const tracked = [+ { contentType: 'youtube', title: 'Video', commentCount: 3, likeCount: 8 },+ { url: 'https://reddit.com/r/x/comments/abc', numComments: 7, score: 1 },+ ];+ assert.deepEqual(commentByContentOf(tracked), [+ { name: 'https://reddit.c', comments: 7 },+ { name: 'Video', comments: 3 },+ ]);+ assert.deepEqual(engagementByContentOf(tracked).map(row => row.engagement), [8, 1]);+ const many = Array.from({ length: 20 }, (_, i) => ({ title: `Post ${i}`, numComments: i }));+ assert.equal(commentByContentOf(many).length, 12);+});++test('category and karma charts', () => {+ assert.deepEqual(categoryViewDataOf(categoryStats), [{ name: 'Technology news', views: 10 }]);+ assert.deepEqual(commentByCategoryOf(categoryStats), [{ name: 'Technology news', comments: 3 }]);+ assert.deepEqual(karmaByAccountOf(groups.reddit), [{ name: 'u/b', karma: 9 }, { name: 'u/averyverylongn', karma: 2 }]);+});diff --git a/frontend/src/features/analytics/overview/overviewLabels.js b/frontend/src/features/analytics/overview/overviewLabels.jsnew file mode 100644index 0000000..9b63b6a--- /dev/null+++ b/frontend/src/features/analytics/overview/overviewLabels.js@@ -0,0 +1,102 @@+// overview tab details and row labels; no JSX or path aliases so node --test can import it++import { platformOf, platformSummary } from '../../../lib/accounts.js';+import { fmtNum } from '../../../utils/formatters.js';+import { IG_CONTENT_TYPES, IG_CONTENT_TYPE_META } from '../../../utils/instagramContent.js';++export function pluralWord(count, word) {+ if (count !== 1) return `${word}s`;+ return word;+}++export function countLabel(count, word) {+ return `${count} ${pluralWord(count, word)}`;+}++export function overviewDescription(accounts) {+ if (accounts.length === 0) return 'Add your first account to start tracking.';+ return `Tracking ${countLabel(accounts.length, 'account')}: ${platformSummary(accounts)}.`;+}++function detailOf(parts, fallback) {+ return parts.filter(Boolean).join(', ') || fallback;+}++function partOf(value, suffix) {+ return value ? `${fmtNum(value)} ${suffix}` : null;+}++export function syncDetail(isSyncing, total) {+ if (isSyncing) return 'Syncing analytics';+ if (total > 0) return 'Across all platforms';+ return 'Open an analytics page to load';+}++export function metricTabsOf(accounts, stats, isSyncing) {+ const { totals, cacheTotals, trackedStats, summary } = stats;+ return [+ {+ value: 'audience', label: 'Audience', figure: fmtNum(summary.totalAudience),+ detail: detailOf([+ partOf(totals.subscribers, 'subscribers'), partOf(totals.followers, 'followers'), partOf(totals.karma, 'karma'),+ ], 'No data yet'),+ },+ {+ value: 'views', label: 'Views', figure: fmtNum(summary.totalViews),+ detail: detailOf([+ partOf(totals.views, 'YouTube'), partOf(cacheTotals.igViews, 'Instagram'), partOf(summary.trackedViewTotal, 'tracked'),+ ], 'No views recorded yet'),+ },+ {+ value: 'content', label: 'Content', figure: fmtNum(summary.totalContent),+ detail: detailOf([+ partOf(totals.videos, 'videos'), partOf(totals.posts, 'Instagram'),+ partOf(cacheTotals.rdPosts, 'Reddit'), partOf(trackedStats.total, 'tracked'),+ ], 'No content yet'),+ },+ { value: 'accounts', label: 'Accounts', figure: accounts.length, detail: platformSummary(accounts) },+ {+ value: 'comments', label: 'Comments', figure: fmtNum(summary.totalComments),+ detail: syncDetail(isSyncing, summary.totalComments),+ },+ {+ value: 'likes', label: 'Likes', figure: fmtNum(summary.totalLikes),+ detail: syncDetail(isSyncing, summary.totalLikes),+ },+ ];+}++export function igTypeSummary(igTypes, field) {+ return IG_CONTENT_TYPES+ .map(type => `${fmtNum(igTypes[type][field])} ${IG_CONTENT_TYPE_META[type].plural.toLowerCase()}`)+ .join(', ');+}++export function categoryMeta(stat) {+ return [+ countLabel(stat.count, 'item'),+ stat.ytCount > 0 && `${stat.ytCount} YouTube`,+ stat.rdCount > 0 && `${stat.rdCount} Reddit`,+ ].filter(Boolean).join(', ');+}++export function topContentLabel(account) {+ const platform = platformOf(account);+ if (platform === 'instagram') return `${fmtNum(account.mediaCount)} items`;+ if (platform === 'reddit') return `${fmtNum(account.totalKarma)} karma`;+ return `${fmtNum(account.viewCount)} views`;+}++export function accountAudienceLabel(account) {+ const platform = platformOf(account);+ if (platform === 'instagram') return `${fmtNum(account.followersCount)} followers`;+ if (platform === 'reddit') return `${fmtNum(account.totalKarma)} karma`;+ return `${fmtNum(account.subscriberCount)} subscribers`;+}++export function accountContentLabel(account) {+ const platform = platformOf(account);+ if (platform === 'instagram') return `${fmtNum(account.mediaCount)} items`;+ if (platform === 'reddit') return `${fmtNum(account.postKarma)} post karma`;+ return `${fmtNum(account.viewCount)} views, ${fmtNum(account.videoCount)} videos`;+}diff --git a/frontend/src/features/analytics/overview/overviewLabels.test.js b/frontend/src/features/analytics/overview/overviewLabels.test.jsnew file mode 100644index 0000000..5383287--- /dev/null+++ b/frontend/src/features/analytics/overview/overviewLabels.test.js@@ -0,0 +1,70 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import {+ countLabel, overviewDescription, syncDetail, metricTabsOf, igTypeSummary, categoryMeta, topContentLabel,+ accountAudienceLabel, accountContentLabel,+} from './overviewLabels.js';++const channel = { id: 'y1', viewCount: 5000, videoCount: 10, subscriberCount: 100 };+const igAccount = { id: 'i1', platform: 'instagram', mediaCount: 20, followersCount: 300 };+const redditAccount = { id: 'r1', platform: 'reddit', totalKarma: 70, postKarma: 60 };++test('count labels pluralise every count except one', () => {+ assert.equal(countLabel(1, 'channel'), '1 channel');+ assert.equal(countLabel(0, 'channel'), '0 channels');+ assert.equal(countLabel(3, 'YouTube channel'), '3 YouTube channels');+});++test('header description summarises the accounts', () => {+ assert.equal(overviewDescription([]), 'Add your first account to start tracking.');+ assert.equal(overviewDescription([channel]), 'Tracking 1 account: 1 YouTube.');+ assert.equal(overviewDescription([channel, igAccount]), 'Tracking 2 accounts: 1 YouTube, 1 Instagram.');+});++test('sync detail prefers the syncing label', () => {+ assert.equal(syncDetail(true, 5), 'Syncing analytics');+ assert.equal(syncDetail(false, 5), 'Across all platforms');+ assert.equal(syncDetail(false, 0), 'Open an analytics page to load');+});++test('metric tabs list present parts or a fallback', () => {+ const stats = {+ totals: { subscribers: 1500, followers: 0, karma: 20, views: 0, videos: 3, posts: 0 },+ cacheTotals: { igViews: 0, rdPosts: 0 },+ trackedStats: { total: 2 },+ summary: { totalAudience: 1520, totalViews: 0, trackedViewTotal: 0, totalContent: 5, totalComments: 0, totalLikes: 9 },+ };+ const tabs = metricTabsOf([channel, redditAccount], stats, false);+ assert.deepEqual(tabs.map(tab => tab.value), ['audience', 'views', 'content', 'accounts', 'comments', 'likes']);+ assert.equal(tabs[0].figure, '1.5K');+ assert.equal(tabs[0].detail, '1.5K subscribers, 20 karma');+ assert.equal(tabs[1].detail, 'No views recorded yet');+ assert.equal(tabs[2].detail, '3 videos, 2 tracked');+ assert.equal(tabs[3].figure, 2);+ assert.equal(tabs[3].detail, '1 YouTube, 1 Reddit');+ assert.equal(tabs[4].detail, 'Open an analytics page to load');+ assert.equal(tabs[5].detail, 'Across all platforms');+});++test('Instagram type summary lists every content type', () => {+ const igTypes = { reel: { count: 2, views: 1200 }, post: { count: 1, views: 0 }, video: { count: 0, views: 0 } };+ assert.equal(igTypeSummary(igTypes, 'views'), '1.2K reels, 0 posts, 0 videos');+ assert.equal(igTypeSummary(igTypes, 'count'), '2 reels, 1 posts, 0 videos');+});++test('category meta skips empty platforms', () => {+ assert.equal(categoryMeta({ count: 1, ytCount: 1, rdCount: 0 }), '1 item, 1 YouTube');+ assert.equal(categoryMeta({ count: 3, ytCount: 1, rdCount: 2 }), '3 items, 1 YouTube, 2 Reddit');+});++test('row labels follow the account platform', () => {+ assert.equal(topContentLabel(channel), '5.0K views');+ assert.equal(topContentLabel(igAccount), '20 items');+ assert.equal(topContentLabel(redditAccount), '70 karma');+ assert.equal(accountAudienceLabel(channel), '100 subscribers');+ assert.equal(accountAudienceLabel(igAccount), '300 followers');+ assert.equal(accountAudienceLabel(redditAccount), '70 karma');+ assert.equal(accountContentLabel(channel), '5.0K views, 10 videos');+ assert.equal(accountContentLabel(igAccount), '20 items');+ assert.equal(accountContentLabel(redditAccount), '60 post karma');+});diff --git a/frontend/src/features/analytics/overview/overviewStats.js b/frontend/src/features/analytics/overview/overviewStats.jsnew file mode 100644index 0000000..a27a25c--- /dev/null+++ b/frontend/src/features/analytics/overview/overviewStats.js@@ -0,0 +1,173 @@+// overview totals; no JSX or path aliases so node --test can import it++import { audienceOf } from '../../../lib/accounts.js';+import { IG_CONTENT_TYPES } from '../../../utils/instagramContent.js';+import { trackedViews } from '../../../utils/trackedContent.js';++function addAccountTotals(totals, account) {+ if (account.platform === 'instagram') {+ return { ...totals, followers: totals.followers + (account.followersCount || 0), posts: totals.posts + (account.mediaCount || 0) };+ }+ if (account.platform === 'reddit') {+ return {+ ...totals,+ karma: totals.karma + (account.totalKarma || 0),+ postKarma: totals.postKarma + (account.postKarma || 0),+ commentKarma: totals.commentKarma + (account.commentKarma || 0),+ };+ }+ return {+ ...totals,+ subscribers: totals.subscribers + (account.subscriberCount || 0),+ views: totals.views + (account.viewCount || 0),+ videos: totals.videos + (account.videoCount || 0),+ };+}++export function accountTotalsOf(accounts) {+ return accounts.reduce(addAccountTotals, {+ subscribers: 0, views: 0, videos: 0, followers: 0, posts: 0, karma: 0, postKarma: 0, commentKarma: 0,+ });+}++function addInstagramCache(result, cache) {+ result.igLikes += cache.totalLikes ?? 0;+ result.igComments += cache.totalComments ?? 0;+ result.igViews += cache.totalViews ?? 0;+ IG_CONTENT_TYPES.forEach(type => {+ result.igTypes[type].count += cache.contentTypes?.[type]?.count ?? 0;+ result.igTypes[type].views += cache.contentTypes?.[type]?.views ?? 0;+ });+}++// only accounts saved with platform 'youtube' count here, unlike the platform splits+export function cacheTotalsOf(accounts, analyticsCache) {+ const result = {+ ytLikes: 0, ytComments: 0, igLikes: 0, igComments: 0, igViews: 0, rdPosts: 0, rdKarma: 0, rdComments: 0,+ igTypes: Object.fromEntries(IG_CONTENT_TYPES.map(type => [type, { count: 0, views: 0 }])),+ };+ accounts.forEach(account => {+ const cache = analyticsCache[account.id];+ if (!cache) return;+ if (account.platform === 'youtube') {+ result.ytLikes += cache.totalLikes ?? 0;+ result.ytComments += cache.totalComments ?? 0;+ } else if (account.platform === 'instagram') {+ addInstagramCache(result, cache);+ } else if (account.platform === 'reddit') {+ result.rdPosts += cache.fetchedPosts ?? 0;+ result.rdKarma += cache.totalScore ?? 0;+ result.rdComments += cache.totalComments ?? 0;+ }+ });+ return result;+}++function sumOf(items, valueOf) {+ return items.reduce((sum, item) => sum + valueOf(item), 0);+}++// reddit post score is karma, so it rolls into karma totals+export function trackedStatsOf(trackedContent) {+ const ytItems = trackedContent.filter(item => item.contentType === 'youtube');+ const rdItems = trackedContent.filter(item => (item.contentType || 'reddit') === 'reddit');+ return {+ total: trackedContent.length,+ ytItems,+ rdItems,+ ytViews: sumOf(ytItems, trackedViews),+ ytLikes: sumOf(ytItems, item => item.likeCount ?? 0),+ ytComments: sumOf(ytItems, item => item.commentCount ?? 0),+ rdViews: sumOf(rdItems, trackedViews),+ rdKarma: sumOf(rdItems, item => item.score ?? 0),+ rdComments: sumOf(rdItems, item => item.numComments ?? 0),+ };+}++function emptyCategory(category) {+ return {+ category,+ count: 0, ytCount: 0, rdCount: 0,+ ytViews: 0, ytLikes: 0, ytComments: 0,+ rdViews: 0, rdKarma: 0, rdComments: 0,+ };+}++function addToCategory(stat, item) {+ stat.count++;+ if (item.contentType === 'youtube') {+ stat.ytCount++;+ stat.ytViews += trackedViews(item);+ stat.ytLikes += item.likeCount ?? 0;+ stat.ytComments += item.commentCount ?? 0;+ return;+ }+ stat.rdCount++;+ stat.rdViews += trackedViews(item);+ stat.rdKarma += item.score ?? 0;+ stat.rdComments += item.numComments ?? 0;+}++export function categoryStatsOf(trackedContent) {+ const withCategory = trackedContent.filter(item => item.category);+ if (!withCategory.length) return [];+ const byCategory = {};+ withCategory.forEach(item => {+ if (!byCategory[item.category]) byCategory[item.category] = emptyCategory(item.category);+ addToCategory(byCategory[item.category], item);+ });+ return Object.values(byCategory)+ .map(stat => ({ ...stat, views: stat.ytViews + stat.rdViews }))+ .sort((a, b) => (b.views + b.rdKarma) - (a.views + a.rdKarma));+}++function shareOf(part, total) {+ return total > 0 ? (part / total) * 100 : 0;+}++// tracked items are never the user's own content, so cache and tracked totals never overlap+export function summaryOf(totals, cacheTotals, trackedStats) {+ const totalContent = totals.videos + totals.posts + cacheTotals.rdPosts + trackedStats.total;+ const trackedViewTotal = trackedStats.ytViews + trackedStats.rdViews;+ const ytComments = cacheTotals.ytComments + trackedStats.ytComments;+ const rdComments = cacheTotals.rdComments + trackedStats.rdComments;+ const totalComments = ytComments + cacheTotals.igComments + rdComments;+ const redditKarma = totals.postKarma + trackedStats.rdKarma;+ const ytLikes = cacheTotals.ytLikes + trackedStats.ytLikes;+ const totalLikes = redditKarma + ytLikes + cacheTotals.igLikes;+ return {+ totalAudience: totals.subscribers + totals.followers + totals.karma,+ totalContent,+ trackedViewTotal,+ totalViews: totals.views + cacheTotals.igViews + trackedViewTotal,+ ytComments, rdComments, totalComments,+ redditKarma, ytLikes, totalLikes,+ avgCommentsPerContent: totalContent > 0 ? Math.round(totalComments / totalContent) : 0,+ commentShare: { youtube: shareOf(ytComments, totalComments), reddit: shareOf(rdComments, totalComments) },+ likeShare: { youtube: shareOf(ytLikes, totalLikes), instagram: shareOf(cacheTotals.igLikes, totalLikes) },+ };+}++function contentOf(account) {+ if (account.platform === 'instagram') return account.mediaCount || 0;+ if (account.platform === 'reddit') return account.totalKarma || 0;+ return account.viewCount || 0;+}++export function sortedByAudience(accounts) {+ return [...accounts].sort((a, b) => audienceOf(b) - audienceOf(a));+}++export function sortedByContent(accounts) {+ return [...accounts].sort((a, b) => contentOf(b) - contentOf(a));+}++export function sortedByChannelViews(ytAccounts) {+ return [...ytAccounts].sort((a, b) => (b.viewCount || 0) - (a.viewCount || 0));+}++export function igAccountRowsOf(igAccounts, analyticsCache) {+ return igAccounts+ .map(account => ({ account, cache: analyticsCache[account.id] }))+ .sort((x, y) => (y.cache?.totalViews ?? 0) - (x.cache?.totalViews ?? 0));+}diff --git a/frontend/src/features/analytics/overview/overviewStats.test.js b/frontend/src/features/analytics/overview/overviewStats.test.jsnew file mode 100644index 0000000..c519988--- /dev/null+++ b/frontend/src/features/analytics/overview/overviewStats.test.js@@ -0,0 +1,91 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import {+ accountTotalsOf, cacheTotalsOf, trackedStatsOf, categoryStatsOf, summaryOf, sortedByAudience, sortedByContent,+ sortedByChannelViews, igAccountRowsOf,+} from './overviewStats.js';++const channel = { id: 'y1', platform: 'youtube', title: 'Studio', subscriberCount: 100, viewCount: 5000, videoCount: 10 };+const legacyYt = { id: 'y2', title: 'Legacy', subscriberCount: 50, viewCount: 9000, videoCount: 4 };+const igAccount = { id: 'i1', platform: 'instagram', username: 'fold', followersCount: 300, mediaCount: 20 };+const redditAccount = { id: 'r1', platform: 'reddit', username: 'ribbon', totalKarma: 70, postKarma: 60, commentKarma: 10 };+const accounts = [channel, legacyYt, igAccount, redditAccount];++const cache = {+ y1: { totalLikes: 5, totalComments: 2 },+ y2: { totalLikes: 99, totalComments: 99 },+ i1: { totalLikes: 7, totalComments: 3, totalViews: 400, contentTypes: { reel: { count: 2, views: 300 }, post: { count: 1, views: 100 } } },+ r1: { fetchedPosts: 4, totalScore: 40, totalComments: 6 },+};++const tracked = [+ { contentType: 'youtube', viewCount: 1000, likeCount: 10, commentCount: 4, category: 'Tech' },+ { contentType: 'reddit', manualViews: 200, score: 30, numComments: 5, category: 'Tech' },+ { score: 8, numComments: 1, category: 'Art' },+ { contentType: 'youtube', viewCount: 50 },+];++test('account totals add each platform into its own fields', () => {+ assert.deepEqual(accountTotalsOf(accounts), {+ subscribers: 150, views: 14000, videos: 14, followers: 300, posts: 20, karma: 70, postKarma: 60, commentKarma: 10,+ });+});++test('cache totals only count YouTube accounts saved with a platform', () => {+ const totals = cacheTotalsOf(accounts, cache);+ assert.equal(totals.ytLikes, 5);+ assert.equal(totals.ytComments, 2);+ assert.equal(totals.igViews, 400);+ assert.deepEqual(totals.igTypes, { reel: { count: 2, views: 300 }, post: { count: 1, views: 100 }, video: { count: 0, views: 0 } });+ assert.equal(totals.rdPosts, 4);+ assert.equal(totals.rdKarma, 40);+ assert.equal(totals.rdComments, 6);+});++test('tracked stats treat a missing content type as Reddit', () => {+ const stats = trackedStatsOf(tracked);+ assert.equal(stats.total, 4);+ assert.equal(stats.ytItems.length, 2);+ assert.equal(stats.rdItems.length, 2);+ assert.equal(stats.ytViews, 1050);+ assert.equal(stats.rdViews, 200);+ assert.equal(stats.rdKarma, 38);+ assert.equal(stats.rdComments, 6);+});++test('category stats are ranked by views plus karma', () => {+ const stats = categoryStatsOf(tracked);+ assert.deepEqual(stats.map(stat => stat.category), ['Tech', 'Art']);+ assert.equal(stats[0].views, 1200);+ assert.equal(stats[0].ytCount, 1);+ assert.equal(stats[0].rdCount, 1);+ assert.equal(stats[1].rdKarma, 8);+ assert.deepEqual(categoryStatsOf([{ contentType: 'youtube' }]), []);+});++test('summary combines account, cache and tracked totals', () => {+ const totals = accountTotalsOf(accounts);+ const summary = summaryOf(totals, cacheTotalsOf(accounts, cache), trackedStatsOf(tracked));+ assert.equal(summary.totalAudience, 520);+ assert.equal(summary.totalContent, 14 + 20 + 4 + 4);+ assert.equal(summary.totalViews, 14000 + 400 + 1250);+ assert.equal(summary.totalComments, (2 + 4) + 3 + (6 + 6));+ assert.equal(summary.totalLikes, (60 + 38) + (5 + 10) + 7);+ assert.equal(summary.avgCommentsPerContent, Math.round(21 / 42));+ assert.equal(summary.commentShare.youtube, (6 / 21) * 100);+ assert.equal(summaryOf(accountTotalsOf([]), cacheTotalsOf([], {}), trackedStatsOf([])).likeShare.youtube, 0);+});++test('account lists sort without changing the input', () => {+ assert.deepEqual(sortedByAudience(accounts).map(account => account.id), ['i1', 'y1', 'r1', 'y2']);+ assert.deepEqual(sortedByContent(accounts).map(account => account.id), ['y2', 'y1', 'r1', 'i1']);+ assert.deepEqual(sortedByChannelViews([channel, legacyYt]).map(account => account.id), ['y2', 'y1']);+ assert.equal(accounts[0], channel);+});++test('Instagram rows pair each account with its cache, most viewed first', () => {+ const other = { id: 'i2', platform: 'instagram' };+ const rows = igAccountRowsOf([other, igAccount], cache);+ assert.deepEqual(rows.map(row => row.account.id), ['i1', 'i2']);+ assert.equal(rows[1].cache, undefined);+});diff --git a/frontend/src/features/analytics/overview/useOverviewData.js b/frontend/src/features/analytics/overview/useOverviewData.jsnew file mode 100644index 0000000..3be69d9--- /dev/null+++ b/frontend/src/features/analytics/overview/useOverviewData.js@@ -0,0 +1,37 @@+import { useEffect, useState } from 'react';+import { api } from '../../../services/api';++const SYNC_POLL_DELAYS = [4000, 8000, 16000];++export function useOverviewData(accounts) {+ const [overviewData, setOverviewData] = useState({ tracked: [], analyticsCache: {} });+ const [overviewLoading, setOverviewLoading] = useState(true);+ const [syncPolls, setSyncPolls] = useState(0);++ useEffect(() => {+ api.getOverview()+ .then(data => {+ if (data && !data.error) setOverviewData(data);+ })+ .catch(() => {})+ .finally(() => setOverviewLoading(false));+ }, []);++ // the backend marks accounts it is still fetching; poll with backoff and stop so the label never hangs+ const isSyncing = !overviewLoading && syncPolls < SYNC_POLL_DELAYS.length && accounts.some(account => {+ return overviewData.analyticsCache[account.id]?.syncing === true;+ });++ useEffect(() => {+ if (!isSyncing) return undefined;+ const timer = setTimeout(() => {+ api.getOverview()+ .then(data => { if (data && !data.error) setOverviewData(data); })+ .catch(() => {})+ .finally(() => setSyncPolls(polls => polls + 1));+ }, SYNC_POLL_DELAYS[syncPolls]);+ return () => clearTimeout(timer);+ }, [isSyncing, syncPolls]);++ return { overviewData, overviewLoading, isSyncing };+}diff --git a/frontend/src/features/analytics/overview/useOverviewStats.js b/frontend/src/features/analytics/overview/useOverviewStats.jsnew file mode 100644index 0000000..4d102cb--- /dev/null+++ b/frontend/src/features/analytics/overview/useOverviewStats.js@@ -0,0 +1,48 @@+import { useMemo } from 'react';+import { groupByPlatform } from '@/lib/accounts';+import {+ accountTotalsOf, cacheTotalsOf, categoryStatsOf, igAccountRowsOf, sortedByAudience, sortedByChannelViews,+ sortedByContent, summaryOf, trackedStatsOf,+} from './overviewStats.js';+import {+ audienceChartDataOf, audienceLegendOf, categoryViewDataOf, commentByCategoryOf, commentByContentOf,+ engagementByContentOf, karmaByAccountOf,+} from './overviewCharts.js';++function useOverviewCharts(groups, trackedContent, categoryStats) {+ const audience = useMemo(() => audienceChartDataOf(groups, categoryStats), [groups, categoryStats]);+ const commentByContent = useMemo(() => commentByContentOf(trackedContent), [trackedContent]);+ const categoryViews = useMemo(() => categoryViewDataOf(categoryStats), [categoryStats]);+ const commentByCategory = useMemo(() => commentByCategoryOf(categoryStats), [categoryStats]);+ const karmaByAccount = useMemo(() => karmaByAccountOf(groups.reddit), [groups.reddit]);+ const engagementByContent = useMemo(() => engagementByContentOf(trackedContent), [trackedContent]);+ return { audience, commentByContent, categoryViews, commentByCategory, karmaByAccount, engagementByContent };+}++export function useOverviewStats(accounts, overviewData) {+ // memoized so the ?? fallbacks keep a stable identity and the memos below actually cache+ const trackedContent = useMemo(() => overviewData.tracked ?? [], [overviewData.tracked]);+ const analyticsCache = useMemo(() => overviewData.analyticsCache ?? {}, [overviewData.analyticsCache]);++ const groups = useMemo(() => groupByPlatform(accounts), [accounts]);+ const totals = useMemo(() => accountTotalsOf(accounts), [accounts]);+ const cacheTotals = useMemo(() => cacheTotalsOf(accounts, analyticsCache), [accounts, analyticsCache]);+ const trackedStats = useMemo(() => trackedStatsOf(trackedContent), [trackedContent]);+ const categoryStats = useMemo(() => categoryStatsOf(trackedContent), [trackedContent]);+ const charts = useOverviewCharts(groups, trackedContent, categoryStats);++ return {+ groups,+ totals,+ cacheTotals,+ trackedStats,+ categoryStats,+ charts,+ summary: summaryOf(totals, cacheTotals, trackedStats),+ legend: audienceLegendOf(groups, categoryStats),+ igAccountRows: igAccountRowsOf(groups.instagram, analyticsCache),+ byAudience: sortedByAudience(accounts),+ byContent: sortedByContent(accounts),+ byChannelViews: sortedByChannelViews(groups.youtube),+ };+}