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.

feat(tracked-content): expand tracked posts to YouTube, redesign Overview with tabs

spacesdrive13abef9d82bc
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b1ff304..019c0d5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,34 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [Unreleased]
+### Changed
+
+**Tracked Content (expanded from Tracked Reddit Posts)**
+- Renamed feature from "Tracked Posts" / "Tracked Reddit Posts" to "Tracked Content" throughout the UI, routing, and API
+- Route changed from `/reddit-tracked` to `/tracked-content` (old route redirects to new)
+- API endpoint changed from `/api/reddit/tracked-posts` to `/api/tracked-content`
+- Frontend page moved from `features/analytics/reddit/RedditTracked.jsx` to `features/analytics/tracked/TrackedContent.jsx`
+- YouTube video and Shorts tracking added: paste any YouTube URL to track viewCount, likeCount, commentCount
+- `content_type` column added to `tracked_posts` table: `'reddit'` (default) or `'youtube'`
+- YouTube and Reddit tracked items share the same categories (categories are plain text labels)
+- `fetchTrackedYouTubeData(videoUrl, apiKey)` added to `backend/services/youtube.js`
+- Route handler now auto-detects URL platform and calls the appropriate fetch function
+- TrackedContent page table: type badge per row, YouTube shows views/likes/comments, Reddit shows score/upvote%/comments
+- Sidebar nav label changed from "Tracked Posts" to "Tracked Content" with updated route
+
+**Overview dashboard redesigned**
+- KPI StatCards replaced with a 6-tab interface: Total Audience, Total Views, Total Content, Accounts, Total Comments, Total Likes
+- Reddit karma now included in Total Audience metric (subs + followers + karma)
+- Tracked content count included in Total Content metric
+- Audience Comparison chart replaced from AreaChart to BarChart; now includes all platforms (YouTube, Instagram, Reddit) and tracked categories
+- Audience Share pie chart now includes Reddit accounts and tracked categories
+- Top by Audience list now includes Reddit accounts (with karma metric)
+- Top by Content list now shows all platforms
+- Total Comments tab: aggregate comment counts from tracked content (Reddit numComments + YouTube commentCount)
+- Total Likes tab: Reddit post karma from connected accounts + tracked YouTube video likes
+- Reddit section card removed; Reddit data fully integrated into the tab views
+- Accounts tab now shows all accounts including Reddit in a unified table
+
### Removed
**X (Twitter) integration removed**
diff --git a/DECISIONS.md b/DECISIONS.md
index cf6b40c..3a5611e 100644
--- a/DECISIONS.md
+++ b/DECISIONS.md
@@ -441,3 +441,47 @@ Records every significant architectural decision, the alternatives considered, a
**Trade-offs:**
- Data shown on the page may be hours or days stale if the user does not refresh manually. The `lastFetchedAt` timestamp is displayed in the table so staleness is visible.
+
+---
+
+## ADR-020: Tracked Content expanded to support YouTube videos alongside Reddit posts
+
+**Date:** 2026-08-04
+**Status:** Accepted
+
+**Decision:** The "Tracked Posts" feature is renamed "Tracked Content" and extended to support YouTube video and Shorts URLs in addition to Reddit post URLs. A `content_type` column (`'reddit'` | `'youtube'`) is added to the `tracked_posts` table. URL platform detection (`detectContentType()`) routes each add/refresh request to the appropriate fetch function.
+
+**Alternatives considered:**
+- Separate `tracked_youtube` table: cleaner schema but duplicates all the category/label/CRUD infrastructure; categories could not be shared between Reddit and YouTube items
+- A separate page for YouTube tracking: splits the UI unnecessarily; categories work best when unified across content types
+
+**Reasoning:**
+- Users often run campaigns or track performance across both YouTube and Reddit simultaneously. Sharing categories between content types enables cross-platform campaign tracking without duplication.
+- `content_type` defaulting to `'reddit'` makes the migration backward-compatible: all existing rows remain valid.
+- `fetchTrackedYouTubeData()` reuses the existing `ytFetch()` helper and `YOUTUBE_API_KEY` already required for channel analytics; no new Worker secrets are needed.
+- YouTube video likes and comment counts require per-video API calls, which the existing per-account analytics endpoints do not aggregate. Tracked content provides the only granular YouTube engagement data available on the Overview.
+
+**Trade-offs:**
+- YouTube comments are disabled on some videos (`commentCount` may be 0 even when comments exist but are restricted by the creator).
+- YouTube `likeCount` is no longer public on some videos - the API returns 0 in those cases; this is an API limitation, not a code bug.
+- The `tracked_posts` table name now refers to a broader concept than posts; a future refactor could rename it to `tracked_content` but the migration overhead is not justified at this scale.
+
+---
+
+## ADR-021: Overview redesigned with tab interface; karma included in Total Audience
+
+**Date:** 2026-08-04
+**Status:** Accepted
+
+**Decision:** The Overview's four StatCards are replaced with a 6-tab interface (Total Audience, Total Views, Total Content, Accounts, Total Comments, Total Likes). Reddit karma is included in the Total Audience metric. The Audience Comparison bar chart includes Reddit accounts and tracked categories. The standalone Reddit section card is removed.
+
+**Supersedes:** ADR-015 (karma excluded from audience metrics)
+
+**Reasoning:**
+- Reddit karma, while not a subscriber count, represents the user's reach and credibility on the platform - it is the closest available proxy for "audience" a Reddit account has, and the user explicitly requested it be included.
+- The tab interface gives each metric a dedicated content area rather than cramming everything into a single scrolling page. This scales better as more platforms and metrics are added.
+- Total Comments and Total Likes tabs provide engagement-focused views of tracked content, fulfilling the need for cross-platform engagement analytics without requiring expensive per-account API calls on every page load.
+
+**Trade-offs:**
+- Including karma in Total Audience makes the number less directly comparable to subscriber/follower counts; this is mitigated by clearly labeling each component (`X subs · Y followers · Z karma`).
+- The tab interface requires the user to click between views rather than seeing everything at once; this is the correct tradeoff for a dense analytics dashboard.
diff --git a/backend/lib/db.js b/backend/lib/db.js
index fa6835f..7d63360 100644
--- a/backend/lib/db.js
+++ b/backend/lib/db.js
@@ -185,6 +185,7 @@ function rowToTrackedPost(row) {
url: row.url,
label: row.label || '',
category: row.category || '',
+ contentType: row.content_type || 'reddit',
createdAt: row.created_at,
updatedAt: row.updated_at,
...(row.data || {}),
@@ -194,7 +195,7 @@ function rowToTrackedPost(row) {
export async function getTrackedPosts(supabase, userId) {
const { data, error } = await supabase
.from('tracked_posts')
- .select('id, account_id, url, label, category, created_at, updated_at, data')
+ .select('id, account_id, url, label, category, content_type, created_at, updated_at, data')
.eq('user_id', userId)
.order('created_at', { ascending: false });
if (error) throw error;
@@ -204,7 +205,7 @@ export async function getTrackedPosts(supabase, userId) {
export async function getTrackedPostById(supabase, id, userId) {
const { data, error } = await supabase
.from('tracked_posts')
- .select('id, account_id, url, label, category, created_at, updated_at, data')
+ .select('id, account_id, url, label, category, content_type, created_at, updated_at, data')
.eq('id', id)
.eq('user_id', userId)
.single();
@@ -213,7 +214,7 @@ export async function getTrackedPostById(supabase, id, userId) {
}
export async function createTrackedPost(supabase, post, userId) {
- const { id, accountId, url, label, category } = post;
+ const { id, accountId, url, label, category, contentType } = post;
const { error } = await supabase.from('tracked_posts').insert({
id,
user_id: userId,
@@ -221,6 +222,7 @@ export async function createTrackedPost(supabase, post, userId) {
url,
label: label || '',
category: category || '',
+ content_type: contentType || 'reddit',
});
if (error) throw error;
}
diff --git a/backend/routes/trackedContent.js b/backend/routes/trackedContent.js
new file mode 100644
index 0000000..9484afb
--- /dev/null
+++ b/backend/routes/trackedContent.js
@@ -0,0 +1,159 @@
+import { Hono } from 'hono';
+import {
+ getTrackedPosts,
+ getTrackedPostById,
+ createTrackedPost,
+ updateTrackedPost,
+ deleteTrackedPost,
+ getAccountById,
+} from '../lib/db.js';
+import { fetchTrackedPostData } from '../services/reddit.js';
+import { fetchTrackedYouTubeData } from '../services/youtube.js';
+
+const router = new Hono();
+
+function detectContentType(url) {
+ const lower = (url || '').toLowerCase();
+ if (lower.includes('reddit.com') || lower.includes('redd.it')) return 'reddit';
+ if (lower.includes('youtube.com') || lower.includes('youtu.be')) return 'youtube';
+ return null;
+}
+
+// List all tracked content for the current user
+router.get('/tracked-content', async (c) => {
+ const userId = c.get('userId');
+ const supabase = c.get('supabase');
+ try {
+ const items = await getTrackedPosts(supabase, userId);
+ return c.json(items);
+ } catch (err) {
+ console.error('GET /tracked-content:', err.message);
+ return c.json({ error: err.message }, 500);
+ }
+});
+
+// Add a new tracked content item (Reddit post or YouTube video)
+router.post('/tracked-content', async (c) => {
+ const userId = c.get('userId');
+ const supabase = c.get('supabase');
+ const body = await c.req.json();
+ const { url, accountId, label, category } = body;
+
+ if (!url) return c.json({ error: 'url is required' }, 400);
+
+ const contentType = detectContentType(url.trim());
+ if (!contentType) return c.json({ error: 'Only Reddit and YouTube URLs are supported' }, 400);
+
+ try {
+ let fetchedData;
+
+ if (contentType === 'youtube') {
+ const apiKey = c.env.YOUTUBE_API_KEY?.replace(/^/, '').trim();
+ if (!apiKey) return c.json({ error: 'YouTube API key not configured on this server' }, 400);
+ fetchedData = await fetchTrackedYouTubeData(url.trim(), apiKey);
+ } else {
+ let cookie = null;
+ if (accountId) {
+ const account = await getAccountById(supabase, accountId, userId);
+ if (!account || account.platform !== 'reddit') return c.json({ error: 'Reddit account not found' }, 404);
+ cookie = account.cookie || null;
+ }
+ fetchedData = await fetchTrackedPostData(url.trim(), cookie);
+ }
+
+ const id = Date.now().toString(36) + Math.random().toString(36).slice(2);
+ await createTrackedPost(supabase, {
+ id,
+ accountId: contentType === 'youtube' ? null : (accountId || null),
+ url: url.trim(),
+ label,
+ category,
+ contentType,
+ }, userId);
+ await updateTrackedPost(supabase, id, { data: fetchedData }, userId);
+
+ const created = await getTrackedPostById(supabase, id, userId);
+ return c.json(created, 201);
+ } catch (err) {
+ console.error('POST /tracked-content:', err.message);
+ return c.json({ error: err.message }, 500);
+ }
+});
+
+// Update label, category, or account on a tracked content item
+router.put('/tracked-content/:id', async (c) => {
+ const id = c.req.param('id');
+ const userId = c.get('userId');
+ const supabase = c.get('supabase');
+ const body = await c.req.json();
+ const { label, category, accountId } = body;
+
+ try {
+ const existing = await getTrackedPostById(supabase, id, userId);
+ if (!existing) return c.json({ error: 'Tracked content not found' }, 404);
+
+ const updates = {};
+ if (label !== undefined) updates.label = label;
+ if (category !== undefined) updates.category = category;
+ if (accountId !== undefined) updates.accountId = accountId;
+ await updateTrackedPost(supabase, id, updates, userId);
+
+ const updated = await getTrackedPostById(supabase, id, userId);
+ return c.json(updated);
+ } catch (err) {
+ console.error(`PUT /tracked-content/${id}:`, err.message);
+ return c.json({ error: err.message }, 500);
+ }
+});
+
+// Delete a tracked content item
+router.delete('/tracked-content/:id', async (c) => {
+ const id = c.req.param('id');
+ const userId = c.get('userId');
+ const supabase = c.get('supabase');
+ try {
+ const existing = await getTrackedPostById(supabase, id, userId);
+ if (!existing) return c.json({ error: 'Tracked content not found' }, 404);
+ await deleteTrackedPost(supabase, id, userId);
+ return c.json({ success: true });
+ } catch (err) {
+ console.error(`DELETE /tracked-content/${id}:`, err.message);
+ return c.json({ error: err.message }, 500);
+ }
+});
+
+// Refresh live data for a single tracked content item
+router.post('/tracked-content/:id/refresh', async (c) => {
+ const id = c.req.param('id');
+ const userId = c.get('userId');
+ const supabase = c.get('supabase');
+ try {
+ const existing = await getTrackedPostById(supabase, id, userId);
+ if (!existing) return c.json({ error: 'Tracked content not found' }, 404);
+
+ const contentType = existing.contentType || 'reddit';
+ let fetchedData;
+
+ if (contentType === 'youtube') {
+ const apiKey = c.env.YOUTUBE_API_KEY?.replace(/^/, '').trim();
+ if (!apiKey) return c.json({ error: 'YouTube API key not configured on this server' }, 400);
+ fetchedData = await fetchTrackedYouTubeData(existing.url, apiKey);
+ } else {
+ let cookie = null;
+ if (existing.accountId) {
+ const account = await getAccountById(supabase, existing.accountId, userId);
+ cookie = account?.cookie || null;
+ }
+ fetchedData = await fetchTrackedPostData(existing.url, cookie);
+ }
+
+ await updateTrackedPost(supabase, id, { data: fetchedData }, userId);
+ const updated = await getTrackedPostById(supabase, id, userId);
+ return c.json(updated);
+ } catch (err) {
+ console.error(`POST /tracked-content/${id}/refresh:`, err.message);
+ return c.json({ error: err.message }, 500);
+ }
+});
+
+export default router;
diff --git a/backend/server.js b/backend/server.js
index a50ec98..1054e0f 100644
--- a/backend/server.js
+++ b/backend/server.js
@@ -10,7 +10,7 @@ import publishingRouter from './routes/publishing.js';
import scheduledPostsRouter from './routes/scheduledPosts.js';
import settingsRouter from './routes/settings.js';
import redditRouter from './routes/reddit.js';
-import trackedPostsRouter from './routes/trackedPosts.js';
+import trackedContentRouter from './routes/trackedContent.js';
import { urlHandler, callbackHandler } from './routes/instagramAuth.js';
import { processScheduledPosts } from './utils/scheduler.js';
import { autoRefreshInstagramTokens } from './services/instagram.js';
@@ -55,7 +55,7 @@ api.route('/', publishingRouter);
api.route('/', scheduledPostsRouter);
api.route('/', settingsRouter);
api.route('/', redditRouter);
-api.route('/', trackedPostsRouter);
+api.route('/', trackedContentRouter);
// Instagram OAuth URL generator - protected (needs userId to create state token)
api.get('/auth/instagram/url', urlHandler);
diff --git a/backend/services/youtube.js b/backend/services/youtube.js
index f5f615a..728afbf 100644
--- a/backend/services/youtube.js
+++ b/backend/services/youtube.js
@@ -154,6 +154,53 @@ function formatCompact(n) {
return n.toString();
}
+function extractYouTubeVideoId(url) {
+ try {
+ const u = new URL(url.trim());
+ if (u.hostname === 'youtu.be') return u.pathname.slice(1).split('?')[0];
+ if (u.hostname.includes('youtube.com')) {
+ if (u.pathname.startsWith('/shorts/')) return u.pathname.split('/')[2];
+ if (u.pathname.startsWith('/embed/')) return u.pathname.split('/')[2];
+ return u.searchParams.get('v');
+ }
+ } catch {}
+ return null;
+}
+
+export async function fetchTrackedYouTubeData(videoUrl, apiKey) {
+ const videoId = extractYouTubeVideoId(videoUrl);
+ if (!videoId) throw new Error('Invalid YouTube URL - could not extract video ID');
+
+ const data = await ytFetch('videos', {
+ part: 'snippet,statistics',
+ id: videoId,
+ }, apiKey);
+
+ if (!data.items || data.items.length === 0) throw new Error('YouTube video not found - check the URL');
+
+ const item = data.items[0];
+ const s = item.snippet;
+ const st = item.statistics;
+ const isShort = videoUrl.includes('/shorts/');
+
+ return {
+ contentType: 'youtube',
+ title: s.title,
+ channelTitle: s.channelTitle,
+ channelId: s.channelId,
+ thumbnail: s.thumbnails?.medium?.url || s.thumbnails?.default?.url || '',
+ publishedAt: s.publishedAt,
+ viewCount: parseInt(st.viewCount || '0', 10),
+ likeCount: parseInt(st.likeCount || '0', 10),
+ commentCount: parseInt(st.commentCount || '0', 10),
+ isShort,
+ permalink: isShort
+ ? `https://www.youtube.com/shorts/${videoId}`
+ : `https://www.youtube.com/watch?v=${videoId}`,
+ lastFetchedAt: new Date().toISOString(),
+ };
+}
+
export function computeVideoAnalytics(videos) {
if (!videos || videos.length === 0) {
return {
diff --git a/docs/architecture/backend/ROUTES.md b/docs/architecture/backend/ROUTES.md
index 3ba48d6..22f1754 100644
--- a/docs/architecture/backend/ROUTES.md
+++ b/docs/architecture/backend/ROUTES.md
@@ -68,14 +68,14 @@ All routes live under `/api`. Routes under the `api` sub-app require a valid Sup
| GET | `/api/accounts/:id/reddit-analytics` | `routes/reddit.js` | Fetch profile + posts + computed analytics; cached in Redis |
| GET | `/api/accounts/:id/reddit-posts` | `routes/reddit.js` | Returns cached post list or live-fetched posts |
-### Tracked Reddit Posts
+### Tracked Content
| Method | Path | File | Purpose |
|---|---|---|---|
-| GET | `/api/reddit/tracked-posts` | `routes/trackedPosts.js` | List all tracked posts for the current user (returns cached data from `data` column) |
-| POST | `/api/reddit/tracked-posts` | `routes/trackedPosts.js` | Add a post URL to track; fetches live data immediately using the selected account's cookie |
-| PUT | `/api/reddit/tracked-posts/:id` | `routes/trackedPosts.js` | Update label, category, or accountId for a tracked post |
-| DELETE | `/api/reddit/tracked-posts/:id` | `routes/trackedPosts.js` | Remove a tracked post |
-| POST | `/api/reddit/tracked-posts/:id/refresh` | `routes/trackedPosts.js` | Re-fetch live score/comment data from Reddit for one tracked post |
+| GET | `/api/tracked-content` | `routes/trackedContent.js` | List all tracked items for the current user (Reddit posts and YouTube videos) |
+| POST | `/api/tracked-content` | `routes/trackedContent.js` | Add a URL to track; auto-detects Reddit or YouTube; fetches live data immediately |
+| PUT | `/api/tracked-content/:id` | `routes/trackedContent.js` | Update label, category, or accountId for a tracked item |
+| DELETE | `/api/tracked-content/:id` | `routes/trackedContent.js` | Remove a tracked item |
+| POST | `/api/tracked-content/:id/refresh` | `routes/trackedContent.js` | Re-fetch live data from Reddit or YouTube API for one tracked item |
### Settings
| Method | Path | File | Purpose |
diff --git a/docs/architecture/database/SCHEMA.md b/docs/architecture/database/SCHEMA.md
index e14b975..3ac40ec 100644
--- a/docs/architecture/database/SCHEMA.md
+++ b/docs/architecture/database/SCHEMA.md
@@ -143,46 +143,61 @@ The `publishing` status is a mutex - it prevents double-publishing when both the
## Table: `tracked_posts`
-Stores Reddit post URLs the user wants to monitor for score and comment count changes.
+Stores Reddit posts and YouTube videos the user wants to monitor. Previously Reddit-only; extended to support YouTube via the `content_type` column.
| Column | Type | Nullable | Description |
|---|---|---|---|
| `id` | text | NOT NULL | PK. Client-generated: `Date.now().toString(36) + Math.random().toString(36).slice(2)` |
| `user_id` | uuid | NOT NULL | FK -> `auth.users.id` ON DELETE CASCADE |
-| `account_id` | text | NULL | FK -> `accounts.id` ON DELETE SET NULL. Which account's cookie to use when fetching |
-| `url` | text | NOT NULL | Full Reddit post URL (e.g. `https://www.reddit.com/r/.../comments/...`) |
-| `label` | text | NOT NULL DEFAULT '' | User-defined name for the post |
-| `category` | text | NOT NULL DEFAULT '' | User-defined grouping label (used for category stats on Overview) |
-| `created_at` | timestamptz | NOT NULL DEFAULT now() | When the user added the tracked post |
+| `account_id` | text | NULL | FK -> `accounts.id` ON DELETE SET NULL. Reddit only: which account's cookie to use |
+| `url` | text | NOT NULL | Full URL of the Reddit post or YouTube video |
+| `label` | text | NOT NULL DEFAULT '' | User-defined name for the item |
+| `category` | text | NOT NULL DEFAULT '' | User-defined grouping label; shared across Reddit and YouTube items |
+| `content_type` | text | NOT NULL DEFAULT 'reddit' | `'reddit'` or `'youtube'` |
+| `created_at` | timestamptz | NOT NULL DEFAULT now() | When the user added the item |
| `updated_at` | timestamptz | NOT NULL DEFAULT now() | Last time any field or the cached data was changed |
-| `data` | jsonb | NULL | Cached post data fetched from Reddit (see below) |
+| `data` | jsonb | NULL | Cached data fetched from the platform API (see below) |
-### `data` jsonb shape
+### `data` jsonb shape for Reddit items
Populated by `fetchTrackedPostData()` in `backend/services/reddit.js`:
```json
{
- "postId": "abc123",
+ "contentType": "reddit",
"title": "Post title from Reddit",
"subreddit": "programming",
"subredditPrefixed": "r/programming",
- "author": "username",
"score": 1234,
"upvoteRatio": 0.97,
"numComments": 56,
"permalink": "https://reddit.com/r/programming/comments/abc123/...",
- "isNsfw": false,
- "createdAt": "2026-01-01T00:00:00Z",
"lastFetchedAt": "2026-08-04T10:00:00Z"
}
```
-Data is fetched on create and on manual refresh. It is not re-fetched on every GET to avoid Reddit rate limits.
+### `data` jsonb shape for YouTube items
-### `account_id` nullable logic
+Populated by `fetchTrackedYouTubeData()` in `backend/services/youtube.js`:
-`account_id` is nullable with `ON DELETE SET NULL`. If the user deletes the Reddit account whose cookie was used, the tracked post is kept but `account_id` becomes `null`. Subsequent refreshes access the post as public (no cookie).
+```json
+{
+ "contentType": "youtube",
+ "title": "Video Title",
+ "channelTitle": "Channel Name",
+ "channelId": "UCxxxxxx",
+ "thumbnail": "https://i.ytimg.com/vi/xxxx/mqdefault.jpg",
+ "publishedAt": "2026-01-01T00:00:00Z",
+ "viewCount": 12345,
+ "likeCount": 567,
+ "commentCount": 89,
+ "isShort": false,
+ "permalink": "https://www.youtube.com/watch?v=xxxx",
+ "lastFetchedAt": "2026-08-04T10:00:00Z"
+}
+```
+
+Data is fetched on create and on manual refresh only. Not re-fetched on every GET.
### Indexes
@@ -190,7 +205,7 @@ Data is fetched on create and on manual refresh. It is not re-fetched on every G
CREATE INDEX tracked_posts_user_id_idx ON tracked_posts(user_id);
```
-### Migration SQL
+### Migration SQL (initial table + content_type addition)
```sql
CREATE TABLE tracked_posts (
@@ -205,6 +220,9 @@ CREATE TABLE tracked_posts (
data jsonb
);
CREATE INDEX tracked_posts_user_id_idx ON tracked_posts(user_id);
+
+-- Added in Tracked Content expansion
+ALTER TABLE tracked_posts ADD COLUMN IF NOT EXISTS content_type text NOT NULL DEFAULT 'reddit';
```
---
diff --git a/docs/architecture/frontend/API_LAYER.md b/docs/architecture/frontend/API_LAYER.md
index ae6e9b5..0c3cc99 100644
--- a/docs/architecture/frontend/API_LAYER.md
+++ b/docs/architecture/frontend/API_LAYER.md
@@ -87,19 +87,19 @@ async function handleAction() {
}
```
-## Tracked Reddit Post Methods
+## Tracked Content Methods
-Added to the `api` object in `api.js`:
+Added to the `api` object in `api.js`. Handles both Reddit posts and YouTube videos:
```js
-getTrackedPosts: () => request('/reddit/tracked-posts'),
-addTrackedPost: (url, accountId, label, category) => request('/reddit/tracked-posts', { method: 'POST', body: JSON.stringify({ url, accountId, label, category }) }),
-updateTrackedPost: (id, updates) => request(`/reddit/tracked-posts/${id}`, { method: 'PUT', body: JSON.stringify(updates) }),
-deleteTrackedPost: (id) => request(`/reddit/tracked-posts/${id}`, { method: 'DELETE' }),
-refreshTrackedPost: (id) => request(`/reddit/tracked-posts/${id}/refresh`, { method: 'POST' }),
+getTrackedContent: () => request('/tracked-content'),
+addTrackedContent: (url, accountId, label, category) => request('/tracked-content', { method: 'POST', body: JSON.stringify({ url, accountId, label, category }) }),
+updateTrackedContent: (id, updates) => request(`/tracked-content/${id}`, { method: 'PUT', body: JSON.stringify(updates) }),
+deleteTrackedContent: (id) => request(`/tracked-content/${id}`, { method: 'DELETE' }),
+refreshTrackedContent: (id) => request(`/tracked-content/${id}/refresh`, { method: 'POST' }),
```
-`accountId` may be `null` (public access without a session cookie).
+`accountId` may be `null`. For YouTube items, `accountId` is always `null` (fetched via the server's `YOUTUBE_API_KEY`). For Reddit items, `accountId` is optional and refers to a Reddit account whose cookie improves datacenter IP access.
## Authentication
diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx
index 7065128..567b62a 100644
--- a/frontend/src/App.jsx
+++ b/frontend/src/App.jsx
@@ -21,7 +21,7 @@ const Settings = lazy(() => import('./features/settings/Settings'));
const RedditAnalytics = lazy(() => import('./features/analytics/reddit/RedditAnalytics'));
const RedditPosts = lazy(() => import('./features/analytics/reddit/RedditPosts'));
const RedditPostsAll = lazy(() => import('./features/analytics/reddit/RedditPostsAll'));
-const RedditTracked = lazy(() => import('./features/analytics/reddit/RedditTracked'));
+const TrackedContent = lazy(() => import('./features/analytics/tracked/TrackedContent'));
const router = createBrowserRouter([
{
@@ -50,7 +50,8 @@ const router = createBrowserRouter([
{ path: 'reddit/:id', element: <RedditAnalytics /> },
{ path: 'reddit-posts', element: <RedditPostsAll /> },
{ path: 'reddit-posts/:id', element: <RedditPosts /> },
- { path: 'reddit-tracked', element: <RedditTracked /> },
+ { path: 'tracked-content', element: <TrackedContent /> },
+ { path: 'reddit-tracked', element: <Navigate to="/tracked-content" replace /> },
{ path: '*', element: <Navigate to="/" replace /> },
],
},
diff --git a/frontend/src/features/analytics/overview/Overview.jsx b/frontend/src/features/analytics/overview/Overview.jsx
index ab98d5d..b74ab29 100644
--- a/frontend/src/features/analytics/overview/Overview.jsx
+++ b/frontend/src/features/analytics/overview/Overview.jsx
@@ -7,8 +7,9 @@ import { Progress } from '@/components/ui/progress';
import { Skeleton } from '@/components/ui/skeleton';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
+import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';
import {
- AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip as ReTooltip,
+ BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip as ReTooltip,
ResponsiveContainer, PieChart, Pie, Cell, Legend,
} from 'recharts';
import StatCard from '../../../components/ui/StatCard';
@@ -16,46 +17,64 @@ import MainCard from '../../../components/MainCard';
import { useAppContext } from '../../../context/AppContext';
import { api } from '../../../services/api';
import { fmtNum, fmtNumFull, timeAgo } from '../../../utils/formatters';
-import { RefreshCw, Users, Eye, VideoIcon, BarChart3, ExternalLink, Flame, Tag } from 'lucide-react';
+import {
+ RefreshCw, Users, VideoIcon, ExternalLink,
+ Tag, ThumbsUp, MessageSquare, Youtube, Flame, BookmarkCheck,
+} from 'lucide-react';
+
+const PLATFORM_COLORS = {
+ youtube: '#ef4444',
+ instagram: '#ec4899',
+ reddit: '#f97316',
+ category: '#a855f7',
+};
-const CHART_COLORS = ['hsl(221.2,83.2%,53.3%)', '#22c55e', '#f97316', '#a855f7', '#06b6d4', '#ec4899', '#6366f1', '#eab308'];
+const CHART_COLORS = [
+ '#ef4444', '#ec4899', '#f97316', '#a855f7',
+ '#06b6d4', '#22c55e', '#6366f1', '#eab308',
+];
+
+function PlatformBadge({ platform }) {
+ const map = {
+ youtube: 'border-red-200 bg-red-50 text-red-700 dark:border-red-900 dark:bg-red-950 dark:text-red-400',
+ instagram: 'border-pink-200 bg-pink-50 text-pink-700 dark:border-pink-900 dark:bg-pink-950 dark:text-pink-400',
+ reddit: 'border-orange-200 bg-orange-50 text-orange-700 dark:border-orange-900 dark:bg-orange-950 dark:text-orange-400',
+ };
+ const labels = { youtube: 'YouTube', instagram: 'Instagram', reddit: 'Reddit' };
+ return (
+ <Badge variant="outline" className={`text-xs ${map[platform] || ''}`}>
+ {labels[platform] || platform}
+ </Badge>
+ );
+}
export default function Overview() {
const { accounts, loading, refreshAll } = useAppContext();
const navigate = useNavigate();
- const [trackedPosts, setTrackedPosts] = useState([]);
+ const [trackedContent, setTrackedContent] = useState([]);
useEffect(() => {
- api.getTrackedPosts().then(data => {
- if (Array.isArray(data)) setTrackedPosts(data);
+ api.getTrackedContent().then(data => {
+ if (Array.isArray(data)) setTrackedContent(data);
}).catch(() => {});
}, []);
- const totalTrackedScore = useMemo(() => trackedPosts.reduce((s, p) => s + (p.score ?? 0), 0), [trackedPosts]);
- const totalTrackedComments = useMemo(() => trackedPosts.reduce((s, p) => s + (p.numComments ?? 0), 0), [trackedPosts]);
-
- const categoryStats = useMemo(() => {
- const withCategory = trackedPosts.filter(p => p.category);
- if (withCategory.length === 0) return [];
- const map = {};
- withCategory.forEach(p => {
- if (!map[p.category]) map[p.category] = { category: p.category, count: 0, totalScore: 0 };
- map[p.category].count++;
- map[p.category].totalScore += p.score ?? 0;
- });
- return Object.values(map).sort((a, b) => b.totalScore - a.totalScore);
- }, [trackedPosts]);
-
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');
- const totals = accounts.reduce((acc, a) => {
+ // Aggregate 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,
+ karma: acc.karma + (a.totalKarma || 0),
+ postKarma: acc.postKarma + (a.postKarma || 0),
+ commentKarma: acc.commentKarma + (a.commentKarma || 0),
+ };
}
return {
...acc,
@@ -63,47 +82,115 @@ export default function Overview() {
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 });
+ }, { subscribers: 0, views: 0, videos: 0, followers: 0, posts: 0, karma: 0, postKarma: 0, commentKarma: 0 }), [accounts]);
- // Karma is engagement-based, not audience-based — excluded from totalAudience
- const totalAudience = totals.subscribers + totals.followers;
+ // Tracked content aggregates
+ 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,
+ totalComments: trackedContent.reduce((s, p) => {
+ const c = p.contentType === 'youtube' ? (p.commentCount ?? 0) : (p.numComments ?? 0);
+ return s + c;
+ }, 0),
+ totalYTLikes: ytItems.reduce((s, p) => s + (p.likeCount ?? 0), 0),
+ totalRdScore: rdItems.reduce((s, p) => s + (p.score ?? 0), 0),
+ };
+ }, [trackedContent]);
- const audienceMetric = (a) => {
+ // Total Likes = Reddit account postKarma + tracked YouTube likeCount
+ const totalLikes = totals.postKarma + trackedStats.totalYTLikes;
+ // Total Audience = subs + followers + karma (per user request)
+ const totalAudience = totals.subscribers + totals.followers + totals.karma;
+ // Total Content = videos + IG posts + tracked content
+ const totalContent = totals.videos + totals.posts + trackedStats.total;
+
+ // Category stats for tracked content
+ const categoryStats = useMemo(() => {
+ const withCategory = trackedContent.filter(p => p.category);
+ if (withCategory.length === 0) return [];
+ const map = {};
+ withCategory.forEach(p => {
+ if (!map[p.category]) map[p.category] = { category: p.category, count: 0, totalScore: 0, totalLikes: 0 };
+ map[p.category].count++;
+ if (p.contentType === 'youtube') {
+ map[p.category].totalLikes += p.likeCount ?? 0;
+ map[p.category].totalScore += p.viewCount ?? 0;
+ } else {
+ map[p.category].totalScore += p.score ?? 0;
+ }
+ });
+ return Object.values(map).sort((a, b) => b.totalScore - a.totalScore);
+ }, [trackedContent]);
+
+ // Audience metric per account (platform-appropriate)
+ function audienceMetric(a) {
if (a.platform === 'instagram') return a.followersCount || 0;
- if (a.platform === 'reddit') return 0;
+ if (a.platform === 'reddit') return a.totalKarma || 0;
return a.subscriberCount || 0;
- };
- const contentMetric = (a) => {
- if (a.platform === 'reddit') return 0;
- if (a.platform === 'instagram') return a.mediaCount || 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 karmaMetric = (a) => (a.platform === 'reddit' ? a.totalKarma || 0 : 0);
+ }
- // Audience charts exclude Reddit - karma is not an audience metric
- const nonRedditAccounts = accounts.filter(a => a.platform !== 'reddit');
+ // All accounts sorted
+ const allSortedByAudience = [...accounts].sort((a, b) => audienceMetric(b) - audienceMetric(a));
+ const allSortedByContent = [...accounts].sort((a, b) => contentMetric(b) - contentMetric(a));
- const sorted = {
- byAudience: [...nonRedditAccounts].sort((a, b) => audienceMetric(b) - audienceMetric(a)),
- byContent: [...nonRedditAccounts].sort((a, b) => contentMetric(b) - contentMetric(a)),
- };
+ // Chart data: all accounts + tracked categories
+ 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 || '').slice(0, 12) + ((a.title || '').length > 12 ? '…' : ''),
+ value: a.followersCount || 0,
+ type: 'instagram',
+ })),
+ ...redditAccounts.map(a => ({
+ name: `u/${a.username || ''}`.slice(0, 12),
+ value: a.totalKarma || 0,
+ type: 'reddit',
+ })),
+ ...categoryStats.map(c => ({
+ name: c.category.slice(0, 12) + (c.category.length > 12 ? '…' : ''),
+ value: c.totalScore,
+ type: 'category',
+ })),
+ ], [ytAccounts, igAccounts, redditAccounts, categoryStats]);
- const chartData = nonRedditAccounts.map(a => ({
- name: (a.title || '').slice(0, 14) + ((a.title || '').length > 14 ? '…' : ''),
- audience: audienceMetric(a),
- }));
+ // Pie chart: all accounts + categories
+ const pieData = useMemo(() => {
+ const entries = [
+ ...accounts.map((a, i) => ({
+ name: (a.title || a.username || '?').slice(0, 14),
+ value: audienceMetric(a),
+ color: CHART_COLORS[i % CHART_COLORS.length],
+ })),
+ ...categoryStats.map((c, i) => ({
+ name: c.category.slice(0, 14),
+ value: c.totalScore,
+ color: CHART_COLORS[(accounts.length + i) % CHART_COLORS.length],
+ })),
+ ].filter(e => e.value > 0);
+ return entries;
+ }, [accounts, categoryStats]);
- const pieData = nonRedditAccounts.map((a, i) => ({
- name: (a.title || '').slice(0, 14) + ((a.title || '').length > 14 ? '…' : ''),
- value: audienceMetric(a),
- color: CHART_COLORS[i % CHART_COLORS.length],
- }));
-
- const handleViewChannel = (acc) => {
+ function handleViewChannel(acc) {
if (acc.platform === 'instagram') navigate(`/instagram/${acc.id}`);
else if (acc.platform === 'reddit') navigate(`/reddit/${acc.id}`);
else navigate(`/channel/${acc.id}`);
- };
+ }
+
+ const tabTriggerCls = 'flex flex-col items-start gap-0 h-auto py-3 px-4 text-left min-w-[140px]';
return (
<div className="space-y-6">
@@ -129,125 +216,12 @@ export default function Overview() {
className="gap-2 shrink-0"
>
<RefreshCw className={`h-3.5 w-3.5 ${loading ? 'animate-spin' : ''}`} />
- {loading ? 'Refreshing…' : 'Refresh All'}
+ {loading ? 'Refreshing...' : 'Refresh All'}
</Button>
</div>
- {/* Loading bar */}
{loading && <Progress className="h-1" value={undefined} />}
- {/* KPI cards */}
- <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-4">
- {[
- { icon: <Users />, label: 'Total Audience', value: fmtNum(totalAudience), subtitle: `${fmtNum(totals.subscribers)} subs · ${fmtNum(totals.followers)} followers`, gradient: 'purple' },
- { icon: <Eye />, label: 'Total Views', value: fmtNum(totals.views), subtitle: fmtNumFull(totals.views), gradient: 'red' },
- { icon: <VideoIcon />, label: 'Total Content', value: fmtNum(totals.videos + totals.posts), subtitle: `${fmtNum(totals.videos)} videos · ${fmtNum(totals.posts)} IG posts`, gradient: 'blue' },
- { icon: <BarChart3 />, label: 'Accounts', value: accounts.length, subtitle: [ytAccounts.length ? `${ytAccounts.length} YouTube` : null, igAccounts.length ? `${igAccounts.length} Instagram` : null, redditAccounts.length ? `${redditAccounts.length} Reddit` : null].filter(Boolean).join(' · '), gradient: 'orange' },
- ].map((card, i) => (
- <StatCard key={i} {...card} loading={loading} />
- ))}
- </div>
-
- {/* Reddit section - accounts, karma totals, and tracked categories in one card */}
- {redditAccounts.length > 0 && (
- <MainCard>
- {/* Header */}
- <div className="flex items-center justify-between mb-4">
- <div className="flex items-center gap-2">
- <Flame className="h-4 w-4 text-orange-500" />
- <span className="text-sm font-semibold">Reddit</span>
- <span className="text-xs text-muted-foreground">
- {redditAccounts.length} account{redditAccounts.length !== 1 ? 's' : ''}
- </span>
- </div>
- <button
- onClick={() => navigate('/reddit-tracked')}
- className="text-xs text-muted-foreground hover:text-foreground transition-colors"
- >
- Tracked posts
- </button>
- </div>
-
- {/* Stats row */}
- <div className="grid grid-cols-3 gap-3 mb-4">
- <div className="text-center p-3 rounded-lg bg-muted/40">
- <p className="text-lg font-bold tabular-nums text-orange-500">{fmtNum(totals.karma)}</p>
- <p className="text-xs font-medium text-muted-foreground mt-0.5">Total Karma</p>
- </div>
- <div className="text-center p-3 rounded-lg bg-muted/40">
- <p className="text-lg font-bold tabular-nums">{fmtNum(totalTrackedScore)}</p>
- <p className="text-xs font-medium text-muted-foreground mt-0.5">Total Upvotes</p>
- <p className="text-[10px] text-muted-foreground">tracked posts</p>
- </div>
- <div className="text-center p-3 rounded-lg bg-muted/40">
- <p className="text-lg font-bold tabular-nums">{fmtNum(totalTrackedComments)}</p>
- <p className="text-xs font-medium text-muted-foreground mt-0.5">Total Comments</p>
- <p className="text-[10px] text-muted-foreground">tracked posts</p>
- </div>
- </div>
-
- {/* Account rows */}
- <div className="space-y-0.5">
- <p className="text-[11px] font-semibold text-muted-foreground uppercase tracking-wider px-2 mb-1">
- Accounts
- </p>
- {[...redditAccounts]
- .sort((a, b) => (b.totalKarma || 0) - (a.totalKarma || 0))
- .map(a => (
- <button
- key={a.id}
- onClick={() => navigate(`/reddit/${a.id}`)}
- className="w-full flex items-center gap-2.5 px-2 py-1.5 rounded-lg hover:bg-muted/60 transition-colors text-left"
- >
- <Avatar className="h-6 w-6 flex-shrink-0">
- <AvatarImage src={a.thumbnail || a.iconUrl} />
- <AvatarFallback className="bg-orange-500 text-white text-[0.5rem] font-bold">
- {(a.username || '?').slice(0, 2).toUpperCase()}
- </AvatarFallback>
- </Avatar>
- <span className="flex-1 text-sm font-medium">u/{a.username}</span>
- <span className="text-sm tabular-nums text-muted-foreground">{fmtNum(a.totalKarma || 0)} karma</span>
- </button>
- ))}
- </div>
-
- {/* Category rows - only when tracked posts with categories exist */}
- {categoryStats.length > 0 && (
- <div className="border-t border-border mt-3 pt-3 space-y-0.5">
- <div className="flex items-center justify-between px-2 mb-1">
- <p className="text-[11px] font-semibold text-muted-foreground uppercase tracking-wider">
- Tracked Categories
- </p>
- <button
- onClick={() => navigate('/reddit-tracked')}
- className="text-xs text-muted-foreground hover:text-foreground transition-colors"
- >
- Manage
- </button>
- </div>
- {categoryStats.map(stat => (
- <button
- key={stat.category}
- onClick={() => navigate('/reddit-tracked')}
- className="w-full flex items-center gap-2.5 px-2 py-1.5 rounded-lg hover:bg-muted/60 transition-colors text-left"
- >
- <div className="h-6 w-6 rounded-md bg-orange-500/10 flex items-center justify-center flex-shrink-0">
- <Tag className="h-3.5 w-3.5 text-orange-500" />
- </div>
- <span className="flex-1 text-sm font-medium">{stat.category}</span>
- <span className="text-xs text-muted-foreground mr-2">
- {stat.count} post{stat.count !== 1 ? 's' : ''}
- </span>
- <span className="text-sm font-semibold tabular-nums text-orange-500">
- {fmtNum(stat.totalScore)}
- </span>
- </button>
- ))}
- </div>
- )}
- </MainCard>
- )}
-
{accounts.length === 0 ? (
<MainCard>
<div className="flex flex-col items-center text-center py-12 gap-4">
@@ -264,164 +238,574 @@ export default function Overview() {
</div>
</MainCard>
) : (
- <>
- {/* Audience charts - YouTube + Instagram only */}
- {nonRedditAccounts.length > 0 && <div className="grid grid-cols-1 xl:grid-cols-3 gap-4">
- <MainCard title="Audience Comparison" className="xl:col-span-2">
- <ResponsiveContainer width="100%" height={260} debounce={200}>
- <AreaChart data={chartData} margin={{ top: 4, right: 4, left: 0, bottom: 0 }}>
- <defs>
- <linearGradient id="audGrad" x1="0" y1="0" x2="0" y2="1">
- <stop offset="5%" stopColor="hsl(221.2,83.2%,53.3%)" stopOpacity={0.15} />
- <stop offset="95%" stopColor="hsl(221.2,83.2%,53.3%)" stopOpacity={0.01} />
- </linearGradient>
- </defs>
- <CartesianGrid strokeDasharray="3 3" stroke="var(--border)" vertical={false} />
- <XAxis dataKey="name" tick={{ fill: 'var(--muted-foreground)', fontSize: 11 }} axisLine={false} tickLine={false} />
- <YAxis tick={{ fill: 'var(--muted-foreground)', fontSize: 11 }} tickFormatter={fmtNum} axisLine={false} tickLine={false} width={48} />
- <ReTooltip
- contentStyle={{ background: 'var(--card)', border: '1px solid var(--border)', borderRadius: 8, fontSize: 12 }}
- formatter={(v) => [fmtNumFull(v), 'Audience']}
- />
- <Area type="monotone" dataKey="audience" stroke="hsl(221.2,83.2%,53.3%)" strokeWidth={2} fill="url(#audGrad)" dot={{ fill: 'hsl(221.2,83.2%,53.3%)', r: 4, strokeWidth: 0 }} />
- </AreaChart>
- </ResponsiveContainer>
+ <Tabs defaultValue="audience" className="space-y-6">
+ {/* Tab triggers - scrollable metric cards */}
+ <div className="overflow-x-auto pb-1">
+ <TabsList className="w-max flex gap-1 bg-muted/50 p-1 rounded-xl" style={{ height: 'auto' }}>
+ {/* Total Audience */}
+ <TabsTrigger value="audience" className={tabTriggerCls}>
+ <span className="text-[11px] font-medium text-muted-foreground uppercase tracking-wide">Total Audience</span>
+ <span className="text-2xl font-bold tabular-nums leading-tight mt-0.5">{fmtNum(totalAudience)}</span>
+ <span className="text-[11px] text-muted-foreground mt-0.5">
+ {[
+ totals.subscribers ? `${fmtNum(totals.subscribers)} subs` : null,
+ totals.followers ? `${fmtNum(totals.followers)} followers` : null,
+ totals.karma ? `${fmtNum(totals.karma)} karma` : null,
+ ].filter(Boolean).join(' · ') || 'no data yet'}
+ </span>
+ </TabsTrigger>
+
+ {/* Total Views */}
+ <TabsTrigger value="views" className={tabTriggerCls}>
+ <span className="text-[11px] font-medium text-muted-foreground uppercase tracking-wide">Total Views</span>
+ <span className="text-2xl font-bold tabular-nums leading-tight mt-0.5">{fmtNum(totals.views)}</span>
+ <span className="text-[11px] text-muted-foreground mt-0.5">
+ {ytAccounts.length > 0 ? `${ytAccounts.length} YouTube channel${ytAccounts.length !== 1 ? 's' : ''}` : 'no YouTube accounts'}
+ </span>
+ </TabsTrigger>
+
+ {/* Total Content */}
+ <TabsTrigger value="content" className={tabTriggerCls}>
+ <span className="text-[11px] font-medium text-muted-foreground uppercase tracking-wide">Total Content</span>
+ <span className="text-2xl font-bold tabular-nums leading-tight mt-0.5">{fmtNum(totalContent)}</span>
+ <span className="text-[11px] text-muted-foreground mt-0.5">
+ {[
+ totals.videos ? `${fmtNum(totals.videos)} videos` : null,
+ totals.posts ? `${fmtNum(totals.posts)} IG posts` : null,
+ trackedStats.total ? `${fmtNum(trackedStats.total)} tracked` : null,
+ ].filter(Boolean).join(' · ') || 'no content yet'}
+ </span>
+ </TabsTrigger>
+
+ {/* Accounts */}
+ <TabsTrigger value="accounts" className={tabTriggerCls}>
+ <span className="text-[11px] font-medium text-muted-foreground uppercase tracking-wide">Accounts</span>
+ <span className="text-2xl font-bold tabular-nums leading-tight mt-0.5">{accounts.length}</span>
+ <span className="text-[11px] text-muted-foreground mt-0.5">
+ {[
+ ytAccounts.length ? `${ytAccounts.length} YouTube` : null,
+ igAccounts.length ? `${igAccounts.length} Instagram` : null,
+ redditAccounts.length ? `${redditAccounts.length} Reddit` : null,
+ ].filter(Boolean).join(' · ')}
+ </span>
+ </TabsTrigger>
+
+ {/* Total Comments */}
+ <TabsTrigger value="comments" className={tabTriggerCls}>
+ <span className="text-[11px] font-medium text-muted-foreground uppercase tracking-wide">Total Comments</span>
+ <span className="text-2xl font-bold tabular-nums leading-tight mt-0.5">{fmtNum(trackedStats.totalComments)}</span>
+ <span className="text-[11px] text-muted-foreground mt-0.5">
+ {trackedStats.total > 0 ? `from ${trackedStats.total} tracked item${trackedStats.total !== 1 ? 's' : ''}` : 'track content to see data'}
+ </span>
+ </TabsTrigger>
+
+ {/* Total Likes */}
+ <TabsTrigger value="likes" className={tabTriggerCls}>
+ <span className="text-[11px] font-medium text-muted-foreground uppercase tracking-wide">Total Likes</span>
+ <span className="text-2xl font-bold tabular-nums leading-tight mt-0.5">{fmtNum(totalLikes)}</span>
+ <span className="text-[11px] text-muted-foreground mt-0.5">
+ {[
+ totals.postKarma ? `${fmtNum(totals.postKarma)} karma` : null,
+ trackedStats.totalYTLikes ? `${fmtNum(trackedStats.totalYTLikes)} YT likes` : null,
+ ].filter(Boolean).join(' · ') || 'track content to see data'}
+ </span>
+ </TabsTrigger>
+ </TabsList>
+ </div>
+
+ {/* ── AUDIENCE TAB ─────────────────────────────────────────────── */}
+ <TabsContent value="audience" className="space-y-4">
+ {/* Audience Comparison + Share */}
+ <div className="grid grid-cols-1 xl:grid-cols-3 gap-4">
+ <MainCard title="Audience Comparison" className="xl:col-span-2">
+ <p className="text-xs text-muted-foreground mb-3">
+ YouTube = subscribers · Instagram = followers · Reddit = karma · Categories = total score
+ </p>
+ {audienceChartData.length === 0 ? (
+ <p className="text-sm text-muted-foreground py-8 text-center">No data to display</p>
+ ) : (
+ <ResponsiveContainer width="100%" height={240} debounce={200}>
+ <BarChart data={audienceChartData} margin={{ top: 4, right: 4, left: 0, bottom: 0 }}>
+ <CartesianGrid strokeDasharray="3 3" stroke="var(--border)" vertical={false} />
+ <XAxis dataKey="name" tick={{ fill: 'var(--muted-foreground)', fontSize: 11 }} axisLine={false} tickLine={false} />
+ <YAxis tick={{ fill: 'var(--muted-foreground)', fontSize: 11 }} tickFormatter={fmtNum} axisLine={false} tickLine={false} width={48} />
+ <ReTooltip
+ contentStyle={{ background: 'var(--card)', border: '1px solid var(--border)', borderRadius: 8, fontSize: 12 }}
+ formatter={(v, name, props) => [fmtNumFull(v), props.payload.type === 'category' ? 'Score' : 'Audience']}
+ />
+ <Bar dataKey="value" radius={[4, 4, 0, 0]}>
+ {audienceChartData.map((entry, i) => (
+ <Cell key={i} fill={PLATFORM_COLORS[entry.type] || CHART_COLORS[i % CHART_COLORS.length]} />
+ ))}
+ </Bar>
+ </BarChart>
+ </ResponsiveContainer>
+ )}
+ {/* Legend */}
+ <div className="flex flex-wrap gap-3 mt-2">
+ {[
+ ytAccounts.length ? { color: PLATFORM_COLORS.youtube, label: 'YouTube (subs)' } : null,
+ igAccounts.length ? { color: PLATFORM_COLORS.instagram, label: 'Instagram (followers)' } : null,
+ redditAccounts.length ? { color: PLATFORM_COLORS.reddit, label: 'Reddit (karma)' } : null,
+ categoryStats.length ? { color: PLATFORM_COLORS.category, label: 'Tracked categories (score)' } : null,
+ ].filter(Boolean).map(({ color, label }) => (
+ <div key={label} className="flex items-center gap-1.5 text-xs text-muted-foreground">
+ <span className="h-2.5 w-2.5 rounded-full flex-shrink-0" style={{ background: color }} />
+ {label}
+ </div>
+ ))}
+ </div>
+ </MainCard>
+
+ <MainCard title="Audience Share">
+ {pieData.length === 0 ? (
+ <p className="text-sm text-muted-foreground py-8 text-center">No data to display</p>
+ ) : (
+ <ResponsiveContainer width="100%" height={260} debounce={200}>
+ <PieChart>
+ <Pie data={pieData} dataKey="value" nameKey="name" cx="50%" cy="44%" outerRadius={85} innerRadius={48} paddingAngle={3} strokeWidth={0}>
+ {pieData.map((entry, i) => (
+ <Cell key={i} fill={entry.color} />
+ ))}
+ </Pie>
+ <ReTooltip contentStyle={{ background: 'var(--card)', border: '1px solid var(--border)', borderRadius: 8, fontSize: 12 }} formatter={(v) => fmtNumFull(v)} />
+ <Legend iconType="circle" iconSize={8} wrapperStyle={{ fontSize: 11, paddingTop: 8 }} />
+ </PieChart>
+ </ResponsiveContainer>
+ )}
+ </MainCard>
+ </div>
+
+ {/* Top by Audience (all platforms) */}
+ <MainCard title="Top by Audience">
+ <div className="space-y-1">
+ {allSortedByAudience.map((a, i) => {
+ const medalColor = i === 0 ? 'text-yellow-500' : i === 1 ? 'text-slate-400' : i === 2 ? 'text-orange-400' : 'text-muted-foreground';
+ const fallbackBg = a.platform === 'instagram' ? 'bg-pink-500' : a.platform === 'reddit' ? 'bg-orange-500' : 'bg-red-500';
+ const metric = a.platform === 'instagram'
+ ? `${fmtNum(a.followersCount)} followers`
+ : a.platform === 'reddit'
+ ? `${fmtNum(a.totalKarma)} karma`
+ : `${fmtNum(a.subscriberCount)} subs`;
+ return (
+ <button
+ key={a.id}
+ onClick={() => handleViewChannel(a)}
+ className="w-full flex items-center gap-3 px-2 py-1.5 rounded-lg hover:bg-muted/60 transition-colors text-left"
+ >
+ <span className={`w-5 text-xs font-bold tabular-nums ${medalColor}`}>{i + 1}</span>
+ <Avatar className="h-7 w-7 flex-shrink-0">
+ <AvatarImage src={a.thumbnail || a.profilePictureUrl || a.thumbnails?.default || a.iconUrl} />
+ <AvatarFallback className={`text-[0.55rem] font-bold text-white ${fallbackBg}`}>
+ {(a.title || a.username || '?').slice(0, 2).toUpperCase()}
+ </AvatarFallback>
+ </Avatar>
+ <span className="flex-1 text-sm font-medium truncate">
+ {a.platform === 'reddit' ? `u/${a.username}` : a.title}
+ </span>
+ <PlatformBadge platform={a.platform} />
+ <span className="text-sm font-semibold text-muted-foreground tabular-nums">{metric}</span>
+ </button>
+ );
+ })}
+ {/* Tracked categories */}
+ {categoryStats.map(stat => (
+ <button
+ key={stat.category}
+ onClick={() => navigate('/tracked-content')}
+ className="w-full flex items-center gap-3 px-2 py-1.5 rounded-lg hover:bg-muted/60 transition-colors text-left"
+ >
+ <span className="w-5 text-xs font-bold tabular-nums text-muted-foreground">#</span>
+ <div className="h-7 w-7 rounded-full bg-purple-500/10 flex items-center justify-center flex-shrink-0">
+ <Tag className="h-3.5 w-3.5 text-purple-500" />
+ </div>
+ <span className="flex-1 text-sm font-medium truncate">{stat.category}</span>
+ <Badge variant="outline" className="text-[10px] border-purple-200 bg-purple-50 text-purple-700 dark:border-purple-900 dark:bg-purple-950 dark:text-purple-400">
+ Category
+ </Badge>
+ <span className="text-sm font-semibold text-muted-foreground tabular-nums">{fmtNum(stat.totalScore)} score</span>
+ </button>
+ ))}
+ </div>
</MainCard>
+ </TabsContent>
- <MainCard title="Audience Share">
- <ResponsiveContainer width="100%" height={260} debounce={200}>
- <PieChart>
- <Pie data={pieData} dataKey="value" nameKey="name" cx="50%" cy="44%" outerRadius={85} innerRadius={48} paddingAngle={3} strokeWidth={0}>
- {pieData.map((entry, i) => (
- <Cell key={i} fill={entry.color} />
+ {/* ── VIEWS TAB ────────────────────────────────────────────────── */}
+ <TabsContent value="views" className="space-y-4">
+ {ytAccounts.length === 0 ? (
+ <MainCard>
+ <p className="text-sm text-muted-foreground text-center py-8">No YouTube accounts connected</p>
+ </MainCard>
+ ) : (
+ <MainCard title="YouTube Views by Channel" content={false}>
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead className="w-10">#</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" />
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {[...ytAccounts].sort((a, b) => (b.viewCount || 0) - (a.viewCount || 0)).map((a, i) => (
+ <TableRow key={a.id} className="cursor-pointer" onClick={() => navigate(`/channel/${a.id}`)}>
+ <TableCell>
+ <span className={`text-xs font-bold ${i === 0 ? 'text-yellow-500' : i === 1 ? 'text-slate-400' : i === 2 ? 'text-orange-400' : 'text-muted-foreground'}`}>{i + 1}</span>
+ </TableCell>
+ <TableCell>
+ <div className="flex items-center gap-2.5">
+ <Avatar className="h-8 w-8">
+ <AvatarImage src={a.thumbnail || a.thumbnails?.default} />
+ <AvatarFallback className="bg-red-500 text-xs font-bold text-white">
+ {(a.title || '?').slice(0, 2).toUpperCase()}
+ </AvatarFallback>
+ </Avatar>
+ <div>
+ <p className="text-sm font-semibold leading-none">{a.title}</p>
+ <p className="text-xs text-muted-foreground mt-0.5">{a.customUrl || a.channelId || ''}</p>
+ </div>
+ </div>
+ </TableCell>
+ <TableCell className="text-right">
+ <p className="text-sm font-bold">{fmtNum(a.viewCount)}</p>
+ <p className="text-xs text-muted-foreground">{fmtNumFull(a.viewCount)}</p>
+ </TableCell>
+ <TableCell className="text-right text-sm">{fmtNum(a.subscriberCount)}</TableCell>
+ <TableCell className="text-right text-sm">{fmtNum(a.videoCount)}</TableCell>
+ <TableCell className="text-right text-xs text-muted-foreground">{timeAgo(a.lastUpdated)}</TableCell>
+ <TableCell>
+ <Tooltip>
+ <TooltipTrigger render={<Button variant="ghost" size="icon" className="size-7" onClick={(e) => { e.stopPropagation(); navigate(`/channel/${a.id}`); }} />}>
+ <ExternalLink />
+ </TooltipTrigger>
+ <TooltipContent>View Analytics</TooltipContent>
+ </Tooltip>
+ </TableCell>
+ </TableRow>
))}
- </Pie>
- <ReTooltip contentStyle={{ background: 'var(--card)', border: '1px solid var(--border)', borderRadius: 8, fontSize: 12 }} formatter={(v) => fmtNumFull(v)} />
- <Legend iconType="circle" iconSize={8} wrapperStyle={{ fontSize: 11, paddingTop: 8 }} />
- </PieChart>
- </ResponsiveContainer>
- </MainCard>
- </div>}
-
- {nonRedditAccounts.length > 0 && (
- <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
- {[
- {
- title: 'Top by Audience',
- list: sorted.byAudience,
- metric: a => a.platform === 'instagram' ? `${fmtNum(a.followersCount)} followers` : `${fmtNum(a.subscriberCount)} subs`,
- },
- {
- title: 'Top by Content',
- list: sorted.byContent,
- metric: a => a.platform === 'instagram' ? `${fmtNum(a.mediaCount)} posts` : `${fmtNum(a.viewCount)} views`,
- },
- ].map(({ title, list, metric }) => (
- <MainCard key={title} title={title}>
+ </TableBody>
+ </Table>
+ </MainCard>
+ )}
+ </TabsContent>
+
+ {/* ── CONTENT TAB ──────────────────────────────────────────────── */}
+ <TabsContent value="content" className="space-y-4">
+ <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
+ <StatCard icon={<Youtube />} label="YouTube Videos" value={fmtNum(totals.videos)} subtitle={`${ytAccounts.length} channel${ytAccounts.length !== 1 ? 's' : ''}`} gradient="red" />
+ <StatCard icon={<VideoIcon />} label="Instagram Posts" value={fmtNum(totals.posts)} subtitle={`${igAccounts.length} account${igAccounts.length !== 1 ? 's' : ''}`} gradient="blue" />
+ <StatCard icon={<BookmarkCheck />} label="Tracked Content" value={fmtNum(trackedStats.total)} subtitle={`${trackedStats.ytItems.length} YouTube · ${trackedStats.rdItems.length} Reddit`} gradient="orange" />
+ </div>
+
+ {/* Top by Content */}
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
+ <MainCard title="Top by Content">
<div className="space-y-1">
- {list.map((a, i) => {
- const ig = a.platform === 'instagram';
- const medalColor = i === 0 ? 'text-yellow-500' : i === 1 ? 'text-slate-400' : i === 2 ? 'text-orange-400' : 'text-muted-foreground';
- const fallbackBg = ig ? 'bg-pink-500' : 'bg-red-500';
- const badgeCls = ig ? 'border-pink-200 bg-pink-50 text-pink-700' : 'border-green-200 bg-green-50 text-green-700';
+ {allSortedByContent.map((a, i) => {
+ const metric = a.platform === 'instagram'
+ ? `${fmtNum(a.mediaCount)} posts`
+ : a.platform === 'reddit'
+ ? `${fmtNum(a.totalKarma)} karma`
+ : `${fmtNum(a.viewCount)} views`;
+ const fallbackBg = a.platform === 'instagram' ? 'bg-pink-500' : a.platform === 'reddit' ? 'bg-orange-500' : 'bg-red-500';
return (
<button
key={a.id}
onClick={() => handleViewChannel(a)}
className="w-full flex items-center gap-3 px-2 py-1.5 rounded-lg hover:bg-muted/60 transition-colors text-left"
>
- <span className={`w-5 text-xs font-bold tabular-nums ${medalColor}`}>{i + 1}</span>
+ <span className={`w-5 text-xs font-bold ${i === 0 ? 'text-yellow-500' : i === 1 ? 'text-slate-400' : i === 2 ? 'text-orange-400' : 'text-muted-foreground'}`}>{i + 1}</span>
<Avatar className="h-7 w-7 flex-shrink-0">
- <AvatarImage src={a.thumbnail || a.profilePictureUrl || a.thumbnails?.default} />
+ <AvatarImage src={a.thumbnail || a.profilePictureUrl || a.thumbnails?.default || a.iconUrl} />
<AvatarFallback className={`text-[0.55rem] font-bold text-white ${fallbackBg}`}>
- {(a.title || '?').slice(0, 2).toUpperCase()}
+ {(a.title || a.username || '?').slice(0, 2).toUpperCase()}
</AvatarFallback>
</Avatar>
- <span className="flex-1 text-sm font-medium truncate">{a.title}</span>
- <Badge variant="outline" className={`text-xs font-semibold ${badgeCls}`}>
- {metric(a)}
- </Badge>
+ <span className="flex-1 text-sm font-medium truncate">
+ {a.platform === 'reddit' ? `u/${a.username}` : a.title}
+ </span>
+ <span className="text-sm font-semibold text-muted-foreground tabular-nums">{metric}</span>
</button>
);
})}
</div>
</MainCard>
- ))}
- </div>
- )}
-
- {nonRedditAccounts.length > 0 && (
- <MainCard title="All Accounts" content={false}>
- <Table>
- <TableHeader>
- <TableRow>
- <TableHead className="w-10">#</TableHead>
- <TableHead>Account</TableHead>
- <TableHead className="text-center">Platform</TableHead>
- <TableHead className="text-right">Audience</TableHead>
- <TableHead className="text-right">Content</TableHead>
- <TableHead className="text-right">Updated</TableHead>
- <TableHead className="w-10" />
- </TableRow>
- </TableHeader>
- <TableBody>
- {sorted.byAudience.map((a, i) => {
- const ig = a.platform === 'instagram';
- const medalColor = i === 0 ? 'text-yellow-500' : i === 1 ? 'text-slate-400' : i === 2 ? 'text-orange-400' : 'text-muted-foreground';
- const fallbackBg = ig ? 'bg-pink-500' : 'bg-red-500';
- const platformBadgeCls = ig ? 'border-pink-200 bg-pink-50 text-pink-700' : 'border-red-200 bg-red-50 text-red-700';
- return (
- <TableRow key={a.id} className="cursor-pointer" onClick={() => handleViewChannel(a)}>
- <TableCell>
- <span className={`text-xs font-bold ${medalColor}`}>{i + 1}</span>
- </TableCell>
- <TableCell>
- <div className="flex items-center gap-2.5">
- <Avatar className="h-8 w-8">
- <AvatarImage src={a.thumbnail || a.profilePictureUrl || a.thumbnails?.default} />
- <AvatarFallback className={`text-xs font-bold text-white ${fallbackBg}`}>
- {(a.title || '?').slice(0, 2).toUpperCase()}
- </AvatarFallback>
- </Avatar>
- <div>
- <p className="text-sm font-semibold leading-none">{a.title}</p>
- <p className="text-xs text-muted-foreground mt-0.5">
- {ig ? `@${a.username || ''}` : (a.customUrl || a.channelId || '')}
+
+ {/* Tracked categories breakdown */}
+ <MainCard title="Tracked Categories">
+ {categoryStats.length === 0 ? (
+ <p className="text-sm text-muted-foreground text-center py-8">
+ Assign categories to tracked content to see breakdown
+ </p>
+ ) : (
+ <div className="space-y-1">
+ {categoryStats.map(stat => {
+ const ytInCat = trackedStats.ytItems.filter(p => p.category === stat.category).length;
+ const rdInCat = trackedStats.rdItems.filter(p => p.category === stat.category).length;
+ return (
+ <button
+ key={stat.category}
+ onClick={() => navigate('/tracked-content')}
+ className="w-full flex items-center gap-2.5 px-2 py-2 rounded-lg hover:bg-muted/60 transition-colors text-left"
+ >
+ <div className="h-7 w-7 rounded-md bg-purple-500/10 flex items-center justify-center flex-shrink-0">
+ <Tag className="h-3.5 w-3.5 text-purple-500" />
+ </div>
+ <div className="flex-1 min-w-0">
+ <p className="text-sm font-medium truncate">{stat.category}</p>
+ <p className="text-xs text-muted-foreground">
+ {stat.count} item{stat.count !== 1 ? 's' : ''}
+ {ytInCat > 0 && rdInCat > 0 ? ` · ${ytInCat} YT · ${rdInCat} Reddit` : ''}
</p>
</div>
- </div>
- </TableCell>
- <TableCell className="text-center">
- <Badge variant="outline" className={`text-xs ${platformBadgeCls}`}>
- {ig ? 'Instagram' : 'YouTube'}
- </Badge>
- </TableCell>
- <TableCell className="text-right">
- <p className="text-sm font-semibold">{fmtNum(ig ? a.followersCount : a.subscriberCount)}</p>
- <p className="text-xs text-muted-foreground">{ig ? 'followers' : 'subscribers'}</p>
- </TableCell>
- <TableCell className="text-right text-sm">
- {ig ? `${fmtNum(a.mediaCount)} posts` : `${fmtNum(a.viewCount)} views · ${fmtNum(a.videoCount)} vids`}
- </TableCell>
- <TableCell className="text-right text-xs text-muted-foreground">
- {timeAgo(a.lastUpdated)}
- </TableCell>
- <TableCell>
- <Tooltip>
- <TooltipTrigger render={<Button variant="ghost" size="icon" className="size-7" onClick={(e) => { e.stopPropagation(); handleViewChannel(a); }} />}>
- <ExternalLink />
- </TooltipTrigger>
- <TooltipContent>View Analytics</TooltipContent>
- </Tooltip>
- </TableCell>
+ <span className="text-sm font-semibold tabular-nums text-purple-500">{fmtNum(stat.totalScore)}</span>
+ </button>
+ );
+ })}
+ </div>
+ )}
+ </MainCard>
+ </div>
+ </TabsContent>
+
+ {/* ── ACCOUNTS TAB ─────────────────────────────────────────────── */}
+ <TabsContent value="accounts" className="space-y-4">
+ <MainCard content={false}>
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead className="w-10">#</TableHead>
+ <TableHead>Account</TableHead>
+ <TableHead className="text-center">Platform</TableHead>
+ <TableHead className="text-right">Audience</TableHead>
+ <TableHead className="text-right">Content</TableHead>
+ <TableHead className="text-right">Updated</TableHead>
+ <TableHead className="w-10" />
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {allSortedByAudience.map((a, i) => {
+ const audience = a.platform === 'instagram'
+ ? `${fmtNum(a.followersCount)} followers`
+ : a.platform === 'reddit'
+ ? `${fmtNum(a.totalKarma)} karma`
+ : `${fmtNum(a.subscriberCount)} subs`;
+ const content = a.platform === 'instagram'
+ ? `${fmtNum(a.mediaCount)} posts`
+ : a.platform === 'reddit'
+ ? `${fmtNum(a.postKarma)} post karma`
+ : `${fmtNum(a.viewCount)} views · ${fmtNum(a.videoCount)} vids`;
+ const fallbackBg = a.platform === 'instagram' ? 'bg-pink-500' : a.platform === 'reddit' ? 'bg-orange-500' : 'bg-red-500';
+ const medalColor = i === 0 ? 'text-yellow-500' : i === 1 ? 'text-slate-400' : i === 2 ? 'text-orange-400' : 'text-muted-foreground';
+ return (
+ <TableRow key={a.id} className="cursor-pointer" onClick={() => handleViewChannel(a)}>
+ <TableCell>
+ <span className={`text-xs font-bold ${medalColor}`}>{i + 1}</span>
+ </TableCell>
+ <TableCell>
+ <div className="flex items-center gap-2.5">
+ <Avatar className="h-8 w-8">
+ <AvatarImage src={a.thumbnail || a.profilePictureUrl || a.thumbnails?.default || a.iconUrl} />
+ <AvatarFallback className={`text-xs font-bold text-white ${fallbackBg}`}>
+ {(a.title || a.username || '?').slice(0, 2).toUpperCase()}
+ </AvatarFallback>
+ </Avatar>
+ <div>
+ <p className="text-sm font-semibold leading-none">
+ {a.platform === 'reddit' ? `u/${a.username}` : a.title}
+ </p>
+ <p className="text-xs text-muted-foreground mt-0.5">
+ {a.platform === 'instagram' ? `@${a.username || ''}` : a.platform === 'reddit' ? 'Reddit' : (a.customUrl || a.channelId || '')}
+ </p>
+ </div>
+ </div>
+ </TableCell>
+ <TableCell className="text-center">
+ <PlatformBadge platform={a.platform} />
+ </TableCell>
+ <TableCell className="text-right text-sm">{audience}</TableCell>
+ <TableCell className="text-right text-sm text-muted-foreground">{content}</TableCell>
+ <TableCell className="text-right text-xs text-muted-foreground">{timeAgo(a.lastUpdated)}</TableCell>
+ <TableCell>
+ <Tooltip>
+ <TooltipTrigger render={<Button variant="ghost" size="icon" className="size-7" onClick={(e) => { e.stopPropagation(); handleViewChannel(a); }} />}>
+ <ExternalLink />
+ </TooltipTrigger>
+ <TooltipContent>View Analytics</TooltipContent>
+ </Tooltip>
+ </TableCell>
+ </TableRow>
+ );
+ })}
+ </TableBody>
+ </Table>
+ </MainCard>
+ </TabsContent>
+
+ {/* ── COMMENTS TAB ─────────────────────────────────────────────── */}
+ <TabsContent value="comments" className="space-y-4">
+ <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
+ <StatCard icon={<MessageSquare />} label="Total Comments" value={fmtNum(trackedStats.totalComments)} subtitle="from tracked content" gradient="blue" />
+ <StatCard icon={<Youtube />} label="YouTube Comments" value={fmtNum(trackedStats.ytItems.reduce((s, p) => s + (p.commentCount ?? 0), 0))} subtitle={`${trackedStats.ytItems.length} video${trackedStats.ytItems.length !== 1 ? 's' : ''} tracked`} gradient="red" />
+ <StatCard icon={<Flame />} label="Reddit Comments" value={fmtNum(trackedStats.rdItems.reduce((s, p) => s + (p.numComments ?? 0), 0))} subtitle={`${trackedStats.rdItems.length} post${trackedStats.rdItems.length !== 1 ? 's' : ''} tracked`} gradient="orange" />
+ </div>
+
+ {trackedContent.length === 0 ? (
+ <MainCard>
+ <div className="flex flex-col items-center text-center py-10 gap-3">
+ <MessageSquare className="h-8 w-8 text-muted-foreground" />
+ <div>
+ <p className="text-sm font-semibold">No tracked content yet</p>
+ <p className="text-xs text-muted-foreground mt-1">Track Reddit posts or YouTube videos to see comment counts here</p>
+ </div>
+ <Button size="sm" onClick={() => navigate('/tracked-content')}>Track Content</Button>
+ </div>
+ </MainCard>
+ ) : (
+ <MainCard title="Tracked Content by Comments" content={false}>
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead>Title</TableHead>
+ <TableHead className="w-28">Category</TableHead>
+ <TableHead className="text-right w-28">Comments</TableHead>
+ <TableHead className="text-right w-28">Likes / Score</TableHead>
</TableRow>
- );
- })}
- </TableBody>
- </Table>
- </MainCard>
- )}
- </>
+ </TableHeader>
+ <TableBody>
+ {[...trackedContent]
+ .sort((a, b) => {
+ const ca = a.contentType === 'youtube' ? (a.commentCount ?? 0) : (a.numComments ?? 0);
+ const cb = b.contentType === 'youtube' ? (b.commentCount ?? 0) : (b.numComments ?? 0);
+ return cb - ca;
+ })
+ .map(item => {
+ const isYT = item.contentType === 'youtube';
+ const comments = isYT ? (item.commentCount ?? 0) : (item.numComments ?? 0);
+ const engagement = isYT ? (item.likeCount ?? 0) : (item.score ?? 0);
+ return (
+ <TableRow key={item.id}>
+ <TableCell>
+ <div className="flex items-center gap-2">
+ {isYT ? (
+ <Youtube className="h-3.5 w-3.5 text-red-500 flex-shrink-0" />
+ ) : (
+ <Flame className="h-3.5 w-3.5 text-orange-500 flex-shrink-0" />
+ )}
+ <span className="text-sm font-medium truncate max-w-xs">
+ {item.title || item.label || item.url}
+ </span>
+ </div>
+ <p className="text-xs text-muted-foreground ml-5 mt-0.5">
+ {isYT ? item.channelTitle : item.subredditPrefixed}
+ </p>
+ </TableCell>
+ <TableCell>
+ {item.category ? (
+ <Badge variant="outline" className="text-xs">{item.category}</Badge>
+ ) : <span className="text-xs text-muted-foreground">-</span>}
+ </TableCell>
+ <TableCell className="text-right text-sm font-semibold tabular-nums">
+ {fmtNum(comments)}
+ </TableCell>
+ <TableCell className={`text-right text-sm font-semibold tabular-nums ${isYT ? 'text-red-500' : 'text-orange-500'}`}>
+ {fmtNum(engagement)}
+ </TableCell>
+ </TableRow>
+ );
+ })}
+ </TableBody>
+ </Table>
+ </MainCard>
+ )}
+ </TabsContent>
+
+ {/* ── LIKES TAB ────────────────────────────────────────────────── */}
+ <TabsContent value="likes" className="space-y-4">
+ <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
+ <StatCard icon={<ThumbsUp />} label="Total Likes" value={fmtNum(totalLikes)} subtitle="karma + YouTube likes" gradient="purple" />
+ <StatCard icon={<Flame />} label="Reddit Karma" value={fmtNum(totals.postKarma)} subtitle="post upvotes across accounts" gradient="orange" />
+ <StatCard icon={<Youtube />} label="YouTube Likes" value={fmtNum(trackedStats.totalYTLikes)} subtitle={`${trackedStats.ytItems.length} tracked video${trackedStats.ytItems.length !== 1 ? 's' : ''}`} gradient="red" />
+ </div>
+
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
+ {/* Reddit accounts by karma */}
+ {redditAccounts.length > 0 && (
+ <MainCard title="Reddit Accounts by Karma">
+ <div className="space-y-1">
+ {[...redditAccounts]
+ .sort((a, b) => (b.postKarma || 0) - (a.postKarma || 0))
+ .map(a => (
+ <button
+ key={a.id}
+ onClick={() => navigate(`/reddit/${a.id}`)}
+ className="w-full flex items-center gap-2.5 px-2 py-1.5 rounded-lg hover:bg-muted/60 transition-colors text-left"
+ >
+ <Avatar className="h-6 w-6 flex-shrink-0">
+ <AvatarImage src={a.iconUrl} />
+ <AvatarFallback className="bg-orange-500 text-white text-[0.5rem] font-bold">
+ {(a.username || '?').slice(0, 2).toUpperCase()}
+ </AvatarFallback>
+ </Avatar>
+ <span className="flex-1 text-sm font-medium">u/{a.username}</span>
+ <div className="text-right">
+ <p className="text-sm font-bold tabular-nums text-orange-500">{fmtNum(a.postKarma || 0)}</p>
+ <p className="text-[10px] text-muted-foreground">post karma</p>
+ </div>
+ </button>
+ ))}
+ </div>
+ </MainCard>
+ )}
+
+ {/* Tracked YouTube by likes */}
+ <MainCard title="Tracked YouTube by Likes">
+ {trackedStats.ytItems.length === 0 ? (
+ <div className="flex flex-col items-center text-center py-8 gap-3">
+ <Youtube className="h-7 w-7 text-muted-foreground" />
+ <div>
+ <p className="text-sm font-medium">No YouTube videos tracked</p>
+ <p className="text-xs text-muted-foreground mt-1">Track YouTube videos to see their like counts</p>
+ </div>
+ <Button size="sm" variant="outline" onClick={() => navigate('/tracked-content')}>Track Videos</Button>
+ </div>
+ ) : (
+ <div className="space-y-1">
+ {[...trackedStats.ytItems]
+ .sort((a, b) => (b.likeCount ?? 0) - (a.likeCount ?? 0))
+ .map(item => (
+ <button
+ key={item.id}
+ onClick={() => window.open(item.permalink || item.url, '_blank')}
+ className="w-full flex items-center gap-2.5 px-2 py-1.5 rounded-lg hover:bg-muted/60 transition-colors text-left"
+ >
+ {item.thumbnail ? (
+ <img src={item.thumbnail} alt="" className="h-9 w-14 rounded object-cover flex-shrink-0" />
+ ) : (
+ <div className="h-9 w-14 rounded bg-red-500/10 flex items-center justify-center flex-shrink-0">
+ <Youtube className="h-4 w-4 text-red-500" />
+ </div>
+ )}
+ <div className="flex-1 min-w-0">
+ <p className="text-sm font-medium truncate">{item.title || item.url}</p>
+ <p className="text-xs text-muted-foreground">{item.channelTitle}</p>
+ </div>
+ <div className="text-right flex-shrink-0">
+ <p className="text-sm font-bold tabular-nums text-red-500">{fmtNum(item.likeCount ?? 0)}</p>
+ <p className="text-[10px] text-muted-foreground">likes</p>
+ </div>
+ </button>
+ ))}
+ </div>
+ )}
+ </MainCard>
+ </div>
+ </TabsContent>
+ </Tabs>
)}
</div>
);
diff --git a/frontend/src/features/analytics/tracked/TrackedContent.jsx b/frontend/src/features/analytics/tracked/TrackedContent.jsx
new file mode 100644
index 0000000..2952677
--- /dev/null
+++ b/frontend/src/features/analytics/tracked/TrackedContent.jsx
@@ -0,0 +1,656 @@
+import React, { useState, useEffect, useMemo, useCallback } from 'react';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+import { Badge } from '@/components/ui/badge';
+import { Checkbox } from '@/components/ui/checkbox';
+import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
+import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
+import { Skeleton } from '@/components/ui/skeleton';
+import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog';
+import StatCard from '../../../components/ui/StatCard';
+import MainCard from '../../../components/MainCard';
+import { useAppContext } from '../../../context/AppContext';
+import { api } from '../../../services/api';
+import { fmtNum, fmtDate } from '../../../utils/formatters';
+import {
+ Plus, RefreshCw, Trash2, Pencil, ExternalLink,
+ Tag, Bookmark, TrendingUp, BookmarkCheck, Youtube, Flame,
+} from 'lucide-react';
+
+function detectContentType(url) {
+ const lower = (url || '').toLowerCase();
+ if (lower.includes('reddit.com') || lower.includes('redd.it')) return 'reddit';
+ if (lower.includes('youtube.com') || lower.includes('youtu.be')) return 'youtube';
+ return null;
+}
+
+function getEngagement(item) {
+ if (item.contentType === 'youtube') return item.likeCount ?? 0;
+ return item.score ?? 0;
+}
+
+function getComments(item) {
+ if (item.contentType === 'youtube') return item.commentCount ?? 0;
+ return item.numComments ?? 0;
+}
+
+function ContentTypeBadge({ type }) {
+ if (type === 'youtube') {
+ return (
+ <Badge variant="outline" className="text-[10px] border-red-200 bg-red-50 text-red-700 dark:border-red-900 dark:bg-red-950 dark:text-red-400 gap-1 px-1.5 py-0">
+ <Youtube className="h-2.5 w-2.5" />
+ YouTube
+ </Badge>
+ );
+ }
+ return (
+ <Badge variant="outline" className="text-[10px] border-orange-200 bg-orange-50 text-orange-700 dark:border-orange-900 dark:bg-orange-950 dark:text-orange-400 gap-1 px-1.5 py-0">
+ <Flame className="h-2.5 w-2.5" />
+ Reddit
+ </Badge>
+ );
+}
+
+export default function TrackedContent() {
+ const { accounts, showToast } = useAppContext();
+ const redditAccounts = accounts.filter(a => a.platform === 'reddit');
+
+ const [items, setItems] = useState([]);
+ const [loading, setLoading] = useState(true);
+ const [addOpen, setAddOpen] = useState(false);
+ const [editItem, setEditItem] = useState(null);
+ const [selected, setSelected] = useState(new Set());
+ const [bulkCategory, setBulkCategory] = useState('');
+ const [query, setQuery] = useState('');
+ const [typeFilter, setTypeFilter] = useState('all');
+ const [categoryFilter, setCategoryFilter] = useState('all');
+ const [sort, setSort] = useState('date-desc');
+ const [refreshingIds, setRefreshingIds] = useState(new Set());
+
+ // Add dialog state
+ const [addUrl, setAddUrl] = useState('');
+ const [detectedType, setDetectedType] = useState(null);
+ const [addAccountId, setAddAccountId] = useState(redditAccounts[0]?.id ?? 'none');
+ const [addLabel, setAddLabel] = useState('');
+ const [addCategory, setAddCategory] = useState('');
+ const [adding, setAdding] = useState(false);
+
+ // Edit dialog state
+ const [editLabel, setEditLabel] = useState('');
+ const [editCategory, setEditCategory] = useState('');
+ const [saving, setSaving] = useState(false);
+
+ const load = useCallback(async () => {
+ try {
+ const data = await api.getTrackedContent();
+ setItems(Array.isArray(data) ? data : []);
+ } catch (err) {
+ showToast(err.message, 'error');
+ } finally {
+ setLoading(false);
+ }
+ }, [showToast]);
+
+ useEffect(() => { load(); }, [load]);
+
+ function handleUrlChange(val) {
+ setAddUrl(val);
+ setDetectedType(detectContentType(val));
+ }
+
+ const categories = useMemo(() => {
+ const seen = new Set(items.map(p => p.category).filter(Boolean));
+ return Array.from(seen).sort();
+ }, [items]);
+
+ const filtered = useMemo(() => {
+ let result = items;
+ if (typeFilter !== 'all') result = result.filter(p => (p.contentType || 'reddit') === typeFilter);
+ if (categoryFilter !== 'all') result = result.filter(p => p.category === categoryFilter);
+ if (query.trim()) {
+ const q = query.toLowerCase();
+ result = result.filter(p =>
+ (p.title || '').toLowerCase().includes(q) ||
+ (p.subreddit || '').toLowerCase().includes(q) ||
+ (p.channelTitle || '').toLowerCase().includes(q) ||
+ (p.label || '').toLowerCase().includes(q) ||
+ (p.category || '').toLowerCase().includes(q)
+ );
+ }
+ return [...result].sort((a, b) => {
+ if (sort === 'engagement-desc') return getEngagement(b) - getEngagement(a);
+ if (sort === 'comments-desc') return getComments(b) - getComments(a);
+ if (sort === 'views-desc') return (b.viewCount ?? 0) - (a.viewCount ?? 0);
+ return new Date(b.createdAt || 0) - new Date(a.createdAt || 0);
+ });
+ }, [items, query, typeFilter, categoryFilter, sort]);
+
+ const stats = useMemo(() => {
+ const ytItems = items.filter(p => p.contentType === 'youtube');
+ const rdItems = items.filter(p => (p.contentType || 'reddit') === 'reddit');
+ return {
+ total: items.length,
+ categories: categories.length,
+ youtube: ytItems.length,
+ reddit: rdItems.length,
+ };
+ }, [items, categories]);
+
+ const allSelected = filtered.length > 0 && filtered.every(p => selected.has(p.id));
+ const someSelected = selected.size > 0;
+
+ function toggleAll() {
+ if (allSelected) {
+ setSelected(prev => { const n = new Set(prev); filtered.forEach(p => n.delete(p.id)); return n; });
+ } else {
+ setSelected(prev => { const n = new Set(prev); filtered.forEach(p => n.add(p.id)); return n; });
+ }
+ }
+
+ function toggleOne(id) {
+ setSelected(prev => { const n = new Set(prev); n.has(id) ? n.delete(id) : n.add(id); return n; });
+ }
+
+ async function handleAdd() {
+ if (!addUrl.trim()) { showToast('Paste a URL to track', 'error'); return; }
+ const type = detectContentType(addUrl.trim());
+ if (!type) { showToast('Only Reddit and YouTube URLs are supported', 'error'); return; }
+ setAdding(true);
+ try {
+ const accountId = (type === 'reddit' && addAccountId !== 'none') ? addAccountId : null;
+ const item = await api.addTrackedContent(addUrl.trim(), accountId, addLabel.trim(), addCategory.trim());
+ setItems(prev => [item, ...prev]);
+ setAddOpen(false);
+ setAddUrl(''); setDetectedType(null); setAddLabel(''); setAddCategory('');
+ showToast('Content is now tracked');
+ } catch (err) {
+ showToast(err.message, 'error');
+ } finally {
+ setAdding(false);
+ }
+ }
+
+ function openEdit(item) {
+ setEditItem(item);
+ setEditLabel(item.label || '');
+ setEditCategory(item.category || '');
+ }
+
+ async function handleSaveEdit() {
+ if (!editItem) return;
+ setSaving(true);
+ try {
+ const updated = await api.updateTrackedContent(editItem.id, { label: editLabel, category: editCategory });
+ setItems(prev => prev.map(p => p.id === editItem.id ? updated : p));
+ setEditItem(null);
+ showToast('Updated');
+ } catch (err) {
+ showToast(err.message, 'error');
+ } finally {
+ setSaving(false);
+ }
+ }
+
+ async function handleDelete(id) {
+ try {
+ await api.deleteTrackedContent(id);
+ setItems(prev => prev.filter(p => p.id !== id));
+ setSelected(prev => { const n = new Set(prev); n.delete(id); return n; });
+ } catch (err) {
+ showToast(err.message, 'error');
+ }
+ }
+
+ async function handleRefresh(id) {
+ setRefreshingIds(prev => new Set(prev).add(id));
+ try {
+ const updated = await api.refreshTrackedContent(id);
+ setItems(prev => prev.map(p => p.id === id ? updated : p));
+ } catch (err) {
+ showToast(err.message, 'error');
+ } finally {
+ setRefreshingIds(prev => { const n = new Set(prev); n.delete(id); return n; });
+ }
+ }
+
+ async function handleBulkCategory() {
+ if (!bulkCategory.trim() || selected.size === 0) return;
+ try {
+ const results = await Promise.allSettled(
+ [...selected].map(id => api.updateTrackedContent(id, { category: bulkCategory.trim() }))
+ );
+ const succeeded = results
+ .map((r, i) => r.status === 'fulfilled' ? { id: [...selected][i], data: r.value } : null)
+ .filter(Boolean);
+ setItems(prev => prev.map(p => {
+ const hit = succeeded.find(s => s.id === p.id);
+ return hit ? hit.data : p;
+ }));
+ setSelected(new Set());
+ setBulkCategory('');
+ showToast(`Category assigned to ${succeeded.length} item${succeeded.length !== 1 ? 's' : ''}`);
+ } catch (err) {
+ showToast(err.message, 'error');
+ }
+ }
+
+ if (loading) {
+ return (
+ <div className="space-y-6">
+ <Skeleton className="h-8 w-48" />
+ <div className="grid grid-cols-4 gap-4">
+ {[0, 1, 2, 3].map(i => <Skeleton key={i} className="h-28" />)}
+ </div>
+ <Skeleton className="h-64" />
+ </div>
+ );
+ }
+
+ return (
+ <div className="space-y-6">
+ {/* Header */}
+ <div className="flex items-start justify-between gap-4">
+ <div>
+ <h1 className="text-2xl font-bold tracking-tight">Tracked Content</h1>
+ <p className="text-sm text-muted-foreground mt-0.5">
+ Monitor Reddit posts and YouTube videos - track scores, likes, and comments over time
+ </p>
+ </div>
+ <Button size="sm" className="gap-2 shrink-0" onClick={() => setAddOpen(true)}>
+ <Plus className="h-3.5 w-3.5" />
+ Track Content
+ </Button>
+ </div>
+
+ {/* Stat cards */}
+ <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-4">
+ <StatCard icon={<BookmarkCheck />} label="Tracked Content" value={stats.total} subtitle="across all categories" gradient="orange" />
+ <StatCard icon={<Tag />} label="Categories" value={stats.categories} subtitle={stats.categories === 0 ? 'none assigned yet' : `${stats.categories} group${stats.categories !== 1 ? 's' : ''}`} gradient="blue" />
+ <StatCard icon={<Youtube />} label="YouTube" value={stats.youtube} subtitle={stats.youtube === 0 ? 'no videos tracked' : `video${stats.youtube !== 1 ? 's' : ''} tracked`} gradient="red" />
+ <StatCard icon={<Flame />} label="Reddit" value={stats.reddit} subtitle={stats.reddit === 0 ? 'no posts tracked' : `post${stats.reddit !== 1 ? 's' : ''} tracked`} gradient="purple" />
+ </div>
+
+ {/* Bulk category bar */}
+ {someSelected && (
+ <MainCard>
+ <div className="flex items-center gap-3">
+ <span className="text-sm font-medium text-muted-foreground">{selected.size} selected</span>
+ <div className="flex-1 flex items-center gap-2">
+ <Tag className="h-4 w-4 text-muted-foreground shrink-0" />
+ <Input
+ placeholder="Category name"
+ value={bulkCategory}
+ onChange={e => setBulkCategory(e.target.value)}
+ className="h-8 max-w-xs"
+ onKeyDown={e => e.key === 'Enter' && handleBulkCategory()}
+ />
+ <Button size="sm" onClick={handleBulkCategory} disabled={!bulkCategory.trim()}>
+ Assign
+ </Button>
+ </div>
+ <Button size="sm" variant="ghost" onClick={() => setSelected(new Set())}>
+ Clear
+ </Button>
+ </div>
+ </MainCard>
+ )}
+
+ {/* Filters */}
+ <MainCard>
+ <div className="flex flex-col sm:flex-row gap-3">
+ <Input
+ placeholder="Search by title, channel, subreddit..."
+ value={query}
+ onChange={e => setQuery(e.target.value)}
+ className="flex-1"
+ />
+ <Select
+ value={typeFilter}
+ onValueChange={setTypeFilter}
+ items={[
+ { value: 'all', label: 'All types' },
+ { value: 'reddit', label: 'Reddit posts' },
+ { value: 'youtube', label: 'YouTube videos' },
+ ]}
+ >
+ <SelectTrigger className="w-full sm:w-40">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="all">All types</SelectItem>
+ <SelectItem value="reddit">Reddit posts</SelectItem>
+ <SelectItem value="youtube">YouTube videos</SelectItem>
+ </SelectContent>
+ </Select>
+ {categories.length > 0 && (
+ <Select
+ value={categoryFilter}
+ onValueChange={setCategoryFilter}
+ items={[{ value: 'all', label: 'All categories' }, ...categories.map(c => ({ value: c, label: c }))]}
+ >
+ <SelectTrigger className="w-full sm:w-44">
+ <SelectValue placeholder="All categories" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="all">All categories</SelectItem>
+ {categories.map(c => <SelectItem key={c} value={c}>{c}</SelectItem>)}
+ </SelectContent>
+ </Select>
+ )}
+ <Select
+ value={sort}
+ onValueChange={setSort}
+ items={[
+ { value: 'date-desc', label: 'Newest first' },
+ { value: 'engagement-desc', label: 'Likes / Score' },
+ { value: 'comments-desc', label: 'Most comments' },
+ { value: 'views-desc', label: 'Most views' },
+ ]}
+ >
+ <SelectTrigger className="w-full sm:w-48">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="date-desc">Newest first</SelectItem>
+ <SelectItem value="engagement-desc">Likes / Score</SelectItem>
+ <SelectItem value="comments-desc">Most comments</SelectItem>
+ <SelectItem value="views-desc">Most views (YouTube)</SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+ </MainCard>
+
+ {/* Table */}
+ <MainCard content={false}>
+ {items.length === 0 ? (
+ <div className="flex flex-col items-center text-center py-16 gap-4">
+ <div className="h-14 w-14 rounded-full bg-primary/10 flex items-center justify-center">
+ <Bookmark className="h-7 w-7 text-primary" />
+ </div>
+ <div>
+ <p className="text-sm font-semibold">No content tracked yet</p>
+ <p className="text-xs text-muted-foreground mt-1">
+ Paste a Reddit post URL or a YouTube video URL to start tracking
+ </p>
+ </div>
+ <Button size="sm" onClick={() => setAddOpen(true)}>
+ <Plus className="h-3.5 w-3.5 mr-1.5" />
+ Track your first item
+ </Button>
+ </div>
+ ) : (
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead className="w-10">
+ <Checkbox checked={allSelected} onCheckedChange={toggleAll} aria-label="Select all" />
+ </TableHead>
+ <TableHead>Title</TableHead>
+ <TableHead className="w-28">Category</TableHead>
+ <TableHead className="text-right w-24">Views</TableHead>
+ <TableHead className="text-right w-24">Likes / Score</TableHead>
+ <TableHead className="text-right w-24">Comments</TableHead>
+ <TableHead className="text-right w-20">Ratio</TableHead>
+ <TableHead className="text-right w-28">Fetched</TableHead>
+ <TableHead className="w-24" />
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {filtered.length === 0 ? (
+ <TableRow>
+ <TableCell colSpan={9} className="text-center text-muted-foreground py-10">
+ No items match the current filters
+ </TableCell>
+ </TableRow>
+ ) : (
+ filtered.map(item => {
+ const isYT = item.contentType === 'youtube';
+ const acc = !isYT ? accounts.find(a => a.id === item.accountId) : null;
+ const isRefreshing = refreshingIds.has(item.id);
+ return (
+ <TableRow key={item.id} className={selected.has(item.id) ? 'bg-muted/30' : ''}>
+ <TableCell>
+ <Checkbox
+ checked={selected.has(item.id)}
+ onCheckedChange={() => toggleOne(item.id)}
+ aria-label={`Select ${item.title}`}
+ />
+ </TableCell>
+ <TableCell>
+ <div className="max-w-sm flex items-start gap-2.5">
+ {isYT && item.thumbnail ? (
+ <img src={item.thumbnail} alt="" className="h-10 w-16 rounded object-cover flex-shrink-0 mt-0.5" />
+ ) : null}
+ <div className="min-w-0">
+ <p className="text-sm font-medium leading-snug line-clamp-2">
+ {item.title || item.label || item.url}
+ </p>
+ <div className="flex items-center gap-2 mt-1 flex-wrap">
+ <ContentTypeBadge type={item.contentType || 'reddit'} />
+ {isYT ? (
+ item.channelTitle && (
+ <span className="text-xs text-muted-foreground">{item.channelTitle}</span>
+ )
+ ) : (
+ item.subredditPrefixed && (
+ <span className="text-xs text-muted-foreground">{item.subredditPrefixed}</span>
+ )
+ )}
+ {item.label && (
+ <span className="text-xs text-muted-foreground italic">{item.label}</span>
+ )}
+ {isYT && item.isShort && (
+ <Badge variant="outline" className="text-[10px] px-1.5 py-0">Short</Badge>
+ )}
+ </div>
+ </div>
+ </div>
+ </TableCell>
+ <TableCell>
+ {item.category ? (
+ <Badge variant="outline" className="text-xs font-medium">{item.category}</Badge>
+ ) : (
+ <span className="text-xs text-muted-foreground">-</span>
+ )}
+ </TableCell>
+ <TableCell className="text-right text-sm tabular-nums text-muted-foreground">
+ {isYT && item.viewCount !== undefined ? fmtNum(item.viewCount) : '-'}
+ </TableCell>
+ <TableCell className="text-right text-sm font-semibold tabular-nums">
+ {isYT
+ ? (item.likeCount !== undefined ? (
+ <span className="text-red-500">{fmtNum(item.likeCount)}</span>
+ ) : '-')
+ : (item.score !== undefined ? (
+ <span className="text-orange-500">{fmtNum(item.score)}</span>
+ ) : '-')
+ }
+ </TableCell>
+ <TableCell className="text-right text-sm tabular-nums">
+ {isYT
+ ? (item.commentCount !== undefined ? fmtNum(item.commentCount) : '-')
+ : (item.numComments !== undefined ? fmtNum(item.numComments) : '-')
+ }
+ </TableCell>
+ <TableCell className="text-right text-sm tabular-nums text-muted-foreground">
+ {!isYT && item.upvoteRatio !== undefined && (item.score ?? 0) >= 10
+ ? `${Math.round(item.upvoteRatio * 100)}%`
+ : '-'}
+ </TableCell>
+ <TableCell className="text-right text-xs text-muted-foreground">
+ {item.lastFetchedAt ? fmtDate(item.lastFetchedAt) : '-'}
+ </TableCell>
+ <TableCell>
+ <div className="flex items-center gap-0.5 justify-end">
+ <Button
+ variant="ghost" size="icon" className="size-7"
+ onClick={() => handleRefresh(item.id)}
+ disabled={isRefreshing}
+ title="Refresh live data"
+ >
+ <RefreshCw className={`h-3.5 w-3.5 ${isRefreshing ? 'animate-spin' : ''}`} />
+ </Button>
+ <Button
+ variant="ghost" size="icon" className="size-7"
+ onClick={() => openEdit(item)}
+ title="Edit label or category"
+ >
+ <Pencil className="h-3.5 w-3.5" />
+ </Button>
+ <a href={item.permalink || item.url} target="_blank" rel="noopener noreferrer">
+ <Button variant="ghost" size="icon" className="size-7" title="Open original">
+ <ExternalLink className="h-3.5 w-3.5" />
+ </Button>
+ </a>
+ <Button
+ variant="ghost" size="icon" className="size-7 text-destructive hover:text-destructive"
+ onClick={() => handleDelete(item.id)}
+ title="Stop tracking"
+ >
+ <Trash2 className="h-3.5 w-3.5" />
+ </Button>
+ </div>
+ </TableCell>
+ </TableRow>
+ );
+ })
+ )}
+ </TableBody>
+ </Table>
+ )}
+ </MainCard>
+
+ {/* Add content dialog */}
+ <Dialog open={addOpen} onOpenChange={v => { setAddOpen(v); if (!v) { setAddUrl(''); setDetectedType(null); setAddLabel(''); setAddCategory(''); } }}>
+ <DialogContent className="max-w-md">
+ <DialogHeader>
+ <DialogTitle>Track Content</DialogTitle>
+ </DialogHeader>
+ <div className="space-y-4 py-2">
+ <div className="space-y-1.5">
+ <label className="text-sm font-medium">URL</label>
+ <div className="relative">
+ <Input
+ placeholder="Reddit post or YouTube video URL"
+ value={addUrl}
+ onChange={e => handleUrlChange(e.target.value)}
+ autoFocus
+ />
+ </div>
+ {detectedType ? (
+ <div className="flex items-center gap-1.5">
+ <ContentTypeBadge type={detectedType} />
+ <span className="text-xs text-muted-foreground">
+ {detectedType === 'youtube' ? 'YouTube video detected' : 'Reddit post detected'}
+ </span>
+ </div>
+ ) : addUrl.trim() ? (
+ <p className="text-xs text-destructive">Only Reddit and YouTube URLs are supported</p>
+ ) : (
+ <p className="text-xs text-muted-foreground">
+ Paste a Reddit post URL or a YouTube video / Shorts URL
+ </p>
+ )}
+ </div>
+
+ {detectedType === 'reddit' && (
+ <div className="space-y-1.5">
+ <label className="text-sm font-medium">Account cookie <span className="text-muted-foreground font-normal">(optional)</span></label>
+ <Select
+ value={addAccountId}
+ onValueChange={setAddAccountId}
+ items={[
+ { value: 'none', label: 'No cookie (public posts only)' },
+ ...redditAccounts.map(a => ({ value: a.id, label: `u/${a.username}` })),
+ ]}
+ >
+ <SelectTrigger>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="none">No cookie (public posts only)</SelectItem>
+ {redditAccounts.map(a => (
+ <SelectItem key={a.id} value={a.id} textValue={`u/${a.username}`}>
+ u/{a.username}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <p className="text-xs text-muted-foreground">
+ A session cookie improves access from datacenter IPs
+ </p>
+ </div>
+ )}
+
+ <div className="grid grid-cols-2 gap-3">
+ <div className="space-y-1.5">
+ <label className="text-sm font-medium">Label <span className="text-muted-foreground font-normal">(optional)</span></label>
+ <Input placeholder="My content" value={addLabel} onChange={e => setAddLabel(e.target.value)} />
+ </div>
+ <div className="space-y-1.5">
+ <label className="text-sm font-medium">Category <span className="text-muted-foreground font-normal">(optional)</span></label>
+ <Input placeholder="Campaign A" value={addCategory} onChange={e => setAddCategory(e.target.value)} />
+ {categories.length > 0 && (
+ <div className="flex flex-wrap gap-1 pt-0.5">
+ {categories.map(c => (
+ <button
+ key={c}
+ onClick={() => setAddCategory(c)}
+ className="text-[10px] px-2 py-0.5 rounded-full border border-border hover:bg-muted transition-colors"
+ >
+ {c}
+ </button>
+ ))}
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+ <DialogFooter>
+ <Button variant="outline" onClick={() => setAddOpen(false)} disabled={adding}>Cancel</Button>
+ <Button onClick={handleAdd} disabled={adding || !addUrl.trim() || !detectedType}>
+ {adding ? 'Fetching...' : 'Track'}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+
+ {/* Edit dialog */}
+ <Dialog open={!!editItem} onOpenChange={v => !v && setEditItem(null)}>
+ <DialogContent className="max-w-sm">
+ <DialogHeader>
+ <DialogTitle>Edit tracked item</DialogTitle>
+ </DialogHeader>
+ <div className="space-y-4 py-2">
+ <div className="space-y-1.5">
+ <label className="text-sm font-medium">Label</label>
+ <Input value={editLabel} onChange={e => setEditLabel(e.target.value)} placeholder="My content" />
+ </div>
+ <div className="space-y-1.5">
+ <label className="text-sm font-medium">Category</label>
+ <Input value={editCategory} onChange={e => setEditCategory(e.target.value)} placeholder="Campaign A" />
+ {categories.length > 0 && (
+ <div className="flex flex-wrap gap-1.5 pt-1">
+ {categories.map(c => (
+ <button
+ key={c}
+ onClick={() => setEditCategory(c)}
+ className="text-xs px-2 py-0.5 rounded-full border border-border hover:bg-muted transition-colors"
+ >
+ {c}
+ </button>
+ ))}
+ </div>
+ )}
+ </div>
+ </div>
+ <DialogFooter>
+ <Button variant="outline" onClick={() => setEditItem(null)} disabled={saving}>Cancel</Button>
+ <Button onClick={handleSaveEdit} disabled={saving}>{saving ? 'Saving...' : 'Save'}</Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ </div>
+ );
+}
diff --git a/frontend/src/layout/Sidebar.jsx b/frontend/src/layout/Sidebar.jsx
index 5d524b2..3ea036b 100644
--- a/frontend/src/layout/Sidebar.jsx
+++ b/frontend/src/layout/Sidebar.jsx
@@ -8,7 +8,7 @@ import {
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import {
LayoutDashboard, PlaySquare, Scissors, Camera,
- Upload, Users, Settings, Flame, BookmarkCheck,
+ Upload, Users, Settings, Flame, Bookmark,
} from 'lucide-react';
import { useAppContext } from '../context/AppContext';
@@ -22,7 +22,7 @@ const NAV_GROUPS = [
{ path: '/shorts', label: 'Shorts', icon: Scissors },
{ path: '/reels', label: 'IG Content', icon: Camera },
{ path: '/reddit-posts', label: 'Reddit Posts', icon: Flame },
- { path: '/reddit-tracked', label: 'Tracked Posts', icon: BookmarkCheck },
+ { path: '/tracked-content', label: 'Tracked Content', icon: Bookmark },
],
},
{
diff --git a/frontend/src/services/api.js b/frontend/src/services/api.js
index 5bbe377..2020c52 100644
--- a/frontend/src/services/api.js
+++ b/frontend/src/services/api.js
@@ -65,12 +65,12 @@ export const api = {
getRedditAnalytics: (id) => request(`/accounts/${id}/reddit-analytics`),
getRedditPosts: (id) => request(`/accounts/${id}/reddit-posts`),
- // Tracked Reddit posts
- getTrackedPosts: () => request('/reddit/tracked-posts'),
- addTrackedPost: (url, accountId, label, category) => request('/reddit/tracked-posts', { method: 'POST', body: JSON.stringify({ url, accountId, label, category }) }),
- updateTrackedPost: (id, updates) => request(`/reddit/tracked-posts/${id}`, { method: 'PUT', body: JSON.stringify(updates) }),
- deleteTrackedPost: (id) => request(`/reddit/tracked-posts/${id}`, { method: 'DELETE' }),
- refreshTrackedPost: (id) => request(`/reddit/tracked-posts/${id}/refresh`, { method: 'POST' }),
+ // Tracked Content (Reddit posts and YouTube videos)
+ getTrackedContent: () => request('/tracked-content'),
+ addTrackedContent: (url, accountId, label, category) => request('/tracked-content', { method: 'POST', body: JSON.stringify({ url, accountId, label, category }) }),
+ updateTrackedContent: (id, updates) => request(`/tracked-content/${id}`, { method: 'PUT', body: JSON.stringify(updates) }),
+ deleteTrackedContent: (id) => request(`/tracked-content/${id}`, { method: 'DELETE' }),
+ refreshTrackedContent: (id) => request(`/tracked-content/${id}/refresh`, { method: 'POST' }),
// GitHub settings
getGithubSettings: () => request('/settings/github'),