Skip to content

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

refactor(channel): split ChannelAnalytics into tabs and helpers

spacesdriveb6ced18a8aa9
diff --git a/docs/architecture/frontend/FEATURES.md b/docs/architecture/frontend/FEATURES.md
index 6076aa4..89d91b4 100644
--- a/docs/architecture/frontend/FEATURES.md
+++ b/docs/architecture/frontend/FEATURES.md
@@ -18,7 +18,12 @@ frontend/src/
├── features/
│ ├── analytics/
│ │ ├── channel/
-│ │ │ └── ChannelAnalytics.jsx <- YouTube channel analytics
+│ │ │ ├── ChannelAnalytics.jsx <- Page: YouTube channel analytics with eight tabs
+│ │ │ ├── ChannelOverviewTab.jsx, ChannelVideosTab.jsx, ChannelEngagementTab.jsx, ChannelContentTab.jsx
+│ │ │ ├── ChannelPublishingTab.jsx, ChannelGrowthTab.jsx, ChannelShortsTab.jsx, ChannelTagsTab.jsx, TagCloud.jsx
+│ │ │ ├── ChannelHeader.jsx, ChannelNoVideos.jsx, ChannelVideoTable.jsx, TrendArea.jsx, MetricGrid.jsx
+│ │ │ ├── useChannelAnalytics.js <- Loads api.getAnalytics(id); returns data, loading and the reload
+│ │ │ └── channelChartData.js <- Pure chart rows and labels (channelChartData.test.js)
│ │ ├── instagram/
│ │ │ ├── InstagramAnalytics.jsx <- Page: Instagram account analytics (loads through useAccountAnalytics)
│ │ │ ├── InstagramHeader.jsx, InstagramMetrics.jsx, InstagramInsightChips.jsx, TypeBadge.jsx
diff --git a/docs/architecture/frontend/REACT_ARCHITECTURE.md b/docs/architecture/frontend/REACT_ARCHITECTURE.md
index 92c05e8..16f6de4 100644
--- a/docs/architecture/frontend/REACT_ARCHITECTURE.md
+++ b/docs/architecture/frontend/REACT_ARCHITECTURE.md
@@ -97,7 +97,7 @@ frontend/src/
features/
analytics/
overview/ Overview.jsx - all-accounts dashboard (page; tabs, hooks and helpers beside it)
- channel/ ChannelAnalytics.jsx - per-channel YouTube
+ channel/ ChannelAnalytics.jsx - per-channel YouTube (page; tabs, hook and helpers beside it)
instagram/ InstagramAnalytics.jsx - per-account Instagram (page; sections and helpers beside it)
videos/ VideoExplorer.jsx - all videos table
shorts/ ShortsExplorer.jsx - shorts-filtered table
diff --git a/frontend/src/features/analytics/channel/ChannelAnalytics.jsx b/frontend/src/features/analytics/channel/ChannelAnalytics.jsx
index 01f90ca..152d459 100644
--- a/frontend/src/features/analytics/channel/ChannelAnalytics.jsx
+++ b/frontend/src/features/analytics/channel/ChannelAnalytics.jsx
@@ -1,32 +1,25 @@
-import React, { useCallback, useEffect, useState } from 'react';
+import { useState } from 'react';
import { useParams } from 'react-router-dom';
-import {
- BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip as ReTooltip, PieChart, Pie, Cell, Legend,
- AreaChart, Area,
-} from 'recharts';
-import {
- RefreshCw, Eye, Users, VideoIcon, ThumbsUp, MessageSquare, TrendingUp, Clock, Trophy, Zap, Flame,
- Calendar, Timer, Film, Tag, Play, BarChart2, UserX,
-} from 'lucide-react';
+import { BarChart2, UserX } from 'lucide-react';
import { Button } from '@/components/ui/button';
-import { Badge } from '@/components/ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
-import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import PageHeader from '@/components/PageHeader';
-import MetricBox from '@/components/MetricBox';
import SurfaceBox from '@/components/SurfaceBox';
-import ChartPanel from '@/components/ChartPanel';
-import SectionHeader from '@/components/SectionHeader';
-import MediaCard, { MediaChip } from '@/components/MediaCard';
import { EmptyState, PageSkeleton } from '@/components/StateViews';
-import { AccountAvatar } from '@/components/platform';
-import { SERIES, axisProps, axisTick, gridProps, legendStyle, tooltipCursor, tooltipStyle } from '@/lib/chart';
import { useAppContext } from '../../../context/AppContext';
-import { api } from '../../../services/api';
-import { fmtNum, fmtNumFull, fmtDate, fmtPercent, fmtDuration, CATEGORY_MAP, fmtCount } from '../../../utils/formatters';
-import { cn } from '@/lib/utils';
-
-const watchUrl = id => `https://www.youtube.com/watch?v=${id}`;
+import { useChannelAnalytics } from './useChannelAnalytics';
+import ChannelHeader from './ChannelHeader';
+import ChannelNoVideos from './ChannelNoVideos';
+import ChannelOverviewTab from './ChannelOverviewTab';
+import ChannelVideosTab from './ChannelVideosTab';
+import ChannelEngagementTab from './ChannelEngagementTab';
+import ChannelContentTab from './ChannelContentTab';
+import ChannelPublishingTab from './ChannelPublishingTab';
+import ChannelGrowthTab from './ChannelGrowthTab';
+import ChannelShortsTab from './ChannelShortsTab';
+import ChannelTagsTab from './ChannelTagsTab';
+
+const BACK = { to: '/', label: 'Overview' };
const TABS = [
{ value: 'overview', label: 'Overview' },
@@ -39,104 +32,17 @@ const TABS = [
{ value: 'tags', label: 'Tags and SEO' },
];
-function MetricGrid({ className, children }) {
- return <div className={cn('grid grid-cols-2 gap-3 sm:grid-cols-4', className)}>{children}</div>;
-}
-
-function VideoTable({ videos }) {
- const rows = (videos || []).filter(Boolean);
- return (
- <SurfaceBox content={false} className="overflow-hidden">
- <div className="max-h-[480px] overflow-y-auto">
- <Table>
- <TableHeader className="sticky top-0 z-10 bg-surface-raised">
- <TableRow>
- <TableHead className="w-10 text-right">#</TableHead>
- <TableHead>Video</TableHead>
- <TableHead className="text-right">Views</TableHead>
- <TableHead className="text-right">Likes</TableHead>
- <TableHead className="text-right">Comments</TableHead>
- <TableHead className="text-right">Engagement</TableHead>
- <TableHead className="text-right">Length</TableHead>
- <TableHead className="text-right">Published</TableHead>
- <TableHead className="w-10"><span className="sr-only">Watch</span></TableHead>
- </TableRow>
- </TableHeader>
- <TableBody>
- {rows.map((v, i) => (
- <TableRow key={v.videoId}>
- <TableCell className="text-right font-mono text-caption text-ink-faint">{i + 1}</TableCell>
- <TableCell className="max-w-[280px]">
- <a href={watchUrl(v.videoId)} target="_blank" rel="noopener noreferrer" className="block truncate text-sm font-medium text-ink hover:underline">{v.title}</a>
- </TableCell>
- <TableCell className="text-right font-semibold text-ink">{fmtNum(v.viewCount)}</TableCell>
- <TableCell className="text-right text-ink-muted">{fmtCount(v.likeCount)}</TableCell>
- <TableCell className="text-right text-ink-muted">{fmtCount(v.commentCount)}</TableCell>
- <TableCell className="text-right">
- <Badge variant={parseFloat(v.engagementRate) > 5 ? 'success' : 'secondary'}>{fmtPercent(v.engagementRate)}</Badge>
- </TableCell>
- <TableCell className="text-right text-ink-muted">{fmtDuration(v.durationSeconds)}</TableCell>
- <TableCell className="text-right text-small text-ink-faint">{fmtDate(v.publishedAt)}</TableCell>
- <TableCell>
- <Button variant="ghost" size="icon-xs" render={<a href={watchUrl(v.videoId)} target="_blank" rel="noopener noreferrer" aria-label={`Watch ${v.title} on YouTube`} />}>
- <Play />
- </Button>
- </TableCell>
- </TableRow>
- ))}
- </TableBody>
- </Table>
- </div>
- </SurfaceBox>
- );
-}
-
-function TrendArea({ data, dataKey = 'value', color, name, percent = false, gradientId }) {
- return (
- <AreaChart data={data}>
- <defs>
- <linearGradient id={gradientId} x1="0" y1="0" x2="0" y2="1">
- <stop offset="5%" stopColor={color} stopOpacity={0.2} />
- <stop offset="95%" stopColor={color} stopOpacity={0} />
- </linearGradient>
- </defs>
- <CartesianGrid {...gridProps} vertical={false} />
- <XAxis dataKey="month" {...axisProps} />
- <YAxis {...axisProps} tickFormatter={percent ? v => `${v}%` : fmtNum} width={48} />
- <ReTooltip contentStyle={tooltipStyle} cursor={{ stroke: 'var(--line-strong)' }} formatter={percent ? undefined : v => fmtNumFull(v)} />
- <Area type="monotone" dataKey={dataKey} stroke={color} fill={`url(#${gradientId})`} strokeWidth={2} name={name} />
- </AreaChart>
- );
-}
-
export default function ChannelAnalytics() {
const { id } = useParams();
const { accounts, showToast } = useAppContext();
- const account = accounts.find(a => a.id === id);
-
- const [data, setData] = useState(null);
- const [loading, setLoading] = useState(true);
+ const account = accounts.find(item => item.id === id);
+ const { data, loading, loadAnalytics } = useChannelAnalytics(id, showToast);
const [tab, setTab] = useState('overview');
- const loadAnalytics = useCallback(async () => {
- setLoading(true);
- try {
- setData(await api.getAnalytics(id));
- } catch (err) {
- showToast(`Couldn't load channel analytics. ${err.message}`, 'error');
- } finally {
- setLoading(false);
- }
- }, [id, showToast]);
-
- useEffect(() => { if (id) loadAnalytics(); }, [id, loadAnalytics]);
-
- const back = { to: '/', label: 'Overview' };
-
if (!account && !loading) {
return (
<div className="flex flex-col gap-6">
- <PageHeader title="YouTube channel" back={back} />
+ <PageHeader title="YouTube channel" back={BACK} />
<SurfaceBox>
<EmptyState icon={<UserX />} title="Channel not found" description="It may have been removed. Choose another account from the sidebar." />
</SurfaceBox>
@@ -149,7 +55,7 @@ export default function ChannelAnalytics() {
if (!data) {
return (
<div className="flex flex-col gap-6">
- <PageHeader title={account?.title || 'YouTube channel'} back={back} />
+ <PageHeader title={account?.title || 'YouTube channel'} back={BACK} />
<SurfaceBox>
<EmptyState
icon={<BarChart2 />}
@@ -164,334 +70,27 @@ export default function ChannelAnalytics() {
const { channel, analytics } = data;
- const dayData = analytics.publishDayDistribution
- ? Object.entries(analytics.publishDayDistribution).map(([day, count]) => ({ day, count }))
- : [];
- const hourData = analytics.publishHourDistribution
- ? Object.entries(analytics.publishHourDistribution).sort((a, b) => parseInt(a[0], 10) - parseInt(b[0], 10)).map(([hour, count]) => ({ hour: `${hour}:00`, count }))
- : [];
- const durationData = analytics.durationDistribution
- ? [
- { name: 'Shorts (under 1m)', value: analytics.durationDistribution.short, color: SERIES.primary },
- { name: 'Medium (1 to 10m)', value: analytics.durationDistribution.medium, color: SERIES.cool },
- { name: 'Long (10 to 60m)', value: analytics.durationDistribution.long, color: SERIES.neutral },
- { name: 'Very long (1h+)', value: analytics.durationDistribution.veryLong, color: SERIES.warm },
- ].filter(d => d.value > 0)
- : [];
- const catData = analytics.categoryDistribution
- ? Object.entries(analytics.categoryDistribution).map(([catId, count]) => ({ name: CATEGORY_MAP[catId] || `Category ${catId}`, value: count }))
- : [];
- const splitData = [
- { name: 'Shorts', value: analytics.shortsCount, color: SERIES.primary },
- { name: 'Regular', value: analytics.regularCount, color: SERIES.cool },
- ].filter(d => d.value > 0);
-
- const meta = [
- channel.customUrl,
- channel.country && channel.country !== 'Unknown' ? channel.country : null,
- `${channel.channelAgeYears} years old`,
- `Since ${fmtDate(channel.publishedAt)}`,
- ].filter(Boolean);
-
return (
<div className="flex flex-col gap-6">
- <PageHeader
- back={back}
- media={<AccountAvatar account={{ ...account, thumbnail: channel.thumbnails?.high || channel.thumbnails?.medium || account?.thumbnail }} size="xl" showPlatform />}
- title={channel.title}
- description={
- <span className="flex flex-wrap gap-1.5">
- {meta.map(m => <Badge key={m} variant="outline">{m}</Badge>)}
- </span>
- }
- actions={
- <Button variant="outline" size="sm" onClick={loadAnalytics}>
- <RefreshCw data-icon="inline-start" />
- Refresh
- </Button>
- }
- />
-
+ <ChannelHeader account={account} channel={channel} back={BACK} onRefresh={loadAnalytics} />
{analytics.totalVideos === 0 ? (
- <>
- <div className="grid grid-cols-1 gap-3 sm:grid-cols-3">
- <MetricBox small icon={<Users />} label="Subscribers" value={fmtNum(channel.subscriberCount)} subtitle={fmtNumFull(channel.subscriberCount)} />
- <MetricBox small icon={<Eye />} label="Total views" value={fmtNum(channel.viewCount)} subtitle={fmtNumFull(channel.viewCount)} />
- <MetricBox small icon={<VideoIcon />} label="Total videos" value={fmtNum(channel.videoCount)} subtitle="Public uploads" />
- </div>
- <SurfaceBox>
- <EmptyState
- icon={<VideoIcon />}
- title="No public videos yet"
- description="Video analytics start with this channel's first public upload. After publishing, choose Refresh."
- />
- </SurfaceBox>
- </>
+ <ChannelNoVideos channel={channel} />
) : (
- <Tabs value={tab} onValueChange={setTab} className="gap-6">
- <div className="scrollbar-hide -mx-4 overflow-x-auto px-4 sm:mx-0 sm:px-0">
- <TabsList className="w-max min-w-full">
- {TABS.map(t => <TabsTrigger key={t.value} value={t.value}>{t.label}</TabsTrigger>)}
- </TabsList>
- </div>
-
- <TabsContent value="overview" className="flex flex-col gap-3">
- <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 xl:grid-cols-6">
- <MetricBox small icon={<Eye />} label="Total views" value={fmtNum(channel.viewCount)} subtitle={fmtNumFull(channel.viewCount)} highlight />
- <MetricBox small icon={<Users />} label="Subscribers" value={fmtNum(channel.subscriberCount)} subtitle={fmtNumFull(channel.subscriberCount)} />
- <MetricBox small icon={<VideoIcon />} label="Total videos" value={fmtNum(channel.videoCount)} subtitle={`${analytics.totalVideos} analyzed`} />
- <MetricBox small icon={<ThumbsUp />} label="Total likes" value={fmtNum(analytics.totalLikes)} subtitle={fmtNumFull(analytics.totalLikes)} />
- <MetricBox small icon={<MessageSquare />} label="Comments" value={fmtNum(analytics.totalComments)} subtitle={fmtNumFull(analytics.totalComments)} />
- <MetricBox small icon={<TrendingUp />} label="Engagement" value={fmtPercent(analytics.overallEngagementRate)} subtitle="Likes and comments per view" />
- </div>
- <MetricGrid>
- <MetricBox small icon={<Zap />} label="Average views per video" value={fmtNum(analytics.avgViews)} />
- <MetricBox small icon={<ThumbsUp />} label="Average likes per video" value={fmtNum(analytics.avgLikes)} />
- <MetricBox small icon={<MessageSquare />} label="Average comments" value={fmtNum(analytics.avgComments)} />
- <MetricBox small icon={<BarChart2 />} label="Median views" value={fmtNum(analytics.medianViews)} />
- </MetricGrid>
- <MetricGrid>
- <MetricBox small icon={<Eye />} label="Views per subscriber" value={channel.viewsPerSubscriber} />
- <MetricBox small icon={<TrendingUp />} label="Subscribers per day" value={fmtNum(channel.avgSubGainPerDay)} />
- <MetricBox small icon={<Eye />} label="Views per day" value={fmtNum(channel.avgViewsPerDay)} />
- <MetricBox small icon={<Timer />} label="Average length" value={analytics.avgDurationFormatted} />
- </MetricGrid>
- <MetricGrid>
- <MetricBox small icon={<Clock />} label="Videos, last 7 days" value={analytics.videosLast7Days} />
- <MetricBox small icon={<Clock />} label="Videos, last 30 days" value={analytics.videosLast30Days} />
- <MetricBox small icon={<Clock />} label="Videos, last 90 days" value={analytics.videosLast90Days} />
- <MetricBox small icon={<Clock />} label="Videos, last 365 days" value={analytics.videosLast365Days} />
- </MetricGrid>
- <MetricGrid>
- <MetricBox small icon={<Calendar />} label="Estimated monthly views" value={fmtNum(channel.estimatedMonthlyViews)} />
- <MetricBox small icon={<Users />} label="Estimated monthly subscribers" value={fmtNum(channel.estimatedMonthlySubGain)} />
- <MetricBox small icon={<Flame />} label="Virality score" value={`${analytics.viralityScore}x`} />
- <MetricBox small icon={<Trophy />} label="Consistency" value={`${analytics.consistencyScore}/100`} />
- </MetricGrid>
-
- <SectionHeader title="Best performing videos" className="mt-5" />
- <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-4">
- {[
- { label: 'Most viewed', video: analytics.bestByViews },
- { label: 'Most liked', video: analytics.bestByLikes },
- { label: 'Most comments', video: analytics.bestByComments },
- { label: 'Best engagement', video: analytics.bestByEngagement },
- ].filter(({ video }) => video).map(({ label, video }) => (
- <MediaCard
- key={label}
- href={watchUrl(video.videoId)}
- image={video.thumbnail}
- title={video.title}
- topLeft={<MediaChip>{label}</MediaChip>}
- meta={<span>{fmtNum(video.viewCount)} views, {video.likeCount == null ? 'likes hidden' : `${fmtNum(video.likeCount)} likes`}</span>}
- />
- ))}
- </div>
- </TabsContent>
-
- <TabsContent value="videos" className="flex flex-col gap-4">
- <ChartPanel title="Top 10 videos by views" height={320}>
- <BarChart data={(analytics.top10ByViews || []).map(v => ({ name: `${(v?.title || '').slice(0, 28)}…`, views: v?.viewCount || 0, likes: v?.likeCount || 0 }))}>
- <CartesianGrid {...gridProps} vertical={false} />
- <XAxis dataKey="name" tick={{ ...axisTick, fontSize: 10 }} angle={-15} textAnchor="end" height={70} />
- <YAxis {...axisProps} tickFormatter={fmtNum} />
- <ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} formatter={v => fmtNumFull(v)} />
- <Bar dataKey="views" fill={SERIES.primary} radius={[4, 4, 0, 0]} name="Views" />
- <Bar dataKey="likes" fill={SERIES.neutral} radius={[4, 4, 0, 0]} name="Likes" />
- <Legend wrapperStyle={legendStyle} />
- </BarChart>
- </ChartPanel>
- <VideoTable videos={
- (analytics.top10ByViews || []).concat(analytics.top10ByLikes || [])
- .filter((v, i, arr) => v && arr.findIndex(x => x?.videoId === v?.videoId) === i)
- .sort((a, b) => (b?.viewCount || 0) - (a?.viewCount || 0))
- } />
- </TabsContent>
-
- <TabsContent value="engagement" className="flex flex-col gap-4">
- <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 xl:grid-cols-6">
- <MetricBox small icon={<ThumbsUp />} label="Total engagement" value={fmtNum(analytics.totalEngagement)} />
- <MetricBox small icon={<TrendingUp />} label="Engagement rate" value={fmtPercent(analytics.overallEngagementRate)} highlight />
- <MetricBox small icon={<ThumbsUp />} label="Like rate" value={analytics.totalViews > 0 ? fmtPercent(analytics.totalLikes / analytics.totalViews * 100) : '0%'} />
- <MetricBox small icon={<MessageSquare />} label="Comment rate" value={analytics.totalViews > 0 ? fmtPercent(analytics.totalComments / analytics.totalViews * 100) : '0%'} />
- <MetricBox small icon={<Flame />} label="Virality score" value={`${analytics.viralityScore}x`} />
- <MetricBox small icon={<BarChart2 />} label="Likes per comment" value={analytics.totalComments > 0 ? `${(analytics.totalLikes / analytics.totalComments).toFixed(1)}:1` : 'Not available'} />
- </div>
- <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
- <ChartPanel title="Engagement rate by month">
- <TrendArea data={analytics.engagementTrend || []} color={SERIES.cool} name="Engagement %" percent gradientId="egGrad" />
- </ChartPanel>
- <ChartPanel title="Like rate by month">
- <TrendArea data={analytics.likeRateTrend || []} color={SERIES.primary} name="Like rate %" percent gradientId="lrGrad" />
- </ChartPanel>
+ <Tabs value={tab} onValueChange={setTab} className="gap-6">
+ <div className="scrollbar-hide -mx-4 overflow-x-auto px-4 sm:mx-0 sm:px-0">
+ <TabsList className="w-max min-w-full">
+ {TABS.map(item => <TabsTrigger key={item.value} value={item.value}>{item.label}</TabsTrigger>)}
+ </TabsList>
</div>
- <SectionHeader title="Top 10 by engagement rate" />
- <VideoTable videos={analytics.top10ByEngagement} />
- </TabsContent>
-
- <TabsContent value="content" className="flex flex-col gap-4">
- <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 xl:grid-cols-6">
- <MetricBox small icon={<Film />} label="HD videos" value={analytics.hdCount} subtitle={fmtPercent(analytics.hdPercentage)} />
- <MetricBox small icon={<MessageSquare />} label="Captions" value={analytics.captionCount} subtitle={fmtPercent(analytics.captionPercentage)} />
- <MetricBox small icon={<Trophy />} label="Licensed" value={analytics.licensedCount} subtitle={fmtPercent(analytics.licensedPercentage)} />
- <MetricBox small icon={<VideoIcon />} label="Embeddable" value={analytics.embeddableCount} subtitle={fmtPercent(analytics.embeddablePercentage)} />
- <MetricBox small icon={<Users />} label="Made for kids" value={analytics.madeForKidsCount} />
- <MetricBox small icon={<Timer />} label="Average length" value={analytics.avgDurationFormatted} />
- </div>
- <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
- <ChartPanel title="Length distribution" empty={durationData.length === 0}>
- <PieChart>
- <Pie data={durationData} dataKey="value" nameKey="name" cx="50%" cy="50%" outerRadius={95} innerRadius={55} paddingAngle={2} strokeWidth={0}>
- {durationData.map(d => <Cell key={d.name} fill={d.color} />)}
- </Pie>
- <ReTooltip contentStyle={tooltipStyle} />
- <Legend iconType="circle" iconSize={8} wrapperStyle={legendStyle} />
- </PieChart>
- </ChartPanel>
- <ChartPanel title="Videos by category" empty={catData.length === 0}>
- <BarChart data={catData} layout="vertical">
- <CartesianGrid {...gridProps} horizontal={false} />
- <XAxis type="number" {...axisProps} />
- <YAxis dataKey="name" type="category" {...axisProps} width={120} />
- <ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} />
- <Bar dataKey="value" fill={SERIES.cool} radius={[0, 4, 4, 0]} name="Videos" />
- </BarChart>
- </ChartPanel>
- </div>
- <ChartPanel title="Videos by view range" height={240}>
- <BarChart data={(analytics.viewsDistribution?.ranges || []).map((r, i) => ({ range: r, count: analytics.viewsDistribution.counts[i] || 0 }))}>
- <CartesianGrid {...gridProps} vertical={false} />
- <XAxis dataKey="range" tick={{ ...axisTick, fontSize: 10 }} angle={-15} textAnchor="end" height={60} />
- <YAxis {...axisProps} />
- <ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} />
- <Bar dataKey="count" fill={SERIES.warm} radius={[4, 4, 0, 0]} name="Videos" />
- </BarChart>
- </ChartPanel>
- </TabsContent>
-
- <TabsContent value="publishing" className="flex flex-col gap-4">
- <MetricGrid>
- <MetricBox small icon={<Calendar />} label="Most common upload day" value={analytics.peakPublishDay || 'Not available'} />
- <MetricBox small icon={<Clock />} label="Most common upload hour" value={analytics.peakPublishHour !== undefined ? `${analytics.peakPublishHour}:00 UTC` : 'Not available'} />
- <MetricBox small icon={<Zap />} label="Uploads per week" value={analytics.uploadFrequencyPerWeek} />
- <MetricBox small icon={<Trophy />} label="Consistency" value={`${analytics.consistencyScore}/100`} />
- </MetricGrid>
- <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
- <ChartPanel title="Uploads by day of week">
- <BarChart data={dayData}>
- <CartesianGrid {...gridProps} vertical={false} />
- <XAxis dataKey="day" {...axisProps} />
- <YAxis {...axisProps} />
- <ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} />
- <Bar dataKey="count" fill={SERIES.cool} radius={[4, 4, 0, 0]} name="Videos" />
- </BarChart>
- </ChartPanel>
- <ChartPanel title="Uploads by hour (UTC)">
- <AreaChart data={hourData}>
- <defs>
- <linearGradient id="hourGrad" x1="0" y1="0" x2="0" y2="1">
- <stop offset="5%" stopColor={SERIES.warm} stopOpacity={0.2} />
- <stop offset="95%" stopColor={SERIES.warm} stopOpacity={0} />
- </linearGradient>
- </defs>
- <CartesianGrid {...gridProps} vertical={false} />
- <XAxis dataKey="hour" {...axisProps} />
- <YAxis {...axisProps} />
- <ReTooltip contentStyle={tooltipStyle} cursor={{ stroke: 'var(--line-strong)' }} />
- <Area type="monotone" dataKey="count" stroke={SERIES.warm} fill="url(#hourGrad)" strokeWidth={2} name="Videos" />
- </AreaChart>
- </ChartPanel>
- </div>
- </TabsContent>
-
- <TabsContent value="growth" className="flex flex-col gap-4">
- <MetricGrid>
- <MetricBox small icon={<TrendingUp />} label="Estimated yearly views" value={fmtNum(channel.estimatedYearlyViews)} highlight />
- <MetricBox small icon={<Users />} label="Estimated yearly subscribers" value={fmtNum(channel.estimatedYearlySubGain)} />
- <MetricBox small icon={<Eye />} label="Views per day" value={fmtNum(channel.avgViewsPerDay)} />
- <MetricBox small icon={<Users />} label="Subscribers per day" value={fmtNum(channel.avgSubGainPerDay)} />
- </MetricGrid>
- <ChartPanel title="Views by month" height={300}>
- <TrendArea data={analytics.viewsTrend || []} color={SERIES.primary} name="Views" gradientId="viewGrad" />
- </ChartPanel>
- <ChartPanel title="Uploads by month" height={240}>
- <BarChart data={(analytics.viewsTrend || []).map(t => ({ month: t.month, uploads: t.count }))}>
- <CartesianGrid {...gridProps} vertical={false} />
- <XAxis dataKey="month" {...axisProps} />
- <YAxis {...axisProps} />
- <ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} />
- <Bar dataKey="uploads" fill={SERIES.neutral} radius={[4, 4, 0, 0]} name="Uploads" />
- </BarChart>
- </ChartPanel>
- </TabsContent>
-
- <TabsContent value="shorts" className="flex flex-col gap-4">
- <MetricGrid>
- <MetricBox small icon={<Flame />} label="Shorts" value={analytics.shortsCount} />
- <MetricBox small icon={<VideoIcon />} label="Regular videos" value={analytics.regularCount} />
- <MetricBox small icon={<Eye />} label="Average views per Short" value={fmtNum(analytics.avgShortViews)} />
- <MetricBox small icon={<Eye />} label="Average views per video" value={fmtNum(analytics.avgRegularViews)} />
- </MetricGrid>
- <div className="grid grid-cols-1 gap-4 md:grid-cols-5">
- <ChartPanel title="Content split" className="md:col-span-2" empty={splitData.length === 0}>
- <PieChart>
- <Pie data={splitData} dataKey="value" nameKey="name" cx="50%" cy="50%" outerRadius={95} innerRadius={55} paddingAngle={2} strokeWidth={0}>
- {splitData.map(d => <Cell key={d.name} fill={d.color} />)}
- </Pie>
- <ReTooltip contentStyle={tooltipStyle} />
- <Legend iconType="circle" iconSize={8} wrapperStyle={legendStyle} />
- </PieChart>
- </ChartPanel>
- <ChartPanel title="Shorts compared with regular videos" className="md:col-span-3">
- <BarChart data={[
- { metric: 'Average views', Shorts: analytics.avgShortViews, Regular: analytics.avgRegularViews },
- { metric: 'Average likes', Shorts: analytics.avgShortLikes, Regular: analytics.avgRegularLikes },
- ]}>
- <CartesianGrid {...gridProps} vertical={false} />
- <XAxis dataKey="metric" {...axisProps} />
- <YAxis {...axisProps} tickFormatter={fmtNum} />
- <ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} formatter={v => fmtNumFull(v)} />
- <Bar dataKey="Shorts" fill={SERIES.primary} radius={[4, 4, 0, 0]} />
- <Bar dataKey="Regular" fill={SERIES.cool} radius={[4, 4, 0, 0]} />
- <Legend wrapperStyle={legendStyle} />
- </BarChart>
- </ChartPanel>
- </div>
- </TabsContent>
-
- <TabsContent value="tags" className="flex flex-col gap-4">
- <MetricGrid>
- <MetricBox small icon={<Tag />} label="Unique tags" value={analytics.tagFrequency?.length || 0} />
- <MetricBox small icon={<MessageSquare />} label="Caption rate" value={fmtPercent(analytics.captionPercentage)} />
- <MetricBox small icon={<Film />} label="HD rate" value={fmtPercent(analytics.hdPercentage)} />
- <MetricBox small icon={<VideoIcon />} label="Embeddable rate" value={fmtPercent(analytics.embeddablePercentage)} />
- </MetricGrid>
- <SurfaceBox title="Most used tags">
- {(analytics.tagFrequency || []).length === 0 ? (
- <p className="text-small text-ink-faint">These videos have no tags.</p>
- ) : (
- <div className="flex flex-wrap gap-1.5">
- {analytics.tagFrequency.map(({ tag, count }, i) => (
- <Badge key={tag} variant={i < 5 ? 'default' : 'outline'} className="h-6 px-2.5">
- {tag}<span className="opacity-70">{count}</span>
- </Badge>
- ))}
- </div>
- )}
- </SurfaceBox>
- {(analytics.tagFrequency || []).length > 0 && (
- <ChartPanel title="Tag usage, top 20" height={400}>
- <BarChart data={analytics.tagFrequency.slice(0, 20)} layout="vertical">
- <CartesianGrid {...gridProps} horizontal={false} />
- <XAxis type="number" {...axisProps} />
- <YAxis dataKey="tag" type="category" {...axisProps} width={140} />
- <ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} />
- <Bar dataKey="count" fill={SERIES.primary} radius={[0, 4, 4, 0]} name="Videos using this tag" />
- </BarChart>
- </ChartPanel>
- )}
- </TabsContent>
- </Tabs>
+ <TabsContent value="overview" className="flex flex-col gap-3"><ChannelOverviewTab channel={channel} analytics={analytics} /></TabsContent>
+ <TabsContent value="videos" className="flex flex-col gap-4"><ChannelVideosTab analytics={analytics} /></TabsContent>
+ <TabsContent value="engagement" className="flex flex-col gap-4"><ChannelEngagementTab analytics={analytics} /></TabsContent>
+ <TabsContent value="content" className="flex flex-col gap-4"><ChannelContentTab analytics={analytics} /></TabsContent>
+ <TabsContent value="publishing" className="flex flex-col gap-4"><ChannelPublishingTab analytics={analytics} /></TabsContent>
+ <TabsContent value="growth" className="flex flex-col gap-4"><ChannelGrowthTab channel={channel} analytics={analytics} /></TabsContent>
+ <TabsContent value="shorts" className="flex flex-col gap-4"><ChannelShortsTab analytics={analytics} /></TabsContent>
+ <TabsContent value="tags" className="flex flex-col gap-4"><ChannelTagsTab analytics={analytics} /></TabsContent>
+ </Tabs>
)}
</div>
);
diff --git a/frontend/src/features/analytics/channel/ChannelContentTab.jsx b/frontend/src/features/analytics/channel/ChannelContentTab.jsx
new file mode 100644
index 0000000..490141b
--- /dev/null
+++ b/frontend/src/features/analytics/channel/ChannelContentTab.jsx
@@ -0,0 +1,53 @@
+import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip as ReTooltip, PieChart, Pie, Cell, Legend } from 'recharts';
+import { Film, MessageSquare, Timer, Trophy, Users, VideoIcon } from 'lucide-react';
+import MetricBox from '@/components/MetricBox';
+import ChartPanel from '@/components/ChartPanel';
+import { SERIES, axisProps, axisTick, gridProps, legendStyle, tooltipCursor, tooltipStyle } from '@/lib/chart';
+import { fmtPercent } from '../../../utils/formatters';
+import { categoryDataOf, durationDataOf, viewRangeDataOf } from './channelChartData.js';
+
+export default function ChannelContentTab({ analytics }) {
+ const durationData = durationDataOf(analytics.durationDistribution);
+ const categoryData = categoryDataOf(analytics.categoryDistribution);
+ return (
+ <>
+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 xl:grid-cols-6">
+ <MetricBox small icon={<Film />} label="HD videos" value={analytics.hdCount} subtitle={fmtPercent(analytics.hdPercentage)} />
+ <MetricBox small icon={<MessageSquare />} label="Captions" value={analytics.captionCount} subtitle={fmtPercent(analytics.captionPercentage)} />
+ <MetricBox small icon={<Trophy />} label="Licensed" value={analytics.licensedCount} subtitle={fmtPercent(analytics.licensedPercentage)} />
+ <MetricBox small icon={<VideoIcon />} label="Embeddable" value={analytics.embeddableCount} subtitle={fmtPercent(analytics.embeddablePercentage)} />
+ <MetricBox small icon={<Users />} label="Made for kids" value={analytics.madeForKidsCount} />
+ <MetricBox small icon={<Timer />} label="Average length" value={analytics.avgDurationFormatted} />
+ </div>
+ <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
+ <ChartPanel title="Length distribution" empty={durationData.length === 0}>
+ <PieChart>
+ <Pie data={durationData} dataKey="value" nameKey="name" cx="50%" cy="50%" outerRadius={95} innerRadius={55} paddingAngle={2} strokeWidth={0}>
+ {durationData.map(slice => <Cell key={slice.name} fill={slice.color} />)}
+ </Pie>
+ <ReTooltip contentStyle={tooltipStyle} />
+ <Legend iconType="circle" iconSize={8} wrapperStyle={legendStyle} />
+ </PieChart>
+ </ChartPanel>
+ <ChartPanel title="Videos by category" empty={categoryData.length === 0}>
+ <BarChart data={categoryData} layout="vertical">
+ <CartesianGrid {...gridProps} horizontal={false} />
+ <XAxis type="number" {...axisProps} />
+ <YAxis dataKey="name" type="category" {...axisProps} width={120} />
+ <ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} />
+ <Bar dataKey="value" fill={SERIES.cool} radius={[0, 4, 4, 0]} name="Videos" />
+ </BarChart>
+ </ChartPanel>
+ </div>
+ <ChartPanel title="Videos by view range" height={240}>
+ <BarChart data={viewRangeDataOf(analytics.viewsDistribution)}>
+ <CartesianGrid {...gridProps} vertical={false} />
+ <XAxis dataKey="range" tick={{ ...axisTick, fontSize: 10 }} angle={-15} textAnchor="end" height={60} />
+ <YAxis {...axisProps} />
+ <ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} />
+ <Bar dataKey="count" fill={SERIES.warm} radius={[4, 4, 0, 0]} name="Videos" />
+ </BarChart>
+ </ChartPanel>
+ </>
+ );
+}
diff --git a/frontend/src/features/analytics/channel/ChannelEngagementTab.jsx b/frontend/src/features/analytics/channel/ChannelEngagementTab.jsx
new file mode 100644
index 0000000..d7b1c3a
--- /dev/null
+++ b/frontend/src/features/analytics/channel/ChannelEngagementTab.jsx
@@ -0,0 +1,34 @@
+import { BarChart2, Flame, MessageSquare, ThumbsUp, TrendingUp } from 'lucide-react';
+import MetricBox from '@/components/MetricBox';
+import ChartPanel from '@/components/ChartPanel';
+import SectionHeader from '@/components/SectionHeader';
+import { SERIES } from '@/lib/chart';
+import { fmtNum, fmtPercent } from '../../../utils/formatters';
+import { likesPerComment, rateOf } from './channelChartData.js';
+import ChannelVideoTable from './ChannelVideoTable';
+import TrendArea from './TrendArea';
+
+export default function ChannelEngagementTab({ analytics }) {
+ return (
+ <>
+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 xl:grid-cols-6">
+ <MetricBox small icon={<ThumbsUp />} label="Total engagement" value={fmtNum(analytics.totalEngagement)} />
+ <MetricBox small icon={<TrendingUp />} label="Engagement rate" value={fmtPercent(analytics.overallEngagementRate)} highlight />
+ <MetricBox small icon={<ThumbsUp />} label="Like rate" value={rateOf(analytics.totalLikes, analytics.totalViews)} />
+ <MetricBox small icon={<MessageSquare />} label="Comment rate" value={rateOf(analytics.totalComments, analytics.totalViews)} />
+ <MetricBox small icon={<Flame />} label="Virality score" value={`${analytics.viralityScore}x`} />
+ <MetricBox small icon={<BarChart2 />} label="Likes per comment" value={likesPerComment(analytics)} />
+ </div>
+ <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
+ <ChartPanel title="Engagement rate by month">
+ <TrendArea data={analytics.engagementTrend || []} color={SERIES.cool} name="Engagement %" percent gradientId="egGrad" />
+ </ChartPanel>
+ <ChartPanel title="Like rate by month">
+ <TrendArea data={analytics.likeRateTrend || []} color={SERIES.primary} name="Like rate %" percent gradientId="lrGrad" />
+ </ChartPanel>
+ </div>
+ <SectionHeader title="Top 10 by engagement rate" />
+ <ChannelVideoTable videos={analytics.top10ByEngagement} />
+ </>
+ );
+}
diff --git a/frontend/src/features/analytics/channel/ChannelGrowthTab.jsx b/frontend/src/features/analytics/channel/ChannelGrowthTab.jsx
new file mode 100644
index 0000000..32bd8e7
--- /dev/null
+++ b/frontend/src/features/analytics/channel/ChannelGrowthTab.jsx
@@ -0,0 +1,34 @@
+import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip as ReTooltip } from 'recharts';
+import { Eye, TrendingUp, Users } from 'lucide-react';
+import MetricBox from '@/components/MetricBox';
+import ChartPanel from '@/components/ChartPanel';
+import { SERIES, axisProps, gridProps, tooltipCursor, tooltipStyle } from '@/lib/chart';
+import { fmtNum } from '../../../utils/formatters';
+import { uploadsByMonthOf } from './channelChartData.js';
+import MetricGrid from './MetricGrid';
+import TrendArea from './TrendArea';
+
+export default function ChannelGrowthTab({ channel, analytics }) {
+ return (
+ <>
+ <MetricGrid>
+ <MetricBox small icon={<TrendingUp />} label="Estimated yearly views" value={fmtNum(channel.estimatedYearlyViews)} highlight />
+ <MetricBox small icon={<Users />} label="Estimated yearly subscribers" value={fmtNum(channel.estimatedYearlySubGain)} />
+ <MetricBox small icon={<Eye />} label="Views per day" value={fmtNum(channel.avgViewsPerDay)} />
+ <MetricBox small icon={<Users />} label="Subscribers per day" value={fmtNum(channel.avgSubGainPerDay)} />
+ </MetricGrid>
+ <ChartPanel title="Views by month" height={300}>
+ <TrendArea data={analytics.viewsTrend || []} color={SERIES.primary} name="Views" gradientId="viewGrad" />
+ </ChartPanel>
+ <ChartPanel title="Uploads by month" height={240}>
+ <BarChart data={uploadsByMonthOf(analytics.viewsTrend)}>
+ <CartesianGrid {...gridProps} vertical={false} />
+ <XAxis dataKey="month" {...axisProps} />
+ <YAxis {...axisProps} />
+ <ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} />
+ <Bar dataKey="uploads" fill={SERIES.neutral} radius={[4, 4, 0, 0]} name="Uploads" />
+ </BarChart>
+ </ChartPanel>
+ </>
+ );
+}
diff --git a/frontend/src/features/analytics/channel/ChannelHeader.jsx b/frontend/src/features/analytics/channel/ChannelHeader.jsx
new file mode 100644
index 0000000..4ca59ee
--- /dev/null
+++ b/frontend/src/features/analytics/channel/ChannelHeader.jsx
@@ -0,0 +1,27 @@
+import { RefreshCw } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import { Badge } from '@/components/ui/badge';
+import PageHeader from '@/components/PageHeader';
+import { AccountAvatar } from '@/components/platform';
+import { channelMeta } from './channelChartData.js';
+
+export default function ChannelHeader({ account, channel, back, onRefresh }) {
+ return (
+ <PageHeader
+ back={back}
+ media={<AccountAvatar account={{ ...account, thumbnail: channel.thumbnails?.high || channel.thumbnails?.medium || account?.thumbnail }} size="xl" showPlatform />}
+ title={channel.title}
+ description={
+ <span className="flex flex-wrap gap-1.5">
+ {channelMeta(channel).map(item => <Badge key={item} variant="outline">{item}</Badge>)}
+ </span>
+ }
+ actions={
+ <Button variant="outline" size="sm" onClick={onRefresh}>
+ <RefreshCw data-icon="inline-start" />
+ Refresh
+ </Button>
+ }
+ />
+ );
+}
diff --git a/frontend/src/features/analytics/channel/ChannelNoVideos.jsx b/frontend/src/features/analytics/channel/ChannelNoVideos.jsx
new file mode 100644
index 0000000..bcf7105
--- /dev/null
+++ b/frontend/src/features/analytics/channel/ChannelNoVideos.jsx
@@ -0,0 +1,24 @@
+import { Eye, Users, VideoIcon } from 'lucide-react';
+import MetricBox from '@/components/MetricBox';
+import SurfaceBox from '@/components/SurfaceBox';
+import { EmptyState } from '@/components/StateViews';
+import { fmtNum, fmtNumFull } from '../../../utils/formatters';
+
+export default function ChannelNoVideos({ channel }) {
+ return (
+ <>
+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-3">
+ <MetricBox small icon={<Users />} label="Subscribers" value={fmtNum(channel.subscriberCount)} subtitle={fmtNumFull(channel.subscriberCount)} />
+ <MetricBox small icon={<Eye />} label="Total views" value={fmtNum(channel.viewCount)} subtitle={fmtNumFull(channel.viewCount)} />
+ <MetricBox small icon={<VideoIcon />} label="Total videos" value={fmtNum(channel.videoCount)} subtitle="Public uploads" />
+ </div>
+ <SurfaceBox>
+ <EmptyState
+ icon={<VideoIcon />}
+ title="No public videos yet"
+ description="Video analytics start with this channel's first public upload. After publishing, choose Refresh."
+ />
+ </SurfaceBox>
+ </>
+ );
+}
diff --git a/frontend/src/features/analytics/channel/ChannelOverviewTab.jsx b/frontend/src/features/analytics/channel/ChannelOverviewTab.jsx
new file mode 100644
index 0000000..b45ac7d
--- /dev/null
+++ b/frontend/src/features/analytics/channel/ChannelOverviewTab.jsx
@@ -0,0 +1,68 @@
+import {
+ BarChart2, Calendar, Clock, Eye, Flame, MessageSquare, ThumbsUp, Timer, TrendingUp, Trophy, Users, VideoIcon, Zap,
+} from 'lucide-react';
+import MetricBox from '@/components/MetricBox';
+import SectionHeader from '@/components/SectionHeader';
+import MediaCard, { MediaChip } from '@/components/MediaCard';
+import { fmtNum, fmtNumFull, fmtPercent } from '../../../utils/formatters';
+import { bestVideosOf, likesLabel, watchUrl } from './channelChartData.js';
+import MetricGrid from './MetricGrid';
+
+function BestVideos({ analytics }) {
+ return (
+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-4">
+ {bestVideosOf(analytics).map(({ label, video }) => (
+ <MediaCard
+ key={label}
+ href={watchUrl(video.videoId)}
+ image={video.thumbnail}
+ title={video.title}
+ topLeft={<MediaChip>{label}</MediaChip>}
+ meta={<span>{fmtNum(video.viewCount)} views, {likesLabel(video.likeCount)}</span>}
+ />
+ ))}
+ </div>
+ );
+}
+
+export default function ChannelOverviewTab({ channel, analytics }) {
+ return (
+ <>
+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 xl:grid-cols-6">
+ <MetricBox small icon={<Eye />} label="Total views" value={fmtNum(channel.viewCount)} subtitle={fmtNumFull(channel.viewCount)} highlight />
+ <MetricBox small icon={<Users />} label="Subscribers" value={fmtNum(channel.subscriberCount)} subtitle={fmtNumFull(channel.subscriberCount)} />
+ <MetricBox small icon={<VideoIcon />} label="Total videos" value={fmtNum(channel.videoCount)} subtitle={`${analytics.totalVideos} analyzed`} />
+ <MetricBox small icon={<ThumbsUp />} label="Total likes" value={fmtNum(analytics.totalLikes)} subtitle={fmtNumFull(analytics.totalLikes)} />
+ <MetricBox small icon={<MessageSquare />} label="Comments" value={fmtNum(analytics.totalComments)} subtitle={fmtNumFull(analytics.totalComments)} />
+ <MetricBox small icon={<TrendingUp />} label="Engagement" value={fmtPercent(analytics.overallEngagementRate)} subtitle="Likes and comments per view" />
+ </div>
+ <MetricGrid>
+ <MetricBox small icon={<Zap />} label="Average views per video" value={fmtNum(analytics.avgViews)} />
+ <MetricBox small icon={<ThumbsUp />} label="Average likes per video" value={fmtNum(analytics.avgLikes)} />
+ <MetricBox small icon={<MessageSquare />} label="Average comments" value={fmtNum(analytics.avgComments)} />
+ <MetricBox small icon={<BarChart2 />} label="Median views" value={fmtNum(analytics.medianViews)} />
+ </MetricGrid>
+ <MetricGrid>
+ <MetricBox small icon={<Eye />} label="Views per subscriber" value={channel.viewsPerSubscriber} />
+ <MetricBox small icon={<TrendingUp />} label="Subscribers per day" value={fmtNum(channel.avgSubGainPerDay)} />
+ <MetricBox small icon={<Eye />} label="Views per day" value={fmtNum(channel.avgViewsPerDay)} />
+ <MetricBox small icon={<Timer />} label="Average length" value={analytics.avgDurationFormatted} />
+ </MetricGrid>
+ <MetricGrid>
+ <MetricBox small icon={<Clock />} label="Videos, last 7 days" value={analytics.videosLast7Days} />
+ <MetricBox small icon={<Clock />} label="Videos, last 30 days" value={analytics.videosLast30Days} />
+ <MetricBox small icon={<Clock />} label="Videos, last 90 days" value={analytics.videosLast90Days} />
+ <MetricBox small icon={<Clock />} label="Videos, last 365 days" value={analytics.videosLast365Days} />
+ </MetricGrid>
+ <MetricGrid>
+ <MetricBox small icon={<Calendar />} label="Estimated monthly views" value={fmtNum(channel.estimatedMonthlyViews)} />
+ <MetricBox small icon={<Users />} label="Estimated monthly subscribers" value={fmtNum(channel.estimatedMonthlySubGain)} />
+ <MetricBox small icon={<Flame />} label="Virality score" value={`${analytics.viralityScore}x`} />
+ <MetricBox small icon={<Trophy />} label="Consistency" value={`${analytics.consistencyScore}/100`} />
+ </MetricGrid>
+
+ <SectionHeader title="Best performing videos" className="mt-5" />
+ <BestVideos analytics={analytics} />
+ </>
+ );
+}
diff --git a/frontend/src/features/analytics/channel/ChannelPublishingTab.jsx b/frontend/src/features/analytics/channel/ChannelPublishingTab.jsx
new file mode 100644
index 0000000..d964ac0
--- /dev/null
+++ b/frontend/src/features/analytics/channel/ChannelPublishingTab.jsx
@@ -0,0 +1,46 @@
+import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip as ReTooltip, AreaChart, Area } from 'recharts';
+import { Calendar, Clock, Trophy, Zap } from 'lucide-react';
+import MetricBox from '@/components/MetricBox';
+import ChartPanel from '@/components/ChartPanel';
+import { SERIES, axisProps, gridProps, tooltipCursor, tooltipStyle } from '@/lib/chart';
+import { dayDataOf, hourDataOf, peakHourLabel } from './channelChartData.js';
+import MetricGrid from './MetricGrid';
+
+export default function ChannelPublishingTab({ analytics }) {
+ return (
+ <>
+ <MetricGrid>
+ <MetricBox small icon={<Calendar />} label="Most common upload day" value={analytics.peakPublishDay || 'Not available'} />
+ <MetricBox small icon={<Clock />} label="Most common upload hour" value={peakHourLabel(analytics.peakPublishHour)} />
+ <MetricBox small icon={<Zap />} label="Uploads per week" value={analytics.uploadFrequencyPerWeek} />
+ <MetricBox small icon={<Trophy />} label="Consistency" value={`${analytics.consistencyScore}/100`} />
+ </MetricGrid>
+ <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
+ <ChartPanel title="Uploads by day of week">
+ <BarChart data={dayDataOf(analytics.publishDayDistribution)}>
+ <CartesianGrid {...gridProps} vertical={false} />
+ <XAxis dataKey="day" {...axisProps} />
+ <YAxis {...axisProps} />
+ <ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} />
+ <Bar dataKey="count" fill={SERIES.cool} radius={[4, 4, 0, 0]} name="Videos" />
+ </BarChart>
+ </ChartPanel>
+ <ChartPanel title="Uploads by hour (UTC)">
+ <AreaChart data={hourDataOf(analytics.publishHourDistribution)}>
+ <defs>
+ <linearGradient id="hourGrad" x1="0" y1="0" x2="0" y2="1">
+ <stop offset="5%" stopColor={SERIES.warm} stopOpacity={0.2} />
+ <stop offset="95%" stopColor={SERIES.warm} stopOpacity={0} />
+ </linearGradient>
+ </defs>
+ <CartesianGrid {...gridProps} vertical={false} />
+ <XAxis dataKey="hour" {...axisProps} />
+ <YAxis {...axisProps} />
+ <ReTooltip contentStyle={tooltipStyle} cursor={{ stroke: 'var(--line-strong)' }} />
+ <Area type="monotone" dataKey="count" stroke={SERIES.warm} fill="url(#hourGrad)" strokeWidth={2} name="Videos" />
+ </AreaChart>
+ </ChartPanel>
+ </div>
+ </>
+ );
+}
diff --git a/frontend/src/features/analytics/channel/ChannelShortsTab.jsx b/frontend/src/features/analytics/channel/ChannelShortsTab.jsx
new file mode 100644
index 0000000..a73abe5
--- /dev/null
+++ b/frontend/src/features/analytics/channel/ChannelShortsTab.jsx
@@ -0,0 +1,48 @@
+import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip as ReTooltip, PieChart, Pie, Cell, Legend } from 'recharts';
+import { Eye, Flame, VideoIcon } from 'lucide-react';
+import MetricBox from '@/components/MetricBox';
+import ChartPanel from '@/components/ChartPanel';
+import { SERIES, axisProps, gridProps, legendStyle, tooltipCursor, tooltipStyle } from '@/lib/chart';
+import { fmtNum, fmtNumFull } from '../../../utils/formatters';
+import { shortsComparisonOf, splitDataOf } from './channelChartData.js';
+import MetricGrid from './MetricGrid';
+
+function fullNumber(value) {
+ return fmtNumFull(value);
+}
+
+export default function ChannelShortsTab({ analytics }) {
+ const splitData = splitDataOf(analytics);
+ return (
+ <>
+ <MetricGrid>
+ <MetricBox small icon={<Flame />} label="Shorts" value={analytics.shortsCount} />
+ <MetricBox small icon={<VideoIcon />} label="Regular videos" value={analytics.regularCount} />
+ <MetricBox small icon={<Eye />} label="Average views per Short" value={fmtNum(analytics.avgShortViews)} />
+ <MetricBox small icon={<Eye />} label="Average views per video" value={fmtNum(analytics.avgRegularViews)} />
+ </MetricGrid>
+ <div className="grid grid-cols-1 gap-4 md:grid-cols-5">
+ <ChartPanel title="Content split" className="md:col-span-2" empty={splitData.length === 0}>
+ <PieChart>
+ <Pie data={splitData} dataKey="value" nameKey="name" cx="50%" cy="50%" outerRadius={95} innerRadius={55} paddingAngle={2} strokeWidth={0}>
+ {splitData.map(slice => <Cell key={slice.name} fill={slice.color} />)}
+ </Pie>
+ <ReTooltip contentStyle={tooltipStyle} />
+ <Legend iconType="circle" iconSize={8} wrapperStyle={legendStyle} />
+ </PieChart>
+ </ChartPanel>
+ <ChartPanel title="Shorts compared with regular videos" className="md:col-span-3">
+ <BarChart data={shortsComparisonOf(analytics)}>
+ <CartesianGrid {...gridProps} vertical={false} />
+ <XAxis dataKey="metric" {...axisProps} />
+ <YAxis {...axisProps} tickFormatter={fmtNum} />
+ <ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} formatter={fullNumber} />
+ <Bar dataKey="Shorts" fill={SERIES.primary} radius={[4, 4, 0, 0]} />
+ <Bar dataKey="Regular" fill={SERIES.cool} radius={[4, 4, 0, 0]} />
+ <Legend wrapperStyle={legendStyle} />
+ </BarChart>
+ </ChartPanel>
+ </div>
+ </>
+ );
+}
diff --git a/frontend/src/features/analytics/channel/ChannelTagsTab.jsx b/frontend/src/features/analytics/channel/ChannelTagsTab.jsx
new file mode 100644
index 0000000..ed7a8b8
--- /dev/null
+++ b/frontend/src/features/analytics/channel/ChannelTagsTab.jsx
@@ -0,0 +1,34 @@
+import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip as ReTooltip } from 'recharts';
+import { Film, MessageSquare, Tag, VideoIcon } from 'lucide-react';
+import MetricBox from '@/components/MetricBox';
+import ChartPanel from '@/components/ChartPanel';
+import { SERIES, axisProps, gridProps, tooltipCursor, tooltipStyle } from '@/lib/chart';
+import { fmtPercent } from '../../../utils/formatters';
+import MetricGrid from './MetricGrid';
+import TagCloud from './TagCloud';
+
+export default function ChannelTagsTab({ analytics }) {
+ const tags = analytics.tagFrequency || [];
+ return (
+ <>
+ <MetricGrid>
+ <MetricBox small icon={<Tag />} label="Unique tags" value={analytics.tagFrequency?.length || 0} />
+ <MetricBox small icon={<MessageSquare />} label="Caption rate" value={fmtPercent(analytics.captionPercentage)} />
+ <MetricBox small icon={<Film />} label="HD rate" value={fmtPercent(analytics.hdPercentage)} />
+ <MetricBox small icon={<VideoIcon />} label="Embeddable rate" value={fmtPercent(analytics.embeddablePercentage)} />
+ </MetricGrid>
+ <TagCloud tags={tags} />
+ {tags.length > 0 && (
+ <ChartPanel title="Tag usage, top 20" height={400}>
+ <BarChart data={tags.slice(0, 20)} layout="vertical">
+ <CartesianGrid {...gridProps} horizontal={false} />
+ <XAxis type="number" {...axisProps} />
+ <YAxis dataKey="tag" type="category" {...axisProps} width={140} />
+ <ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} />
+ <Bar dataKey="count" fill={SERIES.primary} radius={[0, 4, 4, 0]} name="Videos using this tag" />
+ </BarChart>
+ </ChartPanel>
+ )}
+ </>
+ );
+}
diff --git a/frontend/src/features/analytics/channel/ChannelVideoTable.jsx b/frontend/src/features/analytics/channel/ChannelVideoTable.jsx
new file mode 100644
index 0000000..abafd10
--- /dev/null
+++ b/frontend/src/features/analytics/channel/ChannelVideoTable.jsx
@@ -0,0 +1,59 @@
+import { Play } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import { Badge } from '@/components/ui/badge';
+import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
+import SurfaceBox from '@/components/SurfaceBox';
+import { fmtCount, fmtDate, fmtDuration, fmtNum, fmtPercent } from '../../../utils/formatters';
+import { watchUrl } from './channelChartData.js';
+
+function VideoRow({ video, rank }) {
+ return (
+ <TableRow>
+ <TableCell className="text-right font-mono text-caption text-ink-faint">{rank}</TableCell>
+ <TableCell className="max-w-[280px]">
+ <a href={watchUrl(video.videoId)} target="_blank" rel="noopener noreferrer" className="block truncate text-sm font-medium text-ink hover:underline">{video.title}</a>
+ </TableCell>
+ <TableCell className="text-right font-semibold text-ink">{fmtNum(video.viewCount)}</TableCell>
+ <TableCell className="text-right text-ink-muted">{fmtCount(video.likeCount)}</TableCell>
+ <TableCell className="text-right text-ink-muted">{fmtCount(video.commentCount)}</TableCell>
+ <TableCell className="text-right">
+ <Badge variant={parseFloat(video.engagementRate) > 5 ? 'success' : 'secondary'}>{fmtPercent(video.engagementRate)}</Badge>
+ </TableCell>
+ <TableCell className="text-right text-ink-muted">{fmtDuration(video.durationSeconds)}</TableCell>
+ <TableCell className="text-right text-small text-ink-faint">{fmtDate(video.publishedAt)}</TableCell>
+ <TableCell>
+ <Button variant="ghost" size="icon-xs" render={<a href={watchUrl(video.videoId)} target="_blank" rel="noopener noreferrer" aria-label={`Watch ${video.title} on YouTube`} />}>
+ <Play />
+ </Button>
+ </TableCell>
+ </TableRow>
+ );
+}
+
+export default function ChannelVideoTable({ videos }) {
+ const rows = (videos || []).filter(Boolean);
+ return (
+ <SurfaceBox content={false} className="overflow-hidden">
+ <div className="max-h-[480px] overflow-y-auto">
+ <Table>
+ <TableHeader className="sticky top-0 z-10 bg-surface-raised">
+ <TableRow>
+ <TableHead className="w-10 text-right">#</TableHead>
+ <TableHead>Video</TableHead>
+ <TableHead className="text-right">Views</TableHead>
+ <TableHead className="text-right">Likes</TableHead>
+ <TableHead className="text-right">Comments</TableHead>
+ <TableHead className="text-right">Engagement</TableHead>
+ <TableHead className="text-right">Length</TableHead>
+ <TableHead className="text-right">Published</TableHead>
+ <TableHead className="w-10"><span className="sr-only">Watch</span></TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {rows.map((video, i) => <VideoRow key={video.videoId} video={video} rank={i + 1} />)}
+ </TableBody>
+ </Table>
+ </div>
+ </SurfaceBox>
+ );
+}
diff --git a/frontend/src/features/analytics/channel/ChannelVideosTab.jsx b/frontend/src/features/analytics/channel/ChannelVideosTab.jsx
new file mode 100644
index 0000000..fb05ffc
--- /dev/null
+++ b/frontend/src/features/analytics/channel/ChannelVideosTab.jsx
@@ -0,0 +1,29 @@
+import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip as ReTooltip, Legend } from 'recharts';
+import ChartPanel from '@/components/ChartPanel';
+import { SERIES, axisProps, axisTick, gridProps, legendStyle, tooltipCursor, tooltipStyle } from '@/lib/chart';
+import { fmtNum, fmtNumFull } from '../../../utils/formatters';
+import { topVideoRowsOf, topVideosChartOf } from './channelChartData.js';
+import ChannelVideoTable from './ChannelVideoTable';
+
+function fullNumber(value) {
+ return fmtNumFull(value);
+}
+
+export default function ChannelVideosTab({ analytics }) {
+ return (
+ <>
+ <ChartPanel title="Top 10 videos by views" height={320}>
+ <BarChart data={topVideosChartOf(analytics.top10ByViews)}>
+ <CartesianGrid {...gridProps} vertical={false} />
+ <XAxis dataKey="name" tick={{ ...axisTick, fontSize: 10 }} angle={-15} textAnchor="end" height={70} />
+ <YAxis {...axisProps} tickFormatter={fmtNum} />
+ <ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} formatter={fullNumber} />
+ <Bar dataKey="views" fill={SERIES.primary} radius={[4, 4, 0, 0]} name="Views" />
+ <Bar dataKey="likes" fill={SERIES.neutral} radius={[4, 4, 0, 0]} name="Likes" />
+ <Legend wrapperStyle={legendStyle} />
+ </BarChart>
+ </ChartPanel>
+ <ChannelVideoTable videos={topVideoRowsOf(analytics)} />
+ </>
+ );
+}
diff --git a/frontend/src/features/analytics/channel/MetricGrid.jsx b/frontend/src/features/analytics/channel/MetricGrid.jsx
new file mode 100644
index 0000000..5e79d04
--- /dev/null
+++ b/frontend/src/features/analytics/channel/MetricGrid.jsx
@@ -0,0 +1,5 @@
+import { cn } from '@/lib/utils';
+
+export default function MetricGrid({ className, children }) {
+ return <div className={cn('grid grid-cols-2 gap-3 sm:grid-cols-4', className)}>{children}</div>;
+}
diff --git a/frontend/src/features/analytics/channel/TagCloud.jsx b/frontend/src/features/analytics/channel/TagCloud.jsx
new file mode 100644
index 0000000..07ef17e
--- /dev/null
+++ b/frontend/src/features/analytics/channel/TagCloud.jsx
@@ -0,0 +1,20 @@
+import { Badge } from '@/components/ui/badge';
+import SurfaceBox from '@/components/SurfaceBox';
+
+export default function TagCloud({ tags }) {
+ return (
+ <SurfaceBox title="Most used tags">
+ {tags.length === 0 ? (
+ <p className="text-small text-ink-faint">These videos have no tags.</p>
+ ) : (
+ <div className="flex flex-wrap gap-1.5">
+ {tags.map(({ tag, count }, i) => (
+ <Badge key={tag} variant={i < 5 ? 'default' : 'outline'} className="h-6 px-2.5">
+ {tag}<span className="opacity-70">{count}</span>
+ </Badge>
+ ))}
+ </div>
+ )}
+ </SurfaceBox>
+ );
+}
diff --git a/frontend/src/features/analytics/channel/TrendArea.jsx b/frontend/src/features/analytics/channel/TrendArea.jsx
new file mode 100644
index 0000000..2b00587
--- /dev/null
+++ b/frontend/src/features/analytics/channel/TrendArea.jsx
@@ -0,0 +1,29 @@
+import { AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip as ReTooltip } from 'recharts';
+import { axisProps, gridProps, tooltipStyle } from '@/lib/chart';
+import { fmtNum, fmtNumFull } from '../../../utils/formatters';
+
+function percentTick(value) {
+ return `${value}%`;
+}
+
+function fullNumber(value) {
+ return fmtNumFull(value);
+}
+
+export default function TrendArea({ data, dataKey = 'value', color, name, percent = false, gradientId }) {
+ return (
+ <AreaChart data={data}>
+ <defs>
+ <linearGradient id={gradientId} x1="0" y1="0" x2="0" y2="1">
+ <stop offset="5%" stopColor={color} stopOpacity={0.2} />
+ <stop offset="95%" stopColor={color} stopOpacity={0} />
+ </linearGradient>
+ </defs>
+ <CartesianGrid {...gridProps} vertical={false} />
+ <XAxis dataKey="month" {...axisProps} />
+ <YAxis {...axisProps} tickFormatter={percent ? percentTick : fmtNum} width={48} />
+ <ReTooltip contentStyle={tooltipStyle} cursor={{ stroke: 'var(--line-strong)' }} formatter={percent ? undefined : fullNumber} />
+ <Area type="monotone" dataKey={dataKey} stroke={color} fill={`url(#${gradientId})`} strokeWidth={2} name={name} />
+ </AreaChart>
+ );
+}
diff --git a/frontend/src/features/analytics/channel/channelChartData.js b/frontend/src/features/analytics/channel/channelChartData.js
new file mode 100644
index 0000000..9d35847
--- /dev/null
+++ b/frontend/src/features/analytics/channel/channelChartData.js
@@ -0,0 +1,110 @@
+// chart rows and labels for channel analytics; no JSX or path aliases so node --test can import it
+
+import { SERIES } from '../../../lib/chart.js';
+import { CATEGORY_MAP, fmtDate, fmtNum, fmtPercent } from '../../../utils/formatters.js';
+
+export function watchUrl(videoId) {
+ return `https://www.youtube.com/watch?v=${videoId}`;
+}
+
+export function channelMeta(channel) {
+ return [
+ channel.customUrl,
+ channel.country && channel.country !== 'Unknown' ? channel.country : null,
+ `${channel.channelAgeYears} years old`,
+ `Since ${fmtDate(channel.publishedAt)}`,
+ ].filter(Boolean);
+}
+
+export function dayDataOf(distribution) {
+ if (!distribution) return [];
+ return Object.entries(distribution).map(([day, count]) => ({ day, count }));
+}
+
+export function hourDataOf(distribution) {
+ if (!distribution) return [];
+ return Object.entries(distribution)
+ .sort((a, b) => parseInt(a[0], 10) - parseInt(b[0], 10))
+ .map(([hour, count]) => ({ hour: `${hour}:00`, count }));
+}
+
+export function durationDataOf(distribution) {
+ if (!distribution) return [];
+ return [
+ { name: 'Shorts (under 1m)', value: distribution.short, color: SERIES.primary },
+ { name: 'Medium (1 to 10m)', value: distribution.medium, color: SERIES.cool },
+ { name: 'Long (10 to 60m)', value: distribution.long, color: SERIES.neutral },
+ { name: 'Very long (1h+)', value: distribution.veryLong, color: SERIES.warm },
+ ].filter(slice => slice.value > 0);
+}
+
+export function categoryDataOf(distribution) {
+ if (!distribution) return [];
+ return Object.entries(distribution).map(([catId, count]) => ({ name: CATEGORY_MAP[catId] || `Category ${catId}`, value: count }));
+}
+
+export function splitDataOf(analytics) {
+ return [
+ { name: 'Shorts', value: analytics.shortsCount, color: SERIES.primary },
+ { name: 'Regular', value: analytics.regularCount, color: SERIES.cool },
+ ].filter(slice => slice.value > 0);
+}
+
+export function shortsComparisonOf(analytics) {
+ return [
+ { metric: 'Average views', Shorts: analytics.avgShortViews, Regular: analytics.avgRegularViews },
+ { metric: 'Average likes', Shorts: analytics.avgShortLikes, Regular: analytics.avgRegularLikes },
+ ];
+}
+
+// every title gets the ellipsis, even short ones
+export function topVideosChartOf(videos) {
+ return (videos || []).map(video => ({
+ name: `${(video?.title || '').slice(0, 28)}…`, views: video?.viewCount || 0, likes: video?.likeCount || 0,
+ }));
+}
+
+// most viewed and most liked overlap, so each video is listed once, by views
+export function topVideoRowsOf(analytics) {
+ return (analytics.top10ByViews || []).concat(analytics.top10ByLikes || [])
+ .filter((video, i, all) => video && all.findIndex(other => other?.videoId === video?.videoId) === i)
+ .sort((a, b) => (b?.viewCount || 0) - (a?.viewCount || 0));
+}
+
+export function viewRangeDataOf(viewsDistribution) {
+ return (viewsDistribution?.ranges || []).map((range, i) => ({ range, count: viewsDistribution.counts[i] || 0 }));
+}
+
+export function uploadsByMonthOf(viewsTrend) {
+ return (viewsTrend || []).map(point => ({ month: point.month, uploads: point.count }));
+}
+
+export function rateOf(part, total) {
+ if (total > 0) return fmtPercent(part / total * 100);
+ return '0%';
+}
+
+export function likesPerComment(analytics) {
+ if (analytics.totalComments > 0) return `${(analytics.totalLikes / analytics.totalComments).toFixed(1)}:1`;
+ return 'Not available';
+}
+
+// only a missing hour reads as unavailable; null still prints as an hour
+export function peakHourLabel(hour) {
+ if (hour !== undefined) return `${hour}:00 UTC`;
+ return 'Not available';
+}
+
+export function bestVideosOf(analytics) {
+ return [
+ { label: 'Most viewed', video: analytics.bestByViews },
+ { label: 'Most liked', video: analytics.bestByLikes },
+ { label: 'Most comments', video: analytics.bestByComments },
+ { label: 'Best engagement', video: analytics.bestByEngagement },
+ ].filter(({ video }) => video);
+}
+
+export function likesLabel(likeCount) {
+ if (likeCount == null) return 'likes hidden';
+ return `${fmtNum(likeCount)} likes`;
+}
diff --git a/frontend/src/features/analytics/channel/channelChartData.test.js b/frontend/src/features/analytics/channel/channelChartData.test.js
new file mode 100644
index 0000000..919cec7
--- /dev/null
+++ b/frontend/src/features/analytics/channel/channelChartData.test.js
@@ -0,0 +1,81 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import {
+ watchUrl, channelMeta, dayDataOf, hourDataOf, durationDataOf, categoryDataOf, splitDataOf, shortsComparisonOf,
+ topVideosChartOf, topVideoRowsOf, viewRangeDataOf, uploadsByMonthOf, rateOf, likesPerComment, peakHourLabel,
+ bestVideosOf, likesLabel,
+} from './channelChartData.js';
+
+test('watch links point at YouTube', () => {
+ assert.equal(watchUrl('abc'), 'https://www.youtube.com/watch?v=abc');
+});
+
+test('channel meta skips an unknown country and a missing handle', () => {
+ const meta = channelMeta({ country: 'Unknown', channelAgeYears: 3, publishedAt: '2023-01-05T12:00:00Z' });
+ assert.equal(meta.length, 2);
+ assert.equal(meta[0], '3 years old');
+ assert.ok(meta[1].startsWith('Since '));
+ assert.equal(channelMeta({ customUrl: '@dusk', country: 'IN', channelAgeYears: 1 })[1], 'IN');
+});
+
+test('publish distributions become chart rows', () => {
+ assert.deepEqual(dayDataOf({ Mon: 2, Tue: 0 }), [{ day: 'Mon', count: 2 }, { day: 'Tue', count: 0 }]);
+ assert.deepEqual(hourDataOf({ 13: 1, 2: 4, 9: 0 }).map(row => row.hour), ['2:00', '9:00', '13:00']);
+ assert.deepEqual(dayDataOf(undefined), []);
+ assert.deepEqual(hourDataOf(null), []);
+});
+
+test('length and split pies drop empty slices', () => {
+ const durations = durationDataOf({ short: 3, medium: 0, long: 1, veryLong: 0 });
+ assert.deepEqual(durations.map(slice => slice.name), ['Shorts (under 1m)', 'Long (10 to 60m)']);
+ assert.deepEqual(durationDataOf(undefined), []);
+ assert.deepEqual(splitDataOf({ shortsCount: 0, regularCount: 5 }).map(slice => slice.name), ['Regular']);
+});
+
+test('categories use their name or a numbered fallback', () => {
+ assert.deepEqual(categoryDataOf({ 10: 4, 999: 1 }), [{ name: 'Music', value: 4 }, { name: 'Category 999', value: 1 }]);
+});
+
+test('top video chart truncates titles and always adds an ellipsis', () => {
+ const rows = topVideosChartOf([{ title: 'Short', viewCount: 5 }, null]);
+ assert.deepEqual(rows[0], { name: 'Short…', views: 5, likes: 0 });
+ assert.deepEqual(rows[1], { name: '…', views: 0, likes: 0 });
+ assert.deepEqual(topVideosChartOf(undefined), []);
+});
+
+test('top video rows merge both lists once each, by views', () => {
+ const analytics = {
+ top10ByViews: [{ videoId: 'a', viewCount: 10 }, { videoId: 'b', viewCount: 30 }],
+ top10ByLikes: [{ videoId: 'b', viewCount: 30 }, null, { videoId: 'c', viewCount: 20 }],
+ };
+ assert.deepEqual(topVideoRowsOf(analytics).map(video => video.videoId), ['b', 'c', 'a']);
+ assert.deepEqual(topVideoRowsOf({}), []);
+});
+
+test('view ranges, uploads and comparisons', () => {
+ assert.deepEqual(viewRangeDataOf({ ranges: ['0-1K', '1K+'], counts: [3] }), [{ range: '0-1K', count: 3 }, { range: '1K+', count: 0 }]);
+ assert.deepEqual(viewRangeDataOf(undefined), []);
+ assert.deepEqual(uploadsByMonthOf([{ month: 'Jan', count: 2, value: 9 }]), [{ month: 'Jan', uploads: 2 }]);
+ assert.equal(shortsComparisonOf({ avgShortViews: 1, avgRegularViews: 2 })[0].Regular, 2);
+});
+
+test('rates and ratios guard against zero', () => {
+ assert.equal(rateOf(5, 200), '2.5%');
+ assert.equal(rateOf(5, 0), '0%');
+ assert.equal(likesPerComment({ totalLikes: 30, totalComments: 4 }), '7.5:1');
+ assert.equal(likesPerComment({ totalLikes: 30, totalComments: 0 }), 'Not available');
+});
+
+test('peak hour treats only a missing hour as unavailable', () => {
+ assert.equal(peakHourLabel(14), '14:00 UTC');
+ assert.equal(peakHourLabel(0), '0:00 UTC');
+ assert.equal(peakHourLabel(undefined), 'Not available');
+});
+
+test('best videos and like labels', () => {
+ const best = bestVideosOf({ bestByViews: { videoId: 'a' }, bestByEngagement: { videoId: 'b' } });
+ assert.deepEqual(best.map(item => item.label), ['Most viewed', 'Best engagement']);
+ assert.equal(likesLabel(undefined), 'likes hidden');
+ assert.equal(likesLabel(null), 'likes hidden');
+ assert.equal(likesLabel(1500), '1.5K likes');
+});
diff --git a/frontend/src/features/analytics/channel/useChannelAnalytics.js b/frontend/src/features/analytics/channel/useChannelAnalytics.js
new file mode 100644
index 0000000..c4d2a6a
--- /dev/null
+++ b/frontend/src/features/analytics/channel/useChannelAnalytics.js
@@ -0,0 +1,22 @@
+import { useCallback, useEffect, useState } from 'react';
+import { api } from '../../../services/api';
+
+export function useChannelAnalytics(id, showToast) {
+ const [data, setData] = useState(null);
+ const [loading, setLoading] = useState(true);
+
+ const loadAnalytics = useCallback(async () => {
+ setLoading(true);
+ try {
+ setData(await api.getAnalytics(id));
+ } catch (err) {
+ showToast(`Couldn't load channel analytics. ${err.message}`, 'error');
+ } finally {
+ setLoading(false);
+ }
+ }, [id, showToast]);
+
+ useEffect(() => { if (id) loadAnalytics(); }, [id, loadAnalytics]);
+
+ return { data, loading, loadAnalytics };
+}