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(frontend): rebuild the interface on the Twiligent design system
spacesdrive50451abd63f7
diff --git a/frontend/index.html b/frontend/index.htmlindex 3f1656e..f4b9459 100644--- a/frontend/index.html+++ b/frontend/index.html@@ -3,12 +3,18 @@<head><meta charset="UTF-8" />- <link rel="icon" type="image/png" href="/logo.png" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>Twiligent</title>- <link rel="preconnect" href="https://fonts.googleapis.com" />- <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />- <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet" />+ <meta name="description" content="Analytics and publishing for your YouTube, Instagram and Reddit accounts." />+ <meta name="theme-color" content="#F7F3EF" media="(prefers-color-scheme: light)" />+ <meta name="theme-color" content="#140E10" media="(prefers-color-scheme: dark)" />+ <link rel="icon" type="image/svg+xml" href="/App%20icons/twiligent-favicon.svg" />+ <link rel="icon" type="image/png" sizes="32x32" href="/App%20icons/twiligent-favicon-32.png" />+ <link rel="apple-touch-icon" sizes="180x180" href="/App%20icons/twiligent-app-icon-dusk-180.png" />+ <link rel="preload" href="/fonts/manrope-latin-400-normal.woff2" as="font" type="font/woff2" crossorigin />+ <link rel="preload" href="/fonts/manrope-latin-500-normal.woff2" as="font" type="font/woff2" crossorigin />+ <link rel="preload" href="/fonts/manrope-latin-600-normal.woff2" as="font" type="font/woff2" crossorigin />+ <link rel="preload" href="/fonts/sora-latin-600-normal.woff2" as="font" type="font/woff2" crossorigin /></head><body>diff --git a/frontend/package-lock.json b/frontend/package-lock.jsonindex 8361fa3..ea8d0e8 100644--- a/frontend/package-lock.json+++ b/frontend/package-lock.json@@ -9,7 +9,6 @@"version": "0.0.0","dependencies": {"@base-ui/react": "^1.5.0",- "@fontsource-variable/geist": "^5.2.9","@supabase/supabase-js": "^2.110.0","class-variance-authority": "^0.7.1","clsx": "^2.1.1",@@ -1353,15 +1352,6 @@"integrity": "sha512-RiB/yIh78pcIxl6lLMG0CgBXAZ2Y0eVHqMPYugu+9U0AeT6YBeiJpf7lbdJNIugFP5SIjwNRgo4DhR1Qxi26Gg==","license": "MIT"},- "node_modules/@fontsource-variable/geist": {- "version": "5.2.9",- "resolved": "https://registry.npmjs.org/@fontsource-variable/geist/-/geist-5.2.9.tgz",- "integrity": "sha512-TP+QSBG3wxKGPE33CbMy/L0Nu3qvJ6Fy81Yc4LnQ95xH+i+cfEp8fyU8/kfV14YwszxIFPhnoMTbjL71waVpyQ==",- "license": "OFL-1.1",- "funding": {- "url": "https://github.com/sponsors/ayuhito"- }- },"node_modules/@hono/node-server": {"version": "1.19.14","resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-1.19.14.tgz",diff --git a/frontend/package.json b/frontend/package.jsonindex debffa9..337c0f2 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -7,11 +7,11 @@"dev": "vite","build": "vite build","lint": "eslint .",- "preview": "vite preview"+ "preview": "vite preview",+ "test": "node --test \"src/**/*.test.js\""},"dependencies": {"@base-ui/react": "^1.5.0",- "@fontsource-variable/geist": "^5.2.9","@supabase/supabase-js": "^2.110.0","class-variance-authority": "^0.7.1","clsx": "^2.1.1",diff --git a/frontend/src/components/ChartPanel.jsx b/frontend/src/components/ChartPanel.jsxnew file mode 100644index 0000000..e3bee1c--- /dev/null+++ b/frontend/src/components/ChartPanel.jsx@@ -0,0 +1,18 @@+import React from 'react';+import { ResponsiveContainer } from 'recharts';+import SurfaceBox from './SurfaceBox';++// Titled chart container. Pass `empty` to show a quiet message instead of an empty plot.+export default function ChartPanel({ title, subheader, height = 280, empty = false, emptyMessage = 'Not enough data yet', className, children }) {+ return (+ <SurfaceBox title={title} subheader={subheader} className={className} contentClassName="px-3 pt-4 pb-3">+ {empty ? (+ <p className="flex items-center justify-center text-small text-ink-faint" style={{ height }}>{emptyMessage}</p>+ ) : (+ <ResponsiveContainer width="100%" height={height} debounce={200}>+ {children}+ </ResponsiveContainer>+ )}+ </SurfaceBox>+ );+}diff --git a/frontend/src/components/ChoiceCard.jsx b/frontend/src/components/ChoiceCard.jsxnew file mode 100644index 0000000..40e7e96--- /dev/null+++ b/frontend/src/components/ChoiceCard.jsx@@ -0,0 +1,41 @@+import React from 'react';+import { Check } from 'lucide-react';+import { cn } from '@/lib/utils';++// Large selectable card for creation flows. Behaves as a radio when `selected` is defined, else as a button.+export default function ChoiceCard({ icon, title, description, selected, onSelect, disabled, className }) {+ const isRadio = selected !== undefined;+ return (+ <button+ type="button"+ role={isRadio ? 'radio' : undefined}+ aria-checked={isRadio ? selected : undefined}+ onClick={onSelect}+ disabled={disabled}+ className={cn(+ 'group relative flex w-full flex-col items-start gap-3 rounded-panel border bg-surface-wash p-5 text-left transition-colors duration-(--duration-fast)',+ 'focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring disabled:pointer-events-none disabled:opacity-50',+ selected ? 'border-brand bg-brand-soft/50' : 'border-transparent hover:bg-surface-selected',+ className,+ )}+ >+ <span+ className={cn(+ 'flex size-10 items-center justify-center rounded-control [&_svg]:size-5 [&_svg]:stroke-[1.75]',+ selected ? 'bg-brand text-on-brand' : 'bg-surface-sunken text-ink-muted group-hover:text-ink',+ )}+ >+ {icon}+ </span>+ <span className="flex flex-col gap-0.5">+ <span className="text-base font-medium text-ink">{title}</span>+ {description && <span className="text-sm text-ink-muted">{description}</span>}+ </span>+ {selected && (+ <span className="absolute top-3 right-3 flex size-5 items-center justify-center rounded-full bg-brand text-on-brand">+ <Check className="size-3" strokeWidth={2.5} />+ </span>+ )}+ </button>+ );+}diff --git a/frontend/src/components/CommandPalette.jsx b/frontend/src/components/CommandPalette.jsxnew file mode 100644index 0000000..7e1805a--- /dev/null+++ b/frontend/src/components/CommandPalette.jsx@@ -0,0 +1,96 @@+import React, { useMemo, useState } from 'react';+import { useNavigate } from 'react-router-dom';+import { useTheme } from 'next-themes';+import {+ LayoutDashboard, PlaySquare, Scissors, Clapperboard, MessagesSquare, Bookmark, Send,+ Users, Settings, RefreshCw, Sun, Moon, Monitor, LogOut, Tag, Plus,+} from 'lucide-react';+import {+ Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, CommandShortcut,+} from '@/components/ui/command';+import { Dialog, DialogContent, DialogDescription, DialogTitle } from '@/components/ui/dialog';+import { AccountAvatar } from '@/components/platform';+import { filterCommands, groupCommands } from '@/lib/commandSearch';+import { accountName, accountPath, PLATFORM_META, platformOf } from '@/lib/accounts';+import { NAV_GROUPS } from '@/layout/navigation';++const PAGE_ICONS = {+ '/': LayoutDashboard, '/videos': PlaySquare, '/shorts': Scissors, '/reels': Clapperboard,+ '/reddit-posts': MessagesSquare, '/tracked-content': Bookmark, '/upload': Send,+ '/accounts': Users, '/settings': Settings,+};++export default function CommandPalette({ open, onOpenChange, accounts, categories, onRefreshAll, onSignOut }) {+ const navigate = useNavigate();+ const { setTheme } = useTheme();+ const [query, setQuery] = useState('');++ const handleOpenChange = next => {+ if (!next) setQuery('');+ onOpenChange(next);+ };++ const commands = useMemo(() => [+ ...NAV_GROUPS.flatMap(group => group.items.map(item => ({+ id: `page:${item.path}`, group: 'Pages', label: item.label, keywords: [group.label],+ icon: PAGE_ICONS[item.path], run: () => navigate(item.path),+ }))),+ ...accounts.map(account => ({+ id: `account:${account.id}`, group: 'Accounts', label: accountName(account),+ keywords: [PLATFORM_META[platformOf(account)].label, account.username, account.customUrl].filter(Boolean),+ avatar: account, run: () => navigate(accountPath(account)),+ })),+ ...categories.map(category => ({+ id: `category:${category}`, group: 'Categories', label: category, keywords: ['tracked', 'category'],+ icon: Tag, run: () => navigate(`/tracked-content/category/${encodeURIComponent(category)}`),+ })),+ { id: 'action:add-account', group: 'Actions', label: 'Add an account', keywords: ['connect', 'youtube', 'instagram', 'reddit'], icon: Plus, run: () => navigate('/accounts?add=1') },+ { id: 'action:refresh', group: 'Actions', label: 'Refresh all accounts', keywords: ['sync', 'update'], icon: RefreshCw, run: onRefreshAll },+ { id: 'action:theme-light', group: 'Theme', label: 'Use light theme', keywords: ['appearance', 'paper'], icon: Sun, run: () => setTheme('light') },+ { id: 'action:theme-dark', group: 'Theme', label: 'Use dark theme', keywords: ['appearance', 'dusk'], icon: Moon, run: () => setTheme('dark') },+ { id: 'action:theme-system', group: 'Theme', label: 'Match system theme', keywords: ['appearance', 'auto'], icon: Monitor, run: () => setTheme('system') },+ { id: 'action:sign-out', group: 'Account', label: 'Sign out', keywords: ['log out', 'logout'], icon: LogOut, run: onSignOut },+ ], [accounts, categories, navigate, onRefreshAll, onSignOut, setTheme]);++ const grouped = useMemo(() => groupCommands(filterCommands(commands, query)), [commands, query]);++ const runCommand = command => {+ handleOpenChange(false);+ command.run?.();+ };++ return (+ <Dialog open={open} onOpenChange={handleOpenChange}>+ <DialogContent showCloseButton={false} className="top-[18%] translate-y-0 gap-0 overflow-hidden p-0 sm:max-w-xl">+ <DialogTitle className="sr-only">Command palette</DialogTitle>+ <DialogDescription className="sr-only">Search pages, accounts and actions</DialogDescription>+ <Command shouldFilter={false} loop>+ <CommandInput value={query} onValueChange={setQuery} placeholder="Search pages, accounts and actions" />+ <CommandList>+ <CommandEmpty>Nothing matches "{query}"</CommandEmpty>+ {grouped.map(({ group, items }) => (+ <CommandGroup key={group} heading={group}>+ {items.map(command => {+ const Icon = command.icon;+ return (+ <CommandItem key={command.id} value={command.id} onSelect={() => runCommand(command)}>+ {command.avatar ? <AccountAvatar account={command.avatar} size="sm" /> : Icon && <Icon />}+ <span className="truncate">{command.label}</span>+ {command.group === 'Accounts' && (+ <CommandShortcut>{PLATFORM_META[platformOf(command.avatar)].label}</CommandShortcut>+ )}+ </CommandItem>+ );+ })}+ </CommandGroup>+ ))}+ </CommandList>+ <div className="flex items-center justify-between gap-3 border-t border-line px-4 py-2.5 text-caption text-ink-faint">+ <span>Use arrow keys to move, Enter to open</span>+ <kbd className="font-mono">Esc</kbd>+ </div>+ </Command>+ </DialogContent>+ </Dialog>+ );+}diff --git a/frontend/src/components/ConfirmDialog.jsx b/frontend/src/components/ConfirmDialog.jsxnew file mode 100644index 0000000..119b87f--- /dev/null+++ b/frontend/src/components/ConfirmDialog.jsx@@ -0,0 +1,48 @@+import React from 'react';+import { Trash2 } from 'lucide-react';+import {+ AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription,+ AlertDialogFooter, AlertDialogHeader, AlertDialogMedia, AlertDialogTitle,+} from '@/components/ui/alert-dialog';+import { Spinner } from '@/components/ui/spinner';+import HoldToConfirmButton from './HoldToConfirmButton';++// Confirmation for consequential actions. Destructive ones use `hold` so they cannot fire on a stray click.+export default function ConfirmDialog({+ open,+ onOpenChange,+ title,+ description,+ confirmLabel = 'Confirm',+ cancelLabel = 'Cancel',+ onConfirm,+ busy = false,+ hold = false,+ icon = <Trash2 />,+}) {+ return (+ <AlertDialog open={open} onOpenChange={next => { if (!busy) onOpenChange(next); }}>+ <AlertDialogContent>+ <AlertDialogHeader>+ {hold && <AlertDialogMedia>{icon}</AlertDialogMedia>}+ <AlertDialogTitle>{title}</AlertDialogTitle>+ {description && <AlertDialogDescription>{description}</AlertDialogDescription>}+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel disabled={busy}>{cancelLabel}</AlertDialogCancel>+ {hold ? (+ <HoldToConfirmButton onConfirm={onConfirm} disabled={busy}>+ {busy ? <Spinner className="size-4" /> : null}+ {busy ? 'Working' : `Hold to ${confirmLabel.toLowerCase()}`}+ </HoldToConfirmButton>+ ) : (+ <AlertDialogAction onClick={onConfirm} disabled={busy}>+ {busy && <Spinner className="size-4" />}+ {confirmLabel}+ </AlertDialogAction>+ )}+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ );+}diff --git a/frontend/src/components/DetailPanel.jsx b/frontend/src/components/DetailPanel.jsxnew file mode 100644index 0000000..14c1b39--- /dev/null+++ b/frontend/src/components/DetailPanel.jsx@@ -0,0 +1,36 @@+import React from 'react';+import { cn } from '@/lib/utils';++// Side panel for a working surface: sticky on wide screens, stacked below the main area on narrow ones.+export default function DetailPanel({ title, description, children, footer, className }) {+ return (+ <aside+ className={cn(+ 'flex flex-col rounded-card border border-line bg-surface-raised lg:sticky lg:top-[calc(var(--topbar-h)+1.5rem)] lg:max-h-[calc(100dvh-var(--topbar-h)-3rem)]',+ className,+ )}+ >+ {title && (+ <div className="border-b border-divider px-5 py-4">+ <h2 className="font-heading text-section font-semibold text-ink">{title}</h2>+ {description && <p className="mt-0.5 text-small text-ink-muted">{description}</p>}+ </div>+ )}+ <div className="flex min-h-0 flex-1 flex-col gap-5 overflow-y-auto px-5 py-5">{children}</div>+ {footer && <div className="border-t border-divider px-5 py-4">{footer}</div>}+ </aside>+ );+}++// Label, hint and control in one settings-style row.+export function FieldRow({ label, hint, htmlFor, children, className }) {+ return (+ <div className={cn('flex flex-col gap-2', className)}>+ <div className="flex flex-col gap-0.5">+ <label htmlFor={htmlFor} className="text-sm font-medium text-ink">{label}</label>+ {hint && <p className="text-caption text-ink-faint">{hint}</p>}+ </div>+ {children}+ </div>+ );+}diff --git a/frontend/src/components/FilterChips.jsx b/frontend/src/components/FilterChips.jsxnew file mode 100644index 0000000..e6399f5--- /dev/null+++ b/frontend/src/components/FilterChips.jsx@@ -0,0 +1,36 @@+import React from 'react';+import { cn } from '@/lib/utils';++// Single-select chip group. Options are { value, label, icon?, count? }.+export default function FilterChips({ options, value, onChange, className, label = 'Filter' }) {+ return (+ <div role="radiogroup" aria-label={label} className={cn('flex flex-wrap items-center gap-1.5', className)}>+ {options.map(option => {+ const active = option.value === value;+ const Icon = option.icon;+ return (+ <button+ key={option.value}+ type="button"+ role="radio"+ aria-checked={active}+ onClick={() => onChange(option.value)}+ className={cn(+ 'inline-flex h-(--control-h) items-center gap-1.5 rounded-field border px-3 text-sm font-medium transition-colors duration-(--duration-fast)',+ 'focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring',+ active+ ? 'border-brand/40 bg-brand-soft text-brand-text'+ : 'border-line-control bg-surface text-ink-muted hover:bg-surface-hover hover:text-ink',+ )}+ >+ {Icon && <Icon className="size-3.5 stroke-[1.75]" />}+ {option.label}+ {option.count !== undefined && (+ <span className={cn('tabular-nums', active ? 'text-brand-text/80' : 'text-ink-faint')}>{option.count}</span>+ )}+ </button>+ );+ })}+ </div>+ );+}diff --git a/frontend/src/components/HoldToConfirmButton.jsx b/frontend/src/components/HoldToConfirmButton.jsxnew file mode 100644index 0000000..a195fb2--- /dev/null+++ b/frontend/src/components/HoldToConfirmButton.jsx@@ -0,0 +1,74 @@+import React, { useEffect, useRef, useState } from 'react';+import { createHoldController, DEFAULT_HOLD_MS } from '@/lib/holdProgress';+import { cn } from '@/lib/utils';++const HOLD_KEYS = new Set([' ', 'Enter']);++// Destructive confirm that must be held, by pointer or by Space/Enter. A plain click never fires it.+export default function HoldToConfirmButton({+ onConfirm,+ children,+ holdingLabel = 'Keep holding',+ duration = DEFAULT_HOLD_MS,+ disabled = false,+ className,+}) {+ const [progress, setProgress] = useState(0);+ const controllerRef = useRef(null);+ const confirmRef = useRef(onConfirm);++ useEffect(() => { confirmRef.current = onConfirm; }, [onConfirm]);++ useEffect(() => {+ const controller = createHoldController({+ duration,+ onProgress: setProgress,+ onComplete: () => confirmRef.current?.(),+ });+ controllerRef.current = controller;+ return () => controller.cancel();+ }, [duration]);++ useEffect(() => {+ if (disabled) controllerRef.current?.reset();+ }, [disabled]);++ const start = () => { if (!disabled) controllerRef.current?.start(); };+ const cancel = () => controllerRef.current?.cancel();+ const holding = progress > 0 && progress < 1;++ return (+ <button+ type="button"+ disabled={disabled}+ onPointerDown={e => { if (e.button === 0) { e.currentTarget.setPointerCapture?.(e.pointerId); start(); } }}+ onPointerUp={cancel}+ onPointerCancel={cancel}+ onPointerLeave={cancel}+ onKeyDown={e => {+ if (!HOLD_KEYS.has(e.key)) return;+ e.preventDefault();+ if (!e.repeat) start();+ }}+ onKeyUp={e => { if (HOLD_KEYS.has(e.key)) cancel(); }}+ onBlur={cancel}+ onContextMenu={e => e.preventDefault()}+ className={cn(+ 'relative inline-flex h-(--control-h) shrink-0 touch-none items-center justify-center gap-2 overflow-hidden rounded-control bg-danger-soft px-4 text-sm font-medium text-danger select-none',+ 'transition-colors duration-(--duration-fast) focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring',+ 'disabled:pointer-events-none disabled:opacity-50',+ className,+ )}+ >+ <span+ aria-hidden="true"+ className="absolute inset-y-0 left-0 bg-brand"+ style={{ width: `${progress * 100}%` }}+ />+ <span className={cn('relative z-10 flex items-center gap-2', progress > 0.5 && 'text-on-brand')}>+ {holding ? holdingLabel : children}+ </span>+ <span role="progressbar" aria-label="Hold progress" aria-valuemin={0} aria-valuemax={100} aria-valuenow={Math.round(progress * 100)} className="sr-only" />+ </button>+ );+}diff --git a/frontend/src/components/ImageLightbox.jsx b/frontend/src/components/ImageLightbox.jsxindex 581a3a1..ff55f40 100644--- a/frontend/src/components/ImageLightbox.jsx+++ b/frontend/src/components/ImageLightbox.jsx@@ -21,9 +21,9 @@ export default function ImageLightbox({title="View image"aria-label={alt ? `View image for ${alt}` : 'View image'}className={cn(- 'group relative shrink-0 overflow-hidden rounded border border-border bg-muted',- 'cursor-zoom-in transition-opacity hover:opacity-80',- 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',+ 'group relative shrink-0 overflow-hidden rounded-sm border border-line bg-surface-sunken',+ 'cursor-zoom-in transition-opacity duration-(--duration-base) hover:opacity-85',+ 'focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring',thumbClassName,className)}@@ -33,12 +33,12 @@ export default function ImageLightbox({<img src={src} alt={alt} loading="lazy" className="h-full w-full object-cover" /></DialogTrigger>- <DialogContent className="sm:max-w-3xl p-2 gap-2">+ <DialogContent className="gap-2 p-2 sm:max-w-3xl"><DialogTitle className="sr-only">{alt || 'Image preview'}</DialogTitle><imgsrc={src}alt={alt}- className="max-h-[75vh] w-full rounded-lg object-contain"+ className="max-h-[75vh] w-full rounded-card object-contain"/></DialogContent></Dialog>diff --git a/frontend/src/components/ListRow.jsx b/frontend/src/components/ListRow.jsxnew file mode 100644index 0000000..9d172cd--- /dev/null+++ b/frontend/src/components/ListRow.jsx@@ -0,0 +1,50 @@+import React from 'react';+import { cn } from '@/lib/utils';++// Rank shown in mono so digits align; the leader carries the brand accent.+export function RankNumber({ rank, className }) {+ return (+ <span+ className={cn(+ 'w-5 shrink-0 text-right font-mono text-caption tabular-nums',+ rank === 1 ? 'font-semibold text-brand-text' : 'text-ink-faint',+ className,+ )}+ >+ {rank}+ </span>+ );+}++// Dense, clickable row: leading media, a title with one line of metadata, and trailing content.+export default function ListRow({+ leading,+ title,+ meta,+ trailing,+ onClick,+ selected = false,+ className,+}) {+ const Element = onClick ? 'button' : 'div';+ return (+ <Element+ type={onClick ? 'button' : undefined}+ onClick={onClick}+ aria-pressed={onClick && selected ? true : undefined}+ className={cn(+ 'flex w-full min-w-0 items-center gap-3 rounded-row px-2.5 py-2 text-left transition-colors duration-(--duration-fast)',+ onClick && 'hover:bg-surface-hover focus-visible:outline-2 focus-visible:outline-offset-[-2px] focus-visible:outline-ring',+ selected && 'bg-surface-selected',+ className,+ )}+ >+ {leading}+ <span className="flex min-w-0 flex-1 flex-col">+ <span className="truncate text-sm font-medium text-ink">{title}</span>+ {meta && <span className="truncate text-caption text-ink-faint">{meta}</span>}+ </span>+ {trailing && <span className="flex shrink-0 items-center gap-2 text-small text-ink-muted tabular-nums">{trailing}</span>}+ </Element>+ );+}diff --git a/frontend/src/components/MainCard.jsx b/frontend/src/components/MainCard.jsxdeleted file mode 100644index de389ed..0000000--- a/frontend/src/components/MainCard.jsx+++ /dev/null@@ -1,42 +0,0 @@-import React from 'react';-import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';-import { Separator } from '@/components/ui/separator';-import { cn } from '@/lib/utils';--export default function MainCard({- children,- title,- subheader,- secondary,- content = true,- contentClassName = '',- className = '',- noPadding = false,- ...props-}) {- return (- <Card className={cn('border border-border shadow-none', className)} {...props}>- {title && (- <>- <CardHeader className="px-5 py-4 flex-row items-start justify-between space-y-0">- <div>- <CardTitle className="text-sm font-semibold">{title}</CardTitle>- {subheader && (- <p className="text-xs text-muted-foreground mt-0.5">{subheader}</p>- )}- </div>- {secondary && <div className="flex-shrink-0">{secondary}</div>}- </CardHeader>- <Separator />- </>- )}- {content ? (- <CardContent className={cn('px-5 py-4', noPadding && 'p-0', contentClassName)}>- {children}- </CardContent>- ) : (- children- )}- </Card>- );-}diff --git a/frontend/src/components/MediaCard.jsx b/frontend/src/components/MediaCard.jsxnew file mode 100644index 0000000..b34556c--- /dev/null+++ b/frontend/src/components/MediaCard.jsx@@ -0,0 +1,57 @@+import React from 'react';+import { ImageOff } from 'lucide-react';+import { cn } from '@/lib/utils';++const ASPECTS = { video: 'aspect-video', vertical: 'aspect-[9/16]', square: 'aspect-square' };++// Thumbnail card for library grids. Overlay chips sit on a dark scrim so they read on any image.+export function MediaChip({ children, className }) {+ return (+ <span className={cn('inline-flex items-center gap-1 rounded-pill bg-[#0C0809]/75 px-2 py-0.5 text-[0.6875rem] font-semibold text-white backdrop-blur-sm [&_svg]:size-3', className)}>+ {children}+ </span>+ );+}++export default function MediaCard({+ image,+ aspect = 'video',+ title,+ meta,+ topLeft,+ topRight,+ bottomRight,+ href,+ className,+}) {+ const Element = href ? 'a' : 'div';+ return (+ <Element+ href={href}+ target={href ? '_blank' : undefined}+ rel={href ? 'noopener noreferrer' : undefined}+ className={cn(+ 'group flex flex-col overflow-hidden rounded-card border border-line bg-surface-raised transition-colors duration-(--duration-fast)',+ href && 'hover:border-line-strong/50 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring',+ className,+ )}+ >+ <div className={cn('relative overflow-hidden bg-surface-sunken', ASPECTS[aspect])}>+ {image ? (+ <img src={image} alt="" loading="lazy" className="size-full object-cover transition-transform duration-(--duration-slow) ease-(--ease-fold) group-hover:scale-[1.02]" />+ ) : (+ <div className="flex size-full items-center justify-center text-ink-faint">+ <ImageOff className="size-6 stroke-[1.5]" />+ </div>+ )}+ {topLeft && <div className="absolute top-2 left-2">{topLeft}</div>}+ {topRight && <div className="absolute top-2 right-2">{topRight}</div>}+ {bottomRight && <div className="absolute right-2 bottom-2">{bottomRight}</div>}+ </div>+ <div className="flex flex-1 flex-col gap-1.5 p-3">+ {title && <p className="line-clamp-2 text-small font-medium leading-snug text-ink">{title}</p>}+ {meta && <div className="mt-auto flex items-center gap-3 text-caption text-ink-faint tabular-nums [&_svg]:size-3 [&_svg]:stroke-[1.75]">{meta}</div>}+ </div>+ </Element>+ );+}diff --git a/frontend/src/components/MetricAreaChart.jsx b/frontend/src/components/MetricAreaChart.jsxindex f7ef4c0..f9ce679 100644--- a/frontend/src/components/MetricAreaChart.jsx+++ b/frontend/src/components/MetricAreaChart.jsx@@ -4,12 +4,13 @@ import {Tooltip as ReTooltip, ResponsiveContainer,} from 'recharts';import { fmtNum, fmtNumFull } from '../utils/formatters';+import { axisProps, gridProps, tooltipStyle } from '@/lib/chart';export default function MetricAreaChart({data,dataKey,label,- color = 'var(--primary)',+ color = 'var(--chart-1)',height = 240,emptyMessage = 'No data to display',}) {@@ -17,7 +18,7 @@ export default function MetricAreaChart({const gradientId = `metric-area-${useId().replace(/:/g, '')}`;if (!data || data.length === 0) {- return <p className="text-sm text-muted-foreground py-8 text-center">{emptyMessage}</p>;+ return <p className="py-8 text-center text-small text-ink-faint">{emptyMessage}</p>;}return (@@ -25,28 +26,16 @@ export default function MetricAreaChart({<AreaChart data={data} margin={{ top: 8, right: 8, left: 0, bottom: 0 }}><defs><linearGradient id={gradientId} x1="0" y1="0" x2="0" y2="1">- <stop offset="5%" stopColor={color} stopOpacity={0.28} />+ <stop offset="5%" stopColor={color} stopOpacity={0.2} /><stop offset="95%" stopColor={color} stopOpacity={0} /></linearGradient></defs>- <CartesianGrid strokeDasharray="3 3" stroke="var(--border)" vertical={false} />- <XAxis- dataKey="name"- tick={{ fill: 'var(--muted-foreground)', fontSize: 11 }}- axisLine={false}- tickLine={false}- interval="preserveStartEnd"- />- <YAxis- tick={{ fill: 'var(--muted-foreground)', fontSize: 11 }}- tickFormatter={fmtNum}- axisLine={false}- tickLine={false}- width={48}- allowDecimals={false}- />+ <CartesianGrid {...gridProps} vertical={false} />+ <XAxis dataKey="name" {...axisProps} interval="preserveStartEnd" />+ <YAxis {...axisProps} tickFormatter={fmtNum} width={48} allowDecimals={false} /><ReTooltip- contentStyle={{ background: 'var(--card)', border: '1px solid var(--border)', borderRadius: 8, fontSize: 12 }}+ contentStyle={tooltipStyle}+ cursor={{ stroke: 'var(--line-strong)' }}formatter={(v) => [fmtNumFull(v), label]}/><Area@@ -55,7 +44,7 @@ export default function MetricAreaChart({stroke={color}strokeWidth={2}fill={`url(#${gradientId})`}- dot={{ r: 3, fill: color, stroke: 'var(--card)', strokeWidth: 2 }}+ dot={{ r: 3, fill: color, stroke: 'var(--surface-raised)', strokeWidth: 2 }}activeDot={{ r: 6 }}/></AreaChart>diff --git a/frontend/src/components/MetricBox.jsx b/frontend/src/components/MetricBox.jsxnew file mode 100644index 0000000..7011876--- /dev/null+++ b/frontend/src/components/MetricBox.jsx@@ -0,0 +1,71 @@+import React from 'react';+import { TrendingUp, TrendingDown } from 'lucide-react';+import { Skeleton } from '@/components/ui/skeleton';+import { cn } from '@/lib/utils';++// Quiet metric tile: neutral icon, large tabular value, label and one line of context.+export default function MetricBox({+ icon,+ label,+ value,+ subtitle,+ loading,+ small,+ trend,+ trendLabel,+ highlight = false,+ className,+}) {+ return (+ <div+ className={cn(+ 'flex h-full flex-col gap-3 rounded-card border border-line bg-surface-raised',+ small ? 'p-4' : 'p-5',+ className,+ )}+ >+ <div className="flex items-center justify-between gap-2">+ <span className="flex min-w-0 items-center gap-2 text-small font-medium text-ink-muted">+ {icon && (+ <span+ className={cn(+ 'flex shrink-0 items-center justify-center [&_svg]:size-4 [&_svg]:stroke-[1.75]',+ highlight ? 'text-brand-text' : 'text-ink-faint',+ )}+ >+ {icon}+ </span>+ )}+ <span className="truncate">{label}</span>+ </span>+ {trend !== undefined && !loading && (+ <span className={cn('flex items-center gap-0.5 text-caption font-semibold', trend >= 0 ? 'text-success' : 'text-danger')}>+ {trend >= 0 ? <TrendingUp className="size-3" /> : <TrendingDown className="size-3" />}+ {Math.abs(trend)}%+ </span>+ )}+ </div>++ {loading ? (+ <div className="flex flex-col gap-2">+ <Skeleton className={small ? 'h-6 w-16' : 'h-8 w-24'} />+ <Skeleton className="h-3 w-28" />+ </div>+ ) : (+ <div className="flex min-w-0 flex-col gap-1">+ <p+ className={cn(+ 'font-heading font-semibold tracking-[-0.02em] tabular-nums text-ink leading-none',+ small ? 'text-xl' : 'text-[1.75rem]',+ )}+ >+ {value}+ </p>+ {(subtitle || trendLabel) && (+ <p className="truncate text-caption text-ink-faint">{trendLabel || subtitle}</p>+ )}+ </div>+ )}+ </div>+ );+}diff --git a/frontend/src/components/PageHeader.jsx b/frontend/src/components/PageHeader.jsxnew file mode 100644index 0000000..3580a0c--- /dev/null+++ b/frontend/src/components/PageHeader.jsx@@ -0,0 +1,48 @@+import React from 'react';+import { Link } from 'react-router-dom';+import { ArrowLeft } from 'lucide-react';+import { cn } from '@/lib/utils';++// Page title block. One per page; actions sit on the right and wrap under the title on narrow screens.+export default function PageHeader({+ title,+ description,+ eyebrow,+ actions,+ back,+ media,+ size = 'default',+ className,+}) {+ return (+ <header className={cn('flex flex-col gap-4', className)}>+ {back && (+ <Link+ to={back.to}+ className="inline-flex w-fit items-center gap-1.5 rounded-row text-small font-medium text-ink-muted transition-colors duration-(--duration-fast) hover:text-ink"+ >+ <ArrowLeft className="size-4 stroke-[1.75]" />+ {back.label}+ </Link>+ )}+ <div className="flex flex-wrap items-end justify-between gap-x-6 gap-y-4">+ <div className="flex min-w-0 items-center gap-4">+ {media}+ <div className="min-w-0">+ {eyebrow && <p className="eyebrow mb-2 text-brand-text">{eyebrow}</p>}+ <h1+ className={cn(+ 'font-heading font-semibold tracking-[-0.01em] text-ink',+ size === 'display' ? 'text-display' : 'text-page-title',+ )}+ >+ {title}+ </h1>+ {description && <div className="mt-1.5 text-sm text-ink-muted">{description}</div>}+ </div>+ </div>+ {actions && <div className="flex flex-wrap items-center gap-2">{actions}</div>}+ </div>+ </header>+ );+}diff --git a/frontend/src/components/Pager.jsx b/frontend/src/components/Pager.jsxnew file mode 100644index 0000000..2479415--- /dev/null+++ b/frontend/src/components/Pager.jsx@@ -0,0 +1,27 @@+import React from 'react';+import { ChevronLeft, ChevronRight } from 'lucide-react';+import { Button } from '@/components/ui/button';++export default function Pager({ page, pageCount, onPageChange, total, shown, noun = 'items' }) {+ if (pageCount <= 1) {+ return total > 0 ? <p className="text-center text-caption text-ink-faint">{total} {noun}</p> : null;+ }+ return (+ <nav aria-label="Pagination" className="flex flex-wrap items-center justify-between gap-3">+ <p className="text-caption text-ink-faint">+ Showing {shown} of {total} {noun}+ </p>+ <div className="flex items-center gap-2">+ <Button variant="outline" size="icon-sm" onClick={() => onPageChange(page - 1)} disabled={page <= 1} aria-label="Previous page">+ <ChevronLeft />+ </Button>+ <span className="min-w-20 text-center text-small text-ink-muted tabular-nums">+ {page} of {pageCount}+ </span>+ <Button variant="outline" size="icon-sm" onClick={() => onPageChange(page + 1)} disabled={page >= pageCount} aria-label="Next page">+ <ChevronRight />+ </Button>+ </div>+ </nav>+ );+}diff --git a/frontend/src/components/SearchField.jsx b/frontend/src/components/SearchField.jsxnew file mode 100644index 0000000..5a00e33--- /dev/null+++ b/frontend/src/components/SearchField.jsx@@ -0,0 +1,35 @@+import React from 'react';+import { Search, X } from 'lucide-react';+import { cn } from '@/lib/utils';++export default function SearchField({ value, onChange, placeholder = 'Search', className, inputClassName, ...props }) {+ return (+ <div className={cn('relative flex min-w-0 items-center', className)}>+ <Search className="pointer-events-none absolute left-3.5 size-4 stroke-[1.75] text-ink-faint" aria-hidden="true" />+ <input+ type="search"+ value={value}+ onChange={e => onChange(e.target.value)}+ placeholder={placeholder}+ aria-label={props['aria-label'] || placeholder}+ className={cn(+ 'h-(--control-h-lg) w-full min-w-0 rounded-field border border-line-control bg-surface pr-9 pl-10 text-sm text-ink transition-colors duration-(--duration-fast) outline-none',+ 'placeholder:text-ink-faint hover:border-line-strong/60 focus-visible:border-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring',+ '[&::-webkit-search-cancel-button]:appearance-none',+ inputClassName,+ )}+ {...props}+ />+ {value && (+ <button+ type="button"+ onClick={() => onChange('')}+ aria-label="Clear search"+ className="absolute right-2 flex size-6 items-center justify-center rounded-full text-ink-faint transition-colors hover:bg-surface-hover hover:text-ink"+ >+ <X className="size-3.5" />+ </button>+ )}+ </div>+ );+}diff --git a/frontend/src/components/SectionHeader.jsx b/frontend/src/components/SectionHeader.jsxnew file mode 100644index 0000000..061cef1--- /dev/null+++ b/frontend/src/components/SectionHeader.jsx@@ -0,0 +1,14 @@+import React from 'react';+import { cn } from '@/lib/utils';++export default function SectionHeader({ title, description, actions, className }) {+ return (+ <div className={cn('flex flex-wrap items-end justify-between gap-3', className)}>+ <div className="min-w-0">+ <h2 className="font-heading text-section font-semibold text-ink">{title}</h2>+ {description && <p className="mt-0.5 text-small text-ink-muted">{description}</p>}+ </div>+ {actions && <div className="flex items-center gap-2">{actions}</div>}+ </div>+ );+}diff --git a/frontend/src/components/StateViews.jsx b/frontend/src/components/StateViews.jsxnew file mode 100644index 0000000..e7e18ce--- /dev/null+++ b/frontend/src/components/StateViews.jsx@@ -0,0 +1,73 @@+import React from 'react';+import { AlertTriangle } from 'lucide-react';+import { Button } from '@/components/ui/button';+import { Skeleton } from '@/components/ui/skeleton';+import { Spinner } from '@/components/ui/spinner';+import { cn } from '@/lib/utils';++export function EmptyState({ icon, title, description, action, className, compact = false }) {+ return (+ <div+ className={cn(+ 'flex flex-col items-center justify-center gap-4 text-center',+ compact ? 'px-4 py-8' : 'px-6 py-14',+ className,+ )}+ >+ {icon && (+ <span className="flex size-11 items-center justify-center rounded-card border border-line bg-surface-sunken text-ink-muted [&_svg]:size-5 [&_svg]:stroke-[1.75]">+ {icon}+ </span>+ )}+ <div className="flex max-w-sm flex-col gap-1">+ <p className="font-heading text-section font-semibold text-ink">{title}</p>+ {description && <p className="text-small text-ink-muted">{description}</p>}+ </div>+ {action}+ </div>+ );+}++export function ErrorState({ title = 'This page could not load', description, onRetry, className }) {+ return (+ <div role="alert" className={cn('flex flex-col items-center justify-center gap-4 px-6 py-14 text-center', className)}>+ <span className="flex size-11 items-center justify-center rounded-card bg-danger-soft text-danger">+ <AlertTriangle className="size-5 stroke-[1.75]" />+ </span>+ <div className="flex max-w-sm flex-col gap-1">+ <p className="font-heading text-section font-semibold text-ink">+ <span className="sr-only">Error: </span>{title}+ </p>+ {description && <p className="text-small text-ink-muted">{description}</p>}+ </div>+ {onRetry && <Button variant="outline" size="sm" onClick={onRetry}>Try again</Button>}+ </div>+ );+}++export function LoadingState({ label = 'Loading', className }) {+ return (+ <div role="status" className={cn('flex min-h-[40vh] flex-col items-center justify-center gap-3', className)}>+ <Spinner className="size-6 text-brand" />+ <p className="text-small text-ink-muted">{label}</p>+ </div>+ );+}++// Placeholder that mirrors the real page layout: header, metric row, and a large panel.+export function PageSkeleton({ metrics = 4 }) {+ return (+ <div className="flex flex-col gap-8" aria-busy="true" aria-label="Loading page">+ <div className="flex flex-col gap-2">+ <Skeleton className="h-8 w-56" />+ <Skeleton className="h-4 w-80 max-w-full" />+ </div>+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-4">+ {Array.from({ length: metrics }).map((_, i) => (+ <Skeleton key={i} className="h-28 rounded-card" />+ ))}+ </div>+ <Skeleton className="h-72 rounded-card" />+ </div>+ );+}diff --git a/frontend/src/components/SurfaceBox.jsx b/frontend/src/components/SurfaceBox.jsxnew file mode 100644index 0000000..5d4756f--- /dev/null+++ b/frontend/src/components/SurfaceBox.jsx@@ -0,0 +1,37 @@+import React from 'react';+import { cn } from '@/lib/utils';++// The one container for grouped content. A title row is optional; without one the box is a plain panel.+export default function SurfaceBox({+ children,+ title,+ subheader,+ secondary,+ content = true,+ contentClassName = '',+ className = '',+ noPadding = false,+ ...props+}) {+ return (+ <section+ className={cn('flex flex-col rounded-card border border-line bg-surface-raised text-ink', className)}+ {...props}+ >+ {title && (+ <header className="flex items-start justify-between gap-4 border-b border-divider px-5 py-4">+ <div className="min-w-0">+ <h3 className="font-heading text-section font-semibold">{title}</h3>+ {subheader && <p className="mt-0.5 text-small text-ink-muted">{subheader}</p>}+ </div>+ {secondary && <div className="shrink-0">{secondary}</div>}+ </header>+ )}+ {content ? (+ <div className={cn('px-5 py-4', noPadding && 'p-0', contentClassName)}>{children}</div>+ ) : (+ children+ )}+ </section>+ );+}diff --git a/frontend/src/components/app-sidebar.jsx b/frontend/src/components/app-sidebar.jsxdeleted file mode 100644index 22db388..0000000--- a/frontend/src/components/app-sidebar.jsx+++ /dev/null@@ -1,192 +0,0 @@-import * as React from "react"--import { NavMain } from "@/components/nav-main"-import { NavProjects } from "@/components/nav-projects"-import { NavSecondary } from "@/components/nav-secondary"-import { NavUser } from "@/components/nav-user"-import {- Sidebar,- SidebarContent,- SidebarFooter,- SidebarHeader,- SidebarMenu,- SidebarMenuButton,- SidebarMenuItem,-} from "@/components/ui/sidebar"-import { TerminalSquareIcon, BotIcon, BookOpenIcon, Settings2Icon, LifeBuoyIcon, SendIcon, FrameIcon, PieChartIcon, MapIcon, TerminalIcon } from "lucide-react"--const data = {- user: {- name: "shadcn",- email: "[email protected]",- avatar: "/avatars/shadcn.jpg",- },- navMain: [- {- title: "Playground",- url: "#",- icon: (- <TerminalSquareIcon />- ),- isActive: true,- items: [- {- title: "History",- url: "#",- },- {- title: "Starred",- url: "#",- },- {- title: "Settings",- url: "#",- },- ],- },- {- title: "Models",- url: "#",- icon: (- <BotIcon />- ),- items: [- {- title: "Genesis",- url: "#",- },- {- title: "Explorer",- url: "#",- },- {- title: "Quantum",- url: "#",- },- ],- },- {- title: "Documentation",- url: "#",- icon: (- <BookOpenIcon />- ),- items: [- {- title: "Introduction",- url: "#",- },- {- title: "Get Started",- url: "#",- },- {- title: "Tutorials",- url: "#",- },- {- title: "Changelog",- url: "#",- },- ],- },- {- title: "Settings",- url: "#",- icon: (- <Settings2Icon />- ),- items: [- {- title: "General",- url: "#",- },- {- title: "Team",- url: "#",- },- {- title: "Billing",- url: "#",- },- {- title: "Limits",- url: "#",- },- ],- },- ],- navSecondary: [- {- title: "Support",- url: "#",- icon: (- <LifeBuoyIcon />- ),- },- {- title: "Feedback",- url: "#",- icon: (- <SendIcon />- ),- },- ],- projects: [- {- name: "Design Engineering",- url: "#",- icon: (- <FrameIcon />- ),- },- {- name: "Sales & Marketing",- url: "#",- icon: (- <PieChartIcon />- ),- },- {- name: "Travel",- url: "#",- icon: (- <MapIcon />- ),- },- ],-}-export function AppSidebar({- ...props-}) {- return (- <Sidebar- className="top-(--header-height) h-[calc(100svh-var(--header-height))]!"- {...props}>- <SidebarHeader>- <SidebarMenu>- <SidebarMenuItem>- <SidebarMenuButton size="lg" render={<a href="#" />}>- <div- className="flex aspect-square size-8 items-center justify-center rounded-lg bg-sidebar-primary text-sidebar-primary-foreground">- <TerminalIcon className="size-4" />- </div>- <div className="grid flex-1 text-left text-sm leading-tight">- <span className="truncate font-medium">Acme Inc</span>- <span className="truncate text-xs">Enterprise</span>- </div>- </SidebarMenuButton>- </SidebarMenuItem>- </SidebarMenu>- </SidebarHeader>- <SidebarContent>- <NavMain items={data.navMain} />- <NavProjects projects={data.projects} />- <NavSecondary items={data.navSecondary} className="mt-auto" />- </SidebarContent>- <SidebarFooter>- <NavUser user={data.user} />- </SidebarFooter>- </Sidebar>- );-}diff --git a/frontend/src/components/brand/Logo.jsx b/frontend/src/components/brand/Logo.jsxnew file mode 100644index 0000000..601e4ef--- /dev/null+++ b/frontend/src/components/brand/Logo.jsx@@ -0,0 +1,36 @@+import React from 'react';+import { cn } from '@/lib/utils';++const LOGO_DIR = '/Logos';++// Brand rule: the colour lockup sits on paper, the reversed lockup on dusk. Both are rendered and+// CSS picks one, so the right file shows on first paint without waiting for the theme hook.+export function Logo({ variant = 'lockup', className }) {+ if (variant === 'mark') {+ return (+ <img+ src={`${LOGO_DIR}/twiligent-mark-color.svg`}+ alt="Twiligent"+ className={cn('h-6 w-auto shrink-0 select-none', className)}+ draggable={false}+ />+ );+ }++ return (+ <span className={cn('inline-flex shrink-0 select-none', className)}>+ <img+ src={`${LOGO_DIR}/twiligent-lockup-horizontal.svg`}+ alt="Twiligent"+ className="h-full w-auto dark:hidden"+ draggable={false}+ />+ <img+ src={`${LOGO_DIR}/twiligent-lockup-horizontal-reversed.svg`}+ alt="Twiligent"+ className="hidden h-full w-auto dark:block"+ draggable={false}+ />+ </span>+ );+}diff --git a/frontend/src/components/ui/brand-icons.jsx b/frontend/src/components/brand/platform-icons.jsxsimilarity index 58%rename from frontend/src/components/ui/brand-icons.jsxrename to frontend/src/components/brand/platform-icons.jsxindex 46db822..615265f 100644--- a/frontend/src/components/ui/brand-icons.jsx+++ b/frontend/src/components/brand/platform-icons.jsx@@ -13,3 +13,11 @@ export function InstagramIcon({ className, ...props }) {</svg>);}++export function RedditIcon({ className, ...props }) {+ return (+ <svg viewBox="0 0 24 24" className={className} fill="currentColor" aria-hidden="true" {...props}>+ <path d="M12 0A12 12 0 0 0 0 12a12 12 0 0 0 12 12 12 12 0 0 0 12-12A12 12 0 0 0 12 0zm5.01 4.744c.688 0 1.25.561 1.25 1.249a1.25 1.25 0 0 1-2.498.056l-2.597-.547-.8 3.747c1.824.07 3.48.632 4.674 1.488.308-.309.73-.491 1.207-.491.968 0 1.754.786 1.754 1.754 0 .716-.435 1.333-1.01 1.614a3.111 3.111 0 0 1 .042.52c0 2.694-3.13 4.87-7.004 4.87-3.874 0-7.004-2.176-7.004-4.87 0-.183.015-.366.043-.534A1.748 1.748 0 0 1 4.028 12c0-.968.786-1.754 1.754-1.754.463 0 .898.196 1.207.49 1.207-.883 2.878-1.43 4.744-1.487l.885-4.182a.342.342 0 0 1 .14-.197.35.35 0 0 1 .238-.042l2.906.617a1.214 1.214 0 0 1 1.108-.701zM9.25 12C8.561 12 8 12.562 8 13.25c0 .687.561 1.248 1.25 1.248.687 0 1.248-.561 1.248-1.249 0-.688-.561-1.249-1.249-1.249zm5.5 0c-.687 0-1.248.561-1.248 1.25 0 .687.561 1.248 1.249 1.248.688 0 1.249-.561 1.249-1.249 0-.687-.562-1.249-1.25-1.249zm-5.466 3.99a.327.327 0 0 0-.231.094.33.33 0 0 0 0 .463c.842.842 2.484.913 2.961.913.477 0 2.105-.056 2.961-.913a.361.361 0 0 0 .029-.463.33.33 0 0 0-.464 0c-.547.533-1.684.73-2.512.73-.828 0-1.979-.196-2.512-.73a.326.326 0 0 0-.232-.095z" />+ </svg>+ );+}diff --git a/frontend/src/components/nav-main.jsx b/frontend/src/components/nav-main.jsxdeleted file mode 100644index 0ec80d4..0000000--- a/frontend/src/components/nav-main.jsx+++ /dev/null@@ -1,56 +0,0 @@-import {- Collapsible,- CollapsibleContent,- CollapsibleTrigger,-} from "@/components/ui/collapsible"-import {- SidebarGroup,- SidebarGroupLabel,- SidebarMenu,- SidebarMenuAction,- SidebarMenuButton,- SidebarMenuItem,- SidebarMenuSub,- SidebarMenuSubButton,- SidebarMenuSubItem,-} from "@/components/ui/sidebar"-import { ChevronRightIcon } from "lucide-react"--export function NavMain({- items-}) {- return (- <SidebarGroup>- <SidebarGroupLabel>Platform</SidebarGroupLabel>- <SidebarMenu>- {items.map((item) => (- <Collapsible key={item.title} defaultOpen={item.isActive} render={<SidebarMenuItem />}>- <SidebarMenuButton tooltip={item.title} render={<a href={item.url} />}>- {item.icon}- <span>{item.title}</span>- </SidebarMenuButton>- {item.items?.length ? (- <>- <SidebarMenuAction render={<CollapsibleTrigger />} className="aria-expanded:rotate-90">- <ChevronRightIcon />- <span className="sr-only">Toggle</span>- </SidebarMenuAction>- <CollapsibleContent>- <SidebarMenuSub>- {item.items?.map((subItem) => (- <SidebarMenuSubItem key={subItem.title}>- <SidebarMenuSubButton render={<a href={subItem.url} />}>- <span>{subItem.title}</span>- </SidebarMenuSubButton>- </SidebarMenuSubItem>- ))}- </SidebarMenuSub>- </CollapsibleContent>- </>- ) : null}- </Collapsible>- ))}- </SidebarMenu>- </SidebarGroup>- );-}diff --git a/frontend/src/components/nav-projects.jsx b/frontend/src/components/nav-projects.jsxdeleted file mode 100644index 853abe5..0000000--- a/frontend/src/components/nav-projects.jsx+++ /dev/null@@ -1,71 +0,0 @@-import {- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuSeparator,- DropdownMenuTrigger,-} from "@/components/ui/dropdown-menu"-import {- SidebarGroup,- SidebarGroupLabel,- SidebarMenu,- SidebarMenuAction,- SidebarMenuButton,- SidebarMenuItem,- useSidebar,-} from "@/components/ui/sidebar"-import { MoreHorizontalIcon, FolderIcon, ShareIcon, Trash2Icon } from "lucide-react"--export function NavProjects({- projects-}) {- const { isMobile } = useSidebar()- return (- <SidebarGroup className="group-data-[collapsible=icon]:hidden">- <SidebarGroupLabel>Projects</SidebarGroupLabel>- <SidebarMenu>- {projects.map((item) => (- <SidebarMenuItem key={item.name}>- <SidebarMenuButton render={<a href={item.url} />}>- {item.icon}- <span>{item.name}</span>- </SidebarMenuButton>- <DropdownMenu>- <DropdownMenuTrigger- render={- <SidebarMenuAction showOnHover className="aria-expanded:bg-muted" />- }>- <MoreHorizontalIcon />- <span className="sr-only">More</span>- </DropdownMenuTrigger>- <DropdownMenuContent- className="w-48"- side={isMobile ? "bottom" : "right"}- align={isMobile ? "end" : "start"}>- <DropdownMenuItem>- <FolderIcon className="text-muted-foreground" />- <span>View Project</span>- </DropdownMenuItem>- <DropdownMenuItem>- <ShareIcon className="text-muted-foreground" />- <span>Share Project</span>- </DropdownMenuItem>- <DropdownMenuSeparator />- <DropdownMenuItem>- <Trash2Icon className="text-muted-foreground" />- <span>Delete Project</span>- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- </SidebarMenuItem>- ))}- <SidebarMenuItem>- <SidebarMenuButton>- <MoreHorizontalIcon />- <span>More</span>- </SidebarMenuButton>- </SidebarMenuItem>- </SidebarMenu>- </SidebarGroup>- );-}diff --git a/frontend/src/components/nav-secondary.jsx b/frontend/src/components/nav-secondary.jsxdeleted file mode 100644index 850d4a7..0000000--- a/frontend/src/components/nav-secondary.jsx+++ /dev/null@@ -1,31 +0,0 @@-import * as React from "react"--import {- SidebarGroup,- SidebarGroupContent,- SidebarMenu,- SidebarMenuButton,- SidebarMenuItem,-} from "@/components/ui/sidebar"--export function NavSecondary({- items,- ...props-}) {- return (- <SidebarGroup {...props}>- <SidebarGroupContent>- <SidebarMenu>- {items.map((item) => (- <SidebarMenuItem key={item.title}>- <SidebarMenuButton size="sm" render={<a href={item.url} />}>- {item.icon}- <span>{item.title}</span>- </SidebarMenuButton>- </SidebarMenuItem>- ))}- </SidebarMenu>- </SidebarGroupContent>- </SidebarGroup>- );-}diff --git a/frontend/src/components/nav-user.jsx b/frontend/src/components/nav-user.jsxdeleted file mode 100644index bac81f9..0000000--- a/frontend/src/components/nav-user.jsx+++ /dev/null@@ -1,100 +0,0 @@-import {- Avatar,- AvatarFallback,- AvatarImage,-} from "@/components/ui/avatar"-import {- DropdownMenu,- DropdownMenuContent,- DropdownMenuGroup,- DropdownMenuItem,- DropdownMenuLabel,- DropdownMenuSeparator,- DropdownMenuTrigger,-} from "@/components/ui/dropdown-menu"-import {- SidebarMenu,- SidebarMenuButton,- SidebarMenuItem,- useSidebar,-} from "@/components/ui/sidebar"-import { ChevronsUpDownIcon, SparklesIcon, BadgeCheckIcon, CreditCardIcon, BellIcon, LogOutIcon } from "lucide-react"--export function NavUser({- user-}) {- const { isMobile } = useSidebar()- return (- <SidebarMenu>- <SidebarMenuItem>- <DropdownMenu>- <DropdownMenuTrigger- render={- <SidebarMenuButton- size="lg"- className="aria-expanded:bg-muted aria-expanded:text-foreground" />- }>- <Avatar>- <AvatarImage src={user.avatar} alt={user.name} />- <AvatarFallback>CN</AvatarFallback>- </Avatar>- <div className="grid flex-1 text-left text-sm leading-tight">- <span className="truncate font-medium">{user.name}</span>- <span className="truncate text-xs">{user.email}</span>- </div>- <ChevronsUpDownIcon className="ml-auto size-4" />- </DropdownMenuTrigger>- <DropdownMenuContent- className="min-w-56 rounded-lg"- side={isMobile ? "bottom" : "right"}- align="end"- sideOffset={4}>- <DropdownMenuGroup>- <DropdownMenuLabel className="p-0 font-normal">- <div className="flex items-center gap-2 px-1 py-1.5 text-left text-sm">- <Avatar>- <AvatarImage src={user.avatar} alt={user.name} />- <AvatarFallback>CN</AvatarFallback>- </Avatar>- <div className="grid flex-1 text-left text-sm leading-tight">- <span className="truncate font-medium">{user.name}</span>- <span className="truncate text-xs">{user.email}</span>- </div>- </div>- </DropdownMenuLabel>- </DropdownMenuGroup>- <DropdownMenuSeparator />- <DropdownMenuGroup>- <DropdownMenuItem>- <SparklesIcon />- Upgrade to Pro- </DropdownMenuItem>- </DropdownMenuGroup>- <DropdownMenuSeparator />- <DropdownMenuGroup>- <DropdownMenuItem>- <BadgeCheckIcon />- Account- </DropdownMenuItem>- <DropdownMenuItem>- <CreditCardIcon />- Billing- </DropdownMenuItem>- <DropdownMenuItem>- <BellIcon />- Notifications- </DropdownMenuItem>- </DropdownMenuGroup>- <DropdownMenuSeparator />- <DropdownMenuGroup>- <DropdownMenuItem>- <LogOutIcon />- Log out- </DropdownMenuItem>- </DropdownMenuGroup>- </DropdownMenuContent>- </DropdownMenu>- </SidebarMenuItem>- </SidebarMenu>- );-}diff --git a/frontend/src/components/platform.jsx b/frontend/src/components/platform.jsxnew file mode 100644index 0000000..f7c6808--- /dev/null+++ b/frontend/src/components/platform.jsx@@ -0,0 +1,48 @@+import React from 'react';+import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';+import { YouTubeIcon, InstagramIcon, RedditIcon } from '@/components/brand/platform-icons';+import { PLATFORM_META, platformOf, accountImage, accountInitials, accountName } from '@/lib/accounts';+import { cn } from '@/lib/utils';++const ICONS = { youtube: YouTubeIcon, instagram: InstagramIcon, reddit: RedditIcon };++export function PlatformIcon({ platform, className }) {+ const Icon = ICONS[platform] || YouTubeIcon;+ return <Icon className={cn('size-4 shrink-0', className)} />;+}++export function PlatformBadge({ platform, className }) {+ const key = PLATFORM_META[platform] ? platform : 'youtube';+ return (+ <span+ className={cn(+ 'inline-flex h-6 items-center gap-1.5 rounded-pill border border-line px-2 text-caption font-medium text-ink-muted',+ className,+ )}+ >+ <PlatformIcon platform={key} className="size-3" />+ {PLATFORM_META[key].label}+ </span>+ );+}++// Avatar with a small platform glyph in the corner, so platform reads without colour alone+export function AccountAvatar({ account, size = 'default', showPlatform = false, className }) {+ const platform = platformOf(account);+ const sizes = { xs: 'size-5', sm: 'size-6', default: 'size-8', lg: 'size-11', xl: 'size-16' };+ return (+ <span className={cn('relative inline-flex shrink-0', className)}>+ <Avatar className={cn(sizes[size] || sizes.default)}>+ <AvatarImage src={accountImage(account)} alt={accountName(account)} />+ <AvatarFallback className="bg-surface-sunken text-caption font-semibold text-ink-muted">+ {accountInitials(account)}+ </AvatarFallback>+ </Avatar>+ {showPlatform && (+ <span className="absolute -right-1 -bottom-1 flex size-4 items-center justify-center rounded-full bg-surface-raised text-ink-muted ring-2 ring-surface-raised">+ <PlatformIcon platform={platform} className="size-2.5" />+ </span>+ )}+ </span>+ );+}diff --git a/frontend/src/components/search-form.jsx b/frontend/src/components/search-form.jsxdeleted file mode 100644index 6d73802..0000000--- a/frontend/src/components/search-form.jsx+++ /dev/null@@ -1,20 +0,0 @@-import { Label } from "@/components/ui/label"-import { SidebarInput } from "@/components/ui/sidebar"-import { SearchIcon } from "lucide-react"--export function SearchForm({- ...props-}) {- return (- <form {...props}>- <div className="relative">- <Label htmlFor="search" className="sr-only">- Search- </Label>- <SidebarInput id="search" placeholder="Type to search..." className="h-8 pl-7" />- <SearchIcon- className="pointer-events-none absolute top-1/2 left-2 size-4 -translate-y-1/2 opacity-50 select-none" />- </div>- </form>- );-}diff --git a/frontend/src/components/site-header.jsx b/frontend/src/components/site-header.jsxdeleted file mode 100644index 2ed589e..0000000--- a/frontend/src/components/site-header.jsx+++ /dev/null@@ -1,43 +0,0 @@-import { SearchForm } from "@/components/search-form"-import {- Breadcrumb,- BreadcrumbItem,- BreadcrumbLink,- BreadcrumbList,- BreadcrumbPage,- BreadcrumbSeparator,-} from "@/components/ui/breadcrumb"-import { Button } from "@/components/ui/button"-import { Separator } from "@/components/ui/separator"-import { useSidebar } from "@/components/ui/sidebar"-import { PanelLeftIcon } from "lucide-react"--export function SiteHeader() {- const { toggleSidebar } = useSidebar()-- return (- <header- className="sticky top-0 z-50 flex w-full items-center border-b bg-background">- <div className="flex h-(--header-height) w-full items-center gap-2 px-4">- <Button className="h-8 w-8" variant="ghost" size="icon" onClick={toggleSidebar}>- <PanelLeftIcon />- </Button>- <Separator- orientation="vertical"- className="mr-2 data-vertical:h-4 data-vertical:self-auto" />- <Breadcrumb className="hidden sm:block">- <BreadcrumbList>- <BreadcrumbItem>- <BreadcrumbLink href="#">Build Your Application</BreadcrumbLink>- </BreadcrumbItem>- <BreadcrumbSeparator />- <BreadcrumbItem>- <BreadcrumbPage>Data Fetching</BreadcrumbPage>- </BreadcrumbItem>- </BreadcrumbList>- </Breadcrumb>- <SearchForm className="w-full sm:ml-auto sm:w-auto" />- </div>- </header>- );-}diff --git a/frontend/src/components/team-switcher.jsx b/frontend/src/components/team-switcher.jsxdeleted file mode 100644index f274072..0000000--- a/frontend/src/components/team-switcher.jsx+++ /dev/null@@ -1,85 +0,0 @@-import * as React from "react"--import {- DropdownMenu,- DropdownMenuContent,- DropdownMenuGroup,- DropdownMenuItem,- DropdownMenuLabel,- DropdownMenuSeparator,- DropdownMenuShortcut,- DropdownMenuTrigger,-} from "@/components/ui/dropdown-menu"-import {- SidebarMenu,- SidebarMenuButton,- SidebarMenuItem,- useSidebar,-} from "@/components/ui/sidebar"-import { ChevronsUpDownIcon, PlusIcon } from "lucide-react"--export function TeamSwitcher({- teams-}) {- const { isMobile } = useSidebar()- const [activeTeam, setActiveTeam] = React.useState(teams[0])- if (!activeTeam) {- return null- }- return (- <SidebarMenu>- <SidebarMenuItem>- <DropdownMenu>- <DropdownMenuTrigger- render={- <SidebarMenuButton- size="lg"- className="data-open:bg-sidebar-accent data-open:text-sidebar-accent-foreground" />- }>- <div- className="flex aspect-square size-8 items-center justify-center rounded-lg bg-sidebar-primary text-sidebar-primary-foreground">- {activeTeam.logo}- </div>- <div className="grid flex-1 text-left text-sm leading-tight">- <span className="truncate font-medium">{activeTeam.name}</span>- <span className="truncate text-xs">{activeTeam.plan}</span>- </div>- <ChevronsUpDownIcon className="ml-auto" />- </DropdownMenuTrigger>- <DropdownMenuContent- className="w-fit"- align="start"- side={isMobile ? "bottom" : "right"}- sideOffset={4}>- <DropdownMenuGroup>- <DropdownMenuLabel className="text-xs text-muted-foreground">- Teams- </DropdownMenuLabel>- {teams.map((team, index) => (- <DropdownMenuItem key={team.name} onClick={() => setActiveTeam(team)} className="gap-2 p-2">- <div className="flex size-6 items-center justify-center rounded-md border">- {team.logo}- </div>- {team.name}- <DropdownMenuShortcut>⌘{index + 1}</DropdownMenuShortcut>- </DropdownMenuItem>- ))}- </DropdownMenuGroup>- <DropdownMenuSeparator />- <DropdownMenuGroup>- <DropdownMenuItem className="gap-2 p-2">- <div- className="flex size-6 items-center justify-center rounded-md border bg-transparent">- <PlusIcon className="size-4" />- </div>- <div className="font-medium text-muted-foreground">- Add team- </div>- </DropdownMenuItem>- </DropdownMenuGroup>- </DropdownMenuContent>- </DropdownMenu>- </SidebarMenuItem>- </SidebarMenu>- );-}diff --git a/frontend/src/components/ui/Logo.jsx b/frontend/src/components/ui/Logo.jsxdeleted file mode 100644index b7d64d1..0000000--- a/frontend/src/components/ui/Logo.jsx+++ /dev/null@@ -1,9 +0,0 @@-export default function Logo({ size = 40 }) {- return (- <img- src="/logo.png"- alt="Social Analytics"- style={{ width: size, height: size, flexShrink: 0, objectFit: 'contain', borderRadius: 6 }}- />- );-}diff --git a/frontend/src/components/ui/StatCard.jsx b/frontend/src/components/ui/StatCard.jsxdeleted file mode 100644index fb49fce..0000000--- a/frontend/src/components/ui/StatCard.jsx+++ /dev/null@@ -1,77 +0,0 @@-import React from 'react';-import { Card, CardContent } from '@/components/ui/card';-import { Skeleton } from '@/components/ui/skeleton';-import { TrendingUp, TrendingDown } from 'lucide-react';-import { cn } from '@/lib/utils';--const PALETTE = {- blue: { bg: 'bg-blue-50', icon: 'text-blue-600', ring: 'ring-blue-100' },- red: { bg: 'bg-red-50', icon: 'text-red-500', ring: 'ring-red-100' },- green: { bg: 'bg-green-50', icon: 'text-green-600', ring: 'ring-green-100' },- orange: { bg: 'bg-orange-50', icon: 'text-orange-500', ring: 'ring-orange-100' },- purple: { bg: 'bg-purple-50', icon: 'text-purple-600', ring: 'ring-purple-100' },- teal: { bg: 'bg-teal-50', icon: 'text-teal-600', ring: 'ring-teal-100' },- pink: { bg: 'bg-pink-50', icon: 'text-pink-600', ring: 'ring-pink-100' },- indigo: { bg: 'bg-indigo-50', icon: 'text-indigo-600', ring: 'ring-indigo-100' },- cyan: { bg: 'bg-cyan-50', icon: 'text-cyan-600', ring: 'ring-cyan-100' },- amber: { bg: 'bg-amber-50', icon: 'text-amber-600', ring: 'ring-amber-100' },-};--export default function StatCard({- icon,- label,- value,- subtitle,- gradient = 'blue',- loading,- small,- trend,- trendLabel,-}) {- const pal = PALETTE[gradient] || PALETTE.blue;- const iconSize = small ? 'h-4 w-4' : 'h-5 w-5';- const iconBoxSize = small ? 'h-9 w-9' : 'h-11 w-11';-- return (- <Card className="border border-border shadow-none h-full hover:shadow-sm transition-shadow">- <CardContent className={cn('flex flex-col gap-3', small ? 'p-4' : 'p-5')}>- <div className="flex items-start justify-between">- <div className={cn('rounded-xl flex items-center justify-center flex-shrink-0', iconBoxSize, pal.bg)}>- {React.isValidElement(icon)- ? React.cloneElement(icon, { className: cn(iconSize, pal.icon) })- : icon && <span className={cn(iconSize, pal.icon)}>{icon}</span>}- </div>- {trend !== undefined && !loading && (- <div className="flex items-center gap-0.5">- {trend >= 0- ? <TrendingUp className="h-3 w-3 text-green-500" />- : <TrendingDown className="h-3 w-3 text-red-500" />}- <span className={cn('text-xs font-semibold', trend >= 0 ? 'text-green-600' : 'text-red-500')}>- {Math.abs(trend)}%- </span>- </div>- )}- </div>-- {loading ? (- <>- <Skeleton className={cn('rounded', small ? 'h-6 w-16' : 'h-8 w-20')} />- <Skeleton className="h-3 w-28 rounded" />- </>- ) : (- <div>- <p className={cn('font-bold tracking-tight leading-none text-foreground', small ? 'text-xl' : 'text-2xl')}>- {value}- </p>- <p className="text-sm text-muted-foreground font-medium mt-1">{label}</p>- {(subtitle || trendLabel) && (- <p className="text-xs text-muted-foreground mt-0.5 leading-snug">- {trendLabel || subtitle}- </p>- )}- </div>- )}- </CardContent>- </Card>- );-}diff --git a/frontend/src/components/ui/alert-dialog.jsx b/frontend/src/components/ui/alert-dialog.jsxindex 726ac90..4591b4c 100644--- a/frontend/src/components/ui/alert-dialog.jsx+++ b/frontend/src/components/ui/alert-dialog.jsx@@ -32,7 +32,7 @@ function AlertDialogOverlay({<AlertDialogPrimitive.Backdropdata-slot="alert-dialog-overlay"className={cn(- "fixed inset-0 isolate z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",+ "fixed inset-0 isolate z-50 bg-[#0C0809]/40 duration-(--duration-overlay) data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",className)}{...props} />@@ -51,7 +51,7 @@ function AlertDialogContent({data-slot="alert-dialog-content"data-size={size}className={cn(- "group/alert-dialog-content fixed top-1/2 left-1/2 z-50 grid w-full -translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl bg-popover p-4 text-popover-foreground ring-1 ring-foreground/10 duration-100 outline-none data-[size=default]:max-w-xs data-[size=sm]:max-w-xs data-[size=default]:sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",+ "group/alert-dialog-content fixed top-1/2 left-1/2 z-50 grid w-full -translate-x-1/2 -translate-y-1/2 gap-5 rounded-dialog border border-line bg-popover p-8 text-popover-foreground shadow-lg duration-(--duration-overlay) outline-none data-[size=default]:max-w-xs data-[size=sm]:max-w-xs data-[size=default]:sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",className)}{...props} />@@ -82,7 +82,7 @@ function AlertDialogFooter({<divdata-slot="alert-dialog-footer"className={cn(- "-mx-4 -mb-4 flex flex-col-reverse gap-2 rounded-b-xl border-t bg-muted/50 p-4 group-data-[size=sm]/alert-dialog-content:grid group-data-[size=sm]/alert-dialog-content:grid-cols-2 sm:flex-row sm:justify-end",+ "-mx-8 -mb-8 flex flex-col-reverse gap-2 border-t border-line px-8 py-5 group-data-[size=sm]/alert-dialog-content:grid group-data-[size=sm]/alert-dialog-content:grid-cols-2 sm:flex-row sm:justify-end",className)}{...props} />@@ -97,7 +97,7 @@ function AlertDialogMedia({<divdata-slot="alert-dialog-media"className={cn(- "mb-2 inline-flex size-10 items-center justify-center rounded-md bg-muted sm:group-data-[size=default]/alert-dialog-content:row-span-2 *:[svg:not([class*='size-'])]:size-6",+ "mb-2 inline-flex size-10 items-center justify-center rounded-control bg-danger-soft text-danger sm:group-data-[size=default]/alert-dialog-content:row-span-2 *:[svg:not([class*='size-'])]:size-6",className)}{...props} />@@ -112,7 +112,7 @@ function AlertDialogTitle({<AlertDialogPrimitive.Titledata-slot="alert-dialog-title"className={cn(- "font-heading text-base font-medium sm:group-data-[size=default]/alert-dialog-content:group-has-data-[slot=alert-dialog-media]/alert-dialog-content:col-start-2",+ "font-heading text-lg font-semibold tracking-[-0.01em] sm:group-data-[size=default]/alert-dialog-content:group-has-data-[slot=alert-dialog-media]/alert-dialog-content:col-start-2",className)}{...props} />diff --git a/frontend/src/components/ui/alert.jsx b/frontend/src/components/ui/alert.jsxindex bc53c0c..becb12d 100644--- a/frontend/src/components/ui/alert.jsx+++ b/frontend/src/components/ui/alert.jsx@@ -4,13 +4,15 @@ import { cva } from "class-variance-authority";import { cn } from "@/lib/utils"const alertVariants = cva(- "group/alert relative grid w-full gap-0.5 rounded-lg border px-2.5 py-2 text-left text-sm has-data-[slot=alert-action]:relative has-data-[slot=alert-action]:pr-18 has-[>svg]:grid-cols-[auto_1fr] has-[>svg]:gap-x-2 *:[svg]:row-span-2 *:[svg]:translate-y-0.5 *:[svg]:text-current *:[svg:not([class*='size-'])]:size-4",+ "group/alert relative grid w-full gap-0.5 rounded-control border border-line px-3.5 py-3 text-left text-sm has-data-[slot=alert-action]:relative has-data-[slot=alert-action]:pr-18 has-[>svg]:grid-cols-[auto_1fr] has-[>svg]:gap-x-2 *:[svg]:row-span-2 *:[svg]:translate-y-0.5 *:[svg]:text-current *:[svg:not([class*='size-'])]:size-4",{variants: {variant: {- default: "bg-card text-card-foreground",- destructive:- "bg-card text-destructive *:data-[slot=alert-description]:text-destructive/90 *:[svg]:text-current",+ default: "bg-surface-sunken/70 text-ink *:[svg]:text-ink-muted",+ destructive: "border-danger/30 bg-danger-soft text-danger *:data-[slot=alert-description]:text-danger",+ success: "border-success/30 bg-success-soft text-success *:data-[slot=alert-description]:text-success",+ warning: "border-warning/30 bg-warning-soft text-warning *:data-[slot=alert-description]:text-warning",+ info: "border-info/30 bg-info-soft text-info *:data-[slot=alert-description]:text-info",},},defaultVariants: {diff --git a/frontend/src/components/ui/badge.jsx b/frontend/src/components/ui/badge.jsxindex d7622ba..b44caea 100644--- a/frontend/src/components/ui/badge.jsx+++ b/frontend/src/components/ui/badge.jsx@@ -5,20 +5,20 @@ import { cva } from "class-variance-authority";import { cn } from "@/lib/utils"const badgeVariants = cva(- "group/badge inline-flex h-5 w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-4xl border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-all focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3!",+ "group/badge inline-flex h-5 w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-pill border border-transparent px-2 py-0.5 text-caption font-semibold whitespace-nowrap transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3!",{variants: {variant: {- default: "bg-primary text-primary-foreground [a]:hover:bg-primary/80",- secondary:- "bg-secondary text-secondary-foreground [a]:hover:bg-secondary/80",- destructive:- "bg-destructive/10 text-destructive focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:focus-visible:ring-destructive/40 [a]:hover:bg-destructive/20",- outline:- "border-border text-foreground [a]:hover:bg-muted [a]:hover:text-muted-foreground",- ghost:- "hover:bg-muted hover:text-muted-foreground dark:hover:bg-muted/50",- link: "text-primary underline-offset-4 hover:underline",+ default: "bg-brand-soft text-brand-text",+ solid: "bg-brand text-on-brand",+ secondary: "bg-surface-sunken text-ink-muted",+ destructive: "bg-danger-soft text-danger",+ success: "bg-success-soft text-success",+ warning: "bg-warning-soft text-warning",+ info: "bg-info-soft text-info",+ outline: "border-line text-ink-muted",+ ghost: "text-ink-muted hover:bg-surface-hover",+ link: "text-brand-text underline-offset-4 hover:underline",},},defaultVariants: {diff --git a/frontend/src/components/ui/button.jsx b/frontend/src/components/ui/button.jsxindex 87c07ba..398a7eb 100644--- a/frontend/src/components/ui/button.jsx+++ b/frontend/src/components/ui/button.jsx@@ -4,33 +4,32 @@ import { cva } from "class-variance-authority";import { cn } from "@/lib/utils"const buttonVariants = cva(- "group/button inline-flex shrink-0 items-center justify-center rounded-lg border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap transition-all outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:not-aria-[haspopup]:translate-y-px disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",+ "group/button inline-flex shrink-0 items-center justify-center rounded-control border border-transparent bg-clip-padding font-medium whitespace-nowrap transition-colors duration-(--duration-fast) outline-none select-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-danger [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg]:stroke-[1.75] [&_svg:not([class*='size-'])]:size-4",{variants: {variant: {- default: "bg-primary text-primary-foreground hover:bg-primary/80",+ default: "bg-brand text-on-brand hover:bg-brand-hover active:bg-brand-hover",outline:- "border-border bg-background hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",+ "border-line-control bg-surface text-ink hover:bg-surface-hover aria-expanded:bg-surface-hover",secondary:- "bg-secondary text-secondary-foreground hover:bg-[color-mix(in_oklch,var(--secondary),var(--foreground)_5%)] aria-expanded:bg-secondary aria-expanded:text-secondary-foreground",+ "bg-surface-sunken text-ink hover:bg-surface-selected aria-expanded:bg-surface-selected",ghost:- "hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:hover:bg-muted/50",+ "text-ink-muted hover:bg-surface-hover hover:text-ink aria-expanded:bg-surface-hover aria-expanded:text-ink",destructive:- "bg-destructive/10 text-destructive hover:bg-destructive/20 focus-visible:border-destructive/40 focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:hover:bg-destructive/30 dark:focus-visible:ring-destructive/40",- link: "text-primary underline-offset-4 hover:underline",+ "bg-danger-soft text-danger hover:bg-danger hover:text-on-brand",+ link: "rounded-sm px-0! text-brand-text underline-offset-4 hover:underline",+ inverse: "bg-ink text-ink-inverse hover:bg-ink/85",},size: {default:- "h-8 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",- xs: "h-6 gap-1 rounded-[min(var(--radius-md),10px)] px-2 text-xs in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3",- sm: "h-7 gap-1 rounded-[min(var(--radius-md),12px)] px-2.5 text-[0.8rem] in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3.5",- lg: "h-9 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",- icon: "size-8",- "icon-xs":- "size-6 rounded-[min(var(--radius-md),10px)] in-data-[slot=button-group]:rounded-lg [&_svg:not([class*='size-'])]:size-3",- "icon-sm":- "size-7 rounded-[min(var(--radius-md),12px)] in-data-[slot=button-group]:rounded-lg",- "icon-lg": "size-9",+ "h-(--control-h) gap-2 px-3 text-sm has-data-[icon=inline-end]:pr-3 has-data-[icon=inline-start]:pl-3",+ xs: "h-7 gap-1 px-2.5 text-xs [&_svg:not([class*='size-'])]:size-3.5",+ sm: "h-(--control-h-sm) gap-1.5 px-2.5 text-[0.8125rem] has-data-[icon=inline-end]:pr-2.5 has-data-[icon=inline-start]:pl-2.5",+ lg: "h-(--control-h-lg) gap-2 px-4 text-sm",+ icon: "size-(--control-h)",+ "icon-xs": "size-7 [&_svg:not([class*='size-'])]:size-3.5",+ "icon-sm": "size-(--control-h-sm)",+ "icon-lg": "size-(--control-h-lg)",},},defaultVariants: {diff --git a/frontend/src/components/ui/card.jsx b/frontend/src/components/ui/card.jsxindex 6c66656..494c91d 100644--- a/frontend/src/components/ui/card.jsx+++ b/frontend/src/components/ui/card.jsx@@ -12,7 +12,7 @@ function Card({data-slot="card"data-size={size}className={cn(- "group/card flex flex-col gap-(--card-spacing) overflow-hidden rounded-xl bg-card py-(--card-spacing) text-sm text-card-foreground ring-1 ring-foreground/10 [--card-spacing:--spacing(4)] has-data-[slot=card-footer]:pb-0 has-[>img:first-child]:pt-0 data-[size=sm]:[--card-spacing:--spacing(3)] data-[size=sm]:has-data-[slot=card-footer]:pb-0 *:[img:first-child]:rounded-t-xl *:[img:last-child]:rounded-b-xl",+ "group/card flex flex-col gap-(--card-spacing) overflow-hidden rounded-card border border-line bg-card py-(--card-spacing) text-sm text-card-foreground [--card-spacing:--spacing(5)] has-data-[slot=card-footer]:pb-0 has-[>img:first-child]:pt-0 data-[size=sm]:[--card-spacing:--spacing(3)] data-[size=sm]:has-data-[slot=card-footer]:pb-0 *:[img:first-child]:rounded-t-card *:[img:last-child]:rounded-b-card",className)}{...props} />@@ -42,7 +42,7 @@ function CardTitle({<divdata-slot="card-title"className={cn(- "font-heading text-base leading-snug font-medium group-data-[size=sm]/card:text-sm",+ "font-heading text-section font-semibold group-data-[size=sm]/card:text-sm",className)}{...props} />@@ -96,7 +96,7 @@ function CardFooter({<divdata-slot="card-footer"className={cn(- "flex items-center rounded-b-xl border-t bg-muted/50 p-(--card-spacing)",+ "flex items-center rounded-b-card border-t border-line bg-surface-sunken/60 p-(--card-spacing)",className)}{...props} />diff --git a/frontend/src/components/ui/command.jsx b/frontend/src/components/ui/command.jsxindex e4cdd96..eb1f0f2 100644--- a/frontend/src/components/ui/command.jsx+++ b/frontend/src/components/ui/command.jsx@@ -25,7 +25,7 @@ function Command({<CommandPrimitivedata-slot="command"className={cn(- "flex size-full flex-col overflow-hidden rounded-xl! bg-popover p-1 text-popover-foreground",+ "flex size-full flex-col overflow-hidden bg-popover text-popover-foreground",className)}{...props} />@@ -60,9 +60,9 @@ function CommandInput({...props}) {return (- <div data-slot="command-input-wrapper" className="p-1 pb-0">+ <div data-slot="command-input-wrapper"><InputGroup- className="h-8! rounded-lg! border-input/30 bg-input/30 shadow-none! *:data-[slot=input-group-addon]:pl-2!">+ className="h-11! rounded-none! border-0! border-b! border-line! bg-transparent! shadow-none! *:data-[slot=input-group-addon]:pl-4!"><CommandPrimitive.Inputdata-slot="command-input"className={cn(@@ -86,7 +86,7 @@ function CommandList({<CommandPrimitive.Listdata-slot="command-list"className={cn(- "no-scrollbar max-h-72 scroll-py-1 overflow-x-hidden overflow-y-auto outline-none",+ "no-scrollbar max-h-[min(24rem,60dvh)] scroll-py-2 overflow-x-hidden overflow-y-auto p-2 outline-none",className)}{...props} />@@ -100,7 +100,7 @@ function CommandEmpty({return (<CommandPrimitive.Emptydata-slot="command-empty"- className={cn("py-6 text-center text-sm", className)}+ className={cn("py-10 text-center text-sm text-ink-muted", className)}{...props} />);}@@ -113,7 +113,7 @@ function CommandGroup({<CommandPrimitive.Groupdata-slot="command-group"className={cn(- "overflow-hidden p-1 text-foreground **:[[cmdk-group-heading]]:px-2 **:[[cmdk-group-heading]]:py-1.5 **:[[cmdk-group-heading]]:text-xs **:[[cmdk-group-heading]]:font-medium **:[[cmdk-group-heading]]:text-muted-foreground",+ "overflow-hidden pb-1 text-ink **:[[cmdk-group-heading]]:px-2.5 **:[[cmdk-group-heading]]:pt-2 **:[[cmdk-group-heading]]:pb-1 **:[[cmdk-group-heading]]:text-caption **:[[cmdk-group-heading]]:font-medium **:[[cmdk-group-heading]]:text-ink-faint",className)}{...props} />@@ -127,7 +127,7 @@ function CommandSeparator({return (<CommandPrimitive.Separatordata-slot="command-separator"- className={cn("-mx-1 h-px bg-border", className)}+ className={cn("-mx-2 my-1 h-px bg-divider", className)}{...props} />);}@@ -141,7 +141,7 @@ function CommandItem({<CommandPrimitive.Itemdata-slot="command-item"className={cn(- "group/command-item relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none in-data-[slot=dialog-content]:rounded-lg! data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-selected:bg-muted data-selected:text-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 data-selected:*:[svg]:text-foreground",+ "group/command-item relative flex h-9 cursor-default items-center gap-2.5 rounded-row px-2.5 text-sm text-ink-muted outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-selected:bg-surface-selected data-selected:text-ink [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg]:stroke-[1.75] [&_svg:not([class*='size-'])]:size-4",className)}{...props}>@@ -160,7 +160,7 @@ function CommandShortcut({<spandata-slot="command-shortcut"className={cn(- "ml-auto text-xs tracking-widest text-muted-foreground group-data-selected/command-item:text-foreground",+ "ml-auto font-mono text-caption text-ink-faint",className)}{...props} />diff --git a/frontend/src/components/ui/dialog.jsx b/frontend/src/components/ui/dialog.jsxindex bc425ea..dc5d252 100644--- a/frontend/src/components/ui/dialog.jsx+++ b/frontend/src/components/ui/dialog.jsx@@ -37,7 +37,7 @@ function DialogOverlay({<DialogPrimitive.Backdropdata-slot="dialog-overlay"className={cn(- "fixed inset-0 isolate z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",+ "fixed inset-0 isolate z-50 bg-[#0C0809]/40 duration-(--duration-overlay) data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",className)}{...props} />@@ -56,7 +56,7 @@ function DialogContent({<DialogPrimitive.Popupdata-slot="dialog-content"className={cn(- "fixed top-1/2 left-1/2 z-50 grid w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl bg-popover p-4 text-sm text-popover-foreground ring-1 ring-foreground/10 duration-100 outline-none sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",+ "fixed top-1/2 left-1/2 z-50 grid max-h-[calc(100dvh-2rem)] w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 gap-5 overflow-y-auto rounded-dialog border border-line bg-popover p-8 text-sm text-popover-foreground shadow-lg duration-(--duration-overlay) outline-none sm:max-w-md data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",className)}{...props}>@@ -65,7 +65,7 @@ function DialogContent({<DialogPrimitive.Closedata-slot="dialog-close"render={- <Button variant="ghost" className="absolute top-2 right-2" size="icon-sm" />+ <Button variant="ghost" className="absolute top-5 right-5" size="icon-sm" />}><XIcon /><span className="sr-only">Close</span>@@ -98,7 +98,7 @@ function DialogFooter({<divdata-slot="dialog-footer"className={cn(- "-mx-4 -mb-4 flex flex-col-reverse gap-2 rounded-b-xl border-t bg-muted/50 p-4 sm:flex-row sm:justify-end",+ "-mx-8 -mb-8 flex flex-col-reverse gap-2 border-t border-line px-8 py-5 sm:flex-row sm:justify-end",className)}{...props}>@@ -119,7 +119,7 @@ function DialogTitle({return (<DialogPrimitive.Titledata-slot="dialog-title"- className={cn("font-heading text-base leading-none font-medium", className)}+ className={cn("pr-8 font-heading text-lg leading-7 font-semibold tracking-[-0.01em]", className)}{...props} />);}diff --git a/frontend/src/components/ui/dropdown-menu.jsx b/frontend/src/components/ui/dropdown-menu.jsxindex 302da0e..5a91e44 100644--- a/frontend/src/components/ui/dropdown-menu.jsx+++ b/frontend/src/components/ui/dropdown-menu.jsx@@ -43,7 +43,7 @@ function DropdownMenuContent({<MenuPrimitive.Popupdata-slot="dropdown-menu-content"className={cn(- "z-50 max-h-(--available-height) w-(--anchor-width) min-w-32 origin-(--transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover p-1 text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 outline-none data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:overflow-hidden data-closed:fade-out-0 data-closed:zoom-out-95",+ "z-50 max-h-(--available-height) w-(--anchor-width) min-w-32 origin-(--transform-origin) overflow-x-hidden overflow-y-auto rounded-control border border-line bg-popover p-1.5 text-popover-foreground shadow-md duration-100 outline-none data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:overflow-hidden data-closed:fade-out-0 data-closed:zoom-out-95",className)}{...props} />@@ -87,7 +87,7 @@ function DropdownMenuItem({data-inset={inset}data-variant={variant}className={cn(- "group/dropdown-menu-item relative flex cursor-default items-center gap-1.5 rounded-md px-1.5 py-1 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-inset:pl-7 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 data-[variant=destructive]:*:[svg]:text-destructive",+ "group/dropdown-menu-item relative flex cursor-default items-center gap-1.5 rounded-row px-2 py-1.5 text-sm outline-hidden select-none focus:bg-surface-selected focus:text-ink data-inset:pl-7 data-[variant=destructive]:text-danger data-[variant=destructive]:focus:bg-danger-soft data-[variant=destructive]:focus:text-danger data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 data-[variant=destructive]:*:[svg]:text-destructive",className)}{...props} />@@ -111,7 +111,7 @@ function DropdownMenuSubTrigger({data-slot="dropdown-menu-sub-trigger"data-inset={inset}className={cn(- "flex cursor-default items-center gap-1.5 rounded-md px-1.5 py-1 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-inset:pl-7 data-popup-open:bg-accent data-popup-open:text-accent-foreground data-open:bg-accent data-open:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",+ "flex cursor-default items-center gap-1.5 rounded-row px-2 py-1.5 text-sm outline-hidden select-none focus:bg-surface-selected focus:text-ink data-inset:pl-7 data-popup-open:bg-surface-selected data-open:bg-surface-selected [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",className)}{...props}>@@ -133,7 +133,7 @@ function DropdownMenuSubContent({<DropdownMenuContentdata-slot="dropdown-menu-sub-content"className={cn(- "w-auto min-w-[96px] rounded-lg bg-popover p-1 text-popover-foreground shadow-lg ring-1 ring-foreground/10 duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",+ "w-auto min-w-[96px] rounded-control border border-line bg-popover p-1.5 text-popover-foreground shadow-md duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",className)}align={align}@@ -156,7 +156,7 @@ function DropdownMenuCheckboxItem({data-slot="dropdown-menu-checkbox-item"data-inset={inset}className={cn(- "relative flex cursor-default items-center gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground focus:**:text-accent-foreground data-inset:pl-7 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",+ "relative flex cursor-default items-center gap-1.5 rounded-row py-1.5 pr-8 pl-2 text-sm outline-hidden select-none focus:bg-surface-selected focus:text-ink focus:**:text-accent-foreground data-inset:pl-7 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",className)}checked={checked}@@ -190,7 +190,7 @@ function DropdownMenuRadioItem({data-slot="dropdown-menu-radio-item"data-inset={inset}className={cn(- "relative flex cursor-default items-center gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground focus:**:text-accent-foreground data-inset:pl-7 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",+ "relative flex cursor-default items-center gap-1.5 rounded-row py-1.5 pr-8 pl-2 text-sm outline-hidden select-none focus:bg-surface-selected focus:text-ink focus:**:text-accent-foreground data-inset:pl-7 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",className)}{...props}>diff --git a/frontend/src/components/ui/input.jsx b/frontend/src/components/ui/input.jsxindex d6ff8e4..8319e90 100644--- a/frontend/src/components/ui/input.jsx+++ b/frontend/src/components/ui/input.jsx@@ -13,7 +13,7 @@ function Input({type={type}data-slot="input"className={cn(- "h-8 w-full min-w-0 rounded-lg border border-input bg-transparent px-2.5 py-1 text-base transition-colors outline-none file:inline-flex file:h-6 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40",+ "h-(--control-h) w-full min-w-0 rounded-field border border-input bg-surface-raised px-3 py-1 text-base text-ink transition-colors duration-(--duration-fast) outline-none file:inline-flex file:h-6 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-ink placeholder:text-ink-faint hover:border-ink-muted focus-visible:border-ring focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-surface-sunken disabled:opacity-60 aria-invalid:border-danger md:text-sm",className)}{...props} />diff --git a/frontend/src/components/ui/popover.jsx b/frontend/src/components/ui/popover.jsxindex 38ed86d..1752d87 100644--- a/frontend/src/components/ui/popover.jsx+++ b/frontend/src/components/ui/popover.jsx@@ -36,7 +36,7 @@ function PopoverContent({<PopoverPrimitive.Popupdata-slot="popover-content"className={cn(- "z-50 flex w-72 origin-(--transform-origin) flex-col gap-2.5 rounded-lg bg-popover p-2.5 text-sm text-popover-foreground shadow-md ring-1 ring-foreground/10 outline-hidden duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",+ "z-50 flex w-72 origin-(--transform-origin) flex-col gap-2.5 rounded-control border border-line bg-popover p-3 text-sm text-popover-foreground shadow-md outline-hidden duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",className)}{...props} />diff --git a/frontend/src/components/ui/progress.jsx b/frontend/src/components/ui/progress.jsxindex d43495b..d9833cd 100644--- a/frontend/src/components/ui/progress.jsx+++ b/frontend/src/components/ui/progress.jsx@@ -29,7 +29,7 @@ function ProgressTrack({return (<ProgressPrimitive.TrackclassName={cn(- "relative flex h-1 w-full items-center overflow-x-hidden rounded-full bg-muted",+ "relative flex h-1 w-full items-center overflow-x-hidden rounded-full bg-surface-sunken",className)}data-slot="progress-track"@@ -44,7 +44,7 @@ function ProgressIndicator({return (<ProgressPrimitive.Indicatordata-slot="progress-indicator"- className={cn("h-full bg-primary transition-all", className)}+ className={cn("h-full bg-brand transition-all duration-(--duration-slow)", className)}{...props} />);}diff --git a/frontend/src/components/ui/select.jsx b/frontend/src/components/ui/select.jsxindex ea68942..83f286e 100644--- a/frontend/src/components/ui/select.jsx+++ b/frontend/src/components/ui/select.jsx@@ -41,7 +41,7 @@ function SelectTrigger({data-slot="select-trigger"data-size={size}className={cn(- "flex w-fit items-center justify-between gap-1.5 rounded-lg border border-input bg-transparent py-2 pr-2 pl-2.5 text-sm whitespace-nowrap transition-colors outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-placeholder:text-muted-foreground data-[size=default]:h-8 data-[size=sm]:h-7 data-[size=sm]:rounded-[min(var(--radius-md),10px)] *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-1.5 dark:bg-input/30 dark:hover:bg-input/50 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",+ "flex w-fit items-center justify-between gap-1.5 rounded-field border border-input bg-surface-raised py-2 pr-2.5 pl-3 text-sm whitespace-nowrap text-ink transition-colors duration-(--duration-fast) outline-none select-none hover:border-ink-muted focus-visible:border-ring focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-danger data-placeholder:text-ink-faint data-[size=default]:h-(--control-h) data-[size=sm]:h-(--control-h-sm) *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-1.5 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",className)}{...props}>@@ -77,7 +77,7 @@ function SelectContent({data-slot="select-content"data-align-trigger={alignItemWithTrigger}className={cn(- "relative isolate z-50 max-h-(--available-height) w-(--anchor-width) min-w-36 origin-(--transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 data-[align-trigger=true]:animate-none data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",+ "relative isolate z-50 max-h-(--available-height) w-(--anchor-width) min-w-36 origin-(--transform-origin) overflow-x-hidden overflow-y-auto rounded-control border border-line bg-popover p-1 text-popover-foreground shadow-md duration-100 data-[align-trigger=true]:animate-none data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",className)}{...props}>@@ -111,7 +111,7 @@ function SelectItem({<SelectPrimitive.Itemdata-slot="select-item"className={cn(- "relative flex w-full cursor-default items-center gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",+ "relative flex w-full cursor-default items-center gap-1.5 rounded-row py-1.5 pr-8 pl-2 text-sm outline-hidden select-none focus:bg-surface-selected focus:text-ink data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",className)}{...props}>diff --git a/frontend/src/components/ui/sidebar.jsx b/frontend/src/components/ui/sidebar.jsxindex 9fcac6b..eef65c6 100644--- a/frontend/src/components/ui/sidebar.jsx+++ b/frontend/src/components/ui/sidebar.jsx@@ -28,7 +28,7 @@ const SIDEBAR_COOKIE_NAME = "sidebar_state"const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7const SIDEBAR_WIDTH = "16rem"const SIDEBAR_WIDTH_MOBILE = "18rem"-const SIDEBAR_WIDTH_ICON = "3rem"+const SIDEBAR_WIDTH_ICON = "3.5rem"const SIDEBAR_KEYBOARD_SHORTCUT = "b"const SidebarContext = React.createContext(null)@@ -376,7 +376,7 @@ function SidebarGroupLabel({defaultTagName: "div",props: mergeProps({className: cn(- "flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium text-sidebar-foreground/70 ring-sidebar-ring outline-hidden transition-[margin,opacity] duration-200 ease-linear group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0 focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",+ "flex h-8 shrink-0 items-center rounded-row px-2 text-sm font-medium text-ink-muted ring-sidebar-ring outline-hidden transition-[margin,opacity] duration-200 ease-linear group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0 focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",className),}, props),@@ -449,18 +449,18 @@ function SidebarMenuItem({}const sidebarMenuButtonVariants = cva(- "peer/menu-button group/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm ring-sidebar-ring outline-hidden transition-[width,height,padding] group-has-data-[sidebar=menu-action]/menu-item:pr-8 group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-2! hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-open:hover:bg-sidebar-accent data-open:hover:text-sidebar-accent-foreground data-active:bg-sidebar-accent data-active:font-medium data-active:text-sidebar-accent-foreground [&_svg]:size-4 [&_svg]:shrink-0 [&>span:last-child]:truncate",+ "peer/menu-button group/menu-button flex w-full items-center gap-2 overflow-hidden rounded-row px-2 text-left text-sm font-medium text-ink-muted outline-hidden transition-[width,height,padding,color,background-color] duration-(--duration-base) ease-(--ease-standard) group-has-data-[sidebar=menu-action]/menu-item:pr-8 group-data-[collapsible=icon]:size-9! group-data-[collapsible=icon]:justify-center group-data-[collapsible=icon]:p-0! hover:bg-surface-hover hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-[-2px] focus-visible:outline-ring active:bg-surface-selected disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-open:hover:bg-surface-hover data-active:bg-surface-selected data-active:text-ink [&_svg]:size-[18px] [&_svg]:shrink-0 [&_svg]:stroke-[1.75] [&>span:last-child]:truncate",{variants: {variant: {- default: "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",+ default: "",outline:"bg-background shadow-[0_0_0_1px_var(--sidebar-border)] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_var(--sidebar-accent)]",},size: {- default: "h-8 text-sm",- sm: "h-7 text-xs",- lg: "h-12 text-sm group-data-[collapsible=icon]:p-0!",+ default: "h-(--nav-row-h) text-sm",+ sm: "h-7 text-caption",+ lg: "h-11 text-sm group-data-[collapsible=icon]:p-0!",},},defaultVariants: {diff --git a/frontend/src/components/ui/skeleton.jsx b/frontend/src/components/ui/skeleton.jsxindex 38345a7..bb70114 100644--- a/frontend/src/components/ui/skeleton.jsx+++ b/frontend/src/components/ui/skeleton.jsx@@ -7,7 +7,7 @@ function Skeleton({return (<divdata-slot="skeleton"- className={cn("animate-pulse rounded-md bg-muted", className)}+ className={cn("animate-pulse rounded-control bg-surface-sunken", className)}{...props} />);}diff --git a/frontend/src/components/ui/sonner.jsx b/frontend/src/components/ui/sonner.jsxindex a23efa0..0ceecbc 100644--- a/frontend/src/components/ui/sonner.jsx+++ b/frontend/src/components/ui/sonner.jsx@@ -35,12 +35,24 @@ const Toaster = ({"--normal-bg": "var(--popover)","--normal-text": "var(--popover-foreground)","--normal-border": "var(--border)",- "--border-radius": "var(--radius)"+ "--border-radius": "var(--radius-field)",+ "--success-bg": "var(--success-soft)",+ "--success-text": "var(--success)",+ "--success-border": "color-mix(in oklab, var(--success) 30%, transparent)",+ "--error-bg": "var(--danger-soft)",+ "--error-text": "var(--danger)",+ "--error-border": "color-mix(in oklab, var(--danger) 30%, transparent)",+ "--warning-bg": "var(--warning-soft)",+ "--warning-text": "var(--warning)",+ "--warning-border": "color-mix(in oklab, var(--warning) 30%, transparent)",+ "--info-bg": "var(--info-soft)",+ "--info-text": "var(--info)",+ "--info-border": "color-mix(in oklab, var(--info) 30%, transparent)"}}toastOptions={{classNames: {- toast: "cn-toast",+ toast: "cn-toast font-sans",},}}{...props} />diff --git a/frontend/src/components/ui/table.jsx b/frontend/src/components/ui/table.jsxindex 5128be4..8074002 100644--- a/frontend/src/components/ui/table.jsx+++ b/frontend/src/components/ui/table.jsx@@ -23,7 +23,7 @@ function TableHeader({return (<theaddata-slot="table-header"- className={cn("[&_tr]:border-b", className)}+ className={cn("[&_tr]:border-b [&_tr]:border-line [&_tr]:hover:bg-transparent", className)}{...props} />);}@@ -47,7 +47,7 @@ function TableFooter({return (<tfootdata-slot="table-footer"- className={cn("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0", className)}+ className={cn("border-t border-line bg-surface-sunken/60 font-medium [&>tr]:last:border-b-0", className)}{...props} />);}@@ -60,7 +60,7 @@ function TableRow({<trdata-slot="table-row"className={cn(- "border-b transition-colors hover:bg-muted/50 has-aria-expanded:bg-muted/50 data-[state=selected]:bg-muted",+ "border-b border-divider transition-colors duration-(--duration-fast) hover:bg-surface-hover has-aria-expanded:bg-surface-hover data-[state=selected]:bg-surface-selected",className)}{...props} />@@ -75,7 +75,7 @@ function TableHead({<thdata-slot="table-head"className={cn(- "h-10 px-2 text-left align-middle font-medium whitespace-nowrap text-foreground [&:has([role=checkbox])]:pr-0",+ "h-10 px-3 text-left align-middle text-caption font-medium whitespace-nowrap text-ink-muted [&:has([role=checkbox])]:pr-0",className)}{...props} />@@ -90,7 +90,7 @@ function TableCell({<tddata-slot="table-cell"className={cn(- "p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0",+ "px-3 py-2.5 align-middle whitespace-nowrap tabular-nums [&:has([role=checkbox])]:pr-0",className)}{...props} />diff --git a/frontend/src/components/ui/tabs.jsx b/frontend/src/components/ui/tabs.jsxindex 266ddd8..678c2e8 100644--- a/frontend/src/components/ui/tabs.jsx+++ b/frontend/src/components/ui/tabs.jsx@@ -20,12 +20,12 @@ function Tabs({}const tabsListVariants = cva(- "group/tabs-list inline-flex w-fit items-center justify-center rounded-lg p-[3px] text-muted-foreground group-data-horizontal/tabs:h-8 group-data-vertical/tabs:h-fit group-data-vertical/tabs:flex-col data-[variant=line]:rounded-none",+ "group/tabs-list inline-flex w-fit items-center justify-start text-ink-muted group-data-vertical/tabs:h-fit group-data-vertical/tabs:flex-col",{variants: {variant: {- default: "bg-muted",- line: "gap-1 bg-transparent",+ default: "h-[2.625rem] gap-4 border-b border-line bg-transparent",+ segmented: "h-(--control-h) gap-0.5 rounded-control bg-surface-sunken p-1",},},defaultVariants: {@@ -56,10 +56,9 @@ function TabsTrigger({<TabsPrimitive.Tabdata-slot="tabs-trigger"className={cn(- "relative inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-1.5 py-0.5 text-sm font-medium whitespace-nowrap text-foreground/60 transition-all group-data-vertical/tabs:w-full group-data-vertical/tabs:justify-start hover:text-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-1 focus-visible:outline-ring disabled:pointer-events-none disabled:opacity-50 has-data-[icon=inline-end]:pr-1 has-data-[icon=inline-start]:pl-1 aria-disabled:pointer-events-none aria-disabled:opacity-50 dark:text-muted-foreground dark:hover:text-foreground group-data-[variant=default]/tabs-list:data-active:shadow-sm group-data-[variant=line]/tabs-list:data-active:shadow-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",- "group-data-[variant=line]/tabs-list:bg-transparent group-data-[variant=line]/tabs-list:data-active:bg-transparent dark:group-data-[variant=line]/tabs-list:data-active:border-transparent dark:group-data-[variant=line]/tabs-list:data-active:bg-transparent",- "data-active:bg-background data-active:text-foreground dark:data-active:border-input dark:data-active:bg-input/30 dark:data-active:text-foreground",- "after:absolute after:bg-foreground after:opacity-0 after:transition-opacity group-data-horizontal/tabs:after:inset-x-0 group-data-horizontal/tabs:after:bottom-[-5px] group-data-horizontal/tabs:after:h-0.5 group-data-vertical/tabs:after:inset-y-0 group-data-vertical/tabs:after:-right-1 group-data-vertical/tabs:after:w-0.5 group-data-[variant=line]/tabs-list:data-active:after:opacity-100",+ "relative inline-flex items-center justify-center gap-1.5 text-sm font-medium whitespace-nowrap text-ink-muted transition-colors duration-(--duration-fast) outline-none hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-active:text-ink [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg]:stroke-[1.75] [&_svg:not([class*='size-'])]:size-4 group-data-vertical/tabs:w-full group-data-vertical/tabs:justify-start",+ "group-data-[variant=default]/tabs-list:h-full group-data-[variant=default]/tabs-list:px-0.5 after:absolute after:inset-x-0 after:-bottom-px after:h-0.5 after:rounded-full after:bg-brand after:opacity-0 after:transition-opacity group-data-[variant=default]/tabs-list:data-active:after:opacity-100",+ "group-data-[variant=segmented]/tabs-list:h-full group-data-[variant=segmented]/tabs-list:flex-1 group-data-[variant=segmented]/tabs-list:rounded-[8px] group-data-[variant=segmented]/tabs-list:px-3 group-data-[variant=segmented]/tabs-list:data-active:bg-surface-raised group-data-[variant=segmented]/tabs-list:data-active:shadow-sm",className)}{...props} />diff --git a/frontend/src/components/ui/textarea.jsx b/frontend/src/components/ui/textarea.jsxindex decf453..27982bb 100644--- a/frontend/src/components/ui/textarea.jsx+++ b/frontend/src/components/ui/textarea.jsx@@ -10,7 +10,7 @@ function Textarea({<textareadata-slot="textarea"className={cn(- "flex field-sizing-content min-h-16 w-full rounded-lg border border-input bg-transparent px-2.5 py-2 text-base transition-colors outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40",+ "flex field-sizing-content min-h-16 w-full rounded-field border border-input bg-surface-raised px-3 py-2 text-base text-ink transition-colors duration-(--duration-fast) outline-none placeholder:text-ink-faint hover:border-ink-muted focus-visible:border-ring focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring disabled:cursor-not-allowed disabled:bg-surface-sunken disabled:opacity-60 aria-invalid:border-danger md:text-sm",className)}{...props} />diff --git a/frontend/src/components/ui/tooltip.jsx b/frontend/src/components/ui/tooltip.jsxindex aa98ff6..863fd9e 100644--- a/frontend/src/components/ui/tooltip.jsx+++ b/frontend/src/components/ui/tooltip.jsx@@ -43,13 +43,13 @@ function TooltipContent({<TooltipPrimitive.Popupdata-slot="tooltip-content"className={cn(- "z-50 inline-flex w-fit max-w-xs origin-(--transform-origin) items-center gap-1.5 rounded-md bg-foreground px-3 py-1.5 text-xs text-background has-data-[slot=kbd]:pr-1.5 data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 **:data-[slot=kbd]:relative **:data-[slot=kbd]:isolate **:data-[slot=kbd]:z-50 **:data-[slot=kbd]:rounded-sm data-[state=delayed-open]:animate-in data-[state=delayed-open]:fade-in-0 data-[state=delayed-open]:zoom-in-95 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",+ "z-50 inline-flex w-fit max-w-xs origin-(--transform-origin) items-center gap-1.5 rounded-md bg-ink px-2.5 py-1.5 text-caption font-medium text-ink-inverse shadow-md has-data-[slot=kbd]:pr-1.5 data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 **:data-[slot=kbd]:relative **:data-[slot=kbd]:isolate **:data-[slot=kbd]:z-50 **:data-[slot=kbd]:rounded-sm data-[state=delayed-open]:animate-in data-[state=delayed-open]:fade-in-0 data-[state=delayed-open]:zoom-in-95 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",className)}{...props}>{children}<TooltipPrimitive.Arrow- className="z-50 size-2.5 translate-y-[calc(-50%-2px)] rotate-45 rounded-[2px] bg-foreground fill-foreground data-[side=bottom]:top-1 data-[side=inline-end]:top-1/2! data-[side=inline-end]:-left-1 data-[side=inline-end]:-translate-y-1/2 data-[side=inline-start]:top-1/2! data-[side=inline-start]:-right-1 data-[side=inline-start]:-translate-y-1/2 data-[side=left]:top-1/2! data-[side=left]:-right-1 data-[side=left]:-translate-y-1/2 data-[side=right]:top-1/2! data-[side=right]:-left-1 data-[side=right]:-translate-y-1/2 data-[side=top]:-bottom-2.5" />+ className="z-50 size-2.5 translate-y-[calc(-50%-2px)] rotate-45 rounded-[2px] bg-ink fill-ink data-[side=bottom]:top-1 data-[side=inline-end]:top-1/2! data-[side=inline-end]:-left-1 data-[side=inline-end]:-translate-y-1/2 data-[side=inline-start]:top-1/2! data-[side=inline-start]:-right-1 data-[side=inline-start]:-translate-y-1/2 data-[side=left]:top-1/2! data-[side=left]:-right-1 data-[side=left]:-translate-y-1/2 data-[side=right]:top-1/2! data-[side=right]:-left-1 data-[side=right]:-translate-y-1/2 data-[side=top]:-bottom-2.5" /></TooltipPrimitive.Popup></TooltipPrimitive.Positioner></TooltipPrimitive.Portal>diff --git a/frontend/src/context/AppContext.jsx b/frontend/src/context/AppContext.jsxindex 7e093da..ba6460b 100644--- a/frontend/src/context/AppContext.jsx+++ b/frontend/src/context/AppContext.jsx@@ -21,7 +21,7 @@ export function AppProvider({ children }) {const data = await api.getAccounts();setAccounts(data.map(normalizeAccount));} catch (err) {- showToast('Failed to load accounts: ' + err.message, 'error');+ showToast(`Couldn't load your accounts. ${err.message}`, 'error');}}, [showToast]);@@ -30,9 +30,9 @@ export function AppProvider({ children }) {try {const res = await api.refreshAll();setAccounts((res.accounts || []).map(normalizeAccount));- showToast('All accounts refreshed!');+ showToast('All accounts refreshed');} catch (err) {- showToast(err.message, 'error');+ showToast(`Refresh failed. ${err.message}`, 'error');} finally {setLoading(false);}diff --git a/frontend/src/features/accounts/AccountManager.jsx b/frontend/src/features/accounts/AccountManager.jsxindex 3881fce..cba5f7f 100644--- a/frontend/src/features/accounts/AccountManager.jsx+++ b/frontend/src/features/accounts/AccountManager.jsx@@ -1,58 +1,92 @@-import React, { useState, useEffect } from 'react';+import React, { useEffect, useState } from 'react';+import { Link, useSearchParams } from 'react-router-dom';+import {+ Plus, Trash2, RefreshCw, Search, Users, CheckCircle2, Link2, Info, ExternalLink, Lock, ArrowLeft, ArrowUpRight,+} from 'lucide-react';import { Button } from '@/components/ui/button';import { Input } from '@/components/ui/input';import { Badge } from '@/components/ui/badge';-import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';import { Alert, AlertDescription } from '@/components/ui/alert';-import {- Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter,-} from '@/components/ui/dialog';-import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';-import {- Plus, Trash2, RefreshCw, Search, Users, CheckCircle2,- Tv, Camera, Link2, Info, ExternalLink, MessageSquare, Lock,-} from 'lucide-react';-import MainCard from '../../components/MainCard';+import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '@/components/ui/dialog';+import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';+import { Spinner } from '@/components/ui/spinner';+import PageHeader from '@/components/PageHeader';+import SurfaceBox from '@/components/SurfaceBox';+import SectionHeader from '@/components/SectionHeader';+import ChoiceCard from '@/components/ChoiceCard';+import ConfirmDialog from '@/components/ConfirmDialog';+import { FieldRow } from '@/components/DetailPanel';+import { EmptyState } from '@/components/StateViews';+import { AccountAvatar, PlatformIcon } from '@/components/platform';+import { YouTubeIcon, InstagramIcon, RedditIcon } from '@/components/brand/platform-icons';+import { PLATFORM_META, accountHandle, accountName, accountPath, groupByPlatform, platformSummary } from '@/lib/accounts';import { useAppContext } from '../../context/AppContext';import { api } from '../../services/api';import { fmtNum, timeAgo } from '../../utils/formatters';import { cn } from '@/lib/utils';+const PLATFORM_CHOICES = [+ { value: 'youtube', title: 'YouTube channel', description: 'Paste a channel link, @handle or channel ID.', icon: <YouTubeIcon /> },+ { value: 'instagram', title: 'Instagram account', description: 'Sign in with Instagram. Business or Creator accounts only.', icon: <InstagramIcon /> },+ { value: 'reddit', title: 'Reddit account', description: 'Add a username and a session cookie from your browser.', icon: <RedditIcon /> },+];++const IG_ERRORS = {+ already_added: 'This Instagram account is already connected.',+ cancelled: 'Instagram sign-in was cancelled. Try again when you are ready.',+ access_denied: 'Instagram did not grant access. Approve every requested permission and try again.',+ invalid_state: 'The Instagram sign-in link expired. Start the connection again.',+};++const METRICS = {+ youtube: acct => [['Subscribers', acct.subscriberCount], ['Views', acct.viewCount], ['Videos', acct.videoCount]],+ instagram: acct => [['Followers', acct.followersCount], ['Following', acct.followsCount], ['Posts', acct.mediaCount]],+ reddit: acct => [['Karma', acct.totalKarma], ['Post karma', acct.postKarma], ['Comment karma', acct.commentKarma]],+};+export default function AccountManager() {const { accounts, showToast, loadAccounts } = useAppContext();- const [dialogOpen, setDialogOpen] = useState(false);- const [dialogTab, setDialogTab] = useState('youtube');- const [input, setInput] = useState('');- const [resolving, setResolving] = useState(false);- const [resolved, setResolved] = useState(null);- const [adding, setAdding] = useState(false);- const [connecting, setConnecting] = useState(false);+ const [searchParams, setSearchParams] = useSearchParams();++ const [dialogOpen, setDialogOpen] = useState(false);+ const [platform, setPlatform] = useState(null);+ const [input, setInput] = useState('');+ const [resolving, setResolving] = useState(false);+ const [resolved, setResolved] = useState(null);+ const [adding, setAdding] = useState(false);+ const [connecting, setConnecting] = useState(false);const [redditUsername, setRedditUsername] = useState('');- const [redditCookie, setRedditCookie] = useState('');- const [addingReddit, setAddingReddit] = useState(false);- const [refreshingId, setRefreshingId] = useState(null);+ const [redditCookie, setRedditCookie] = useState('');+ const [addingReddit, setAddingReddit] = useState(false);+ const [refreshingId, setRefreshingId] = useState(null);+ const [pendingDelete, setPendingDelete] = useState(null);+ const [deleting, setDeleting] = useState(false);- // Handle Instagram OAuth redirect result (?ig_connected=true or ?ig_error=...)+ // Instagram OAuth returns here with ?ig_connected=true or ?ig_error=...; ?add=1 opens the add flowuseEffect(() => {- const params = new URLSearchParams(window.location.search);- const connected = params.get('ig_connected');- const igError = params.get('ig_error');+ const connected = searchParams.get('ig_connected');+ const igError = searchParams.get('ig_error');+ const add = searchParams.get('add');+ if (!connected && !igError && !add) return;if (connected === 'true') {- showToast('Instagram account connected successfully!');- window.history.replaceState({}, '', window.location.pathname);+ showToast('Instagram account connected');loadAccounts();} else if (igError) {- const msg =- igError === 'already_added' ? 'This Instagram account is already connected' :- igError === 'cancelled' ? 'Instagram authorization was cancelled' :- igError === 'access_denied' ? 'Instagram authorization was denied' :- igError === 'invalid_state' ? 'Authorization expired - please try again' :- 'Instagram connection failed: ' + igError;- showToast(msg, 'error');- window.history.replaceState({}, '', window.location.pathname);+ showToast(IG_ERRORS[igError] || `Instagram connection failed: ${igError}`, 'error');}- }, []);+ if (add) setDialogOpen(true);+ setSearchParams({}, { replace: true });+ }, [searchParams, setSearchParams, showToast, loadAccounts]);++ const closeDialog = () => {+ setDialogOpen(false);+ setPlatform(null);+ setResolved(null);+ setInput('');+ setRedditUsername('');+ setRedditCookie('');+ };const handleResolve = async () => {if (!input.trim()) return;@@ -62,7 +96,7 @@ export default function AccountManager() {const res = await api.resolveChannel(input.trim());setResolved(res.data || res);} catch (err) {- showToast('Could not resolve channel: ' + err.message, 'error');+ showToast(`Couldn't find that channel. ${err.message}`, 'error');} finally {setResolving(false);}@@ -73,11 +107,11 @@ export default function AccountManager() {setAdding(true);try {await api.addAccount(input.trim());- showToast('Channel added successfully!');+ showToast('YouTube channel added');closeDialog();loadAccounts();} catch (err) {- showToast('Failed to add account: ' + err.message, 'error');+ showToast(`Couldn't add the channel. ${err.message}`, 'error');} finally {setAdding(false);}@@ -87,32 +121,52 @@ export default function AccountManager() {setConnecting(true);try {const { url } = await api.getInstagramAuthUrl();- // Navigate the same tab - Instagram will redirect back to /accounts?ig_connected=true+ // Same tab: Instagram redirects back to /accounts?ig_connected=truewindow.location.href = url;} catch (err) {- showToast('Failed to start Instagram login: ' + err.message, 'error');+ showToast(`Couldn't start Instagram sign-in. ${err.message}`, 'error');setConnecting(false);}};- const handleDelete = async (id) => {+ const handleAddReddit = async () => {+ if (!redditUsername.trim() || !redditCookie.trim()) return;+ setAddingReddit(true);try {- await api.deleteAccount(id);- showToast('Account removed');+ await api.addRedditAccount(redditUsername.trim(), redditCookie.trim());+ showToast('Reddit account added');+ closeDialog();loadAccounts();} catch (err) {- showToast('Failed to delete: ' + err.message, 'error');+ showToast(`Couldn't add the Reddit account. ${err.message}`, 'error');+ } finally {+ setAddingReddit(false);}};- const handleRefreshOne = async (id) => {+ const handleDelete = async () => {+ if (!pendingDelete) return;+ setDeleting(true);+ try {+ await api.deleteAccount(pendingDelete.id);+ showToast(`${accountName(pendingDelete)} removed`);+ setPendingDelete(null);+ loadAccounts();+ } catch (err) {+ showToast(`Couldn't remove the account. ${err.message}`, 'error');+ } finally {+ setDeleting(false);+ }+ };++ const handleRefreshOne = async id => {setRefreshingId(id);try {await api.refreshAccount(id);showToast('Account refreshed');loadAccounts();} catch (err) {- showToast('Refresh failed: ' + err.message, 'error');+ showToast(`Refresh failed. ${err.message}`, 'error');} finally {setRefreshingId(null);}@@ -125,388 +179,296 @@ export default function AccountManager() {showToast('All accounts refreshed');loadAccounts();} catch (err) {- showToast('Refresh all failed: ' + err.message, 'error');+ showToast(`Refresh failed. ${err.message}`, 'error');} finally {setRefreshingId(null);}};- const handleAddReddit = async () => {- if (!redditUsername.trim() || !redditCookie.trim()) return;- setAddingReddit(true);- try {- await api.addRedditAccount(redditUsername.trim(), redditCookie.trim());- showToast('Reddit account added');- closeDialog();- loadAccounts();- } catch (err) {- showToast('Failed to add Reddit account: ' + err.message, 'error');- } finally {- setAddingReddit(false);- }- };-- const closeDialog = () => {- setDialogOpen(false);- setResolved(null);- setInput('');- setRedditUsername('');- setRedditCookie('');- };-- const ytAccounts = accounts.filter(a => !['instagram', 'reddit'].includes(a.platform));- const igAccounts = accounts.filter(a => a.platform === 'instagram');- const redditAccounts = accounts.filter(a => a.platform === 'reddit');+ const groups = groupByPlatform(accounts);+ const sections = [+ { key: 'youtube', title: 'YouTube channels' },+ { key: 'instagram', title: 'Instagram accounts' },+ { key: 'reddit', title: 'Reddit accounts' },+ ].filter(s => groups[s.key].length > 0);return (- <div className="space-y-6">- {/* Header */}- <div className="flex items-center justify-between gap-4 flex-wrap">- <div>- <h1 className="text-2xl font-bold tracking-tight">Manage Accounts</h1>- <p className="text-sm 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(' · ') || 'No accounts added yet'}- </p>- </div>- <div className="flex gap-2">- <Button variant="outline" size="sm" onClick={handleRefreshAll} disabled={refreshingId === 'all'} className="gap-2">- <RefreshCw className={cn('h-3.5 w-3.5', refreshingId === 'all' && 'animate-spin')} />- {refreshingId === 'all' ? 'Refreshing...' : 'Refresh All'}- </Button>- <Button size="sm" onClick={() => setDialogOpen(true)} className="gap-2">- <Plus className="h-3.5 w-3.5" />- Add Account- </Button>- </div>- </div>+ <div className="flex flex-col gap-8">+ <PageHeader+ title="Accounts"+ description={accounts.length > 0 ? platformSummary(accounts) : 'No accounts added yet'}+ actions={+ <>+ {accounts.length > 0 && (+ <Button variant="outline" onClick={handleRefreshAll} disabled={refreshingId === 'all'}>+ <RefreshCw data-icon="inline-start" className={cn(refreshingId === 'all' && 'animate-spin')} />+ {refreshingId === 'all' ? 'Refreshing' : 'Refresh all'}+ </Button>+ )}+ <Button onClick={() => setDialogOpen(true)}>+ <Plus data-icon="inline-start" />+ Add account+ </Button>+ </>+ }+ />{accounts.length === 0 ? (- <MainCard>- <div className="flex flex-col items-center text-center py-12 gap-4">- <div className="h-14 w-14 rounded-full bg-primary/10 flex items-center justify-center">- <Users className="h-7 w-7 text-primary" />- </div>- <div>- <h3 className="text-lg font-semibold">No Accounts Added</h3>- <p className="text-sm text-muted-foreground mt-1 max-w-sm">- Add a YouTube channel or connect an Instagram account to start tracking analytics.- </p>- </div>- <Button onClick={() => setDialogOpen(true)} className="gap-2">- <Plus className="h-4 w-4" /> Add Your First Account- </Button>+ <div className="flex flex-col gap-4">+ <SectionHeader title="Choose what to connect" />+ <div role="list" className="grid grid-cols-1 gap-x-3 gap-y-5 md:grid-cols-3">+ {PLATFORM_CHOICES.map(choice => (+ <div role="listitem" key={choice.value}>+ <ChoiceCard+ icon={choice.icon}+ title={choice.title}+ description={choice.description}+ onSelect={() => { setPlatform(choice.value); setDialogOpen(true); }}+ className="h-full"+ />+ </div>+ ))}</div>- </MainCard>+ </div>) : (- <div className="space-y-8">- {/* YouTube */}- {ytAccounts.length > 0 && (- <div>- <div className="flex items-center gap-2 mb-3">- <Tv className="h-5 w-5 text-red-500" />- <h2 className="text-base font-semibold">YouTube Channels</h2>- <Badge variant="outline" className="border-red-200 bg-red-50 text-red-600 text-xs">{ytAccounts.length}</Badge>- </div>- <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-4">- {ytAccounts.map(acct => (- <AccountCard- key={acct.id}- acct={acct}- platform="youtube"- metrics={[- { label: 'Subscribers', value: fmtNum(acct.subscriberCount), className: 'bg-red-50 text-red-700' },- { label: 'Views', value: fmtNum(acct.viewCount), className: 'bg-blue-50 text-blue-700' },- { label: 'Videos', value: fmtNum(acct.videoCount), className: 'bg-green-50 text-green-700' },- ]}- refreshingId={refreshingId}- onRefresh={handleRefreshOne}- onDelete={handleDelete}- />- ))}- </div>+ sections.map(section => (+ <section key={section.key} className="flex flex-col gap-3">+ <SectionHeader+ title={+ <span className="flex items-center gap-2">+ <PlatformIcon platform={section.key} className="size-4 text-ink-muted" />+ {section.title}+ <Badge variant="secondary">{groups[section.key].length}</Badge>+ </span>+ }+ />+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-3">+ {groups[section.key].map(acct => (+ <AccountCard+ key={acct.id}+ acct={acct}+ platform={section.key}+ refreshing={refreshingId === acct.id}+ onRefresh={() => handleRefreshOne(acct.id)}+ onDelete={() => setPendingDelete(acct)}+ />+ ))}</div>- )}-- {/* Instagram */}- {igAccounts.length > 0 && (- <div>- <div className="flex items-center gap-2 mb-3">- <Camera className="h-5 w-5 text-pink-500" />- <h2 className="text-base font-semibold">Instagram Accounts</h2>- <Badge variant="outline" className="border-pink-200 bg-pink-50 text-pink-600 text-xs">{igAccounts.length}</Badge>- </div>- <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-4">- {igAccounts.map(acct => (- <AccountCard- key={acct.id}- acct={acct}- platform="instagram"- metrics={[- { label: 'Followers', value: fmtNum(acct.followersCount), className: 'bg-pink-50 text-pink-700' },- { label: 'Following', value: fmtNum(acct.followsCount), className: 'bg-purple-50 text-purple-700' },- { label: 'Posts', value: fmtNum(acct.mediaCount), className: 'bg-green-50 text-green-700' },- ]}- refreshingId={refreshingId}- onRefresh={handleRefreshOne}- onDelete={handleDelete}- />- ))}- </div>- </div>- )}-- {/* Reddit */}- {redditAccounts.length > 0 && (- <div>- <div className="flex items-center gap-2 mb-3">- <MessageSquare className="h-5 w-5 text-orange-500" />- <h2 className="text-base font-semibold">Reddit Accounts</h2>- <Badge variant="outline" className="border-orange-200 bg-orange-50 text-orange-600 text-xs">{redditAccounts.length}</Badge>- </div>- <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-4">- {redditAccounts.map(acct => (- <AccountCard- key={acct.id}- acct={acct}- platform="reddit"- metrics={[- { label: 'Total Karma', value: fmtNum(acct.totalKarma), className: 'bg-orange-50 text-orange-700' },- { label: 'Post Karma', value: fmtNum(acct.postKarma), className: 'bg-red-50 text-red-700' },- { label: 'Comment Karma', value: fmtNum(acct.commentKarma), className: 'bg-amber-50 text-amber-700' },- ]}- refreshingId={refreshingId}- onRefresh={handleRefreshOne}- onDelete={handleDelete}- />- ))}- </div>- </div>- )}- </div>+ </section>+ )))}- {/* Add Account Dialog */}- <Dialog open={dialogOpen} onOpenChange={(open) => { if (!open) closeDialog(); }}>- <DialogContent className="sm:max-w-md">+ <Dialog open={dialogOpen} onOpenChange={open => { if (!open) closeDialog(); }}>+ <DialogContent className="sm:max-w-xl"><DialogHeader>- <DialogTitle>Add Account</DialogTitle>- <DialogDescription>Connect a YouTube channel or Instagram account.</DialogDescription>+ <DialogTitle>{platform ? PLATFORM_CHOICES.find(c => c.value === platform).title : 'Add an account'}</DialogTitle>+ <DialogDescription>+ {platform ? 'Fill in the details, review, then add.' : 'Choose the platform you want to track.'}+ </DialogDescription></DialogHeader>- <Tabs value={dialogTab} onValueChange={setDialogTab}>- <TabsList className="w-full">- <TabsTrigger value="youtube" className="flex-1 gap-1.5">- <Tv className="h-3.5 w-3.5" /> YouTube- </TabsTrigger>- <TabsTrigger value="instagram" className="flex-1 gap-1.5">- <Camera className="h-3.5 w-3.5" /> Instagram- </TabsTrigger>- <TabsTrigger value="reddit" className="flex-1 gap-1.5">- <MessageSquare className="h-3.5 w-3.5" /> Reddit- </TabsTrigger>- </TabsList>+ {!platform && (+ <div role="radiogroup" aria-label="Platform" className="grid grid-cols-1 gap-3 sm:grid-cols-3">+ {PLATFORM_CHOICES.map(choice => (+ <ChoiceCard+ key={choice.value}+ icon={choice.icon}+ title={PLATFORM_META[choice.value].label}+ description={choice.description}+ selected={false}+ onSelect={() => setPlatform(choice.value)}+ />+ ))}+ </div>+ )}- <TabsContent value="youtube" className="space-y-4 mt-4">- <p className="text-sm text-muted-foreground">- Enter a YouTube channel URL, @handle, or channel ID.- </p>- <div className="flex gap-2">- <div className="relative flex-1">- <Link2 className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />- <Input- className="pl-9"- value={input}- onChange={e => setInput(e.target.value)}- placeholder="@MrBeast, https://youtube.com/@MrBeast, UCX6..."- onKeyDown={e => e.key === 'Enter' && handleResolve()}- />+ {platform === 'youtube' && (+ <div className="flex flex-col gap-4">+ <FieldRow label="Channel" hint="A channel URL, an @handle or a channel ID that starts with UC." htmlFor="yt-channel">+ <div className="flex gap-2">+ <div className="relative flex-1">+ <Link2 className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-ink-faint" />+ <Input+ id="yt-channel"+ className="h-(--control-h-lg) pl-9"+ value={input}+ onChange={e => { setInput(e.target.value); setResolved(null); }}+ placeholder="youtube.com/@channel"+ onKeyDown={e => e.key === 'Enter' && handleResolve()}+ autoFocus+ />+ </div>+ <Button variant="outline" size="lg" onClick={handleResolve} disabled={resolving || !input.trim()}>+ {resolving ? <Spinner className="size-4" /> : <Search data-icon="inline-start" />}+ Find+ </Button></div>- <Button onClick={handleResolve} disabled={resolving || !input.trim()} className="gap-1.5">- {resolving ? <RefreshCw className="h-4 w-4 animate-spin" /> : <Search className="h-4 w-4" />}- </Button>- </div>+ </FieldRow>{resolved && (- <div className="flex items-center gap-3 p-3 rounded-lg bg-green-50 border border-green-200">- <Avatar className="h-10 w-10">- <AvatarImage src={resolved.thumbnails?.medium || resolved.thumbnails?.default} />- <AvatarFallback className="bg-green-200 text-green-700 text-xs font-bold">- {(resolved.title || 'YT').slice(0, 2).toUpperCase()}- </AvatarFallback>- </Avatar>- <div className="flex-1 min-w-0">- <div className="flex items-center gap-1.5">- <p className="text-sm font-semibold truncate">{resolved.title}</p>- <CheckCircle2 className="h-4 w-4 text-green-600 flex-shrink-0" />- </div>- <p className="text-xs text-muted-foreground">{resolved.customUrl}</p>+ <div className="flex items-center gap-3 rounded-card border border-success/30 bg-success-soft p-3">+ <AccountAvatar account={{ platform: 'youtube', title: resolved.title, thumbnail: resolved.thumbnails?.medium || resolved.thumbnails?.default }} size="lg" />+ <div className="min-w-0 flex-1">+ <p className="flex items-center gap-1.5 text-sm font-semibold text-ink">+ <span className="truncate">{resolved.title}</span>+ <CheckCircle2 className="size-4 shrink-0 text-success" aria-label="Channel found" />+ </p>+ <p className="text-caption text-ink-muted">{resolved.customUrl}</p>{resolved.subscriberCount != null && (- <div className="flex gap-1.5 mt-1">- <Badge variant="secondary" className="text-xs h-5">{fmtNum(resolved.subscriberCount)} subs</Badge>- <Badge variant="secondary" className="text-xs h-5">{fmtNum(resolved.videoCount)} videos</Badge>- </div>+ <p className="mt-0.5 text-caption text-ink-muted">+ {fmtNum(resolved.subscriberCount)} subscribers, {fmtNum(resolved.videoCount)} videos+ </p>)}</div></div>)}- </TabsContent>+ </div>+ )}- <TabsContent value="instagram" className="space-y-4 mt-4">- <p className="text-sm text-muted-foreground">- You'll be taken to Instagram to log in and grant access. After approval, you'll be redirected back automatically.+ {platform === 'instagram' && (+ <div className="flex flex-col gap-4">+ <p className="text-sm text-ink-muted">+ We open Instagram so you can sign in and approve access. When you finish, Instagram sends you back here and the account appears in the list.</p>- <Button- onClick={handleConnectInstagram}- disabled={connecting}- className="w-full gap-2 bg-gradient-to-r from-pink-500 to-purple-600 hover:from-pink-600 hover:to-purple-700 text-white border-0"- >- {connecting- ? <RefreshCw className="h-4 w-4 animate-spin" />- : <ExternalLink className="h-4 w-4" />}- {connecting ? 'Opening Instagram...' : 'Connect with Instagram'}- </Button>- <Alert>- <Info className="h-4 w-4" />- <AlertDescription className="text-xs">- Your account must be a <strong>Business</strong> or <strong>Creator</strong> professional account. Personal accounts are not supported by the Instagram API.+ <Alert variant="info">+ <Info />+ <AlertDescription>+ The account must be an Instagram Business or Creator account. Personal accounts cannot be connected through the Instagram API.</AlertDescription></Alert>- </TabsContent>+ </div>+ )}- <TabsContent value="reddit" className="space-y-4 mt-4">- <p className="text-sm text-muted-foreground">- A session cookie is required to fetch Reddit analytics from the server.- </p>- <div className="space-y-3">+ {platform === 'reddit' && (+ <div className="flex flex-col gap-4">+ <FieldRow label="Username" htmlFor="reddit-user"><div className="relative">- <span className="absolute left-3 top-1/2 -translate-y-1/2 text-sm text-muted-foreground font-medium">u/</span>+ <span className="pointer-events-none absolute top-1/2 left-3 -translate-y-1/2 text-sm font-medium text-ink-faint">u/</span><Input- className="pl-8"+ id="reddit-user"+ className="h-(--control-h-lg) pl-8"value={redditUsername}onChange={e => setRedditUsername(e.target.value)}- placeholder="your_username"+ placeholder="username"onKeyDown={e => e.key === 'Enter' && handleAddReddit()}+ autoFocus/></div>- <div className="space-y-1.5">- <label className="text-xs font-medium">Session cookie</label>- <Input- type="password"- value={redditCookie}- onChange={e => setRedditCookie(e.target.value)}- placeholder="reddit_session value"- onKeyDown={e => e.key === 'Enter' && handleAddReddit()}- />- </div>- </div>+ </FieldRow>+ <FieldRow label="Session cookie" hint="We store it on the server and never show it again." htmlFor="reddit-cookie">+ <Input+ id="reddit-cookie"+ type="password"+ className="h-(--control-h-lg) font-mono"+ value={redditCookie}+ onChange={e => setRedditCookie(e.target.value)}+ placeholder="reddit_session value"+ onKeyDown={e => e.key === 'Enter' && handleAddReddit()}+ />+ </FieldRow><Alert>- <Info className="h-4 w-4" />- <AlertDescription className="text-xs">- Log in to reddit.com in your browser. Open DevTools (F12), go to <strong>Application > Cookies > https://www.reddit.com</strong>, find the cookie named <strong>reddit_session</strong>, and copy its value.+ <Info />+ <AlertDescription>+ Sign in to reddit.com in your browser, open DevTools (F12), go to Application, then Cookies, then https://www.reddit.com, and copy the value of <strong className="font-semibold text-ink">reddit_session</strong>.</AlertDescription></Alert>- </TabsContent>- </Tabs>+ </div>+ )}<DialogFooter>- <Button variant="ghost" onClick={closeDialog}>Cancel</Button>- {dialogTab === 'youtube' && (- <Button onClick={handleAdd} disabled={!input.trim() || adding} className="gap-1.5">- {adding && <RefreshCw className="h-3.5 w-3.5 animate-spin" />}- Add Channel+ {platform ? (+ <Button variant="ghost" onClick={() => { setPlatform(null); setResolved(null); }} className="sm:mr-auto">+ <ArrowLeft data-icon="inline-start" />+ Back+ </Button>+ ) : null}+ <Button variant="outline" onClick={closeDialog}>Cancel</Button>+ {platform === 'youtube' && (+ <Button onClick={handleAdd} disabled={!input.trim() || adding}>+ {adding && <Spinner className="size-4" />}+ {adding ? 'Adding channel' : 'Add channel'}+ </Button>+ )}+ {platform === 'instagram' && (+ <Button onClick={handleConnectInstagram} disabled={connecting}>+ {connecting ? <Spinner className="size-4" /> : <ExternalLink data-icon="inline-start" />}+ {connecting ? 'Opening Instagram' : 'Continue to Instagram'}</Button>)}- {dialogTab === 'reddit' && (- <Button onClick={handleAddReddit} disabled={!redditUsername.trim() || !redditCookie.trim() || addingReddit} className="gap-1.5">- {addingReddit && <RefreshCw className="h-3.5 w-3.5 animate-spin" />}- Add Reddit Account+ {platform === 'reddit' && (+ <Button onClick={handleAddReddit} disabled={!redditUsername.trim() || !redditCookie.trim() || addingReddit}>+ {addingReddit && <Spinner className="size-4" />}+ {addingReddit ? 'Adding account' : 'Add Reddit account'}</Button>)}</DialogFooter></DialogContent></Dialog>++ <ConfirmDialog+ open={!!pendingDelete}+ onOpenChange={open => { if (!open) setPendingDelete(null); }}+ title={pendingDelete ? `Remove ${accountName(pendingDelete)}?` : 'Remove account?'}+ description="Its cached analytics are deleted. Scheduled posts for this account are removed with it. You can add the account again later."+ confirmLabel="Remove"+ onConfirm={handleDelete}+ busy={deleting}+ hold+ /></div>);}-function AccountCard({ acct, platform, metrics, refreshingId, onRefresh, onDelete }) {- const isIG = platform === 'instagram';- const isReddit = platform === 'reddit';- const initials = (acct.title || '?').slice(0, 2).toUpperCase();- const fallbackBg = isIG ? 'bg-pink-500' : isReddit ? 'bg-orange-500' : 'bg-red-500';- const subtitle = isIG- ? `@${acct.username || acct.igUsername || ''}`- : isReddit- ? `u/${acct.username || ''}`- : (acct.customUrl || '');-+function AccountCard({ acct, platform, refreshing, onRefresh, onDelete }) {+ const metrics = METRICS[platform](acct);return (- <div className="border border-border rounded-xl p-4 bg-card hover:shadow-sm transition-shadow space-y-3">+ <article className="flex flex-col gap-4 rounded-card border border-line bg-surface-raised p-4"><div className="flex items-center gap-3">- <Avatar className="h-11 w-11">- <AvatarImage src={acct.thumbnail || acct.profilePictureUrl || acct.thumbnails?.default} />- <AvatarFallback className={`text-xs font-bold text-white ${fallbackBg}`}>- {initials}- </AvatarFallback>- </Avatar>- <div className="flex-1 min-w-0">- <p className="text-sm font-semibold truncate">{acct.title || acct.channelId}</p>- <p className="text-xs text-muted-foreground truncate">{subtitle}</p>+ <AccountAvatar account={acct} size="lg" showPlatform />+ <div className="min-w-0 flex-1">+ <Link to={accountPath(acct)} className="block truncate text-sm font-semibold text-ink hover:underline">{accountName(acct)}</Link>+ <p className="truncate text-caption text-ink-faint">{platform === 'reddit' ? `u/${acct.username || ''}` : accountHandle(acct)}</p></div>+ <Tooltip>+ <TooltipTrigger render={<Button variant="ghost" size="icon-sm" render={<Link to={accountPath(acct)} aria-label={`Open analytics for ${accountName(acct)}`} />} />}>+ <ArrowUpRight />+ </TooltipTrigger>+ <TooltipContent>Open analytics</TooltipContent>+ </Tooltip></div>- <div className="grid grid-cols-3 gap-1.5">- {metrics.map(m => (- <div key={m.label} className={cn('text-center p-2 rounded-lg', m.className, 'bg-opacity-60')}>- <p className="text-[0.6rem] uppercase tracking-wide font-medium opacity-70">{m.label}</p>- <p className="text-sm font-bold">{m.value}</p>+ <dl className="grid grid-cols-3 divide-x divide-divider rounded-control bg-surface-sunken/60 py-2.5">+ {metrics.map(([label, value]) => (+ <div key={label} className="flex flex-col items-center gap-0.5 px-2 text-center">+ <dt className="text-caption text-ink-faint">{label}</dt>+ <dd className="font-heading text-base font-semibold text-ink tabular-nums">{fmtNum(value)}</dd></div>))}- </div>+ </dl>- {isReddit && (- <div className="flex items-center gap-1.5 text-xs">- {acct.hasCookie ? (- <>- <Lock className="h-3 w-3 text-green-500" />- <span className="text-green-600">Session cookie stored</span>- </>+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-caption text-ink-faint">+ {platform === 'reddit' && (+ acct.hasCookie ? (+ <span className="flex items-center gap-1 text-success"><Lock className="size-3" />Session cookie stored</span>) : (- <>- <Lock className="h-3 w-3 text-destructive" />- <span className="text-destructive">No cookie - re-add account</span>- </>- )}- </div>- )}- {acct.lastUpdated && (- <p className="text-xs text-muted-foreground">Updated {timeAgo(acct.lastUpdated)}</p>- )}+ <span className="flex items-center gap-1 text-danger"><Lock className="size-3" />Error: no session cookie. Remove and add the account again.</span>+ )+ )}+ {acct.lastUpdated && <span>Updated {timeAgo(acct.lastUpdated).toLowerCase()}</span>}+ </div>- <div className="flex gap-2">- <Button- variant="outline"- size="sm"- className="flex-1 gap-1.5"- onClick={() => onRefresh(acct.id)}- disabled={refreshingId === acct.id}- >- <RefreshCw className={cn('h-3.5 w-3.5', refreshingId === acct.id && 'animate-spin')} />- {refreshingId === acct.id ? 'Refreshing...' : 'Refresh'}- </Button>- <Button- variant="outline"- size="sm"- className="text-destructive hover:text-destructive hover:bg-destructive/10 border-destructive/30"- onClick={() => onDelete(acct.id)}- >- <Trash2 className="h-3.5 w-3.5" />+ <div className="mt-auto flex gap-2">+ <Button variant="outline" size="sm" className="flex-1" onClick={onRefresh} disabled={refreshing}>+ <RefreshCw data-icon="inline-start" className={cn(refreshing && 'animate-spin')} />+ {refreshing ? 'Refreshing' : 'Refresh'}</Button>+ <Tooltip>+ <TooltipTrigger render={<Button variant="ghost" size="icon-sm" onClick={onDelete} aria-label={`Remove ${accountName(acct)}`} className="text-ink-muted hover:bg-danger-soft hover:text-danger" />}>+ <Trash2 />+ </TooltipTrigger>+ <TooltipContent>Remove account</TooltipContent>+ </Tooltip></div>- </div>+ </article>);}diff --git a/frontend/src/features/analytics/channel/ChannelAnalytics.jsx b/frontend/src/features/analytics/channel/ChannelAnalytics.jsxindex 45b88ea..61043fd 100644--- a/frontend/src/features/analytics/channel/ChannelAnalytics.jsx+++ b/frontend/src/features/analytics/channel/ChannelAnalytics.jsx@@ -1,288 +1,290 @@-import React, { useState, useEffect } from 'react';-import { useParams, useNavigate } from 'react-router-dom';+import React, { useCallback, useEffect, useState } from 'react';+import { useParams } from 'react-router-dom';+import {+ BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip as ReTooltip, PieChart, Pie, Cell, Legend,+ AreaChart, Area,+} from 'recharts';+import {+ RefreshCw, Eye, Users, VideoIcon, ThumbsUp, MessageSquare, TrendingUp, Clock, Trophy, Zap, Flame,+ Calendar, Timer, Film, Tag, Play, BarChart2, UserX,+} from 'lucide-react';import { Button } from '@/components/ui/button';import { Badge } from '@/components/ui/badge';-import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';-import { Alert, AlertDescription } from '@/components/ui/alert';-import { Skeleton } from '@/components/ui/skeleton';-import { Progress } from '@/components/ui/progress';-import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';-import { ScrollArea } from '@/components/ui/scroll-area';-import {- BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip as ReTooltip,- ResponsiveContainer, LineChart, Line, PieChart, Pie, Cell, Legend,- AreaChart, Area,-} from 'recharts';-import StatCard from '../../../components/ui/StatCard';-import MainCard from '../../../components/MainCard';+import PageHeader from '@/components/PageHeader';+import MetricBox from '@/components/MetricBox';+import SurfaceBox from '@/components/SurfaceBox';+import ChartPanel from '@/components/ChartPanel';+import SectionHeader from '@/components/SectionHeader';+import MediaCard, { MediaChip } from '@/components/MediaCard';+import { EmptyState, PageSkeleton } from '@/components/StateViews';+import { AccountAvatar } from '@/components/platform';+import { SERIES, axisProps, axisTick, gridProps, legendStyle, tooltipCursor, tooltipStyle } from '@/lib/chart';import { useAppContext } from '../../../context/AppContext';import { api } from '../../../services/api';import { fmtNum, fmtNumFull, fmtDate, fmtPercent, fmtDuration, CATEGORY_MAP } from '../../../utils/formatters';-import {- ArrowLeft, RefreshCw, Eye, Users, VideoIcon, ThumbsUp, MessageSquare,- TrendingUp, Clock, Trophy, Zap, Flame, Calendar, Timer, Film,- Tag, Play, BarChart2, AlertTriangle,-} from 'lucide-react';import { cn } from '@/lib/utils';-const C = {- blue: 'hsl(221.2,83.2%,53.3%)',- green: '#22c55e',- orange: '#f97316',- red: '#ef4444',- purple: '#a855f7',- cyan: '#06b6d4',- pink: '#ec4899',- indigo: '#6366f1',- amber: '#f59e0b',-};+const watchUrl = id => `https://www.youtube.com/watch?v=${id}`;-const TS = { background: 'var(--card)', border: '1px solid var(--border)', borderRadius: 8, fontSize: 12 };+const TABS = [+ { value: 'overview', label: 'Overview' },+ { value: 'videos', label: 'Videos' },+ { value: 'engagement', label: 'Engagement' },+ { value: 'content', label: 'Content' },+ { value: 'publishing', label: 'Publishing' },+ { value: 'growth', label: 'Growth' },+ { value: 'shorts', label: 'Shorts and regular' },+ { value: 'tags', label: 'Tags and SEO' },+];-function ChartCard({ title, children, height = 280 }) {- return (- <MainCard title={title} contentClassName="p-3">- <ResponsiveContainer width="100%" height={height} debounce={200}>- {children}- </ResponsiveContainer>- </MainCard>- );+function MetricGrid({ className, children }) {+ return <div className={cn('grid grid-cols-2 gap-3 sm:grid-cols-4', className)}>{children}</div>;}function VideoTable({ videos }) {+ const rows = (videos || []).filter(Boolean);return (- <MainCard content={false}>- <ScrollArea className="h-[480px]">+ <SurfaceBox content={false} className="overflow-hidden">+ <div className="max-h-[480px] overflow-y-auto"><Table>- <TableHeader className="sticky top-0 bg-background z-10">+ <TableHeader className="sticky top-0 z-10 bg-surface-raised"><TableRow>- <TableHead className="w-8">#</TableHead>+ <TableHead className="w-10 text-right">#</TableHead><TableHead>Video</TableHead><TableHead className="text-right">Views</TableHead><TableHead className="text-right">Likes</TableHead><TableHead className="text-right">Comments</TableHead>- <TableHead className="text-right">Eng%</TableHead>- <TableHead className="text-right">Duration</TableHead>+ <TableHead className="text-right">Engagement</TableHead>+ <TableHead className="text-right">Length</TableHead><TableHead className="text-right">Published</TableHead>- <TableHead className="w-8" />+ <TableHead className="w-10"><span className="sr-only">Watch</span></TableHead></TableRow></TableHeader><TableBody>- {(videos || []).filter(Boolean).map((v, i) => (- <TableRow key={v.videoId} className="cursor-pointer" onClick={() => window.open(`https://www.youtube.com/watch?v=${v.videoId}`, '_blank', 'noopener')}>- <TableCell className="text-xs text-muted-foreground">{i + 1}</TableCell>- <TableCell className="max-w-[280px]"><p className="text-sm font-medium truncate">{v.title}</p></TableCell>- <TableCell className="text-right text-sm font-semibold">{fmtNum(v.viewCount)}</TableCell>- <TableCell className="text-right text-sm">{fmtNum(v.likeCount)}</TableCell>- <TableCell className="text-right text-sm">{fmtNum(v.commentCount)}</TableCell>+ {rows.map((v, i) => (+ <TableRow key={v.videoId}>+ <TableCell className="text-right font-mono text-caption text-ink-faint">{i + 1}</TableCell>+ <TableCell className="max-w-[280px]">+ <a href={watchUrl(v.videoId)} target="_blank" rel="noopener noreferrer" className="block truncate text-sm font-medium text-ink hover:underline">{v.title}</a>+ </TableCell>+ <TableCell className="text-right font-semibold text-ink">{fmtNum(v.viewCount)}</TableCell>+ <TableCell className="text-right text-ink-muted">{fmtNum(v.likeCount)}</TableCell>+ <TableCell className="text-right text-ink-muted">{fmtNum(v.commentCount)}</TableCell><TableCell className="text-right">- <Badge variant="outline" className={cn('text-xs', parseFloat(v.engagementRate) > 5 ? 'border-green-200 bg-green-50 text-green-700' : '')}>- {fmtPercent(v.engagementRate)}- </Badge>+ <Badge variant={parseFloat(v.engagementRate) > 5 ? 'success' : 'secondary'}>{fmtPercent(v.engagementRate)}</Badge></TableCell>- <TableCell className="text-right text-sm">{fmtDuration(v.durationSeconds)}</TableCell>- <TableCell className="text-right text-xs text-muted-foreground">{fmtDate(v.publishedAt)}</TableCell>+ <TableCell className="text-right text-ink-muted">{fmtDuration(v.durationSeconds)}</TableCell>+ <TableCell className="text-right text-small text-ink-faint">{fmtDate(v.publishedAt)}</TableCell><TableCell>- <Button variant="ghost" size="icon" className="h-6 w-6 text-red-500 hover:bg-red-50" onClick={e => { e.stopPropagation(); window.open(`https://www.youtube.com/watch?v=${v.videoId}`, '_blank', 'noopener'); }}>- <Play className="h-3 w-3" />+ <Button variant="ghost" size="icon-xs" render={<a href={watchUrl(v.videoId)} target="_blank" rel="noopener noreferrer" aria-label={`Watch ${v.title} on YouTube`} />}>+ <Play /></Button></TableCell></TableRow>))}</TableBody></Table>- </ScrollArea>- </MainCard>+ </div>+ </SurfaceBox>+ );+}++function TrendArea({ data, dataKey = 'value', color, name, percent = false, gradientId }) {+ return (+ <AreaChart data={data}>+ <defs>+ <linearGradient id={gradientId} x1="0" y1="0" x2="0" y2="1">+ <stop offset="5%" stopColor={color} stopOpacity={0.2} />+ <stop offset="95%" stopColor={color} stopOpacity={0} />+ </linearGradient>+ </defs>+ <CartesianGrid {...gridProps} vertical={false} />+ <XAxis dataKey="month" {...axisProps} />+ <YAxis {...axisProps} tickFormatter={percent ? v => `${v}%` : fmtNum} width={48} />+ <ReTooltip contentStyle={tooltipStyle} cursor={{ stroke: 'var(--line-strong)' }} formatter={percent ? undefined : v => fmtNumFull(v)} />+ <Area type="monotone" dataKey={dataKey} stroke={color} fill={`url(#${gradientId})`} strokeWidth={2} name={name} />+ </AreaChart>);}export default function ChannelAnalytics() {const { id } = useParams();- const navigate = useNavigate();const { accounts, showToast } = useAppContext();const account = accounts.find(a => a.id === id);- const [data, setData] = useState(null);+ const [data, setData] = useState(null);const [loading, setLoading] = useState(true);- const [tab, setTab] = useState('overview');-- useEffect(() => { if (id) loadAnalytics(); }, [id]);+ const [tab, setTab] = useState('overview');- const loadAnalytics = async () => {+ const loadAnalytics = useCallback(async () => {setLoading(true);try {- const res = await api.getAnalytics(id);- setData(res);+ setData(await api.getAnalytics(id));} catch (err) {- showToast('Failed to load analytics: ' + err.message, 'error');+ showToast(`Couldn't load channel analytics. ${err.message}`, 'error');} finally {setLoading(false);}- };+ }, [id, showToast]);++ useEffect(() => { if (id) loadAnalytics(); }, [id, loadAnalytics]);++ const back = { to: '/', label: 'Overview' };if (!account && !loading) {return (- <div className="space-y-4">- <Button variant="ghost" onClick={() => navigate('/')} className="gap-2 -ml-2 text-muted-foreground">- <ArrowLeft className="h-4 w-4" /> Back to Overview- </Button>- <Alert variant="destructive"><AlertTriangle className="h-4 w-4" /><AlertDescription>Account not found. It may have been removed.</AlertDescription></Alert>+ <div className="flex flex-col gap-6">+ <PageHeader title="YouTube channel" back={back} />+ <SurfaceBox>+ <EmptyState icon={<UserX />} title="Channel not found" description="It may have been removed. Choose another account from the sidebar." />+ </SurfaceBox></div>);}- if (loading) {+ if (loading) return <PageSkeleton metrics={4} />;++ if (!data) {return (- <div className="space-y-4">- <Button variant="ghost" className="gap-2 -ml-2 text-muted-foreground" onClick={() => navigate('/')}>- <ArrowLeft className="h-4 w-4" /> Back- </Button>- <Progress className="h-1" />- <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">- {[...Array(8)].map((_, i) => <Skeleton key={i} className="h-24 rounded-xl" />)}- </div>+ <div className="flex flex-col gap-6">+ <PageHeader title={account?.title || 'YouTube channel'} back={back} />+ <SurfaceBox>+ <EmptyState+ icon={<BarChart2 />}+ title="Analytics are unavailable"+ description="The channel's analytics could not be loaded. Check the YouTube API key in Settings, then try again."+ action={<Button variant="outline" size="sm" onClick={loadAnalytics}>Try again</Button>}+ />+ </SurfaceBox></div>);}- if (!data) return null;const { channel, analytics } = data;- const dayData = analytics.publishDayDistribution+ const dayData = analytics.publishDayDistribution? Object.entries(analytics.publishDayDistribution).map(([day, count]) => ({ day, count })): [];const hourData = analytics.publishHourDistribution- ? Object.entries(analytics.publishHourDistribution).sort((a, b) => parseInt(a[0]) - parseInt(b[0])).map(([hour, count]) => ({ hour: `${hour}:00`, count }))+ ? Object.entries(analytics.publishHourDistribution).sort((a, b) => parseInt(a[0], 10) - parseInt(b[0], 10)).map(([hour, count]) => ({ hour: `${hour}:00`, count })): [];const durationData = analytics.durationDistribution? [- { name: 'Shorts (<1m)', value: analytics.durationDistribution.short, color: C.red },- { name: 'Medium (1-10m)', value: analytics.durationDistribution.medium, color: C.blue },- { name: 'Long (10-60m)', value: analytics.durationDistribution.long, color: C.green },- { name: 'Very Long (>1h)',value: analytics.durationDistribution.veryLong, color: C.orange },+ { name: 'Shorts (under 1m)', value: analytics.durationDistribution.short, color: SERIES.primary },+ { name: 'Medium (1 to 10m)', value: analytics.durationDistribution.medium, color: SERIES.cool },+ { name: 'Long (10 to 60m)', value: analytics.durationDistribution.long, color: SERIES.neutral },+ { name: 'Very long (1h+)', value: analytics.durationDistribution.veryLong, color: SERIES.warm },].filter(d => d.value > 0): [];const catData = analytics.categoryDistribution- ? Object.entries(analytics.categoryDistribution).map(([id, count]) => ({ name: CATEGORY_MAP[id] || `Cat ${id}`, value: count }))+ ? Object.entries(analytics.categoryDistribution).map(([catId, count]) => ({ name: CATEGORY_MAP[catId] || `Category ${catId}`, value: count })): [];+ const splitData = [+ { name: 'Shorts', value: analytics.shortsCount, color: SERIES.primary },+ { name: 'Regular', value: analytics.regularCount, color: SERIES.cool },+ ].filter(d => d.value > 0);- return (- <div className="space-y-4">- {/* Back */}- <Button variant="ghost" onClick={() => navigate('/')} className="gap-2 -ml-2 text-muted-foreground h-8">- <ArrowLeft className="h-4 w-4" /> Back to Overview- </Button>+ const meta = [+ channel.customUrl,+ channel.country && channel.country !== 'Unknown' ? channel.country : null,+ `${channel.channelAgeYears} years old`,+ `Since ${fmtDate(channel.publishedAt)}`,+ ].filter(Boolean);- {/* Channel header */}- <MainCard content={false}>- <div className="p-4 flex items-center gap-4 flex-wrap">- <Avatar className="h-16 w-16 border-2 border-border">- <AvatarImage src={channel.thumbnails?.high || channel.thumbnails?.medium} />- <AvatarFallback className="bg-red-500 text-white text-lg font-bold">{(channel.title || 'YT').slice(0, 2).toUpperCase()}</AvatarFallback>- </Avatar>- <div className="flex-1 min-w-0">- <h2 className="text-xl font-bold">{channel.title}</h2>- <div className="flex flex-wrap gap-1.5 mt-1.5">- {channel.customUrl && <Badge variant="outline" className="text-xs">{channel.customUrl}</Badge>}- {channel.country && channel.country !== 'Unknown' && <Badge variant="outline" className="text-xs">{channel.country}</Badge>}- <Badge variant="outline" className="text-xs">{channel.channelAgeYears} years old</Badge>- <Badge variant="outline" className="text-xs">Since {fmtDate(channel.publishedAt)}</Badge>- </div>- </div>- <Button size="sm" onClick={loadAnalytics} className="gap-2 shrink-0">- <RefreshCw className="h-3.5 w-3.5" /> Refresh+ return (+ <div className="flex flex-col gap-6">+ <PageHeader+ back={back}+ media={<AccountAvatar account={{ ...account, thumbnail: channel.thumbnails?.high || channel.thumbnails?.medium || account?.thumbnail }} size="xl" showPlatform />}+ title={channel.title}+ description={+ <span className="flex flex-wrap gap-1.5">+ {meta.map(m => <Badge key={m} variant="outline">{m}</Badge>)}+ </span>+ }+ actions={+ <Button variant="outline" size="sm" onClick={loadAnalytics}>+ <RefreshCw data-icon="inline-start" />+ Refresh</Button>- </div>- </MainCard>+ }+ />- {/* Tabs */}- <Tabs value={tab} onValueChange={setTab}>- <div className="overflow-x-auto scrollbar-hide">- <TabsList className="w-max">- {['overview','videos','engagement','content','publishing','growth','shorts','tags'].map((t, i) => (- <TabsTrigger key={t} value={t} className="text-xs px-3">- {['Overview','Videos','Engagement','Content','Publishing','Growth','Shorts vs Regular','Tags & SEO'][i]}- </TabsTrigger>- ))}+ <Tabs value={tab} onValueChange={setTab} className="gap-6">+ <div className="scrollbar-hide -mx-4 overflow-x-auto px-4 sm:mx-0 sm:px-0">+ <TabsList className="w-max min-w-full">+ {TABS.map(t => <TabsTrigger key={t.value} value={t.value}>{t.label}</TabsTrigger>)}</TabsList></div>- {/* Overview */}- <TabsContent value="overview" className="space-y-4 mt-4">- <div className="grid grid-cols-2 sm:grid-cols-3 xl:grid-cols-6 gap-3">- <StatCard icon={<Eye />} label="Total Views" value={fmtNum(channel.viewCount)} subtitle={fmtNumFull(channel.viewCount)} gradient="red" small />- <StatCard icon={<Users />} label="Subscribers" value={fmtNum(channel.subscriberCount)} subtitle={fmtNumFull(channel.subscriberCount)} gradient="green" small />- <StatCard icon={<VideoIcon />} label="Total Videos" value={fmtNum(channel.videoCount)} subtitle={`${analytics.totalVideos} analyzed`} gradient="orange" small />- <StatCard icon={<ThumbsUp />} label="Total Likes" value={fmtNum(analytics.totalLikes)} subtitle={fmtNumFull(analytics.totalLikes)} gradient="blue" small />- <StatCard icon={<MessageSquare />} label="Comments" value={fmtNum(analytics.totalComments)} subtitle={fmtNumFull(analytics.totalComments)} gradient="purple" small />- <StatCard icon={<TrendingUp />} label="Engagement" value={fmtPercent(analytics.overallEngagementRate)} subtitle="Likes+Comments/Views" gradient="teal" small />- </div>- <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">- <StatCard icon={<Zap />} label="Avg Views/Video" value={fmtNum(analytics.avgViews)} gradient="cyan" small />- <StatCard icon={<ThumbsUp />} label="Avg Likes/Video" value={fmtNum(analytics.avgLikes)} gradient="indigo" small />- <StatCard icon={<MessageSquare />} label="Avg Comments" value={fmtNum(analytics.avgComments)} gradient="pink" small />- <StatCard icon={<BarChart2 />} label="Median Views" value={fmtNum(analytics.medianViews)} gradient="amber" small />- </div>- <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">- <StatCard icon={<Eye />} label="Views/Subscriber" value={channel.viewsPerSubscriber} gradient="red" small />- <StatCard icon={<TrendingUp />} label="Avg Subs/Day" value={fmtNum(channel.avgSubGainPerDay)} gradient="green" small />- <StatCard icon={<Eye />} label="Avg Views/Day" value={fmtNum(channel.avgViewsPerDay)} gradient="blue" small />- <StatCard icon={<Timer />} label="Avg Duration" value={analytics.avgDurationFormatted} gradient="orange" small />- </div>- <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">- <StatCard icon={<Clock />} label="Videos (7d)" value={analytics.videosLast7Days} gradient="red" small />- <StatCard icon={<Clock />} label="Videos (30d)" value={analytics.videosLast30Days} gradient="blue" small />- <StatCard icon={<Clock />} label="Videos (90d)" value={analytics.videosLast90Days} gradient="green" small />- <StatCard icon={<Clock />} label="Videos (365d)" value={analytics.videosLast365Days} gradient="orange" small />- </div>- <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">- <StatCard icon={<Calendar />} label="Est. Monthly Views" value={fmtNum(channel.estimatedMonthlyViews)} gradient="indigo" small />- <StatCard icon={<Users />} label="Est. Monthly Subs" value={fmtNum(channel.estimatedMonthlySubGain)} gradient="teal" small />- <StatCard icon={<Flame />} label="Virality Score" value={`${analytics.viralityScore}x`} gradient="pink" small />- <StatCard icon={<Trophy />} label="Consistency" value={`${analytics.consistencyScore}/100`} gradient="amber" small />+ <TabsContent value="overview" className="flex flex-col gap-3">+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 xl:grid-cols-6">+ <MetricBox small icon={<Eye />} label="Total views" value={fmtNum(channel.viewCount)} subtitle={fmtNumFull(channel.viewCount)} highlight />+ <MetricBox small icon={<Users />} label="Subscribers" value={fmtNum(channel.subscriberCount)} subtitle={fmtNumFull(channel.subscriberCount)} />+ <MetricBox small icon={<VideoIcon />} label="Total videos" value={fmtNum(channel.videoCount)} subtitle={`${analytics.totalVideos} analyzed`} />+ <MetricBox small icon={<ThumbsUp />} label="Total likes" value={fmtNum(analytics.totalLikes)} subtitle={fmtNumFull(analytics.totalLikes)} />+ <MetricBox small icon={<MessageSquare />} label="Comments" value={fmtNum(analytics.totalComments)} subtitle={fmtNumFull(analytics.totalComments)} />+ <MetricBox small icon={<TrendingUp />} label="Engagement" value={fmtPercent(analytics.overallEngagementRate)} subtitle="Likes and comments per view" /></div>+ <MetricGrid>+ <MetricBox small icon={<Zap />} label="Average views per video" value={fmtNum(analytics.avgViews)} />+ <MetricBox small icon={<ThumbsUp />} label="Average likes per video" value={fmtNum(analytics.avgLikes)} />+ <MetricBox small icon={<MessageSquare />} label="Average comments" value={fmtNum(analytics.avgComments)} />+ <MetricBox small icon={<BarChart2 />} label="Median views" value={fmtNum(analytics.medianViews)} />+ </MetricGrid>+ <MetricGrid>+ <MetricBox small icon={<Eye />} label="Views per subscriber" value={channel.viewsPerSubscriber} />+ <MetricBox small icon={<TrendingUp />} label="Subscribers per day" value={fmtNum(channel.avgSubGainPerDay)} />+ <MetricBox small icon={<Eye />} label="Views per day" value={fmtNum(channel.avgViewsPerDay)} />+ <MetricBox small icon={<Timer />} label="Average length" value={analytics.avgDurationFormatted} />+ </MetricGrid>+ <MetricGrid>+ <MetricBox small icon={<Clock />} label="Videos, last 7 days" value={analytics.videosLast7Days} />+ <MetricBox small icon={<Clock />} label="Videos, last 30 days" value={analytics.videosLast30Days} />+ <MetricBox small icon={<Clock />} label="Videos, last 90 days" value={analytics.videosLast90Days} />+ <MetricBox small icon={<Clock />} label="Videos, last 365 days" value={analytics.videosLast365Days} />+ </MetricGrid>+ <MetricGrid>+ <MetricBox small icon={<Calendar />} label="Estimated monthly views" value={fmtNum(channel.estimatedMonthlyViews)} />+ <MetricBox small icon={<Users />} label="Estimated monthly subscribers" value={fmtNum(channel.estimatedMonthlySubGain)} />+ <MetricBox small icon={<Flame />} label="Virality score" value={`${analytics.viralityScore}x`} />+ <MetricBox small icon={<Trophy />} label="Consistency" value={`${analytics.consistencyScore}/100`} />+ </MetricGrid>- <div>- <h3 className="text-base font-semibold mb-3 flex items-center gap-2">- <Trophy className="h-4 w-4 text-yellow-500" /> Best Performing Videos- </h3>- <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-3">- {[- { label: 'Most Viewed', video: analytics.bestByViews, color: 'bg-red-500' },- { label: 'Most Liked', video: analytics.bestByLikes, color: 'bg-green-500' },- { label: 'Most Comments', video: analytics.bestByComments, color: 'bg-blue-500' },- { label: 'Best Engagement', video: analytics.bestByEngagement, color: 'bg-orange-500' },- ].filter(({ video }) => video).map(({ label, video, color }) => (- <div key={label} className="border border-border rounded-xl overflow-hidden cursor-pointer hover:shadow-md transition-shadow" onClick={() => window.open(`https://www.youtube.com/watch?v=${video.videoId}`, '_blank', 'noopener')}>- <div className="relative">- <img src={video.thumbnail} className="w-full aspect-video object-cover" alt="" />- <span className={`absolute top-2 left-2 text-white text-xs font-semibold px-2 py-0.5 rounded ${color}`}>{label}</span>- </div>- <div className="p-2.5">- <p className="text-xs font-semibold line-clamp-2">{video.title}</p>- <p className="text-xs text-muted-foreground mt-1">{fmtNum(video.viewCount)} views · {fmtNum(video.likeCount)} likes</p>- </div>- </div>- ))}- </div>+ <SectionHeader title="Best performing videos" className="mt-5" />+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-4">+ {[+ { label: 'Most viewed', video: analytics.bestByViews },+ { label: 'Most liked', video: analytics.bestByLikes },+ { label: 'Most comments', video: analytics.bestByComments },+ { label: 'Best engagement', video: analytics.bestByEngagement },+ ].filter(({ video }) => video).map(({ label, video }) => (+ <MediaCard+ key={label}+ href={watchUrl(video.videoId)}+ image={video.thumbnail}+ title={video.title}+ topLeft={<MediaChip>{label}</MediaChip>}+ meta={<span>{fmtNum(video.viewCount)} views, {fmtNum(video.likeCount)} likes</span>}+ />+ ))}</div></TabsContent>- {/* Videos */}- <TabsContent value="videos" className="space-y-4 mt-4">- <ChartCard title="Top 10 Videos by Views" height={320}>- <BarChart data={(analytics.top10ByViews || []).map(v => ({ name: (v?.title || '').slice(0, 28) + '…', views: v?.viewCount || 0, likes: v?.likeCount || 0 }))}>- <CartesianGrid strokeDasharray="3 3" stroke="var(--border)" vertical={false} />- <XAxis dataKey="name" tick={{ fill: 'var(--muted-foreground)', fontSize: 10 }} angle={-15} textAnchor="end" height={70} />- <YAxis tick={{ fill: 'var(--muted-foreground)', fontSize: 11 }} tickFormatter={fmtNum} axisLine={false} tickLine={false} />- <ReTooltip contentStyle={TS} formatter={v => fmtNumFull(v)} />- <Bar dataKey="views" fill={C.red} radius={[4, 4, 0, 0]} name="Views" />- <Bar dataKey="likes" fill={C.green} radius={[4, 4, 0, 0]} name="Likes" />- <Legend />+ <TabsContent value="videos" className="flex flex-col gap-4">+ <ChartPanel title="Top 10 videos by views" height={320}>+ <BarChart data={(analytics.top10ByViews || []).map(v => ({ name: `${(v?.title || '').slice(0, 28)}…`, views: v?.viewCount || 0, likes: v?.likeCount || 0 }))}>+ <CartesianGrid {...gridProps} vertical={false} />+ <XAxis dataKey="name" tick={{ ...axisTick, fontSize: 10 }} angle={-15} textAnchor="end" height={70} />+ <YAxis {...axisProps} tickFormatter={fmtNum} />+ <ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} formatter={v => fmtNumFull(v)} />+ <Bar dataKey="views" fill={SERIES.primary} radius={[4, 4, 0, 0]} name="Views" />+ <Bar dataKey="likes" fill={SERIES.neutral} radius={[4, 4, 0, 0]} name="Likes" />+ <Legend wrapperStyle={legendStyle} /></BarChart>- </ChartCard>+ </ChartPanel><VideoTable videos={(analytics.top10ByViews || []).concat(analytics.top10ByLikes || []).filter((v, i, arr) => v && arr.findIndex(x => x?.videoId === v?.videoId) === i)@@ -290,214 +292,187 @@ export default function ChannelAnalytics() {} /></TabsContent>- {/* Engagement */}- <TabsContent value="engagement" className="space-y-4 mt-4">- <div className="grid grid-cols-2 sm:grid-cols-3 xl:grid-cols-6 gap-3">- <StatCard icon={<ThumbsUp />} label="Total Engagement" value={fmtNum(analytics.totalEngagement)} gradient="blue" small />- <StatCard icon={<TrendingUp />} label="Engagement Rate" value={fmtPercent(analytics.overallEngagementRate)} gradient="green" small />- <StatCard icon={<ThumbsUp />} label="Avg Like Rate" value={analytics.totalViews > 0 ? fmtPercent(analytics.totalLikes / analytics.totalViews * 100) : '0%'} gradient="red" small />- <StatCard icon={<MessageSquare />} label="Avg Comment Rate" value={analytics.totalViews > 0 ? fmtPercent(analytics.totalComments / analytics.totalViews * 100) : '0%'} gradient="purple" small />- <StatCard icon={<Flame />} label="Virality Score" value={`${analytics.viralityScore}x`} gradient="orange" small />- <StatCard icon={<BarChart2 />} label="Like:Comment" value={analytics.totalComments > 0 ? (analytics.totalLikes / analytics.totalComments).toFixed(1) + ':1' : 'N/A'} gradient="teal" small />+ <TabsContent value="engagement" className="flex flex-col gap-4">+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 xl:grid-cols-6">+ <MetricBox small icon={<ThumbsUp />} label="Total engagement" value={fmtNum(analytics.totalEngagement)} />+ <MetricBox small icon={<TrendingUp />} label="Engagement rate" value={fmtPercent(analytics.overallEngagementRate)} highlight />+ <MetricBox small icon={<ThumbsUp />} label="Like rate" value={analytics.totalViews > 0 ? fmtPercent(analytics.totalLikes / analytics.totalViews * 100) : '0%'} />+ <MetricBox small icon={<MessageSquare />} label="Comment rate" value={analytics.totalViews > 0 ? fmtPercent(analytics.totalComments / analytics.totalViews * 100) : '0%'} />+ <MetricBox small icon={<Flame />} label="Virality score" value={`${analytics.viralityScore}x`} />+ <MetricBox small icon={<BarChart2 />} label="Likes per comment" value={analytics.totalComments > 0 ? `${(analytics.totalLikes / analytics.totalComments).toFixed(1)}:1` : 'Not available'} /></div>- <div className="grid grid-cols-1 md:grid-cols-2 gap-4">- <ChartCard title="Engagement Rate Trend">- <AreaChart data={analytics.engagementTrend || []}>- <defs><linearGradient id="egGrad" x1="0" y1="0" x2="0" y2="1"><stop offset="5%" stopColor={C.green} stopOpacity={0.15} /><stop offset="95%" stopColor={C.green} stopOpacity={0.01} /></linearGradient></defs>- <CartesianGrid strokeDasharray="3 3" stroke="var(--border)" vertical={false} />- <XAxis dataKey="month" tick={{ fill: 'var(--muted-foreground)', fontSize: 11 }} axisLine={false} tickLine={false} />- <YAxis tick={{ fill: 'var(--muted-foreground)', fontSize: 11 }} tickFormatter={v => v + '%'} axisLine={false} tickLine={false} />- <ReTooltip contentStyle={TS} />- <Area type="monotone" dataKey="value" stroke={C.green} fill="url(#egGrad)" strokeWidth={2} name="Engagement %" />- </AreaChart>- </ChartCard>- <ChartCard title="Like Rate Trend">- <AreaChart data={analytics.likeRateTrend || []}>- <defs><linearGradient id="lrGrad" x1="0" y1="0" x2="0" y2="1"><stop offset="5%" stopColor={C.red} stopOpacity={0.12} /><stop offset="95%" stopColor={C.red} stopOpacity={0.01} /></linearGradient></defs>- <CartesianGrid strokeDasharray="3 3" stroke="var(--border)" vertical={false} />- <XAxis dataKey="month" tick={{ fill: 'var(--muted-foreground)', fontSize: 11 }} axisLine={false} tickLine={false} />- <YAxis tick={{ fill: 'var(--muted-foreground)', fontSize: 11 }} tickFormatter={v => v + '%'} axisLine={false} tickLine={false} />- <ReTooltip contentStyle={TS} />- <Area type="monotone" dataKey="value" stroke={C.red} fill="url(#lrGrad)" strokeWidth={2} name="Like Rate %" />- </AreaChart>- </ChartCard>+ <div className="grid grid-cols-1 gap-4 md:grid-cols-2">+ <ChartPanel title="Engagement rate by month">+ <TrendArea data={analytics.engagementTrend || []} color={SERIES.cool} name="Engagement %" percent gradientId="egGrad" />+ </ChartPanel>+ <ChartPanel title="Like rate by month">+ <TrendArea data={analytics.likeRateTrend || []} color={SERIES.primary} name="Like rate %" percent gradientId="lrGrad" />+ </ChartPanel></div>- <MainCard title="Top 10 by Engagement Rate" content={false}>- <VideoTable videos={analytics.top10ByEngagement} />- </MainCard>+ <SectionHeader title="Top 10 by engagement rate" />+ <VideoTable videos={analytics.top10ByEngagement} /></TabsContent>- {/* Content */}- <TabsContent value="content" className="space-y-4 mt-4">- <div className="grid grid-cols-2 sm:grid-cols-3 xl:grid-cols-6 gap-3">- <StatCard icon={<Film />} label="HD Videos" value={analytics.hdCount} subtitle={fmtPercent(analytics.hdPercentage)} gradient="blue" small />- <StatCard icon={<MessageSquare />} label="Captions" value={analytics.captionCount} subtitle={fmtPercent(analytics.captionPercentage)} gradient="green" small />- <StatCard icon={<Trophy />} label="Licensed" value={analytics.licensedCount} subtitle={fmtPercent(analytics.licensedPercentage)} gradient="purple" small />- <StatCard icon={<VideoIcon />} label="Embeddable" value={analytics.embeddableCount} subtitle={fmtPercent(analytics.embeddablePercentage)} gradient="orange" small />- <StatCard icon={<Users />} label="Kids Content" value={analytics.madeForKidsCount} gradient="cyan" small />- <StatCard icon={<Timer />} label="Avg Duration" value={analytics.avgDurationFormatted} gradient="amber" small />+ <TabsContent value="content" className="flex flex-col gap-4">+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 xl:grid-cols-6">+ <MetricBox small icon={<Film />} label="HD videos" value={analytics.hdCount} subtitle={fmtPercent(analytics.hdPercentage)} />+ <MetricBox small icon={<MessageSquare />} label="Captions" value={analytics.captionCount} subtitle={fmtPercent(analytics.captionPercentage)} />+ <MetricBox small icon={<Trophy />} label="Licensed" value={analytics.licensedCount} subtitle={fmtPercent(analytics.licensedPercentage)} />+ <MetricBox small icon={<VideoIcon />} label="Embeddable" value={analytics.embeddableCount} subtitle={fmtPercent(analytics.embeddablePercentage)} />+ <MetricBox small icon={<Users />} label="Made for kids" value={analytics.madeForKidsCount} />+ <MetricBox small icon={<Timer />} label="Average length" value={analytics.avgDurationFormatted} /></div>- <div className="grid grid-cols-1 md:grid-cols-2 gap-4">- <ChartCard title="Duration Distribution">+ <div className="grid grid-cols-1 gap-4 md:grid-cols-2">+ <ChartPanel title="Length distribution" empty={durationData.length === 0}><PieChart>- <Pie data={durationData} dataKey="value" nameKey="name" cx="50%" cy="50%" outerRadius={95} innerRadius={50} paddingAngle={3} strokeWidth={0}>- {durationData.map((d, i) => <Cell key={i} fill={d.color} />)}+ <Pie data={durationData} dataKey="value" nameKey="name" cx="50%" cy="50%" outerRadius={95} innerRadius={55} paddingAngle={2} strokeWidth={0}>+ {durationData.map(d => <Cell key={d.name} fill={d.color} />)}</Pie>- <ReTooltip contentStyle={TS} />- <Legend iconType="circle" iconSize={8} wrapperStyle={{ fontSize: 11 }} />+ <ReTooltip contentStyle={tooltipStyle} />+ <Legend iconType="circle" iconSize={8} wrapperStyle={legendStyle} /></PieChart>- </ChartCard>- <ChartCard title="Category Distribution">+ </ChartPanel>+ <ChartPanel title="Videos by category" empty={catData.length === 0}><BarChart data={catData} layout="vertical">- <CartesianGrid strokeDasharray="3 3" stroke="var(--border)" horizontal={false} />- <XAxis type="number" tick={{ fill: 'var(--muted-foreground)', fontSize: 11 }} axisLine={false} tickLine={false} />- <YAxis dataKey="name" type="category" tick={{ fill: 'var(--muted-foreground)', fontSize: 11 }} width={110} axisLine={false} tickLine={false} />- <ReTooltip contentStyle={TS} />- <Bar dataKey="value" fill={C.blue} radius={[0, 4, 4, 0]} name="Videos" />+ <CartesianGrid {...gridProps} horizontal={false} />+ <XAxis type="number" {...axisProps} />+ <YAxis dataKey="name" type="category" {...axisProps} width={120} />+ <ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} />+ <Bar dataKey="value" fill={SERIES.cool} radius={[0, 4, 4, 0]} name="Videos" /></BarChart>- </ChartCard>+ </ChartPanel></div>- <ChartCard title="Views Distribution" height={240}>+ <ChartPanel title="Videos by view range" height={240}><BarChart data={(analytics.viewsDistribution?.ranges || []).map((r, i) => ({ range: r, count: analytics.viewsDistribution.counts[i] || 0 }))}>- <CartesianGrid strokeDasharray="3 3" stroke="var(--border)" vertical={false} />- <XAxis dataKey="range" tick={{ fill: 'var(--muted-foreground)', fontSize: 10 }} angle={-15} textAnchor="end" height={60} />- <YAxis tick={{ fill: 'var(--muted-foreground)', fontSize: 11 }} axisLine={false} tickLine={false} />- <ReTooltip contentStyle={TS} />- <Bar dataKey="count" fill={C.orange} radius={[4, 4, 0, 0]} name="Videos" />+ <CartesianGrid {...gridProps} vertical={false} />+ <XAxis dataKey="range" tick={{ ...axisTick, fontSize: 10 }} angle={-15} textAnchor="end" height={60} />+ <YAxis {...axisProps} />+ <ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} />+ <Bar dataKey="count" fill={SERIES.warm} radius={[4, 4, 0, 0]} name="Videos" /></BarChart>- </ChartCard>+ </ChartPanel></TabsContent>- {/* Publishing */}- <TabsContent value="publishing" className="space-y-4 mt-4">- <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">- <StatCard icon={<Calendar />} label="Peak Publish Day" value={analytics.peakPublishDay || 'N/A'} gradient="blue" small />- <StatCard icon={<Clock />} label="Peak Publish Hour" value={analytics.peakPublishHour !== undefined ? `${analytics.peakPublishHour}:00 UTC` : 'N/A'} gradient="green" small />- <StatCard icon={<Zap />} label="Uploads/Week" value={analytics.uploadFrequencyPerWeek} gradient="orange" small />- <StatCard icon={<Trophy />} label="Consistency" value={`${analytics.consistencyScore}/100`} gradient="purple" small />- </div>- <div className="grid grid-cols-1 md:grid-cols-2 gap-4">- <ChartCard title="Publish Day Distribution">+ <TabsContent value="publishing" className="flex flex-col gap-4">+ <MetricGrid>+ <MetricBox small icon={<Calendar />} label="Most common upload day" value={analytics.peakPublishDay || 'Not available'} />+ <MetricBox small icon={<Clock />} label="Most common upload hour" value={analytics.peakPublishHour !== undefined ? `${analytics.peakPublishHour}:00 UTC` : 'Not available'} />+ <MetricBox small icon={<Zap />} label="Uploads per week" value={analytics.uploadFrequencyPerWeek} />+ <MetricBox small icon={<Trophy />} label="Consistency" value={`${analytics.consistencyScore}/100`} />+ </MetricGrid>+ <div className="grid grid-cols-1 gap-4 md:grid-cols-2">+ <ChartPanel title="Uploads by day of week"><BarChart data={dayData}>- <CartesianGrid strokeDasharray="3 3" stroke="var(--border)" vertical={false} />- <XAxis dataKey="day" tick={{ fill: 'var(--muted-foreground)', fontSize: 11 }} axisLine={false} tickLine={false} />- <YAxis tick={{ fill: 'var(--muted-foreground)', fontSize: 11 }} axisLine={false} tickLine={false} />- <ReTooltip contentStyle={TS} />- <Bar dataKey="count" fill={C.blue} radius={[4, 4, 0, 0]} name="Videos" />+ <CartesianGrid {...gridProps} vertical={false} />+ <XAxis dataKey="day" {...axisProps} />+ <YAxis {...axisProps} />+ <ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} />+ <Bar dataKey="count" fill={SERIES.cool} radius={[4, 4, 0, 0]} name="Videos" /></BarChart>- </ChartCard>- <ChartCard title="Publish Hour Distribution (UTC)">+ </ChartPanel>+ <ChartPanel title="Uploads by hour (UTC)"><AreaChart data={hourData}>- <defs><linearGradient id="hourGrad" x1="0" y1="0" x2="0" y2="1"><stop offset="5%" stopColor={C.orange} stopOpacity={0.15} /><stop offset="95%" stopColor={C.orange} stopOpacity={0.01} /></linearGradient></defs>- <CartesianGrid strokeDasharray="3 3" stroke="var(--border)" vertical={false} />- <XAxis dataKey="hour" tick={{ fill: 'var(--muted-foreground)', fontSize: 11 }} axisLine={false} tickLine={false} />- <YAxis tick={{ fill: 'var(--muted-foreground)', fontSize: 11 }} axisLine={false} tickLine={false} />- <ReTooltip contentStyle={TS} />- <Area type="monotone" dataKey="count" stroke={C.orange} fill="url(#hourGrad)" strokeWidth={2} name="Videos" />+ <defs>+ <linearGradient id="hourGrad" x1="0" y1="0" x2="0" y2="1">+ <stop offset="5%" stopColor={SERIES.warm} stopOpacity={0.2} />+ <stop offset="95%" stopColor={SERIES.warm} stopOpacity={0} />+ </linearGradient>+ </defs>+ <CartesianGrid {...gridProps} vertical={false} />+ <XAxis dataKey="hour" {...axisProps} />+ <YAxis {...axisProps} />+ <ReTooltip contentStyle={tooltipStyle} cursor={{ stroke: 'var(--line-strong)' }} />+ <Area type="monotone" dataKey="count" stroke={SERIES.warm} fill="url(#hourGrad)" strokeWidth={2} name="Videos" /></AreaChart>- </ChartCard>+ </ChartPanel></div></TabsContent>- {/* Growth */}- <TabsContent value="growth" className="space-y-4 mt-4">- <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">- <StatCard icon={<TrendingUp />} label="Est. Yearly Views" value={fmtNum(channel.estimatedYearlyViews)} gradient="red" small />- <StatCard icon={<Users />} label="Est. Yearly Subs" value={fmtNum(channel.estimatedYearlySubGain)} gradient="green" small />- <StatCard icon={<Eye />} label="Views/Day Avg" value={fmtNum(channel.avgViewsPerDay)} gradient="blue" small />- <StatCard icon={<Users />} label="Subs/Day Avg" value={fmtNum(channel.avgSubGainPerDay)} gradient="purple" small />- </div>- <ChartCard title="Monthly Views Trend" height={300}>- <AreaChart data={analytics.viewsTrend || []}>- <defs><linearGradient id="viewGrad" x1="0" y1="0" x2="0" y2="1"><stop offset="5%" stopColor={C.red} stopOpacity={0.12} /><stop offset="95%" stopColor={C.red} stopOpacity={0.01} /></linearGradient></defs>- <CartesianGrid strokeDasharray="3 3" stroke="var(--border)" vertical={false} />- <XAxis dataKey="month" tick={{ fill: 'var(--muted-foreground)', fontSize: 11 }} axisLine={false} tickLine={false} />- <YAxis tick={{ fill: 'var(--muted-foreground)', fontSize: 11 }} tickFormatter={fmtNum} axisLine={false} tickLine={false} />- <ReTooltip contentStyle={TS} formatter={v => fmtNumFull(v)} />- <Area type="monotone" dataKey="value" stroke={C.red} fill="url(#viewGrad)" strokeWidth={2} name="Views" />- </AreaChart>- </ChartCard>- <ChartCard title="Monthly Upload Count" height={240}>+ <TabsContent value="growth" className="flex flex-col gap-4">+ <MetricGrid>+ <MetricBox small icon={<TrendingUp />} label="Estimated yearly views" value={fmtNum(channel.estimatedYearlyViews)} highlight />+ <MetricBox small icon={<Users />} label="Estimated yearly subscribers" value={fmtNum(channel.estimatedYearlySubGain)} />+ <MetricBox small icon={<Eye />} label="Views per day" value={fmtNum(channel.avgViewsPerDay)} />+ <MetricBox small icon={<Users />} label="Subscribers per day" value={fmtNum(channel.avgSubGainPerDay)} />+ </MetricGrid>+ <ChartPanel title="Views by month" height={300}>+ <TrendArea data={analytics.viewsTrend || []} color={SERIES.primary} name="Views" gradientId="viewGrad" />+ </ChartPanel>+ <ChartPanel title="Uploads by month" height={240}><BarChart data={(analytics.viewsTrend || []).map(t => ({ month: t.month, uploads: t.count }))}>- <CartesianGrid strokeDasharray="3 3" stroke="var(--border)" vertical={false} />- <XAxis dataKey="month" tick={{ fill: 'var(--muted-foreground)', fontSize: 11 }} axisLine={false} tickLine={false} />- <YAxis tick={{ fill: 'var(--muted-foreground)', fontSize: 11 }} axisLine={false} tickLine={false} />- <ReTooltip contentStyle={TS} />- <Bar dataKey="uploads" fill={C.green} radius={[4, 4, 0, 0]} name="Uploads" />+ <CartesianGrid {...gridProps} vertical={false} />+ <XAxis dataKey="month" {...axisProps} />+ <YAxis {...axisProps} />+ <ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} />+ <Bar dataKey="uploads" fill={SERIES.neutral} radius={[4, 4, 0, 0]} name="Uploads" /></BarChart>- </ChartCard>+ </ChartPanel></TabsContent>- {/* Shorts vs Regular */}- <TabsContent value="shorts" className="space-y-4 mt-4">- <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">- <StatCard icon={<Flame />} label="Shorts Count" value={analytics.shortsCount} gradient="red" small />- <StatCard icon={<VideoIcon />} label="Regular Videos" value={analytics.regularCount} gradient="blue" small />- <StatCard icon={<Eye />} label="Avg Short Views" value={fmtNum(analytics.avgShortViews)} gradient="orange" small />- <StatCard icon={<Eye />} label="Avg Regular Views" value={fmtNum(analytics.avgRegularViews)} gradient="green" small />- </div>- <div className="grid grid-cols-1 md:grid-cols-5 gap-4">- <div className="md:col-span-2">- <ChartCard title="Content Split">- <PieChart>- <Pie data={[{ name: 'Shorts', value: analytics.shortsCount, color: C.red }, { name: 'Regular', value: analytics.regularCount, color: C.blue }].filter(d => d.value > 0)}- dataKey="value" nameKey="name" cx="50%" cy="50%" outerRadius={95} innerRadius={50} paddingAngle={4} strokeWidth={0}>- {[{ color: C.red }, { color: C.blue }].map((d, i) => <Cell key={i} fill={d.color} />)}- </Pie>- <ReTooltip contentStyle={TS} />- <Legend iconType="circle" iconSize={8} wrapperStyle={{ fontSize: 11 }} />- </PieChart>- </ChartCard>- </div>- <div className="md:col-span-3">- <ChartCard title="Performance Comparison">- <BarChart data={[- { metric: 'Avg Views', Shorts: analytics.avgShortViews, Regular: analytics.avgRegularViews },- { metric: 'Avg Likes', Shorts: analytics.avgShortLikes, Regular: analytics.avgRegularLikes },- ]}>- <CartesianGrid strokeDasharray="3 3" stroke="var(--border)" vertical={false} />- <XAxis dataKey="metric" 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} />- <ReTooltip contentStyle={TS} formatter={v => fmtNumFull(v)} />- <Bar dataKey="Shorts" fill={C.red} radius={[4, 4, 0, 0]} />- <Bar dataKey="Regular" fill={C.blue} radius={[4, 4, 0, 0]} />- <Legend />- </BarChart>- </ChartCard>- </div>+ <TabsContent value="shorts" className="flex flex-col gap-4">+ <MetricGrid>+ <MetricBox small icon={<Flame />} label="Shorts" value={analytics.shortsCount} />+ <MetricBox small icon={<VideoIcon />} label="Regular videos" value={analytics.regularCount} />+ <MetricBox small icon={<Eye />} label="Average views per Short" value={fmtNum(analytics.avgShortViews)} />+ <MetricBox small icon={<Eye />} label="Average views per video" value={fmtNum(analytics.avgRegularViews)} />+ </MetricGrid>+ <div className="grid grid-cols-1 gap-4 md:grid-cols-5">+ <ChartPanel title="Content split" className="md:col-span-2" empty={splitData.length === 0}>+ <PieChart>+ <Pie data={splitData} dataKey="value" nameKey="name" cx="50%" cy="50%" outerRadius={95} innerRadius={55} paddingAngle={2} strokeWidth={0}>+ {splitData.map(d => <Cell key={d.name} fill={d.color} />)}+ </Pie>+ <ReTooltip contentStyle={tooltipStyle} />+ <Legend iconType="circle" iconSize={8} wrapperStyle={legendStyle} />+ </PieChart>+ </ChartPanel>+ <ChartPanel title="Shorts compared with regular videos" className="md:col-span-3">+ <BarChart data={[+ { metric: 'Average views', Shorts: analytics.avgShortViews, Regular: analytics.avgRegularViews },+ { metric: 'Average likes', Shorts: analytics.avgShortLikes, Regular: analytics.avgRegularLikes },+ ]}>+ <CartesianGrid {...gridProps} vertical={false} />+ <XAxis dataKey="metric" {...axisProps} />+ <YAxis {...axisProps} tickFormatter={fmtNum} />+ <ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} formatter={v => fmtNumFull(v)} />+ <Bar dataKey="Shorts" fill={SERIES.primary} radius={[4, 4, 0, 0]} />+ <Bar dataKey="Regular" fill={SERIES.cool} radius={[4, 4, 0, 0]} />+ <Legend wrapperStyle={legendStyle} />+ </BarChart>+ </ChartPanel></div></TabsContent>- {/* Tags & SEO */}- <TabsContent value="tags" className="space-y-4 mt-4">- <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">- <StatCard icon={<Tag />} label="Unique Tags" value={analytics.tagFrequency?.length || 0} gradient="blue" small />- <StatCard icon={<MessageSquare />} label="Caption Rate" value={fmtPercent(analytics.captionPercentage)} gradient="green" small />- <StatCard icon={<Film />} label="HD Rate" value={fmtPercent(analytics.hdPercentage)} gradient="purple" small />- <StatCard icon={<VideoIcon />} label="Embeddable" value={fmtPercent(analytics.embeddablePercentage)} gradient="orange" small />- </div>- <MainCard title="Most Used Tags">- <div className="flex flex-wrap gap-2">- {(analytics.tagFrequency || []).map(({ tag, count }, i) => (- <Badge key={i} variant={i < 5 ? 'default' : 'outline'} className={cn('text-xs', i < 5 ? 'bg-primary' : '')}>- {tag} ({count})- </Badge>- ))}- {(!analytics.tagFrequency || analytics.tagFrequency.length === 0) && (- <p className="text-sm text-muted-foreground">No tags data available</p>- )}- </div>- </MainCard>+ <TabsContent value="tags" className="flex flex-col gap-4">+ <MetricGrid>+ <MetricBox small icon={<Tag />} label="Unique tags" value={analytics.tagFrequency?.length || 0} />+ <MetricBox small icon={<MessageSquare />} label="Caption rate" value={fmtPercent(analytics.captionPercentage)} />+ <MetricBox small icon={<Film />} label="HD rate" value={fmtPercent(analytics.hdPercentage)} />+ <MetricBox small icon={<VideoIcon />} label="Embeddable rate" value={fmtPercent(analytics.embeddablePercentage)} />+ </MetricGrid>+ <SurfaceBox title="Most used tags">+ {(analytics.tagFrequency || []).length === 0 ? (+ <p className="text-small text-ink-faint">These videos have no tags.</p>+ ) : (+ <div className="flex flex-wrap gap-1.5">+ {analytics.tagFrequency.map(({ tag, count }, i) => (+ <Badge key={tag} variant={i < 5 ? 'default' : 'outline'} className="h-6 px-2.5">+ {tag}<span className="opacity-70">{count}</span>+ </Badge>+ ))}+ </div>+ )}+ </SurfaceBox>{(analytics.tagFrequency || []).length > 0 && (- <ChartCard title="Tag Usage Frequency (Top 20)" height={400}>- <BarChart data={(analytics.tagFrequency || []).slice(0, 20)} layout="vertical">- <CartesianGrid strokeDasharray="3 3" stroke="var(--border)" horizontal={false} />- <XAxis type="number" tick={{ fill: 'var(--muted-foreground)', fontSize: 11 }} axisLine={false} tickLine={false} />- <YAxis dataKey="tag" type="category" tick={{ fill: 'var(--muted-foreground)', fontSize: 11 }} width={140} axisLine={false} tickLine={false} />- <ReTooltip contentStyle={TS} />- <Bar dataKey="count" fill={C.red} radius={[0, 4, 4, 0]} name="Usage Count" />+ <ChartPanel title="Tag usage, top 20" height={400}>+ <BarChart data={analytics.tagFrequency.slice(0, 20)} layout="vertical">+ <CartesianGrid {...gridProps} horizontal={false} />+ <XAxis type="number" {...axisProps} />+ <YAxis dataKey="tag" type="category" {...axisProps} width={140} />+ <ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} />+ <Bar dataKey="count" fill={SERIES.primary} radius={[0, 4, 4, 0]} name="Videos using this tag" /></BarChart>- </ChartCard>+ </ChartPanel>)}</TabsContent></Tabs>diff --git a/frontend/src/features/analytics/instagram/InstagramAnalytics.jsx b/frontend/src/features/analytics/instagram/InstagramAnalytics.jsxindex 8ed04cd..c80bd36 100644--- a/frontend/src/features/analytics/instagram/InstagramAnalytics.jsx+++ b/frontend/src/features/analytics/instagram/InstagramAnalytics.jsx@@ -1,48 +1,65 @@-import React, { useState, useEffect } from 'react';-import { useParams, useNavigate } from 'react-router-dom';+import React, { useCallback, useEffect, useState } from 'react';+import { useParams } from 'react-router-dom';+import {+ BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip as ReTooltip, PieChart, Pie, Cell, Legend,+ AreaChart, Area,+} from 'recharts';+import {+ RefreshCw, Heart, MessageCircle, Users, UserPlus, Image, TrendingUp, Calendar, Clock, Zap, Flame,+ Trophy, Star, ExternalLink, BarChart2, Hash, Eye, Clapperboard, Film, UserX,+} from 'lucide-react';import { Button } from '@/components/ui/button';import { Badge } from '@/components/ui/badge';-import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';-import { Skeleton } from '@/components/ui/skeleton';import { Progress } from '@/components/ui/progress';import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';-import { Separator } from '@/components/ui/separator';-import {- BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip as ReTooltip,- ResponsiveContainer, PieChart, Pie, Cell, Legend, AreaChart, Area,-} from 'recharts';-import { Spinner } from '@/components/ui/spinner';-import StatCard from '../../../components/ui/StatCard';-import MainCard from '../../../components/MainCard';+import PageHeader from '@/components/PageHeader';+import MetricBox from '@/components/MetricBox';+import SurfaceBox from '@/components/SurfaceBox';+import ChartPanel from '@/components/ChartPanel';+import { MediaChip } from '@/components/MediaCard';+import { EmptyState, PageSkeleton } from '@/components/StateViews';+import { AccountAvatar } from '@/components/platform';+import { SERIES, axisProps, gridProps, legendStyle, tooltipCursor, tooltipStyle } from '@/lib/chart';import { useAppContext } from '../../../context/AppContext';import { api } from '../../../services/api';import { fmtNum, fmtNumFull, fmtDate, timeAgo } from '../../../utils/formatters';import { IG_CONTENT_TYPES, IG_CONTENT_TYPE_META, igContentTypeMeta, fmtIGViews } from '../../../utils/instagramContent';-import {- ArrowLeft, RefreshCw, Heart, MessageCircle, Users, UserPlus, Image,- TrendingUp, Calendar, Clock, Zap, Flame, Trophy, Star, Camera,- ExternalLink, BarChart2, Hash, Eye, Clapperboard, Film,-} from 'lucide-react';+import { cn } from '@/lib/utils';++const CONTENT_TYPE_ICONS = { reel: Clapperboard, post: Image, video: Film };-const IG_COLORS = ['#F58529', '#DD2A7B', '#8134AF', '#515BD4', '#FEDA77', '#405DE6'];-const CONTENT_TYPE_ICONS = { reel: <Clapperboard />, post: <Image />, video: <Film /> };-const CONTENT_TYPE_GRADIENTS = { reel: 'pink', post: 'orange', video: 'purple' };+function TypeBadge({ type }) {+ const meta = igContentTypeMeta(type);+ return (+ <span className="inline-flex h-5 items-center gap-1.5 rounded-pill border border-line px-2 text-caption font-medium text-ink-muted">+ <span className="size-2 rounded-full" style={{ background: meta.color }} />+ {meta.label}+ </span>+ );+}-const TS = { background: 'var(--card)', border: '1px solid var(--border)', borderRadius: 8, fontSize: 12 };+function InsightChip({ icon, children }) {+ const Icon = icon;+ return (+ <span className="inline-flex h-8 items-center gap-1.5 rounded-field border border-line bg-surface px-3 text-small font-medium text-ink">+ <Icon className="size-3.5 stroke-[1.75] text-ink-faint" />+ {children}+ </span>+ );+}export default function InstagramAnalytics() {const { id } = useParams();const { accounts, showToast } = useAppContext();- const navigate = useNavigate();const account = accounts.find(a => a.id === id);- const [loading, setLoading] = useState(true);- const [profile, setProfile] = useState(null);- const [analytics, setAnalytics] = useState(null);+ const [loading, setLoading] = useState(true);+ const [profile, setProfile] = useState(null);+ const [analytics, setAnalytics] = useState(null);const [refreshing, setRefreshing] = useState(false);- const loadAnalytics = async () => {+ const loadAnalytics = useCallback(async () => {if (!account) return;setLoading(true);try {@@ -50,48 +67,43 @@ export default function InstagramAnalytics() {setProfile(data.profile);setAnalytics(data.analytics);} catch (err) {- showToast('Failed to load Instagram analytics: ' + err.message, 'error');+ showToast(`Couldn't load Instagram analytics. ${err.message}`, 'error');} finally {setLoading(false);}- };+ // Keyed on the account id so a background account refresh does not refetch analytics+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [account?.id, showToast]);- useEffect(() => { loadAnalytics(); }, [id]);+ useEffect(() => { loadAnalytics(); }, [id, loadAnalytics]);const handleRefresh = async () => {setRefreshing(true);try {await api.refreshAccount(account.id);await loadAnalytics();- showToast('Instagram account refreshed!');+ showToast('Instagram account refreshed');} catch (err) {- showToast('Refresh failed: ' + err.message, 'error');+ showToast(`Refresh failed. ${err.message}`, 'error');} finally {setRefreshing(false);}};+ const back = { to: '/', label: 'Overview' };+if (!account) {return (- <div className="space-y-3">- <Button variant="ghost" onClick={() => navigate('/')} className="gap-2 -ml-2 text-muted-foreground">- <ArrowLeft className="h-4 w-4" /> Back- </Button>- <p className="text-muted-foreground">Account not found.</p>+ <div className="flex flex-col gap-6">+ <PageHeader title="Instagram account" back={back} />+ <SurfaceBox>+ <EmptyState icon={<UserX />} title="Account not found" description="It may have been removed. Choose another account from the sidebar." />+ </SurfaceBox></div>);}- if (loading) {- return (- <div className="flex items-center justify-center min-h-[50vh]">- <div className="flex flex-col items-center gap-3">- <Spinner className="size-10" />- <p className="text-sm text-muted-foreground">Loading analytics…</p>- </div>- </div>- );- }+ if (loading) return <PageSkeleton metrics={6} />;const p = profile || account;const a = analytics || {};@@ -103,353 +115,291 @@ export default function InstagramAnalytics() {const contentMixData = typeRows.map(row => ({ name: row.name, value: row.count, color: row.color }));const topPostsData = (a.topPosts || []).slice(0, 8).map((post, i) => ({ name: `#${i + 1}`, likes: post.likeCount, comments: post.commentsCount }));const dayOfWeekData = (a.postsByDayOfWeek || []).map(d => ({ name: d.shortDay, posts: d.posts, avgEngagement: d.avgEngagement, avgLikes: d.avgLikes }));- const timelineData = (a.engagementTimeline || []).map(m => ({ name: m.month, posts: m.posts, likes: m.likes, comments: m.comments, avgLikes: m.avgLikes }));- const captionData = a.captionLengthCorrelation || [];+ const timelineData = (a.engagementTimeline || []).map(m => ({ name: m.month, posts: m.posts, likes: m.likes, comments: m.comments, avgLikes: m.avgLikes }));+ const captionData = a.captionLengthCorrelation || [];return (- <div className="space-y-5">- {/* Profile header */}- <div className="flex items-start justify-between gap-4 flex-wrap">- <div className="flex items-center gap-3">- <Button variant="ghost" onClick={() => navigate('/')} size="icon" className="h-9 w-9 text-muted-foreground">- <ArrowLeft className="h-4 w-4" />+ <div className="flex flex-col gap-6">+ <PageHeader+ back={back}+ media={<AccountAvatar account={{ ...account, profilePictureUrl: p.profilePictureUrl || account.profilePictureUrl }} size="xl" showPlatform />}+ title={p.name || p.username}+ description={+ <span className="flex flex-col gap-1">+ <span>@{p.username}</span>+ {p.biography && <span className="line-clamp-2 max-w-xl text-small text-ink-faint">{p.biography}</span>}+ </span>+ }+ actions={+ <Button variant="outline" size="sm" onClick={handleRefresh} disabled={refreshing}>+ <RefreshCw data-icon="inline-start" className={cn(refreshing && 'animate-spin')} />+ {refreshing ? 'Refreshing' : 'Refresh'}</Button>- <Avatar className="h-14 w-14 border-2 border-border">- <AvatarImage src={p.profilePictureUrl} />- <AvatarFallback className="bg-gradient-to-br from-pink-500 to-purple-600 text-white font-bold">- {(p.name || p.username || 'IG').slice(0, 2).toUpperCase()}- </AvatarFallback>- </Avatar>- <div>- <div className="flex items-center gap-2">- <h2 className="text-xl font-bold">{p.name || p.username}</h2>- <Camera className="h-4 w-4 text-pink-500" />- </div>- <p className="text-sm text-muted-foreground">@{p.username}</p>- {p.biography && <p className="text-xs text-muted-foreground mt-0.5 max-w-md line-clamp-2">{p.biography}</p>}- </div>- </div>- <Button size="sm" onClick={handleRefresh} disabled={refreshing} className="gap-2 shrink-0">- <RefreshCw className={`h-3.5 w-3.5 ${refreshing ? 'animate-spin' : ''}`} />- Refresh- </Button>- </div>+ }+ />- {refreshing && <Progress className="h-1" />}+ {refreshing && <Progress value={null} aria-label="Refreshing account" />}- {/* KPI stats */}- <div className="grid grid-cols-2 sm:grid-cols-3 xl:grid-cols-6 gap-3">- <StatCard icon={<Users />} label="Followers" value={fmtNum(p.followersCount)} subtitle={fmtNumFull(p.followersCount)} gradient="purple" small />- <StatCard icon={<UserPlus />} label="Following" value={fmtNum(p.followsCount)} subtitle={fmtNumFull(p.followsCount)} gradient="blue" small />- <StatCard icon={<Image />} label="Total Posts" value={fmtNum(a.totalPosts || p.mediaCount)} subtitle={`${a.fetchedPosts || 0} analyzed`} gradient="orange" small />- <StatCard icon={<Heart />} label="Total Likes" value={fmtNum(a.totalLikes)} subtitle={fmtNumFull(a.totalLikes)} gradient="red" small />- <StatCard icon={<MessageCircle />} label="Total Comments" value={fmtNum(a.totalComments)} subtitle={fmtNumFull(a.totalComments)} gradient="teal" small />- <StatCard icon={<TrendingUp />} label="Engagement Rate" value={`${a.engagementRate || 0}%`} subtitle={`Avg ${fmtNum(a.avgLikes)} likes/post`} gradient="green" small />- </div>- <div className="grid grid-cols-2 xl:grid-cols-4 gap-3">- <StatCard icon={<Eye />} label="Total Views" value={fmtNum(a.totalViews)} subtitle={`${a.mediaWithViews || 0} of ${a.fetchedPosts || 0} items report views`} gradient="blue" small />- {IG_CONTENT_TYPES.map(type => {- const stats = typeStats[type] || {};- return (- <StatCard- key={type}- icon={CONTENT_TYPE_ICONS[type]}- label={IG_CONTENT_TYPE_META[type].plural}- value={fmtNum(stats.count)}- subtitle={stats.viewsReported > 0 ? `${fmtNum(stats.totalViews)} views, ${fmtNum(stats.avgViews)} avg` : 'no views reported'}- gradient={CONTENT_TYPE_GRADIENTS[type]}- small- />- );- })}- </div>- <div className="grid grid-cols-2 sm:grid-cols-3 xl:grid-cols-6 gap-3">- <StatCard icon={<Zap />} label="Avg Likes/Post" value={fmtNum(a.avgLikes)} gradient="cyan" small />- <StatCard icon={<MessageCircle />} label="Avg Comments" value={fmtNum(a.avgComments)} gradient="indigo" small />- <StatCard icon={<BarChart2 />} label="Median Likes" value={fmtNum(a.medianLikes)} gradient="amber" small />- <StatCard icon={<Users />} label="Follower Ratio" value={p.followersCount > 0 ? (p.followersCount / Math.max(1, p.followsCount)).toFixed(1) : '0'} subtitle="Followers / Following" gradient="pink" small />- <StatCard icon={<Heart />} label="Likes/Follower" value={`${a.likesPerFollower || 0}%`} subtitle="Per post avg" gradient="red" small />- <StatCard icon={<TrendingUp />} label="Like:Comment" value={`${a.likesToCommentsRatio || 0}:1`} subtitle="Ratio" gradient="blue" small />- </div>- <div className="grid grid-cols-2 sm:grid-cols-3 xl:grid-cols-6 gap-3">- <StatCard icon={<Calendar />} label="Posts/Week" value={a.postFrequency?.perWeek || 0} subtitle={`${a.postFrequency?.perMonth || 0}/month`} gradient="orange" small />- <StatCard icon={<Calendar />} label="Last 7 Days" value={a.postsLast7Days || 0} subtitle="Recent posts" gradient="red" small />- <StatCard icon={<Calendar />} label="Last 30 Days" value={a.postsLast30Days || 0} subtitle="Monthly" gradient="green" small />- <StatCard icon={<Calendar />} label="Last 90 Days" value={a.postsLast90Days || 0} subtitle="Quarterly" gradient="blue" small />- <StatCard icon={<Flame />} label="Virality" value={`${a.viralityScore || 0}x`} subtitle="Best vs Average" gradient="pink" small />- <StatCard icon={<Trophy />} label="Consistency" value={`${a.consistencyScore || 0}/100`} subtitle="Engagement stability" gradient="amber" small />+ <div className="flex flex-col gap-3">+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 xl:grid-cols-6">+ <MetricBox small icon={<Users />} label="Followers" value={fmtNum(p.followersCount)} subtitle={fmtNumFull(p.followersCount)} highlight />+ <MetricBox small icon={<UserPlus />} label="Following" value={fmtNum(p.followsCount)} subtitle={fmtNumFull(p.followsCount)} />+ <MetricBox small icon={<Image />} label="Total posts" value={fmtNum(a.totalPosts || p.mediaCount)} subtitle={`${a.fetchedPosts || 0} analyzed`} />+ <MetricBox small icon={<Heart />} label="Total likes" value={fmtNum(a.totalLikes)} subtitle={fmtNumFull(a.totalLikes)} />+ <MetricBox small icon={<MessageCircle />} label="Total comments" value={fmtNum(a.totalComments)} subtitle={fmtNumFull(a.totalComments)} />+ <MetricBox small icon={<TrendingUp />} label="Engagement rate" value={`${a.engagementRate || 0}%`} subtitle={`${fmtNum(a.avgLikes)} likes per post on average`} />+ </div>+ <div className="grid grid-cols-2 gap-3 xl:grid-cols-4">+ <MetricBox small icon={<Eye />} label="Total views" value={fmtNum(a.totalViews)} subtitle={`${a.mediaWithViews || 0} of ${a.fetchedPosts || 0} items report views`} />+ {IG_CONTENT_TYPES.map(type => {+ const stats = typeStats[type] || {};+ const Icon = CONTENT_TYPE_ICONS[type];+ return (+ <MetricBox+ key={type}+ small+ icon={<Icon />}+ label={IG_CONTENT_TYPE_META[type].plural}+ value={fmtNum(stats.count)}+ subtitle={stats.viewsReported > 0 ? `${fmtNum(stats.totalViews)} views, ${fmtNum(stats.avgViews)} on average` : 'No views reported'}+ />+ );+ })}+ </div>+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 xl:grid-cols-6">+ <MetricBox small icon={<Zap />} label="Likes per post" value={fmtNum(a.avgLikes)} />+ <MetricBox small icon={<MessageCircle />} label="Comments per post" value={fmtNum(a.avgComments)} />+ <MetricBox small icon={<BarChart2 />} label="Median likes" value={fmtNum(a.medianLikes)} />+ <MetricBox small icon={<Users />} label="Follower ratio" value={p.followersCount > 0 ? (p.followersCount / Math.max(1, p.followsCount)).toFixed(1) : '0'} subtitle="Followers per account followed" />+ <MetricBox small icon={<Heart />} label="Likes per follower" value={`${a.likesPerFollower || 0}%`} subtitle="Per post, on average" />+ <MetricBox small icon={<TrendingUp />} label="Likes per comment" value={`${a.likesToCommentsRatio || 0}:1`} />+ </div>+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 xl:grid-cols-6">+ <MetricBox small icon={<Calendar />} label="Posts per week" value={a.postFrequency?.perWeek || 0} subtitle={`${a.postFrequency?.perMonth || 0} per month`} />+ <MetricBox small icon={<Calendar />} label="Last 7 days" value={a.postsLast7Days || 0} subtitle="Posts" />+ <MetricBox small icon={<Calendar />} label="Last 30 days" value={a.postsLast30Days || 0} subtitle="Posts" />+ <MetricBox small icon={<Calendar />} label="Last 90 days" value={a.postsLast90Days || 0} subtitle="Posts" />+ <MetricBox small icon={<Flame />} label="Virality" value={`${a.viralityScore || 0}x`} subtitle="Best post against the average" />+ <MetricBox small icon={<Trophy />} label="Consistency" value={`${a.consistencyScore || 0}/100`} subtitle="Engagement stability" />+ </div></div>- {/* Insights row */}- <MainCard>- <div className="flex gap-2 flex-wrap items-center">- {a.bestPostingDay && (- <span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-semibold bg-amber-50 border border-amber-200 text-amber-700">- <Star className="h-3 w-3" /> Best Day: {a.bestPostingDay}- </span>- )}- {a.bestPostingHour && (- <span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-semibold bg-green-50 border border-green-200 text-green-700">- <Clock className="h-3 w-3" /> Best Hour: {a.bestPostingHour}- </span>- )}- <span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-semibold bg-blue-50 border border-blue-200 text-blue-700">- <TrendingUp className="h-3 w-3" /> Avg Engagement: {fmtNum(a.avgEngagement || 0)}/post- </span>- <span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-semibold bg-purple-50 border border-purple-200 text-purple-700">- <Trophy className="h-3 w-3" /> Consistency: {a.consistencyScore || 0}/100- </span>- </div>- </MainCard>+ <div className="flex flex-wrap items-center gap-2">+ {a.bestPostingDay && <InsightChip icon={Star}>Best day: {a.bestPostingDay}</InsightChip>}+ {a.bestPostingHour && <InsightChip icon={Clock}>Best hour: {a.bestPostingHour}</InsightChip>}+ <InsightChip icon={TrendingUp}>Average engagement: {fmtNum(a.avgEngagement || 0)} per post</InsightChip>+ <InsightChip icon={Trophy}>Consistency: {a.consistencyScore || 0}/100</InsightChip>+ </div>- {/* Engagement timeline + content mix */}- <div className="grid grid-cols-1 xl:grid-cols-3 gap-4">- <MainCard title="Engagement Timeline" className="xl:col-span-2" contentClassName="p-3">- {timelineData.length > 0 ? (- <ResponsiveContainer width="100%" height={280} debounce={200}>- <AreaChart data={timelineData}>- <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 }} axisLine={false} tickLine={false} width={44} />- <ReTooltip contentStyle={TS} />- <Area type="monotone" dataKey="likes" name="Likes" stroke="#DD2A7B" fill="rgba(221,42,123,0.1)" />- <Area type="monotone" dataKey="comments" name="Comments" stroke="#8134AF" fill="rgba(129,52,175,0.1)" />- </AreaChart>- </ResponsiveContainer>- ) : <p className="text-sm text-muted-foreground text-center py-10">Not enough data for timeline</p>}- </MainCard>- <MainCard title="Content Type Mix" contentClassName="p-3">- {contentMixData.length > 0 ? (- <ResponsiveContainer width="100%" height={280} debounce={200}>- <PieChart>- <Pie data={contentMixData} dataKey="value" nameKey="name" cx="50%" cy="44%" outerRadius={80} innerRadius={42} paddingAngle={3} strokeWidth={0}>- {contentMixData.map((entry, i) => <Cell key={i} fill={entry.color} />)}- </Pie>- <ReTooltip contentStyle={TS} formatter={(v, n) => [`${v} posts`, n]} />- <Legend iconType="circle" iconSize={8} wrapperStyle={{ fontSize: 11, paddingTop: 8 }} />- </PieChart>- </ResponsiveContainer>- ) : <p className="text-sm text-muted-foreground text-center py-10">No data</p>}- </MainCard>+ <div className="grid grid-cols-1 gap-4 xl:grid-cols-3">+ <ChartPanel title="Engagement over time" className="xl:col-span-2" empty={timelineData.length === 0} emptyMessage="Not enough posts to chart a timeline">+ <AreaChart data={timelineData}>+ <defs>+ <linearGradient id="igLikesGrad" x1="0" y1="0" x2="0" y2="1">+ <stop offset="5%" stopColor={SERIES.primary} stopOpacity={0.2} />+ <stop offset="95%" stopColor={SERIES.primary} stopOpacity={0} />+ </linearGradient>+ </defs>+ <CartesianGrid {...gridProps} vertical={false} />+ <XAxis dataKey="name" {...axisProps} />+ <YAxis {...axisProps} width={44} tickFormatter={fmtNum} />+ <ReTooltip contentStyle={tooltipStyle} cursor={{ stroke: 'var(--line-strong)' }} />+ <Area type="monotone" dataKey="likes" name="Likes" stroke={SERIES.primary} strokeWidth={2} fill="url(#igLikesGrad)" />+ <Area type="monotone" dataKey="comments" name="Comments" stroke={SERIES.cool} strokeWidth={2} fill="transparent" />+ <Legend wrapperStyle={legendStyle} />+ </AreaChart>+ </ChartPanel>+ <ChartPanel title="Content type mix" empty={contentMixData.length === 0}>+ <PieChart>+ <Pie data={contentMixData} dataKey="value" nameKey="name" cx="50%" cy="44%" outerRadius={80} innerRadius={48} paddingAngle={2} strokeWidth={0}>+ {contentMixData.map(entry => <Cell key={entry.name} fill={entry.color} />)}+ </Pie>+ <ReTooltip contentStyle={tooltipStyle} formatter={(v, n) => [`${v} items`, n]} />+ <Legend iconType="circle" iconSize={8} wrapperStyle={{ ...legendStyle, paddingTop: 8 }} />+ </PieChart>+ </ChartPanel></div>- {/* Performance by type + Day of week */}- <div className="grid grid-cols-1 md:grid-cols-2 gap-4">- <MainCard title="Performance by Content Type" contentClassName="p-3">- {typeRows.length > 0 ? (- <ResponsiveContainer width="100%" height={260} debounce={200}>- <BarChart data={typeRows}>- <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 }} axisLine={false} tickLine={false} width={44} />- <ReTooltip contentStyle={TS} />- <Bar dataKey="avgLikes" name="Avg Likes" fill="#DD2A7B" radius={[4, 4, 0, 0]} />- <Bar dataKey="avgComments" name="Avg Comments" fill="#8134AF" radius={[4, 4, 0, 0]} />- <Legend />- </BarChart>- </ResponsiveContainer>- ) : <p className="text-sm text-muted-foreground text-center py-10">No data</p>}- </MainCard>- <MainCard title="Best Posting Days" contentClassName="p-3">- {dayOfWeekData.length > 0 ? (- <ResponsiveContainer width="100%" height={260} debounce={200}>- <BarChart data={dayOfWeekData}>- <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 }} axisLine={false} tickLine={false} width={44} />- <ReTooltip contentStyle={TS} />- <Bar dataKey="avgEngagement" name="Avg Engagement" fill="#F58529" radius={[4, 4, 0, 0]} />- <Bar dataKey="posts" name="Posts" fill="var(--muted)" radius={[4, 4, 0, 0]} />- <Legend />- </BarChart>- </ResponsiveContainer>- ) : <p className="text-sm text-muted-foreground text-center py-10">No data</p>}- </MainCard>+ <div className="grid grid-cols-1 gap-4 md:grid-cols-2">+ <ChartPanel title="Performance by content type" height={260} empty={typeRows.length === 0}>+ <BarChart data={typeRows}>+ <CartesianGrid {...gridProps} vertical={false} />+ <XAxis dataKey="name" {...axisProps} />+ <YAxis {...axisProps} width={44} tickFormatter={fmtNum} />+ <ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} />+ <Bar dataKey="avgLikes" name="Average likes" fill={SERIES.primary} radius={[4, 4, 0, 0]} />+ <Bar dataKey="avgComments" name="Average comments" fill={SERIES.neutral} radius={[4, 4, 0, 0]} />+ <Legend wrapperStyle={legendStyle} />+ </BarChart>+ </ChartPanel>+ <ChartPanel title="Best days to post" height={260} empty={dayOfWeekData.length === 0}>+ <BarChart data={dayOfWeekData}>+ <CartesianGrid {...gridProps} vertical={false} />+ <XAxis dataKey="name" {...axisProps} />+ <YAxis {...axisProps} width={44} tickFormatter={fmtNum} />+ <ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} />+ <Bar dataKey="avgEngagement" name="Average engagement" fill={SERIES.warm} radius={[4, 4, 0, 0]} />+ <Bar dataKey="posts" name="Posts" fill={SERIES.neutral} radius={[4, 4, 0, 0]} />+ <Legend wrapperStyle={legendStyle} />+ </BarChart>+ </ChartPanel></div>- {/* Top posts + caption length */}- <div className="grid grid-cols-1 md:grid-cols-2 gap-4">- <MainCard title="Top Posts by Engagement" contentClassName="p-3">- {topPostsData.length > 0 ? (- <ResponsiveContainer width="100%" height={260} debounce={200}>- <BarChart data={topPostsData}>- <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 }} axisLine={false} tickLine={false} width={44} />- <ReTooltip contentStyle={TS} />- <Bar dataKey="likes" name="Likes" fill="#DD2A7B" radius={[4, 4, 0, 0]} />- <Bar dataKey="comments" name="Comments" fill="#8134AF" radius={[4, 4, 0, 0]} />- <Legend />- </BarChart>- </ResponsiveContainer>- ) : <p className="text-sm text-muted-foreground text-center py-10">No data</p>}- </MainCard>- <MainCard title="Caption Length vs Engagement" contentClassName="p-3">- {captionData.length > 0 ? (- <ResponsiveContainer width="100%" height={260} debounce={200}>- <BarChart data={captionData}>- <CartesianGrid strokeDasharray="3 3" stroke="var(--border)" vertical={false} />- <XAxis dataKey="label" tick={{ fill: 'var(--muted-foreground)', fontSize: 11 }} axisLine={false} tickLine={false} />- <YAxis tick={{ fill: 'var(--muted-foreground)', fontSize: 11 }} axisLine={false} tickLine={false} width={44} />- <ReTooltip contentStyle={TS} />- <Bar dataKey="avgEngagement" name="Avg Engagement" fill="#515BD4" radius={[4, 4, 0, 0]} />- </BarChart>- </ResponsiveContainer>- ) : <p className="text-sm text-muted-foreground text-center py-10">No data</p>}- </MainCard>+ <div className="grid grid-cols-1 gap-4 md:grid-cols-2">+ <ChartPanel title="Top posts by engagement" height={260} empty={topPostsData.length === 0}>+ <BarChart data={topPostsData}>+ <CartesianGrid {...gridProps} vertical={false} />+ <XAxis dataKey="name" {...axisProps} />+ <YAxis {...axisProps} width={44} tickFormatter={fmtNum} />+ <ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} />+ <Bar dataKey="likes" name="Likes" fill={SERIES.primary} radius={[4, 4, 0, 0]} />+ <Bar dataKey="comments" name="Comments" fill={SERIES.neutral} radius={[4, 4, 0, 0]} />+ <Legend wrapperStyle={legendStyle} />+ </BarChart>+ </ChartPanel>+ <ChartPanel title="Caption length and engagement" height={260} empty={captionData.length === 0}>+ <BarChart data={captionData}>+ <CartesianGrid {...gridProps} vertical={false} />+ <XAxis dataKey="label" {...axisProps} />+ <YAxis {...axisProps} width={44} tickFormatter={fmtNum} />+ <ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} />+ <Bar dataKey="avgEngagement" name="Average engagement" fill={SERIES.cool} radius={[4, 4, 0, 0]} />+ </BarChart>+ </ChartPanel></div>- {/* Monthly posting volume */}{timelineData.length > 1 && (- <MainCard title="Monthly Posting Volume" contentClassName="p-3">- <ResponsiveContainer width="100%" height={220} debounce={200}>- <BarChart data={timelineData}>- <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 }} axisLine={false} tickLine={false} width={44} />- <ReTooltip contentStyle={TS} />- <Bar dataKey="posts" name="Posts" fill="#F58529" radius={[4, 4, 0, 0]} />- </BarChart>- </ResponsiveContainer>- </MainCard>+ <ChartPanel title="Posts per month" height={220}>+ <BarChart data={timelineData}>+ <CartesianGrid {...gridProps} vertical={false} />+ <XAxis dataKey="name" {...axisProps} />+ <YAxis {...axisProps} width={44} />+ <ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} />+ <Bar dataKey="posts" name="Posts" fill={SERIES.warm} radius={[4, 4, 0, 0]} />+ </BarChart>+ </ChartPanel>)}- {/* Top hashtags */}{(a.hashtagAnalysis || []).length > 0 && (- <MainCard title="Top Hashtags">- <div className="flex flex-wrap gap-2">+ <SurfaceBox title="Top hashtags">+ <div className="flex flex-wrap gap-1.5">{a.hashtagAnalysis.slice(0, 20).map((h, i) => (<Tooltip key={h.tag}>- <TooltipTrigger>- <Badge- variant="outline"- className="text-xs cursor-default"- style={{ borderColor: `${IG_COLORS[i % IG_COLORS.length]}60`, color: IG_COLORS[i % IG_COLORS.length], background: `${IG_COLORS[i % IG_COLORS.length]}10` }}- >- <Hash className="h-2.5 w-2.5 mr-0.5" />{h.tag} ({h.count})- </Badge>+ <TooltipTrigger render={<Badge variant={i < 5 ? 'default' : 'outline'} className="h-6 cursor-default px-2.5" />}>+ <Hash />{h.tag}<span className="opacity-70">{h.count}</span></TooltipTrigger>- <TooltipContent>Used {h.count}x · Avg engagement: {fmtNum(h.avgEngagement)}</TooltipContent>+ <TooltipContent>Used {h.count} times, {fmtNum(h.avgEngagement)} average engagement</TooltipContent></Tooltip>))}</div>- </MainCard>+ </SurfaceBox>)}- {/* Recent posts grid */}- <MainCard title={`Recent Posts (${a.fetchedPosts || 0} loaded)`}>+ <SurfaceBox title="Recent posts" subheader={`${a.fetchedPosts || 0} loaded`}>{(a.recentMedia || []).length > 0 ? (- <div className="grid grid-cols-3 sm:grid-cols-4 md:grid-cols-6 xl:grid-cols-8 gap-2">- {a.recentMedia.map((post) => (- <div- key={post.id}- className="relative aspect-square rounded-lg overflow-hidden border border-border cursor-pointer group hover:shadow-md transition-shadow"- onClick={() => post.permalink && window.open(post.permalink, '_blank')}- >- <img src={post.contentType === 'post' ? (post.thumbnailUrl || post.mediaUrl) : post.thumbnailUrl} className="w-full h-full object-cover" alt=""- onError={e => { e.target.style.display = 'none'; }} />- {post.contentType !== 'post' && (- <span className="absolute top-1 right-1 bg-black/65 text-white text-[9px] font-semibold px-1 rounded">- {igContentTypeMeta(post.contentType).label}+ <div className="grid grid-cols-3 gap-2 sm:grid-cols-4 md:grid-cols-6 xl:grid-cols-8">+ {a.recentMedia.map(post => {+ const thumb = post.contentType === 'post' ? (post.thumbnailUrl || post.mediaUrl) : post.thumbnailUrl;+ return (+ <a+ key={post.id}+ href={post.permalink}+ target="_blank"+ rel="noopener noreferrer"+ aria-label={`Open ${igContentTypeMeta(post.contentType).label.toLowerCase()} on Instagram`}+ className="group relative aspect-square overflow-hidden rounded-control border border-line bg-surface-sunken focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring"+ >+ {thumb && <img src={thumb} alt="" loading="lazy" className="size-full object-cover" onError={e => { e.currentTarget.style.display = 'none'; }} />}+ {post.contentType !== 'post' && (+ <span className="absolute top-1 right-1"><MediaChip className="px-1.5 text-[0.625rem]">{igContentTypeMeta(post.contentType).label}</MediaChip></span>+ )}+ <span className="absolute inset-x-0 bottom-0 flex justify-center gap-2 bg-gradient-to-t from-[#0C0809]/80 to-transparent pt-4 pb-1 text-[0.625rem] font-semibold text-white opacity-0 transition-opacity duration-(--duration-base) group-hover:opacity-100 group-focus-visible:opacity-100 [&_svg]:size-2.5">+ <span className="flex items-center gap-0.5"><Eye />{fmtIGViews(post.viewCount)}</span>+ <span className="flex items-center gap-0.5"><Heart />{fmtNum(post.likeCount)}</span>+ <span className="flex items-center gap-0.5"><MessageCircle />{fmtNum(post.commentsCount)}</span></span>- )}- <div className="absolute inset-0 bg-gradient-to-t from-black/60 via-transparent opacity-0 group-hover:opacity-100 transition-opacity flex items-end justify-center pb-1 gap-2">- <span className="flex items-center gap-0.5 text-white text-[10px] font-semibold"><Eye className="h-2.5 w-2.5" />{fmtIGViews(post.viewCount)}</span>- <span className="flex items-center gap-0.5 text-white text-[10px] font-semibold"><Heart className="h-2.5 w-2.5" />{fmtNum(post.likeCount)}</span>- <span className="flex items-center gap-0.5 text-white text-[10px] font-semibold"><MessageCircle className="h-2.5 w-2.5" />{fmtNum(post.commentsCount)}</span>- </div>- </div>- ))}+ </a>+ );+ })}</div>- ) : <p className="text-sm text-muted-foreground text-center py-6">No posts found</p>}- </MainCard>+ ) : (+ <EmptyState compact icon={<Image />} title="No posts yet" description="This account has not published anything we can read." />+ )}+ </SurfaceBox>- {/* Top posts table */}{(a.topPosts || []).length > 0 && (- <MainCard title="Top Performing Posts" content={false}>+ <SurfaceBox title="Top performing posts" content={false} className="overflow-hidden"><Table><TableHeader><TableRow>- <TableHead className="w-8">#</TableHead>+ <TableHead className="w-10 text-right">#</TableHead><TableHead>Caption</TableHead><TableHead>Type</TableHead><TableHead className="text-right">Views</TableHead><TableHead className="text-right">Likes</TableHead><TableHead className="text-right">Comments</TableHead><TableHead className="text-right">Engagement</TableHead>- <TableHead>Date</TableHead>- <TableHead className="w-8" />+ <TableHead>Posted</TableHead>+ <TableHead className="w-10"><span className="sr-only">Open</span></TableHead></TableRow></TableHeader><TableBody>- {a.topPosts.slice(0, 10).map((post, i) => {- const meta = igContentTypeMeta(post.contentType);- return (- <TableRow key={post.id}>- <TableCell className="text-xs text-muted-foreground">{i + 1}</TableCell>- <TableCell className="max-w-[200px]"><p className="text-sm truncate">{post.caption || '(no caption)'}</p></TableCell>- <TableCell>- <Badge variant="outline" className="text-[10px] h-5" style={{ borderColor: `${meta.color}50`, color: meta.color, background: `${meta.color}10` }}>- {meta.label}- </Badge>- </TableCell>- <TableCell className="text-right text-sm">{fmtIGViews(post.viewCount)}</TableCell>- <TableCell className="text-right text-sm">{fmtNum(post.likeCount)}</TableCell>- <TableCell className="text-right text-sm">{fmtNum(post.commentsCount)}</TableCell>- <TableCell className="text-right text-sm">{fmtNum(post.engagement)}</TableCell>- <TableCell className="text-xs text-muted-foreground">{fmtDate(post.timestamp)}</TableCell>- <TableCell>- {post.permalink && (- <Button variant="ghost" size="icon" className="h-6 w-6" onClick={() => window.open(post.permalink, '_blank')}>- <ExternalLink className="h-3 w-3" />- </Button>- )}- </TableCell>- </TableRow>- );- })}+ {a.topPosts.slice(0, 10).map((post, i) => (+ <TableRow key={post.id}>+ <TableCell className="text-right font-mono text-caption text-ink-faint">{i + 1}</TableCell>+ <TableCell className="max-w-[220px]"><p className="truncate text-sm text-ink">{post.caption || 'No caption'}</p></TableCell>+ <TableCell><TypeBadge type={post.contentType} /></TableCell>+ <TableCell className="text-right text-ink-muted">{fmtIGViews(post.viewCount)}</TableCell>+ <TableCell className="text-right font-semibold text-ink">{fmtNum(post.likeCount)}</TableCell>+ <TableCell className="text-right text-ink-muted">{fmtNum(post.commentsCount)}</TableCell>+ <TableCell className="text-right text-ink-muted">{fmtNum(post.engagement)}</TableCell>+ <TableCell className="text-small text-ink-faint">{fmtDate(post.timestamp)}</TableCell>+ <TableCell>+ {post.permalink && (+ <Button variant="ghost" size="icon-xs" render={<a href={post.permalink} target="_blank" rel="noopener noreferrer" aria-label="Open post on Instagram" />}>+ <ExternalLink />+ </Button>+ )}+ </TableCell>+ </TableRow>+ ))}</TableBody></Table>- </MainCard>+ </SurfaceBox>)}- {/* Performance by type table */}{typeRows.length > 0 && (- <MainCard title="Performance Summary by Content Type" content={false}>+ <SurfaceBox title="Summary by content type" content={false} className="overflow-hidden"><Table><TableHeader><TableRow><TableHead>Type</TableHead><TableHead className="text-right">Count</TableHead>- <TableHead className="text-right">Total Views</TableHead>- <TableHead className="text-right">Avg Views</TableHead>- <TableHead className="text-right">Avg Likes</TableHead>- <TableHead className="text-right">Avg Comments</TableHead>- <TableHead className="text-right">Avg Engagement</TableHead>+ <TableHead className="text-right">Total views</TableHead>+ <TableHead className="text-right">Average views</TableHead>+ <TableHead className="text-right">Average likes</TableHead>+ <TableHead className="text-right">Average comments</TableHead>+ <TableHead className="text-right">Average engagement</TableHead></TableRow></TableHeader><TableBody>{typeRows.map(row => (<TableRow key={row.type}>- <TableCell>- <Badge variant="outline" className="text-xs" style={{ borderColor: `${row.color}50`, color: row.color, background: `${row.color}10` }}>- {row.name}- </Badge>- </TableCell>- <TableCell className="text-right">{row.count}</TableCell>- <TableCell className="text-right">{row.viewsReported > 0 ? fmtNum(row.totalViews) : '-'}</TableCell>- <TableCell className="text-right">{row.viewsReported > 0 ? fmtNum(row.avgViews) : '-'}</TableCell>- <TableCell className="text-right">{fmtNum(row.avgLikes)}</TableCell>- <TableCell className="text-right">{fmtNum(row.avgComments)}</TableCell>- <TableCell className="text-right">{fmtNum(row.avgEngagement)}</TableCell>+ <TableCell><TypeBadge type={row.type} /></TableCell>+ <TableCell className="text-right text-ink">{row.count}</TableCell>+ <TableCell className="text-right text-ink-muted">{row.viewsReported > 0 ? fmtNum(row.totalViews) : '-'}</TableCell>+ <TableCell className="text-right text-ink-muted">{row.viewsReported > 0 ? fmtNum(row.avgViews) : '-'}</TableCell>+ <TableCell className="text-right text-ink-muted">{fmtNum(row.avgLikes)}</TableCell>+ <TableCell className="text-right text-ink-muted">{fmtNum(row.avgComments)}</TableCell>+ <TableCell className="text-right font-semibold text-ink">{fmtNum(row.avgEngagement)}</TableCell></TableRow>))}</TableBody></Table>- </MainCard>+ </SurfaceBox>)}- <p className="text-xs text-muted-foreground text-center">Last updated: {timeAgo(account.lastUpdated)}</p>+ <p className="text-center text-caption text-ink-faint">Last updated {timeAgo(account.lastUpdated).toLowerCase()}</p></div>);}diff --git a/frontend/src/features/analytics/overview/Overview.jsx b/frontend/src/features/analytics/overview/Overview.jsxindex 1b8f545..1cc2d35 100644--- a/frontend/src/features/analytics/overview/Overview.jsx+++ b/frontend/src/features/analytics/overview/Overview.jsx@@ -1,56 +1,49 @@import React, { useState, useEffect, useMemo } from 'react';-import { useNavigate } from 'react-router-dom';+import { Link, useNavigate } from 'react-router-dom';+import {+ AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip as ReTooltip, ResponsiveContainer,+} from 'recharts';+import {+ RefreshCw, Users, VideoIcon, Camera, BarChart2, Eye, Tag, ThumbsUp, MessageSquare, CirclePlay,+ MessagesSquare, BookmarkCheck, Bookmark, Send, Plus, PlaySquare, Scissors, Clapperboard, ArrowUpRight,+} from 'lucide-react';import { Button } from '@/components/ui/button';import { Badge } from '@/components/ui/badge';-import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';import { Progress } from '@/components/ui/progress';import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';-import {- Empty, EmptyHeader, EmptyMedia, EmptyTitle, EmptyDescription, EmptyContent,-} from '@/components/ui/empty';-import {- AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip as ReTooltip,- ResponsiveContainer,-} from 'recharts';-import StatCard from '../../../components/ui/StatCard';-import MainCard from '../../../components/MainCard';-import MetricAreaChart from '../../../components/MetricAreaChart';+import PageHeader from '@/components/PageHeader';+import MetricBox from '@/components/MetricBox';+import SurfaceBox from '@/components/SurfaceBox';+import MetricAreaChart from '@/components/MetricAreaChart';+import ListRow, { RankNumber } from '@/components/ListRow';+import { EmptyState } from '@/components/StateViews';+import { AccountAvatar, PlatformBadge } from '@/components/platform';+import { PLATFORM_META, accountHandle, accountName, accountPath, platformOf, platformSummary } from '@/lib/accounts';+import { SERIES, axisProps, gridProps, tooltipStyle } from '@/lib/chart';import { useAppContext } from '../../../context/AppContext';+import { useAuth } from '../../../context/AuthContext';import { api } from '../../../services/api';import { fmtNum, fmtNumFull, fmtPercent, timeAgo } from '../../../utils/formatters';import { trackedViews } from '../../../utils/trackedContent';import { IG_CONTENT_TYPES, IG_CONTENT_TYPE_META } from '../../../utils/instagramContent';-import {- RefreshCw, Users, VideoIcon, ExternalLink, Camera, BarChart2, Eye,- Tag, ThumbsUp, MessageSquare, CirclePlay, Flame, BookmarkCheck,-} from 'lucide-react';+import { cn } from '@/lib/utils';-const PLATFORM_COLORS = {- youtube: '#ef4444',- instagram: '#ec4899',- reddit: '#f97316',- category: '#a855f7',-};--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>- );+const CATEGORY_SERIES = SERIES.neutral;++function greeting(date = new Date()) {+ const hour = date.getHours();+ if (hour < 12) return 'Good morning';+ if (hour < 18) return 'Good afternoon';+ return 'Good evening';}export default function Overview() {const { accounts, loading: accountsLoading, refreshAll } = useAppContext();+ const { user } = useAuth();const navigate = useNavigate();+ const [activeTab, setActiveTab] = useState('audience');const [overviewData, setOverviewData] = useState({ tracked: [], analyticsCache: {} });const [overviewLoading, setOverviewLoading] = useState(true);@@ -171,7 +164,7 @@ export default function Overview() {const totalViews = totals.views + cacheTotals.igViews + trackedViewTotal;const igTypeSummary = (field) => IG_CONTENT_TYPES.map(t => `${fmtNum(cacheTotals.igTypes[t][field])} ${IG_CONTENT_TYPE_META[t].plural.toLowerCase()}`)- .join(' · ');+ .join(', ');const igAccountRows = igAccounts.map(a => ({ account: a, cache: analyticsCache[a.id] })).sort((x, y) => (y.cache?.totalViews ?? 0) - (x.cache?.totalViews ?? 0));@@ -318,262 +311,237 @@ export default function Overview() {[trackedContent]);+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}`);+ navigate(accountPath(acc));}- const tabTriggerCls = 'flex flex-col items-start gap-0 h-auto py-3 px-4 text-left w-[175px] overflow-hidden';+ const firstName = (user?.email || '').split('@')[0].split(/[._-]/)[0];+ const greetingName = firstName ? firstName[0].toUpperCase() + firstName.slice(1) : '';++ const metricTabs = [+ {+ value: 'audience', label: 'Audience', value_: fmtNum(totalAudience),+ detail: [+ totals.subscribers ? `${fmtNum(totals.subscribers)} subscribers` : null,+ totals.followers ? `${fmtNum(totals.followers)} followers` : null,+ totals.karma ? `${fmtNum(totals.karma)} karma` : null,+ ].filter(Boolean).join(', ') || 'No data yet',+ },+ {+ value: 'views', label: 'Views', value_: fmtNum(totalViews),+ detail: [+ totals.views ? `${fmtNum(totals.views)} YouTube` : null,+ cacheTotals.igViews ? `${fmtNum(cacheTotals.igViews)} Instagram` : null,+ trackedViewTotal ? `${fmtNum(trackedViewTotal)} tracked` : null,+ ].filter(Boolean).join(', ') || 'No views recorded yet',+ },+ {+ value: 'content', label: 'Content', value_: fmtNum(totalContent),+ detail: [+ totals.videos ? `${fmtNum(totals.videos)} videos` : null,+ totals.posts ? `${fmtNum(totals.posts)} Instagram` : null,+ cacheTotals.rdPosts ? `${fmtNum(cacheTotals.rdPosts)} Reddit` : null,+ trackedStats.total ? `${fmtNum(trackedStats.total)} tracked` : null,+ ].filter(Boolean).join(', ') || 'No content yet',+ },+ { value: 'accounts', label: 'Accounts', value_: accounts.length, detail: platformSummary(accounts) },+ {+ value: 'comments', label: 'Comments', value_: fmtNum(totalComments),+ detail: isSyncing ? 'Syncing analytics' : totalComments > 0 ? 'Across all platforms' : 'Open an analytics page to load',+ },+ {+ value: 'likes', label: 'Likes', value_: fmtNum(totalLikes),+ detail: isSyncing ? 'Syncing analytics' : totalLikes > 0 ? 'Across all platforms' : 'Open an analytics page to load',+ },+ ];++ const quickActions = [+ { to: '/upload', label: 'Publish', icon: Send },+ { to: '/accounts?add=1', label: 'Add account', icon: Plus },+ { to: '/tracked-content', label: 'Track content', icon: Bookmark },+ { to: '/videos', label: 'Videos', icon: PlaySquare },+ { to: '/shorts', label: 'Shorts', icon: Scissors },+ { to: '/reels', label: 'Instagram', icon: Clapperboard },+ { to: '/reddit-posts', label: 'Reddit', icon: MessagesSquare },+ ];++ const accountRow = (a, i, trailing) => (+ <ListRow+ key={a.id}+ onClick={() => handleViewChannel(a)}+ leading={<><RankNumber rank={i + 1} /><AccountAvatar account={a} showPlatform /></>}+ title={accountName(a)}+ meta={accountHandle(a)}+ trailing={trailing}+ />+ );++ const categoryRow = (stat, trailing) => (+ <ListRow+ key={stat.category}+ onClick={() => navigate(`/tracked-content/category/${encodeURIComponent(stat.category)}`)}+ leading={<><span className="w-5 shrink-0" /><span className="flex size-8 items-center justify-center rounded-control bg-surface-sunken text-ink-muted"><Tag className="size-4 stroke-[1.75]" /></span></>}+ title={stat.category}+ meta={[`${stat.count} item${stat.count !== 1 ? 's' : ''}`, stat.ytCount > 0 && `${stat.ytCount} YouTube`, stat.rdCount > 0 && `${stat.rdCount} Reddit`].filter(Boolean).join(', ')}+ trailing={trailing}+ />+ );++ const legend = [+ ytAccounts.length ? { color: PLATFORM_META.youtube.series, label: 'YouTube subscribers' } : null,+ igAccounts.length ? { color: PLATFORM_META.instagram.series, label: 'Instagram followers' } : null,+ redditAccounts.length ? { color: PLATFORM_META.reddit.series, label: 'Reddit karma' } : null,+ categoryStats.length ? { color: CATEGORY_SERIES, label: 'Category karma' } : null,+ ].filter(Boolean);return (- <div className="space-y-6">- {/* Page header */}- <div className="flex items-start justify-between gap-4">- <div>- <h1 className="text-2xl font-bold tracking-tight">Dashboard Overview</h1>- <p className="text-sm text-muted-foreground mt-0.5">- {accounts.length === 0- ? 'Add your first account to start tracking'- : [- `Tracking ${accounts.length} account${accounts.length !== 1 ? 's' : ''}`,- ytAccounts.length ? `${ytAccounts.length} YouTube` : null,- igAccounts.length ? `${igAccounts.length} Instagram` : null,- redditAccounts.length ? `${redditAccounts.length} Reddit` : null,- ].filter(Boolean).join(' · ')}- </p>- </div>- <div className="flex items-center gap-2 shrink-0">- {isSyncing && (- <span className="text-xs text-muted-foreground flex items-center gap-1.5">- <RefreshCw className="h-3 w-3 animate-spin" />- Syncing analytics...- </span>- )}- <Button- onClick={refreshAll}- disabled={loading || accounts.length === 0}- size="sm"- className="gap-2"+ <div className="flex flex-col gap-8">+ <PageHeader+ size="display"+ title={greetingName ? `${greeting()}, ${greetingName}` : greeting()}+ description={accounts.length === 0+ ? 'Add your first account to start tracking.'+ : `Tracking ${accounts.length} account${accounts.length !== 1 ? 's' : ''}: ${platformSummary(accounts)}.`}+ actions={+ <>+ {isSyncing && (+ <span className="flex items-center gap-1.5 text-small text-ink-muted" role="status">+ <RefreshCw className="size-3.5 animate-spin" />+ Syncing analytics+ </span>+ )}+ <Button onClick={refreshAll} disabled={loading || accounts.length === 0} variant="outline">+ <RefreshCw data-icon="inline-start" className={cn(loading && 'animate-spin')} />+ {loading ? 'Refreshing' : 'Refresh all'}+ </Button>+ </>+ }+ />++ <nav aria-label="Quick actions" className="grid grid-cols-4 gap-x-3 gap-y-5 sm:grid-cols-7">+ {quickActions.map(action => {+ const Icon = action.icon;+ return (+ <Link+ key={action.to}+ to={action.to}+ className="group flex flex-col items-center gap-2 rounded-card py-2 text-center focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring">- <RefreshCw className={`h-3.5 w-3.5 ${loading ? 'animate-spin' : ''}`} />- {loading ? 'Refreshing...' : 'Refresh All'}- </Button>- </div>- </div>+ <span className="flex size-12 items-center justify-center rounded-card bg-surface-wash text-ink-muted transition-colors duration-(--duration-base) group-hover:bg-surface-selected group-hover:text-ink">+ <Icon className="size-5 stroke-[1.75]" />+ </span>+ <span className="text-small font-medium text-ink">{action.label}</span>+ </Link>+ );+ })}+ </nav>- {loading && <Progress className="h-1" value={undefined} />}+ {loading && <Progress value={null} aria-label="Loading accounts" />}{accounts.length === 0 ? (- <MainCard>- <div className="flex flex-col items-center text-center py-12 gap-4">- <div className="h-16 w-16 rounded-full bg-primary/10 flex items-center justify-center">- <Users className="h-8 w-8 text-primary" />- </div>- <div>- <h3 className="text-lg font-semibold">Welcome to Twiligent</h3>- <p className="text-sm text-muted-foreground mt-1 max-w-sm">- Add your first YouTube channel, Instagram account, or Reddit profile to start tracking analytics- </p>- </div>- <Button onClick={() => navigate('/accounts')}>Add Account</Button>+ <section className="relative overflow-hidden rounded-panel border border-line bg-surface-raised">+ <div aria-hidden="true" className="fold-band absolute inset-y-0 right-0 hidden w-2/5 [clip-path:polygon(35%_0,100%_0,100%_100%,0_100%)] md:block" />+ <div className="relative flex max-w-xl flex-col gap-4 p-8">+ <p className="eyebrow text-brand-text">Getting started</p>+ <h2 className="font-heading text-page-title font-semibold text-ink">Bring your channels into one picture.</h2>+ <p className="text-sm text-ink-muted">Add a YouTube channel, connect an Instagram Business or Creator account, or add a Reddit profile. Analytics start filling in as soon as an account is added.</p>+ <div><Button render={<Link to="/accounts?add=1" />}><Plus data-icon="inline-start" />Add an account</Button></div></div>- </MainCard>+ </section>) : (- <Tabs defaultValue="audience" className="space-y-6">- {/* Tab triggers */}- <div className="overflow-x-auto pb-1">- <TabsList className="w-max flex gap-1 bg-muted/50 p-1 rounded-xl" style={{ height: 'auto' }}>-- <TabsTrigger value="audience" className={tabTriggerCls}>- <span className="text-[11px] font-medium text-muted-foreground uppercase tracking-wide truncate w-full">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 truncate w-full">- {[- 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>-- <TabsTrigger value="views" className={tabTriggerCls}>- <span className="text-[11px] font-medium text-muted-foreground uppercase tracking-wide truncate w-full">Total Views</span>- <span className="text-2xl font-bold tabular-nums leading-tight mt-0.5">{fmtNum(totalViews)}</span>- <span className="text-[11px] text-muted-foreground mt-0.5 truncate w-full">- {[- totals.views ? `${fmtNum(totals.views)} YouTube` : null,- cacheTotals.igViews ? `${fmtNum(cacheTotals.igViews)} Instagram` : null,- trackedViewTotal ? `${fmtNum(trackedViewTotal)} tracked` : null,- ].filter(Boolean).join(' · ') || 'no views recorded yet'}- </span>- </TabsTrigger>-- <TabsTrigger value="content" className={tabTriggerCls}>- <span className="text-[11px] font-medium text-muted-foreground uppercase tracking-wide truncate w-full">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 truncate w-full">- {[- totals.videos ? `${fmtNum(totals.videos)} videos` : null,- totals.posts ? `${fmtNum(totals.posts)} Instagram` : null,- cacheTotals.rdPosts ? `${fmtNum(cacheTotals.rdPosts)} Reddit` : null,- trackedStats.total ? `${fmtNum(trackedStats.total)} tracked` : null,- ].filter(Boolean).join(' · ') || 'no content yet'}- </span>- </TabsTrigger>-- <TabsTrigger value="accounts" className={tabTriggerCls}>- <span className="text-[11px] font-medium text-muted-foreground uppercase tracking-wide truncate w-full">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 truncate w-full">- {[- ytAccounts.length ? `${ytAccounts.length} YouTube` : null,- igAccounts.length ? `${igAccounts.length} Instagram` : null,- redditAccounts.length ? `${redditAccounts.length} Reddit` : null,- ].filter(Boolean).join(' · ')}- </span>- </TabsTrigger>-- <TabsTrigger value="comments" className={tabTriggerCls}>- <span className="text-[11px] font-medium text-muted-foreground uppercase tracking-wide truncate w-full">Total Comments</span>- <span className="text-2xl font-bold tabular-nums leading-tight mt-0.5">{fmtNum(totalComments)}</span>- <span className="text-[11px] text-muted-foreground mt-0.5 truncate w-full">- {isSyncing ? 'syncing analytics...' : totalComments > 0 ? 'across all platforms' : 'visit analytics pages to load'}- </span>- </TabsTrigger>-- <TabsTrigger value="likes" className={tabTriggerCls}>- <span className="text-[11px] font-medium text-muted-foreground uppercase tracking-wide truncate w-full">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 truncate w-full">- {isSyncing ? 'syncing analytics...' : totalLikes > 0 ? 'across all platforms' : 'visit analytics pages to load'}- </span>+ <Tabs value={activeTab} onValueChange={setActiveTab} className="gap-6">+ <TabsList+ variant="none"+ aria-label="Overview metrics"+ className="grid w-full grid-cols-2 gap-3 sm:grid-cols-3 xl:grid-cols-6"+ >+ {metricTabs.map(tab => (+ <TabsTrigger+ key={tab.value}+ value={tab.value}+ className="h-auto min-w-0 flex-col items-start justify-start gap-1 rounded-card border border-line bg-surface-raised p-4 text-left after:hidden hover:border-line-strong/40 data-active:border-brand data-active:bg-brand-soft/40"+ >+ <span className="text-small font-medium text-ink-muted">{tab.label}</span>+ <span className="font-heading text-2xl font-semibold tracking-[-0.02em] text-ink tabular-nums">{tab.value_}</span>+ <span className="w-full truncate text-caption font-normal text-ink-faint">{tab.detail}</span></TabsTrigger>+ ))}+ </TabsList>- </TabsList>- </div>-- {/* ── AUDIENCE TAB ──────────────────────────────────────────────── */}- <TabsContent value="audience" className="space-y-4">- <MainCard title="Audience Comparison">- <p className="text-xs text-muted-foreground mb-3">- YouTube = subscribers · Instagram = followers · Reddit = karma · Categories = karma- </p>+ <TabsContent value="audience" className="flex flex-col gap-4">+ <SurfaceBox title="Audience by account" subheader="Subscribers, followers and karma, plus karma earned by each tracked category">{audienceChartData.length === 0 ? (- <p className="text-sm text-muted-foreground py-8 text-center">No data to display</p>+ <EmptyState compact icon={<Users />} title="No audience data yet" description="Refresh your accounts to load subscriber and follower counts." />) : (- <ResponsiveContainer width="100%" height={260} debounce={200}>- <AreaChart data={audienceChartData} margin={{ top: 8, right: 8, left: 0, bottom: 0 }}>- <defs>- <linearGradient id="audienceAreaGrad" x1="0" y1="0" x2="0" y2="1">- <stop offset="5%" stopColor="var(--primary)" stopOpacity={0.28} />- <stop offset="95%" stopColor="var(--primary)" stopOpacity={0} />- </linearGradient>- </defs>- <CartesianGrid strokeDasharray="3 3" stroke="var(--border)" vertical={false} />- <XAxis dataKey="name" tick={{ fill: 'var(--muted-foreground)', fontSize: 11 }} axisLine={false} tickLine={false} />- <YAxis tick={{ fill: 'var(--muted-foreground)', fontSize: 11 }} tickFormatter={fmtNum} axisLine={false} tickLine={false} width={48} />- <ReTooltip- contentStyle={{ background: 'var(--card)', border: '1px solid var(--border)', borderRadius: 8, fontSize: 12 }}- formatter={(v, name, props) => [fmtNumFull(v), props.payload.type === 'category' ? 'Karma' : 'Audience']}- />- <Area- type="monotone"- dataKey="value"- stroke="var(--primary)"- strokeWidth={2}- fill="url(#audienceAreaGrad)"- dot={(props) => {- const { cx, cy, payload, index } = props;- return (+ <>+ <ResponsiveContainer width="100%" height={260} debounce={200}>+ <AreaChart data={audienceChartData} margin={{ top: 8, right: 8, left: 0, bottom: 0 }}>+ <defs>+ <linearGradient id="audienceAreaGrad" x1="0" y1="0" x2="0" y2="1">+ <stop offset="5%" stopColor="var(--chart-1)" stopOpacity={0.22} />+ <stop offset="95%" stopColor="var(--chart-1)" stopOpacity={0} />+ </linearGradient>+ </defs>+ <CartesianGrid {...gridProps} vertical={false} />+ <XAxis dataKey="name" {...axisProps} />+ <YAxis {...axisProps} tickFormatter={fmtNum} width={48} />+ <ReTooltip+ contentStyle={tooltipStyle}+ cursor={{ stroke: 'var(--line-strong)' }}+ formatter={(v, name, props) => [fmtNumFull(v), props.payload.type === 'category' ? 'Karma' : 'Audience']}+ />+ <Area+ type="monotone"+ dataKey="value"+ stroke="var(--chart-1)"+ strokeWidth={2}+ fill="url(#audienceAreaGrad)"+ dot={({ cx, cy, payload, index }) => (<circlekey={`dot-${index}`}cx={cx}cy={cy}- r={5}- fill={PLATFORM_COLORS[payload.type] || '#6366f1'}- stroke="var(--card)"+ r={4.5}+ fill={payload.type === 'category' ? CATEGORY_SERIES : PLATFORM_META[payload.type]?.series}+ stroke="var(--surface-raised)"strokeWidth={2}/>- );- }}- activeDot={{ r: 7 }}- />- </AreaChart>- </ResponsiveContainer>+ )}+ activeDot={{ r: 6 }}+ />+ </AreaChart>+ </ResponsiveContainer>+ <ul className="mt-3 flex flex-wrap gap-x-4 gap-y-1.5">+ {legend.map(({ color, label }) => (+ <li key={label} className="flex items-center gap-1.5 text-caption text-ink-muted">+ <span className="size-2.5 shrink-0 rounded-full" style={{ background: color }} />+ {label}+ </li>+ ))}+ </ul>+ </>)}- <div className="flex flex-wrap gap-3 mt-2">- {[- ytAccounts.length ? { color: PLATFORM_COLORS.youtube, label: 'YouTube (subs)' } : null,- igAccounts.length ? { color: PLATFORM_COLORS.instagram, label: 'Instagram (followers)' } : null,- redditAccounts.length ? { color: PLATFORM_COLORS.reddit, label: 'Reddit (karma)' } : null,- categoryStats.length ? { color: PLATFORM_COLORS.category, label: 'Category (karma)' } : null,- ].filter(Boolean).map(({ color, label }) => (- <div key={label} className="flex items-center gap-1.5 text-xs text-muted-foreground">- <span className="h-2.5 w-2.5 rounded-full flex-shrink-0" style={{ background: color }} />- {label}- </div>- ))}- </div>- </MainCard>-- {/* Top by Audience - accounts only, no metric label */}- <MainCard title="Top by Audience">- <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';- 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} />- </button>- );- })}- {categoryStats.map(stat => (- <button- key={stat.category}- onClick={() => navigate(`/tracked-content/category/${encodeURIComponent(stat.category)}`)}- 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-xs border-purple-200 bg-purple-50 text-purple-700 dark:border-purple-900 dark:bg-purple-950 dark:text-purple-400 shrink-0">- Category- </Badge>- </button>- ))}+ </SurfaceBox>++ <SurfaceBox title="Top by audience" contentClassName="px-2 py-2">+ <div className="flex flex-col">+ {allSortedByAudience.map((a, i) => accountRow(a, i, <PlatformBadge platform={platformOf(a)} />))}+ {categoryStats.map(stat => categoryRow(stat, <Badge variant="outline">Category</Badge>))}</div>- </MainCard>+ </SurfaceBox></TabsContent>- {/* ── VIEWS TAB ──────────────────────────────────────────────────── */}- <TabsContent value="views" className="space-y-4">- <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-4">- <StatCard icon={<Eye />} label="Total Views" value={fmtNum(totalViews)} subtitle="YouTube, Instagram, and tracked content combined" gradient="blue" />- <StatCard icon={<CirclePlay />} label="Channel Views" value={fmtNum(totals.views)} subtitle={`${ytAccounts.length} YouTube channel${ytAccounts.length !== 1 ? 's' : ''}`} gradient="red" />- <StatCard icon={<Camera />} label="Instagram Views" value={fmtNum(cacheTotals.igViews)} subtitle={igAccounts.length > 0 ? igTypeSummary('views') : 'no Instagram accounts'} gradient="pink" />- <StatCard icon={<BookmarkCheck />} label="Tracked Views" value={fmtNum(trackedViewTotal)} subtitle={`${fmtNum(trackedStats.ytViews)} YouTube · ${fmtNum(trackedStats.rdViews)} Reddit`} gradient="purple" />+ <TabsContent value="views" className="flex flex-col gap-4">+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-4">+ <MetricBox icon={<Eye />} label="Total views" value={fmtNum(totalViews)} subtitle="YouTube, Instagram and tracked content" highlight />+ <MetricBox icon={<CirclePlay />} label="Channel views" value={fmtNum(totals.views)} subtitle={`${ytAccounts.length} YouTube channel${ytAccounts.length !== 1 ? 's' : ''}`} />+ <MetricBox icon={<Camera />} label="Instagram views" value={fmtNum(cacheTotals.igViews)} subtitle={igAccounts.length > 0 ? igTypeSummary('views') : 'No Instagram accounts'} />+ <MetricBox icon={<BookmarkCheck />} label="Tracked views" value={fmtNum(trackedViewTotal)} subtitle={`${fmtNum(trackedStats.ytViews)} YouTube, ${fmtNum(trackedStats.rdViews)} Reddit`} /></div>{igAccounts.length > 0 && (- <MainCard title="Instagram Views by Content Type" content={false}>+ <SurfaceBox title="Instagram views by content type" content={false} className="overflow-hidden"><Table><TableHeader><TableRow>@@ -581,24 +549,19 @@ export default function Overview() {{IG_CONTENT_TYPES.map(t => (<TableHead key={t} className="text-right">{IG_CONTENT_TYPE_META[t].plural}</TableHead>))}- <TableHead className="text-right">Total Views</TableHead>- <TableHead className="w-10" />+ <TableHead className="text-right">Total views</TableHead>+ <TableHead className="w-10"><span className="sr-only">Open</span></TableHead></TableRow></TableHeader><TableBody>{igAccountRows.map(({ account: a, cache }) => (- <TableRow key={a.id} className="cursor-pointer" onClick={() => navigate(`/instagram/${a.id}`)}>+ <TableRow key={a.id}><TableCell><div className="flex items-center gap-2.5">- <Avatar className="h-8 w-8">- <AvatarImage src={a.profilePictureUrl} />- <AvatarFallback className="bg-pink-500 text-xs font-bold text-white">- {(a.title || a.username || '?').slice(0, 2).toUpperCase()}- </AvatarFallback>- </Avatar>+ <AccountAvatar account={a} /><div>- <p className="text-sm font-semibold leading-none">{a.title || a.username}</p>- <p className="text-xs text-muted-foreground mt-0.5">@{a.username || ''}</p>+ <p className="text-sm font-medium text-ink">{accountName(a)}</p>+ <p className="text-caption text-ink-faint">{accountHandle(a)}</p></div></div></TableCell>@@ -606,372 +569,220 @@ export default function Overview() {<TableCell key={t} className="text-right">{cache?.cacheWarmed ? (<>- <p className="text-sm font-semibold">{fmtNum(cache.contentTypes?.[t]?.views)}</p>- <p className="text-xs text-muted-foreground">{fmtNum(cache.contentTypes?.[t]?.count)} {IG_CONTENT_TYPE_META[t].plural.toLowerCase()}</p>+ <p className="text-sm font-medium text-ink">{fmtNum(cache.contentTypes?.[t]?.views)}</p>+ <p className="text-caption text-ink-faint">{fmtNum(cache.contentTypes?.[t]?.count)} {IG_CONTENT_TYPE_META[t].plural.toLowerCase()}</p></>- ) : <span className="text-sm text-muted-foreground">-</span>}+ ) : <span className="text-ink-faint">-</span>}</TableCell>))}- <TableCell className="text-right text-sm font-bold">- {cache?.cacheWarmed ? fmtNum(cache.totalViews) : <span className="font-normal text-muted-foreground">{isSyncing ? 'syncing...' : '-'}</span>}+ <TableCell className="text-right font-semibold text-ink">+ {cache?.cacheWarmed ? fmtNum(cache.totalViews) : <span className="font-normal text-ink-faint">{isSyncing ? 'Syncing' : '-'}</span>}</TableCell><TableCell>- <Tooltip>- <TooltipTrigger render={<Button variant="ghost" size="icon" className="size-7" onClick={(e) => { e.stopPropagation(); navigate(`/instagram/${a.id}`); }} />}>- <ExternalLink />- </TooltipTrigger>- <TooltipContent>View Analytics</TooltipContent>- </Tooltip>+ <OpenAnalytics onClick={() => handleViewChannel(a)} name={accountName(a)} /></TableCell></TableRow>))}</TableBody></Table>- </MainCard>+ </SurfaceBox>)}{categoryStats.length > 0 && (- <MainCard- title="Views by Category"- subheader="YouTube video views plus manually entered Reddit post views"- >- <MetricAreaChart- data={categoryViewData}- dataKey="views"- label="Views"- color="#06b6d4"- emptyMessage="No views recorded for these categories yet"- />- </MainCard>+ <SurfaceBox title="Views by category" subheader="YouTube video views plus Reddit post views entered by hand">+ <MetricAreaChart data={categoryViewData} dataKey="views" label="Views" color={SERIES.cool} emptyMessage="No views recorded for these categories yet" />+ </SurfaceBox>)}- {ytAccounts.length === 0 ? null : (- <MainCard title="YouTube Views by Channel" content={false}>+ {ytAccounts.length > 0 && (+ <SurfaceBox title="YouTube views by channel" content={false} className="overflow-hidden"><Table><TableHeader><TableRow>- <TableHead className="w-10">#</TableHead>+ <TableHead className="w-10 text-right">#</TableHead><TableHead>Channel</TableHead>- <TableHead className="text-right">Total Views</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" />+ <TableHead className="w-10"><span className="sr-only">Open</span></TableHead></TableRow></TableHeader><TableBody>{[...ytAccounts].sort((a, b) => (b.viewCount || 0) - (a.viewCount || 0)).map((a, i) => (- <TableRow key={a.id} 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>+ <TableRow key={a.id}>+ <TableCell className="text-right"><RankNumber rank={i + 1} className="w-auto" /></TableCell><TableCell><div className="flex items-center gap-2.5">- <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>+ <AccountAvatar account={a} /><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>+ <p className="text-sm font-medium text-ink">{a.title}</p>+ <p className="text-caption text-ink-faint">{accountHandle(a)}</p></div></div></TableCell><TableCell className="text-right">- <p className="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>+ <p className="font-semibold text-ink">{fmtNum(a.viewCount)}</p>+ <p className="text-caption text-ink-faint">{fmtNumFull(a.viewCount)}</p></TableCell>+ <TableCell className="text-right text-ink-muted">{fmtNum(a.subscriberCount)}</TableCell>+ <TableCell className="text-right text-ink-muted">{fmtNum(a.videoCount)}</TableCell>+ <TableCell className="text-right text-small text-ink-faint">{timeAgo(a.lastUpdated)}</TableCell>+ <TableCell><OpenAnalytics onClick={() => handleViewChannel(a)} name={a.title} /></TableCell></TableRow>))}</TableBody></Table>- </MainCard>+ </SurfaceBox>)}</TabsContent>- {/* ── CONTENT TAB ────────────────────────────────────────────────── */}- <TabsContent value="content" className="space-y-4">- <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">- <StatCard icon={<CirclePlay />} label="YouTube Videos" value={fmtNum(totals.videos)} subtitle={`${ytAccounts.length} channel${ytAccounts.length !== 1 ? 's' : ''}`} gradient="red" />- <StatCard icon={<VideoIcon />} label="Instagram Content" value={fmtNum(totals.posts)} subtitle={IG_CONTENT_TYPES.some(t => cacheTotals.igTypes[t].count > 0) ? igTypeSummary('count') : `${igAccounts.length} account${igAccounts.length !== 1 ? 's' : ''}`} gradient="blue" />- <StatCard icon={<Flame />} label="Reddit Posts" value={fmtNum(cacheTotals.rdPosts)} subtitle={cacheTotals.rdPosts > 0 ? 'from analytics cache' : 'visit Reddit analytics to load'} gradient="orange" />- <StatCard icon={<BookmarkCheck />} label="Tracked Content" value={fmtNum(trackedStats.total)} subtitle={`${trackedStats.ytItems.length} YouTube · ${trackedStats.rdItems.length} Reddit`} gradient="purple" />+ <TabsContent value="content" className="flex flex-col gap-4">+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">+ <MetricBox icon={<CirclePlay />} label="YouTube videos" value={fmtNum(totals.videos)} subtitle={`${ytAccounts.length} channel${ytAccounts.length !== 1 ? 's' : ''}`} />+ <MetricBox icon={<VideoIcon />} label="Instagram content" value={fmtNum(totals.posts)} subtitle={IG_CONTENT_TYPES.some(t => cacheTotals.igTypes[t].count > 0) ? igTypeSummary('count') : `${igAccounts.length} account${igAccounts.length !== 1 ? 's' : ''}`} />+ <MetricBox icon={<MessagesSquare />} label="Reddit posts" value={fmtNum(cacheTotals.rdPosts)} subtitle={cacheTotals.rdPosts > 0 ? 'From the analytics cache' : 'Open Reddit analytics to load'} />+ <MetricBox icon={<BookmarkCheck />} label="Tracked content" value={fmtNum(trackedStats.total)} subtitle={`${trackedStats.ytItems.length} YouTube, ${trackedStats.rdItems.length} Reddit`} /></div>- <div className="grid grid-cols-1 md:grid-cols-2 gap-4">- <MainCard title="Top by Content">- <div className="space-y-1">- {allSortedByContent.map((a, i) => {- const metric = a.platform === 'instagram'- ? `${fmtNum(a.mediaCount)} items`- : 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 ${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 || 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>- <span className="text-sm font-semibold text-muted-foreground tabular-nums">{metric}</span>- </button>- );- })}+ <div className="grid grid-cols-1 gap-4 md:grid-cols-2">+ <SurfaceBox title="Top by content" contentClassName="px-2 py-2">+ <div className="flex flex-col">+ {allSortedByContent.map((a, i) => accountRow(a, i, (+ <span className="font-medium text-ink-muted">+ {platformOf(a) === 'instagram' ? `${fmtNum(a.mediaCount)} items`+ : platformOf(a) === 'reddit' ? `${fmtNum(a.totalKarma)} karma`+ : `${fmtNum(a.viewCount)} views`}+ </span>+ )))}</div>- </MainCard>+ </SurfaceBox>- <MainCard title="Tracked Categories">+ <SurfaceBox title="Tracked categories" contentClassName="px-2 py-2">{categoryStats.length === 0 ? (- <p className="text-sm text-muted-foreground text-center py-8">- Assign categories to tracked content to see breakdown- </p>+ <EmptyState+ compact+ icon={<Tag />}+ title="No categories yet"+ description="Assign categories to tracked content to see this breakdown."+ action={<Button size="sm" variant="outline" render={<Link to="/tracked-content" />}>Open tracked content</Button>}+ />) : (- <div className="space-y-1">- {categoryStats.map(stat => (- <button- key={stat.category}- onClick={() => navigate(`/tracked-content/category/${encodeURIComponent(stat.category)}`)}- 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' : ''}- {stat.ytCount > 0 && ` · ${stat.ytCount} YouTube`}- {stat.rdCount > 0 && ` · ${stat.rdCount} Reddit`}- </p>- </div>- <div className="text-right">- {stat.views > 0 && (- <p className="text-xs font-semibold tabular-nums text-cyan-500 leading-none">- {fmtNum(stat.views)} views- </p>- )}- {stat.rdCount > 0 && (- <p className="text-xs font-semibold tabular-nums text-orange-500 leading-none mt-0.5">- {fmtNum(stat.rdKarma)} karma- </p>- )}- </div>- </button>- ))}+ <div className="flex flex-col">+ {categoryStats.map(stat => categoryRow(stat, (+ <span className="flex flex-col items-end gap-0.5 text-caption">+ {stat.views > 0 && <span className="font-medium text-ink">{fmtNum(stat.views)} views</span>}+ {stat.rdCount > 0 && <span className="text-ink-faint">{fmtNum(stat.rdKarma)} karma</span>}+ </span>+ )))}</div>)}- </MainCard>+ </SurfaceBox></div></TabsContent>- {/* ── ACCOUNTS TAB ──────────────────────────────────────────────── */}- <TabsContent value="accounts" className="space-y-4">- <MainCard content={false}>+ <TabsContent value="accounts" className="flex flex-col gap-4">+ <SurfaceBox content={false} className="overflow-hidden"><Table><TableHeader><TableRow>- <TableHead className="w-10">#</TableHead>+ <TableHead className="w-10 text-right">#</TableHead><TableHead>Account</TableHead>- <TableHead className="text-center">Platform</TableHead>+ <TableHead>Platform</TableHead><TableHead className="text-right">Audience</TableHead><TableHead className="text-right">Content</TableHead><TableHead className="text-right">Updated</TableHead>- <TableHead className="w-10" />+ <TableHead className="w-10"><span className="sr-only">Open</span></TableHead></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)} items`- : 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';+ const platform = platformOf(a);+ const audience = platform === 'instagram' ? `${fmtNum(a.followersCount)} followers`+ : platform === 'reddit' ? `${fmtNum(a.totalKarma)} karma`+ : `${fmtNum(a.subscriberCount)} subscribers`;+ const content = platform === 'instagram' ? `${fmtNum(a.mediaCount)} items`+ : platform === 'reddit' ? `${fmtNum(a.postKarma)} post karma`+ : `${fmtNum(a.viewCount)} views, ${fmtNum(a.videoCount)} videos`;return (- <TableRow key={a.id} className="cursor-pointer" onClick={() => handleViewChannel(a)}>- <TableCell>- <span className={`text-xs font-bold ${medalColor}`}>{i + 1}</span>- </TableCell>+ <TableRow key={a.id}>+ <TableCell className="text-right"><RankNumber rank={i + 1} className="w-auto" /></TableCell><TableCell><div className="flex items-center gap-2.5">- <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>+ <AccountAvatar account={a} /><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>+ <p className="text-sm font-medium text-ink">{accountName(a)}</p>+ <p className="text-caption text-ink-faint">{accountHandle(a)}</p></div></div></TableCell>- <TableCell 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>+ <TableCell><PlatformBadge platform={platform} /></TableCell>+ <TableCell className="text-right text-ink">{audience}</TableCell>+ <TableCell className="text-right text-ink-muted">{content}</TableCell>+ <TableCell className="text-right text-small text-ink-faint">{timeAgo(a.lastUpdated)}</TableCell>+ <TableCell><OpenAnalytics onClick={() => handleViewChannel(a)} name={accountName(a)} /></TableCell></TableRow>);})}</TableBody></Table>- </MainCard>+ </SurfaceBox></TabsContent>- {/* ── COMMENTS TAB ──────────────────────────────────────────────── */}- <TabsContent value="comments" className="space-y-4">- <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-4">- <StatCard icon={<MessageSquare />} label="Total Comments" value={fmtNum(totalComments)} subtitle={totalComments > 0 ? 'across all platforms' : 'visit analytics pages to load'} gradient="blue" />- <StatCard icon={<CirclePlay />} label="YouTube Comments" value={fmtNum(ytComments)} subtitle={`${fmtPercent(commentShare.youtube)} of all comments`} gradient="red" />- <StatCard icon={<Flame />} label="Reddit Comments" value={fmtNum(rdComments)} subtitle={`${fmtPercent(commentShare.reddit)} of all comments`} gradient="orange" />- <StatCard icon={<BarChart2 />} label="Comments per Content" value={fmtNum(avgCommentsPerContent)} subtitle={`average across ${fmtNum(totalContent)} item${totalContent !== 1 ? 's' : ''}`} gradient="purple" />+ <TabsContent value="comments" className="flex flex-col gap-4">+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-4">+ <MetricBox icon={<MessageSquare />} label="Total comments" value={fmtNum(totalComments)} subtitle={totalComments > 0 ? 'Across all platforms' : 'Open an analytics page to load'} highlight />+ <MetricBox icon={<CirclePlay />} label="YouTube comments" value={fmtNum(ytComments)} subtitle={`${fmtPercent(commentShare.youtube)} of all comments`} />+ <MetricBox icon={<MessagesSquare />} label="Reddit comments" value={fmtNum(rdComments)} subtitle={`${fmtPercent(commentShare.reddit)} of all comments`} />+ <MetricBox icon={<BarChart2 />} label="Comments per item" value={fmtNum(avgCommentsPerContent)} subtitle={`Average across ${fmtNum(totalContent)} item${totalContent !== 1 ? 's' : ''}`} /></div>{totalComments === 0 ? (- <MainCard>- <Empty>- <EmptyHeader>- <EmptyMedia variant="icon">- <MessageSquare />- </EmptyMedia>- <EmptyTitle>No comment data yet</EmptyTitle>- <EmptyDescription>- Open a channel or account analytics page to load its comment data, or track individual posts and videos.- </EmptyDescription>- </EmptyHeader>- <EmptyContent>- <Button size="sm" onClick={() => navigate('/tracked-content')}>Track Content</Button>- </EmptyContent>- </Empty>- </MainCard>+ <SurfaceBox>+ <EmptyState+ icon={<MessageSquare />}+ title="No comment data yet"+ description="Open a channel or account analytics page to load its comments, or track individual posts and videos."+ action={<Button size="sm" render={<Link to="/tracked-content" />}>Track content</Button>}+ />+ </SurfaceBox>) : (- <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">- <MainCard- title="Comments by Tracked Content"- subheader="Top 12 tracked items ranked by comment count"- >- <MetricAreaChart- data={commentByContentData}- dataKey="comments"- label="Comments"- color="#06b6d4"- emptyMessage="Track content to compare comment volume"- />- </MainCard>-- <MainCard- title="Comments by Category"- subheader="Total comments across every item in each category"- >- <MetricAreaChart- data={commentByCategoryData}- dataKey="comments"- label="Comments"- color="#a855f7"- emptyMessage="Assign categories to tracked content to see this breakdown"- />- </MainCard>+ <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">+ <SurfaceBox title="Comments by tracked content" subheader="Top 12 tracked items ranked by comments">+ <MetricAreaChart data={commentByContentData} dataKey="comments" label="Comments" color={SERIES.cool} emptyMessage="Track content to compare comment volume" />+ </SurfaceBox>+ <SurfaceBox title="Comments by category" subheader="Total comments across every item in each category">+ <MetricAreaChart data={commentByCategoryData} dataKey="comments" label="Comments" color={SERIES.warm} emptyMessage="Assign categories to tracked content to see this breakdown" />+ </SurfaceBox></div>)}</TabsContent>- {/* ── LIKES TAB ──────────────────────────────────────────────────── */}- <TabsContent value="likes" className="space-y-4">- <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-4">- <StatCard icon={<ThumbsUp />} label="Total Likes" value={fmtNum(totalLikes)} subtitle={totalLikes > 0 ? 'YouTube likes, Instagram likes, Reddit karma' : 'visit analytics pages to load'} gradient="purple" />- <StatCard icon={<Flame />} label="Reddit Karma" value={fmtNum(redditKarma)} subtitle={`${fmtNum(totals.postKarma)} account · ${fmtNum(trackedStats.rdKarma)} tracked`} gradient="orange" />- <StatCard icon={<CirclePlay />} label="YouTube Likes" value={fmtNum(ytLikes)} subtitle={`${fmtPercent(likeShare.youtube)} of all likes`} gradient="red" />- <StatCard icon={<Camera />} label="Instagram Likes" value={fmtNum(cacheTotals.igLikes)} subtitle={igAccounts.length > 0 ? `${fmtPercent(likeShare.instagram)} of all likes` : 'no Instagram accounts'} gradient="pink" />+ <TabsContent value="likes" className="flex flex-col gap-4">+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-4">+ <MetricBox icon={<ThumbsUp />} label="Total likes" value={fmtNum(totalLikes)} subtitle={totalLikes > 0 ? 'YouTube likes, Instagram likes, Reddit karma' : 'Open an analytics page to load'} highlight />+ <MetricBox icon={<MessagesSquare />} label="Reddit karma" value={fmtNum(redditKarma)} subtitle={`${fmtNum(totals.postKarma)} account, ${fmtNum(trackedStats.rdKarma)} tracked`} />+ <MetricBox icon={<CirclePlay />} label="YouTube likes" value={fmtNum(ytLikes)} subtitle={`${fmtPercent(likeShare.youtube)} of all likes`} />+ <MetricBox icon={<Camera />} label="Instagram likes" value={fmtNum(cacheTotals.igLikes)} subtitle={igAccounts.length > 0 ? `${fmtPercent(likeShare.instagram)} of all likes` : 'No Instagram accounts'} /></div>{totalLikes === 0 ? (- <MainCard>- <Empty>- <EmptyHeader>- <EmptyMedia variant="icon">- <ThumbsUp />- </EmptyMedia>- <EmptyTitle>No engagement data yet</EmptyTitle>- <EmptyDescription>- Open a channel or account analytics page to load its like data, or track individual posts and videos.- </EmptyDescription>- </EmptyHeader>- <EmptyContent>- <Button size="sm" onClick={() => navigate('/tracked-content')}>Track Content</Button>- </EmptyContent>- </Empty>- </MainCard>+ <SurfaceBox>+ <EmptyState+ icon={<ThumbsUp />}+ title="No engagement data yet"+ description="Open a channel or account analytics page to load its likes, or track individual posts and videos."+ action={<Button size="sm" render={<Link to="/tracked-content" />}>Track content</Button>}+ />+ </SurfaceBox>) : (- <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">- <MainCard- title="Karma by Reddit Account"- subheader="Post karma earned by each connected account"- >- <MetricAreaChart- data={karmaByAccountData}- dataKey="karma"- label="Post karma"- color="#f97316"- emptyMessage="Connect a Reddit account to see karma"- />- </MainCard>-- <MainCard- title="Engagement by Tracked Content"- subheader="YouTube likes and Reddit karma for the top 12 tracked items"- >- <MetricAreaChart- data={engagementByContentData}- dataKey="engagement"- label="Likes / karma"- color="#a855f7"- emptyMessage="Track content to compare engagement"- />- </MainCard>+ <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">+ <SurfaceBox title="Karma by Reddit account" subheader="Post karma earned by each connected account">+ <MetricAreaChart data={karmaByAccountData} dataKey="karma" label="Post karma" color={PLATFORM_META.reddit.series} emptyMessage="Connect a Reddit account to see karma" />+ </SurfaceBox>+ <SurfaceBox title="Engagement by tracked content" subheader="YouTube likes and Reddit karma for the top 12 tracked items">+ <MetricAreaChart data={engagementByContentData} dataKey="engagement" label="Likes or karma" color={SERIES.primary} emptyMessage="Track content to compare engagement" />+ </SurfaceBox></div>)}</TabsContent>@@ -980,3 +791,14 @@ export default function Overview() {</div>);}++function OpenAnalytics({ onClick, name }) {+ return (+ <Tooltip>+ <TooltipTrigger render={<Button variant="ghost" size="icon-xs" onClick={onClick} aria-label={`Open analytics for ${name}`} />}>+ <ArrowUpRight />+ </TooltipTrigger>+ <TooltipContent>Open analytics</TooltipContent>+ </Tooltip>+ );+}diff --git a/frontend/src/features/analytics/reddit/RedditAnalytics.jsx b/frontend/src/features/analytics/reddit/RedditAnalytics.jsxindex 6d2f1f3..024281f 100644--- a/frontend/src/features/analytics/reddit/RedditAnalytics.jsx+++ b/frontend/src/features/analytics/reddit/RedditAnalytics.jsx@@ -1,46 +1,54 @@-import React, { useState, useEffect } from 'react';-import { useParams, useNavigate, Link } from 'react-router-dom';+import React, { useCallback, useEffect, useState } from 'react';+import { Link, useParams } from 'react-router-dom';+import {+ BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip as ReTooltip, AreaChart, Area, PieChart, Pie,+ Cell, Legend,+} from 'recharts';+import { RefreshCw, TrendingUp, MessageSquare, Award, Star, ExternalLink, FileText, UserX } from 'lucide-react';import { Button } from '@/components/ui/button';import { Badge } from '@/components/ui/badge';-import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';-import { Skeleton } from '@/components/ui/skeleton';import { Progress } from '@/components/ui/progress';import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';-import { Separator } from '@/components/ui/separator';-import {- BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip as ReTooltip,- ResponsiveContainer, AreaChart, Area, PieChart, Pie, Cell, Legend,-} from 'recharts';-import { Spinner } from '@/components/ui/spinner';-import StatCard from '../../../components/ui/StatCard';-import MainCard from '../../../components/MainCard';+import PageHeader from '@/components/PageHeader';+import MetricBox from '@/components/MetricBox';+import SurfaceBox from '@/components/SurfaceBox';+import ChartPanel from '@/components/ChartPanel';+import { RankNumber } from '@/components/ListRow';+import { EmptyState, PageSkeleton } from '@/components/StateViews';+import { AccountAvatar } from '@/components/platform';+import { SERIES, axisProps, axisTick, gridProps, legendStyle, seriesAt, tooltipCursor, tooltipStyle } from '@/lib/chart';import { useAppContext } from '../../../context/AppContext';import { api } from '../../../services/api';import { fmtNum, fmtNumFull, fmtDate, timeAgo } from '../../../utils/formatters';-import {- ArrowLeft, RefreshCw, TrendingUp, MessageSquare, Award, BarChart2,- Calendar, Clock, Zap, Flame, Trophy, ExternalLink, FileText, Link2,- Image, Video, Star,-} from 'lucide-react';+import { MEDIA_TYPE_LABELS } from './redditPostUtils';+import { cn } from '@/lib/utils';-const REDDIT_COLORS = ['#FF4500', '#FF6534', '#FF8C00', '#FFA500', '#FFB347', '#FFC080'];-const MEDIA_TYPE_LABELS = { text: 'Text', image: 'Image', video: 'Video', link: 'Link' };-const MEDIA_TYPE_COLORS = { text: '#6366f1', image: '#22c55e', video: '#f97316', link: '#06b6d4' };+const MEDIA_TYPE_ORDER = ['text', 'image', 'video', 'link'];-const TS = { background: 'var(--card)', border: '1px solid var(--border)', borderRadius: 8, fontSize: 12 };+function StatList({ rows }) {+ return (+ <dl className="flex flex-col divide-y divide-divider">+ {rows.map(row => (+ <div key={row.label} className="flex items-center justify-between gap-4 py-2.5 first:pt-0 last:pb-0">+ <dt className="text-sm text-ink-muted">{row.label}</dt>+ <dd className="text-sm font-semibold text-ink tabular-nums">{row.value}</dd>+ </div>+ ))}+ </dl>+ );+}export default function RedditAnalytics() {const { id } = useParams();const { accounts, showToast } = useAppContext();- const navigate = useNavigate();const account = accounts.find(a => a.id === id);- const [loading, setLoading] = useState(true);- const [profile, setProfile] = useState(null);- const [analytics, setAnalytics] = useState(null);+ const [loading, setLoading] = useState(true);+ const [profile, setProfile] = useState(null);+ const [analytics, setAnalytics] = useState(null);const [refreshing, setRefreshing] = useState(false);- const loadAnalytics = async () => {+ const loadAnalytics = useCallback(async () => {if (!account) return;setLoading(true);try {@@ -48,13 +56,15 @@ export default function RedditAnalytics() {setProfile(data.profile);setAnalytics(data.analytics);} catch (err) {- showToast('Failed to load Reddit analytics: ' + err.message, 'error');+ showToast(`Couldn't load Reddit analytics. ${err.message}`, 'error');} finally {setLoading(false);}- };+ // Keyed on the account id so a background account refresh does not refetch analytics+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [account?.id, showToast]);- useEffect(() => { loadAnalytics(); }, [id]);+ useEffect(() => { loadAnalytics(); }, [id, loadAnalytics]);const handleRefresh = async () => {setRefreshing(true);@@ -63,360 +73,267 @@ export default function RedditAnalytics() {await loadAnalytics();showToast('Reddit account refreshed');} catch (err) {- showToast('Refresh failed: ' + err.message, 'error');+ showToast(`Refresh failed. ${err.message}`, 'error');} finally {setRefreshing(false);}};+ const back = { to: '/', label: 'Overview' };+if (!account) {return (- <div className="space-y-3">- <Button variant="ghost" onClick={() => navigate('/')} className="gap-2 -ml-2 text-muted-foreground">- <ArrowLeft className="h-4 w-4" /> Back- </Button>- <p className="text-muted-foreground">Account not found.</p>+ <div className="flex flex-col gap-6">+ <PageHeader title="Reddit account" back={back} />+ <SurfaceBox>+ <EmptyState icon={<UserX />} title="Account not found" description="It may have been removed. Choose another account from the sidebar." />+ </SurfaceBox></div>);}- if (loading) {- return (- <div className="flex items-center justify-center min-h-[50vh]">- <div className="flex flex-col items-center gap-3">- <Spinner className="size-10" />- <p className="text-sm text-muted-foreground">Loading Reddit analytics...</p>- </div>- </div>- );- }+ if (loading) return <PageSkeleton metrics={4} />;const p = profile || account;const a = analytics || {};const mediaTypeData = a.mediaTypeDistribution- ? Object.entries(a.mediaTypeDistribution).map(([key, value], i) => ({+ ? Object.entries(a.mediaTypeDistribution).map(([key, value]) => ({name: MEDIA_TYPE_LABELS[key] || key,value,- color: MEDIA_TYPE_COLORS[key] || REDDIT_COLORS[i % REDDIT_COLORS.length],+ color: seriesAt(Math.max(0, MEDIA_TYPE_ORDER.indexOf(key))),})): [];return (- <div className="space-y-6">- {/* Back button */}- <Button variant="ghost" onClick={() => navigate('/')} className="gap-2 -ml-2 text-muted-foreground">- <ArrowLeft className="h-4 w-4" /> Back- </Button>-- {/* Profile header */}- <MainCard>- <div className="flex flex-col sm:flex-row gap-4 sm:items-center sm:justify-between">- <div className="flex items-center gap-4">- <Avatar className="h-16 w-16">- <AvatarImage src={p.iconUrl || account.thumbnail} />- <AvatarFallback className="bg-orange-500 text-white font-bold text-lg">- {(p.username || account.title || '?').slice(0, 2).toUpperCase()}- </AvatarFallback>- </Avatar>- <div>- <div className="flex items-center gap-2 flex-wrap">- <h1 className="text-xl font-bold">u/{p.username || account.username}</h1>- {p.isGold && <Badge className="bg-yellow-500 text-white text-xs">Gold</Badge>}- {p.verified && <Badge className="bg-blue-500 text-white text-xs">Verified</Badge>}- {p.isMod && <Badge variant="outline" className="text-xs">Moderator</Badge>}- </div>- <p className="text-sm text-muted-foreground mt-0.5">- Reddit account- {p.createdAt ? ` - joined ${fmtDate(p.createdAt)}` : ''}- </p>- <p className="text-xs text-muted-foreground mt-0.5">- Last refreshed: {timeAgo(account.lastUpdated)}- </p>- </div>- </div>- <div className="flex gap-2 shrink-0 flex-wrap">- <Button- variant="outline"- size="sm"- className="gap-2"- onClick={() => navigate(`/reddit-posts/${account.id}`)}- >- <FileText className="h-3.5 w-3.5" />- View Posts+ <div className="flex flex-col gap-6">+ <PageHeader+ back={back}+ media={<AccountAvatar account={{ ...account, iconUrl: p.iconUrl || account.iconUrl }} size="xl" showPlatform />}+ title={`u/${p.username || account.username}`}+ description={+ <span className="flex flex-wrap items-center gap-1.5">+ {p.isGold && <Badge variant="warning">Gold</Badge>}+ {p.verified && <Badge variant="info">Verified</Badge>}+ {p.isMod && <Badge variant="outline">Moderator</Badge>}+ <span>+ {p.createdAt ? `Joined ${fmtDate(p.createdAt)}. ` : ''}Refreshed {timeAgo(account.lastUpdated).toLowerCase()}.+ </span>+ </span>+ }+ actions={+ <>+ <Button variant="outline" size="sm" render={<Link to={`/reddit-posts/${account.id}`} />}>+ <FileText data-icon="inline-start" />+ View posts</Button>- <Button- size="sm"- className="gap-2"- onClick={handleRefresh}- disabled={refreshing}- >- <RefreshCw className={`h-3.5 w-3.5 ${refreshing ? 'animate-spin' : ''}`} />- {refreshing ? 'Refreshing...' : 'Refresh'}+ <Button variant="outline" size="sm" onClick={handleRefresh} disabled={refreshing}>+ <RefreshCw data-icon="inline-start" className={cn(refreshing && 'animate-spin')} />+ {refreshing ? 'Refreshing' : 'Refresh'}</Button>- </div>- </div>- </MainCard>+ </>+ }+ />- {/* Karma - separate from profile since it's the key engagement metric on Reddit */}- <MainCard>- <div className="flex items-center gap-2 mb-4">- <Flame className="h-4 w-4 text-orange-500" />- <span className="text-sm font-semibold">Karma</span>- <span className="text-xs text-muted-foreground">earned across posts and comments</span>- </div>- <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">+ {refreshing && <Progress value={null} aria-label="Refreshing account" />}++ <SurfaceBox title="Karma" subheader="Earned across posts and comments">+ <div className="grid grid-cols-2 gap-x-6 gap-y-5 sm:grid-cols-4">{[- { label: 'Total Karma', value: fmtNum(p.totalKarma), sub: fmtNumFull(p.totalKarma) },- { label: 'Post Karma', value: fmtNum(p.postKarma), sub: 'from submitted posts' },- { label: 'Comment Karma', value: fmtNum(p.commentKarma), sub: 'from comments' },- { label: 'Awardee Karma', value: fmtNum(p.awardeeKarma ?? 0), sub: 'from received awards' },+ { label: 'Total karma', value: fmtNum(p.totalKarma), sub: fmtNumFull(p.totalKarma), lead: true },+ { label: 'Post karma', value: fmtNum(p.postKarma), sub: 'From submitted posts' },+ { label: 'Comment karma', value: fmtNum(p.commentKarma), sub: 'From comments' },+ { label: 'Awardee karma', value: fmtNum(p.awardeeKarma ?? 0), sub: 'From awards received' },].map(item => (- <div key={item.label} className="text-center p-3 rounded-lg bg-muted/40">- <p className="text-xl font-bold tabular-nums text-orange-500">{item.value}</p>- <p className="text-xs font-medium mt-0.5">{item.label}</p>- <p className="text-[10px] text-muted-foreground mt-0.5">{item.sub}</p>+ <div key={item.label} className="flex flex-col gap-1">+ <span className="text-small font-medium text-ink-muted">{item.label}</span>+ <span className={cn('font-heading text-2xl font-semibold tracking-[-0.02em] tabular-nums', item.lead ? 'text-brand-text' : 'text-ink')}>{item.value}</span>+ <span className="text-caption text-ink-faint">{item.sub}</span></div>))}</div>- </MainCard>+ </SurfaceBox>- {/* KPI cards */}- <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-4">- <StatCard icon={<TrendingUp />} label="Posts Fetched" value={fmtNum(a.fetchedPosts)} subtitle={`${a.postsLast30Days ?? 0} in the last 30 days`} gradient="orange" />- <StatCard icon={<Award />} label="Total Karma" value={fmtNum(a.totalScore)} subtitle={`Avg ${fmtNum(a.avgScore)} per post`} gradient="red" />- <StatCard icon={<MessageSquare />} label="Total Comments" value={fmtNum(a.totalComments)} subtitle={`Avg ${fmtNum(a.avgComments)} per post`} gradient="blue" />- <StatCard icon={<Star />} label="Awards Received" value={fmtNum(a.totalAwards ?? 0)} subtitle={`Avg ${a.avgAwards ?? 0} per post`} gradient="purple" />+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-4">+ <MetricBox icon={<TrendingUp />} label="Posts fetched" value={fmtNum(a.fetchedPosts)} subtitle={`${a.postsLast30Days ?? 0} in the last 30 days`} />+ <MetricBox icon={<Award />} label="Karma from posts" value={fmtNum(a.totalScore)} subtitle={`${fmtNum(a.avgScore)} per post on average`} highlight />+ <MetricBox icon={<MessageSquare />} label="Comments" value={fmtNum(a.totalComments)} subtitle={`${fmtNum(a.avgComments)} per post on average`} />+ <MetricBox icon={<Star />} label="Awards received" value={fmtNum(a.totalAwards ?? 0)} subtitle={`${a.avgAwards ?? 0} per post on average`} /></div>- {/* Karma timeline + media type pie */}{a.monthlyBreakdown?.length > 0 && (- <div className="grid grid-cols-1 xl:grid-cols-3 gap-4">- <MainCard title="Karma Over Time" className="xl:col-span-2">- <ResponsiveContainer width="100%" height={240} debounce={200}>- <AreaChart data={a.monthlyBreakdown} margin={{ top: 4, right: 4, left: 0, bottom: 0 }}>- <defs>- <linearGradient id="redditGrad" x1="0" y1="0" x2="0" y2="1">- <stop offset="5%" stopColor="#FF4500" stopOpacity={0.18} />- <stop offset="95%" stopColor="#FF4500" stopOpacity={0.01} />- </linearGradient>- </defs>- <CartesianGrid strokeDasharray="3 3" stroke="var(--border)" vertical={false} />- <XAxis dataKey="month" tick={{ fill: 'var(--muted-foreground)', fontSize: 11 }} axisLine={false} tickLine={false} />- <YAxis tick={{ fill: 'var(--muted-foreground)', fontSize: 11 }} tickFormatter={fmtNum} axisLine={false} tickLine={false} width={48} />- <ReTooltip contentStyle={TS} formatter={(v, n) => [fmtNumFull(v), n === 'score' ? 'Total Karma' : 'Posts']} />- <Area type="monotone" dataKey="score" stroke="#FF4500" strokeWidth={2} fill="url(#redditGrad)" dot={{ fill: '#FF4500', r: 3, strokeWidth: 0 }} />- </AreaChart>- </ResponsiveContainer>- </MainCard>+ <div className="grid grid-cols-1 gap-4 xl:grid-cols-3">+ <ChartPanel title="Karma over time" height={240} className="xl:col-span-2">+ <AreaChart data={a.monthlyBreakdown} margin={{ top: 4, right: 4, left: 0, bottom: 0 }}>+ <defs>+ <linearGradient id="redditGrad" x1="0" y1="0" x2="0" y2="1">+ <stop offset="5%" stopColor={SERIES.primary} stopOpacity={0.2} />+ <stop offset="95%" stopColor={SERIES.primary} stopOpacity={0} />+ </linearGradient>+ </defs>+ <CartesianGrid {...gridProps} vertical={false} />+ <XAxis dataKey="month" {...axisProps} />+ <YAxis {...axisProps} tickFormatter={fmtNum} width={48} />+ <ReTooltip contentStyle={tooltipStyle} cursor={{ stroke: 'var(--line-strong)' }} formatter={(v, n) => [fmtNumFull(v), n === 'score' ? 'Karma' : 'Posts']} />+ <Area type="monotone" dataKey="score" stroke={SERIES.primary} strokeWidth={2} fill="url(#redditGrad)" dot={{ fill: SERIES.primary, r: 3, strokeWidth: 0 }} />+ </AreaChart>+ </ChartPanel>{mediaTypeData.length > 0 && (- <MainCard title="Post Type Breakdown">- <ResponsiveContainer width="100%" height={240} debounce={200}>- <PieChart>- <Pie data={mediaTypeData} dataKey="value" nameKey="name" cx="50%" cy="44%" outerRadius={80} innerRadius={44} paddingAngle={3} strokeWidth={0}>- {mediaTypeData.map((entry, i) => <Cell key={i} fill={entry.color} />)}- </Pie>- <ReTooltip contentStyle={TS} formatter={(v) => [fmtNumFull(v), 'posts']} />- <Legend iconType="circle" iconSize={8} wrapperStyle={{ fontSize: 11, paddingTop: 8 }} />- </PieChart>- </ResponsiveContainer>- </MainCard>+ <ChartPanel title="Post types" height={240}>+ <PieChart>+ <Pie data={mediaTypeData} dataKey="value" nameKey="name" cx="50%" cy="44%" outerRadius={80} innerRadius={48} paddingAngle={2} strokeWidth={0}>+ {mediaTypeData.map(entry => <Cell key={entry.name} fill={entry.color} />)}+ </Pie>+ <ReTooltip contentStyle={tooltipStyle} formatter={v => [fmtNumFull(v), 'Posts']} />+ <Legend iconType="circle" iconSize={8} wrapperStyle={{ ...legendStyle, paddingTop: 8 }} />+ </PieChart>+ </ChartPanel>)}</div>)}- {/* Detailed metrics */}- <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-4">- <MainCard title="Posting Frequency">- <div className="space-y-3">- {[- { label: 'Last 7 days', value: `${a.postsLast7Days} posts` },- { label: 'Last 30 days', value: `${a.postsLast30Days} posts` },- { label: 'Last 90 days', value: `${a.postsLast90Days} posts` },- ].map(item => (- <div key={item.label} className="flex items-center justify-between">- <span className="text-sm text-muted-foreground">{item.label}</span>- <span className="text-sm font-semibold tabular-nums">{item.value}</span>- </div>- ))}- <Separator />- <div className="flex items-center justify-between">- <span className="text-sm text-muted-foreground">Avg per week</span>- <span className="text-sm font-semibold tabular-nums">{a.postFrequency?.perWeek ?? 0}</span>- </div>- <div className="flex items-center justify-between">- <span className="text-sm text-muted-foreground">Avg per month</span>- <span className="text-sm font-semibold tabular-nums">{a.postFrequency?.perMonth ?? 0}</span>- </div>- </div>- </MainCard>+ <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-3">+ <SurfaceBox title="Posting frequency">+ <StatList rows={[+ { label: 'Last 7 days', value: `${a.postsLast7Days ?? 0} posts` },+ { label: 'Last 30 days', value: `${a.postsLast30Days ?? 0} posts` },+ { label: 'Last 90 days', value: `${a.postsLast90Days ?? 0} posts` },+ { label: 'Per week', value: a.postFrequency?.perWeek ?? 0 },+ { label: 'Per month', value: a.postFrequency?.perMonth ?? 0 },+ ]} />+ </SurfaceBox>- <MainCard title="Karma Breakdown">- <div className="space-y-3">- {[- { label: 'Average karma', value: fmtNum(a.avgScore) },- { label: 'Median karma', value: fmtNum(a.medianScore) },- { label: 'Best single post', value: fmtNum(a.topPosts?.[0]?.score) },- { label: 'Avg upvote ratio', value: `${a.avgUpvoteRatio ?? 0}%` },- { label: 'Total comments', value: fmtNum(a.totalComments) },- { label: 'Avg comments', value: fmtNum(a.avgComments) },- ].map(item => (- <div key={item.label} className="flex items-center justify-between">- <span className="text-sm text-muted-foreground">{item.label}</span>- <span className="text-sm font-semibold tabular-nums">{item.value}</span>- </div>- ))}- </div>- </MainCard>+ <SurfaceBox title="Karma breakdown">+ <StatList rows={[+ { label: 'Average karma', value: fmtNum(a.avgScore) },+ { label: 'Median karma', value: fmtNum(a.medianScore) },+ { label: 'Best single post', value: fmtNum(a.topPosts?.[0]?.score) },+ { label: 'Average upvote ratio', value: `${a.avgUpvoteRatio ?? 0}%` },+ { label: 'Total comments', value: fmtNum(a.totalComments) },+ { label: 'Average comments', value: fmtNum(a.avgComments) },+ ]} />+ </SurfaceBox>- <MainCard title="Performance Indicators">- <div className="space-y-4">+ <SurfaceBox title="Performance indicators">+ <div className="flex flex-col gap-5">{[- { label: 'Virality Score', value: a.viralityScore, max: Math.max(10, a.viralityScore), desc: 'Ratio of peak post karma to average - higher means bigger outlier hits' },- { label: 'Consistency', value: a.consistencyScore, max: 100, desc: 'Karma reliability across posts - 100 means very uniform performance' },+ { label: 'Virality score', value: a.viralityScore ?? 0, max: Math.max(10, a.viralityScore ?? 0), desc: 'Best post karma against the average. Higher means bigger outlier hits.' },+ { label: 'Consistency', value: a.consistencyScore ?? 0, max: 100, desc: 'How evenly karma spreads across posts. 100 means every post performs alike.' },].map(item => (- <div key={item.label} className="space-y-1.5">+ <div key={item.label} className="flex flex-col gap-2"><div className="flex items-center justify-between text-sm">- <span className="font-medium">{item.label}</span>- <span className="text-muted-foreground tabular-nums">{item.value}</span>+ <span className="font-medium text-ink">{item.label}</span>+ <span className="text-ink-muted tabular-nums">{item.value}</span></div>- <Progress value={(item.value / item.max) * 100} className="h-1.5" />- <p className="text-xs text-muted-foreground">{item.desc}</p>+ <Progress value={(item.value / item.max) * 100} aria-label={item.label} />+ <p className="text-caption text-ink-faint">{item.desc}</p></div>))}</div>- </MainCard>+ </SurfaceBox></div>- {/* Best posting times */}{a.postsByDayOfWeek?.length > 0 && (- <div className="grid grid-cols-1 xl:grid-cols-2 gap-4">- <MainCard title="Posts by Day of Week">- <ResponsiveContainer width="100%" height={220} debounce={200}>- <BarChart data={a.postsByDayOfWeek} margin={{ top: 4, right: 4, left: 0, bottom: 0 }}>- <CartesianGrid strokeDasharray="3 3" stroke="var(--border)" vertical={false} />- <XAxis dataKey="shortDay" tick={{ fill: 'var(--muted-foreground)', fontSize: 11 }} axisLine={false} tickLine={false} />- <YAxis tick={{ fill: 'var(--muted-foreground)', fontSize: 11 }} tickFormatter={fmtNum} axisLine={false} tickLine={false} width={36} />- <ReTooltip contentStyle={TS} formatter={(v, n) => [fmtNumFull(v), n === 'avgScore' ? 'Avg Karma' : 'Posts']} />- <Bar dataKey="posts" fill="#FF4500" opacity={0.35} radius={[3, 3, 0, 0]} />- <Bar dataKey="avgScore" fill="#FF4500" radius={[3, 3, 0, 0]} />- </BarChart>- </ResponsiveContainer>- {a.bestPostingDay && (- <p className="text-xs text-muted-foreground mt-2">- Best day: <span className="font-medium text-foreground">{a.bestPostingDay}</span>- </p>- )}- </MainCard>+ <div className="grid grid-cols-1 gap-4 xl:grid-cols-2">+ <ChartPanel title="Posts by day of week" subheader={a.bestPostingDay ? `Best day: ${a.bestPostingDay}` : undefined} height={220}>+ <BarChart data={a.postsByDayOfWeek} margin={{ top: 4, right: 4, left: 0, bottom: 0 }}>+ <CartesianGrid {...gridProps} vertical={false} />+ <XAxis dataKey="shortDay" {...axisProps} />+ <YAxis {...axisProps} tickFormatter={fmtNum} width={36} />+ <ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} formatter={(v, n) => [fmtNumFull(v), n === 'avgScore' ? 'Average karma' : 'Posts']} />+ <Bar dataKey="posts" fill={SERIES.neutral} radius={[3, 3, 0, 0]} />+ <Bar dataKey="avgScore" fill={SERIES.primary} radius={[3, 3, 0, 0]} />+ </BarChart>+ </ChartPanel>- <MainCard title="Posts by Hour">- <ResponsiveContainer width="100%" height={220} debounce={200}>- <BarChart data={a.postsByHour} margin={{ top: 4, right: 4, left: 0, bottom: 0 }}>- <CartesianGrid strokeDasharray="3 3" stroke="var(--border)" vertical={false} />- <XAxis dataKey="hour" tickFormatter={h => `${h}h`} tick={{ fill: 'var(--muted-foreground)', fontSize: 10 }} axisLine={false} tickLine={false} interval={3} />- <YAxis tick={{ fill: 'var(--muted-foreground)', fontSize: 11 }} tickFormatter={fmtNum} axisLine={false} tickLine={false} width={36} />- <ReTooltip contentStyle={TS} formatter={(v, n) => [fmtNumFull(v), n === 'avgScore' ? 'Avg Karma' : 'Posts']} />- <Bar dataKey="avgScore" fill="#FF6534" radius={[3, 3, 0, 0]} />- </BarChart>- </ResponsiveContainer>- {a.bestPostingHour && (- <p className="text-xs text-muted-foreground mt-2">- Best hour: <span className="font-medium text-foreground">{a.bestPostingHour}</span>- </p>- )}- </MainCard>+ <ChartPanel title="Average karma by hour" subheader={a.bestPostingHour ? `Best hour: ${a.bestPostingHour}` : undefined} height={220}>+ <BarChart data={a.postsByHour} margin={{ top: 4, right: 4, left: 0, bottom: 0 }}>+ <CartesianGrid {...gridProps} vertical={false} />+ <XAxis dataKey="hour" tickFormatter={h => `${h}h`} tick={{ ...axisTick, fontSize: 10 }} axisLine={false} tickLine={false} interval={3} />+ <YAxis {...axisProps} tickFormatter={fmtNum} width={36} />+ <ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} formatter={(v, n) => [fmtNumFull(v), n === 'avgScore' ? 'Average karma' : 'Posts']} />+ <Bar dataKey="avgScore" fill={SERIES.warm} radius={[3, 3, 0, 0]} />+ </BarChart>+ </ChartPanel></div>)}- {/* Subreddit breakdown */}{a.subredditBreakdown?.length > 0 && (- <MainCard title="Top Subreddits" content={false}>+ <SurfaceBox title="Top subreddits" content={false} className="overflow-hidden"><Table><TableHeader><TableRow>- <TableHead className="w-8">#</TableHead>+ <TableHead className="w-10 text-right">#</TableHead><TableHead>Subreddit</TableHead><TableHead className="text-right">Posts</TableHead>- <TableHead className="text-right">Total Karma</TableHead>- <TableHead className="text-right">Avg Karma</TableHead>- <TableHead className="text-right">Avg Comments</TableHead>+ <TableHead className="text-right">Total karma</TableHead>+ <TableHead className="text-right">Average karma</TableHead>+ <TableHead className="text-right">Average comments</TableHead></TableRow></TableHeader><TableBody>{a.subredditBreakdown.map((sub, i) => (<TableRow key={sub.subreddit}>- <TableCell className="text-xs text-muted-foreground">{i + 1}</TableCell>+ <TableCell className="text-right font-mono text-caption text-ink-faint">{i + 1}</TableCell><TableCell>- <a- href={`https://reddit.com/r/${sub.subreddit}`}- target="_blank"- rel="noopener noreferrer"- className="text-sm font-medium hover:underline flex items-center gap-1"- >+ <a href={`https://reddit.com/r/${sub.subreddit}`} target="_blank" rel="noopener noreferrer" className="flex items-center gap-1 text-sm font-medium text-ink hover:underline">r/{sub.subreddit}- <ExternalLink className="h-3 w-3 text-muted-foreground" />+ <ExternalLink className="size-3 text-ink-faint" /></a></TableCell>- <TableCell className="text-right text-sm tabular-nums">{sub.posts}</TableCell>- <TableCell className="text-right text-sm tabular-nums">{fmtNum(sub.totalScore)}</TableCell>- <TableCell className="text-right text-sm tabular-nums">{fmtNum(sub.avgScore)}</TableCell>- <TableCell className="text-right text-sm tabular-nums">{fmtNum(sub.avgComments)}</TableCell>+ <TableCell className="text-right text-ink-muted">{sub.posts}</TableCell>+ <TableCell className="text-right font-semibold text-ink">{fmtNum(sub.totalScore)}</TableCell>+ <TableCell className="text-right text-ink-muted">{fmtNum(sub.avgScore)}</TableCell>+ <TableCell className="text-right text-ink-muted">{fmtNum(sub.avgComments)}</TableCell></TableRow>))}</TableBody></Table>- </MainCard>+ </SurfaceBox>)}- {/* Top posts */}{a.topPosts?.length > 0 && (- <MainCard title="Top Posts by Karma" content={false}>+ <SurfaceBox title="Top posts by karma" content={false} className="overflow-hidden"><Table><TableHeader><TableRow>- <TableHead className="w-8">#</TableHead>+ <TableHead className="w-10 text-right">#</TableHead><TableHead>Post</TableHead><TableHead className="text-right">Karma</TableHead><TableHead className="text-right">Comments</TableHead>- <TableHead className="text-right">Upvote %</TableHead>+ <TableHead className="text-right">Upvoted</TableHead><TableHead className="text-right">Posted</TableHead>- <TableHead className="w-8" />+ <TableHead className="w-10"><span className="sr-only">Open</span></TableHead></TableRow></TableHeader><TableBody>{a.topPosts.map((post, i) => (<TableRow key={post.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>+ <TableCell className="text-right"><RankNumber rank={i + 1} className="w-auto" /></TableCell>+ <TableCell className="whitespace-normal"><div className="max-w-sm">- <p className="text-sm font-medium leading-snug line-clamp-2">{post.title}</p>- <div className="flex items-center gap-2 mt-0.5">- <span className="text-xs text-muted-foreground">{post.subredditPrefixed}</span>- {post.flair && <Badge variant="outline" className="text-[10px] px-1 py-0">{post.flair}</Badge>}+ <p className="line-clamp-2 text-sm font-medium leading-snug text-ink">{post.title}</p>+ <div className="mt-1 flex items-center gap-1.5">+ <span className="text-caption text-ink-faint">{post.subredditPrefixed}</span>+ {post.flair && <Badge variant="outline">{post.flair}</Badge>}</div></div></TableCell>- <TableCell className="text-right text-sm font-semibold tabular-nums text-orange-500">{fmtNum(post.score)}</TableCell>- <TableCell className="text-right text-sm tabular-nums">{fmtNum(post.numComments)}</TableCell>- <TableCell className="text-right text-sm tabular-nums">{Math.round((post.upvoteRatio ?? 0) * 100)}%</TableCell>- <TableCell className="text-right text-xs text-muted-foreground">{fmtDate(post.createdAt)}</TableCell>+ <TableCell className="text-right font-semibold text-ink">{fmtNum(post.score)}</TableCell>+ <TableCell className="text-right text-ink-muted">{fmtNum(post.numComments)}</TableCell>+ <TableCell className="text-right text-ink-muted">{Math.round((post.upvoteRatio ?? 0) * 100)}%</TableCell>+ <TableCell className="text-right text-small text-ink-faint">{fmtDate(post.createdAt)}</TableCell><TableCell>- <a href={post.permalink} target="_blank" rel="noopener noreferrer">- <Button variant="ghost" size="icon" className="size-7">- <ExternalLink className="h-3.5 w-3.5" />- </Button>- </a>+ <Button variant="ghost" size="icon-xs" render={<a href={post.permalink} target="_blank" rel="noopener noreferrer" aria-label={`Open "${post.title}" on Reddit`} />}>+ <ExternalLink />+ </Button></TableCell></TableRow>))}</TableBody></Table>- </MainCard>+ </SurfaceBox>)}</div>);diff --git a/frontend/src/features/analytics/reddit/RedditPosts.jsx b/frontend/src/features/analytics/reddit/RedditPosts.jsxindex 429fa64..08bb369 100644--- a/frontend/src/features/analytics/reddit/RedditPosts.jsx+++ b/frontend/src/features/analytics/reddit/RedditPosts.jsx@@ -1,45 +1,25 @@-import React, { useState, useEffect, useMemo } from 'react';-import { useParams, useNavigate } from 'react-router-dom';-import { Button } from '@/components/ui/button';-import { Input } from '@/components/ui/input';-import { Badge } from '@/components/ui/badge';+import React, { useEffect, useMemo, useState } from 'react';+import { useParams } from 'react-router-dom';+import { UserX } from 'lucide-react';import { Skeleton } from '@/components/ui/skeleton';-import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';-import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';-import { Spinner } from '@/components/ui/spinner';-import MainCard from '../../../components/MainCard';+import PageHeader from '@/components/PageHeader';+import SurfaceBox from '@/components/SurfaceBox';+import { EmptyState } from '@/components/StateViews';+import { AccountAvatar } from '@/components/platform';import { useAppContext } from '../../../context/AppContext';import { api } from '../../../services/api';-import { fmtNum, fmtDate } from '../../../utils/formatters';-import { ArrowLeft, Search, ExternalLink, TrendingUp, MessageSquare, FileText, Image, Video, Link2 } from 'lucide-react';--const MEDIA_TYPE_LABELS = { text: 'Text', image: 'Image', video: 'Video', link: 'Link' };-const SORT_OPTIONS = [- { value: 'score-desc', label: 'Karma (high to low)' },- { value: 'score-asc', label: 'Karma (low to high)' },- { value: 'comments-desc', label: 'Comments (most)' },- { value: 'date-desc', label: 'Newest first' },- { value: 'date-asc', label: 'Oldest first' },-];--function MediaTypeIcon({ type }) {- const props = { className: 'h-3.5 w-3.5' };- if (type === 'image') return <Image {...props} />;- if (type === 'video') return <Video {...props} />;- if (type === 'link') return <Link2 {...props} />;- return <FileText {...props} />;-}+import { RedditPostFilters, RedditPostTable } from './redditPostTable';+import { filterAndSortRedditPosts, subredditsOf } from './redditPostUtils';export default function RedditPosts() {const { id } = useParams();const { accounts, showToast } = useAppContext();- const navigate = useNavigate();const account = accounts.find(a => a.id === id);- const [loading, setLoading] = useState(true);- const [posts, setPosts] = useState([]);- const [query, setQuery] = useState('');- const [sort, setSort] = useState('score-desc');+ const [loading, setLoading] = useState(true);+ const [posts, setPosts] = useState([]);+ const [query, setQuery] = useState('');+ const [sort, setSort] = useState('score-desc');const [subFilter, setSubFilter] = useState('all');useEffect(() => {@@ -47,180 +27,51 @@ export default function RedditPosts() {setLoading(true);api.getRedditPosts(account.id).then(data => setPosts(Array.isArray(data) ? data : []))- .catch(err => showToast('Failed to load posts: ' + err.message, 'error'))+ .catch(err => showToast(`Couldn't load posts. ${err.message}`, 'error')).finally(() => setLoading(false));+ // Reload only when the route changes, not on every account list refresh+ // eslint-disable-next-line react-hooks/exhaustive-deps}, [id]);- const subreddits = useMemo(() => {- const seen = new Set();- posts.forEach(p => seen.add(p.subreddit));- return ['all', ...Array.from(seen).sort()];- }, [posts]);-- const filtered = useMemo(() => {- let result = posts;- if (subFilter !== 'all') result = result.filter(p => p.subreddit === subFilter);- if (query.trim()) {- const q = query.toLowerCase();- result = result.filter(p =>- p.title.toLowerCase().includes(q) ||- p.subreddit.toLowerCase().includes(q) ||- (p.flair || '').toLowerCase().includes(q)- );- }- return [...result].sort((a, b) => {- if (sort === 'score-desc') return b.score - a.score;- if (sort === 'score-asc') return a.score - b.score;- if (sort === 'comments-desc') return b.numComments - a.numComments;- if (sort === 'date-desc') return new Date(b.createdAt) - new Date(a.createdAt);- if (sort === 'date-asc') return new Date(a.createdAt) - new Date(b.createdAt);- return 0;- });- }, [posts, query, sort, subFilter]);+ const subreddits = useMemo(() => subredditsOf(posts), [posts]);+ const filtered = useMemo(+ () => filterAndSortRedditPosts(posts, { query, sort, subreddit: subFilter }),+ [posts, query, sort, subFilter],+ );if (!account) {return (- <div className="space-y-3">- <Button variant="ghost" onClick={() => navigate('/')} className="gap-2 -ml-2 text-muted-foreground">- <ArrowLeft className="h-4 w-4" /> Back- </Button>- <p className="text-muted-foreground">Account not found.</p>+ <div className="flex flex-col gap-6">+ <PageHeader title="Reddit posts" back={{ to: '/reddit-posts', label: 'All Reddit posts' }} />+ <SurfaceBox>+ <EmptyState icon={<UserX />} title="Account not found" description="It may have been removed. Choose another account from the sidebar." />+ </SurfaceBox></div>);}return (- <div className="space-y-6">- <div className="flex items-start justify-between gap-4">- <div>- <Button variant="ghost" onClick={() => navigate(`/reddit/${account.id}`)} className="gap-2 -ml-2 text-muted-foreground mb-2">- <ArrowLeft className="h-4 w-4" /> Back to Analytics- </Button>- <h1 className="text-2xl font-bold tracking-tight">Posts - u/{account.username}</h1>- <p className="text-sm text-muted-foreground mt-0.5">- {loading ? 'Loading...' : `${filtered.length} of ${posts.length} posts`}- </p>- </div>- </div>+ <div className="flex flex-col gap-6">+ <PageHeader+ back={{ to: `/reddit/${account.id}`, label: `u/${account.username} analytics` }}+ media={<AccountAvatar account={account} size="lg" />}+ title={`Posts by u/${account.username}`}+ description={loading ? 'Loading posts' : `${filtered.length} of ${posts.length} posts`}+ />{loading ? (- <div className="flex items-center justify-center min-h-[40vh]">- <div className="flex flex-col items-center gap-3">- <Spinner className="size-10" />- <p className="text-sm text-muted-foreground">Loading posts...</p>- </div>+ <div className="flex flex-col gap-4">+ <Skeleton className="h-10 rounded-field" />+ <Skeleton className="h-96 rounded-card" /></div>) : (<>- {/* Filters */}- <MainCard>- <div className="flex flex-col sm:flex-row gap-3">- <div className="relative flex-1">- <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />- <Input- placeholder="Search posts..."- value={query}- onChange={e => setQuery(e.target.value)}- className="pl-9"- />- </div>- <Select value={subFilter} onValueChange={setSubFilter}>- <SelectTrigger className="w-full sm:w-48">- <SelectValue placeholder="All subreddits" />- </SelectTrigger>- <SelectContent>- <SelectItem value="all">All subreddits</SelectItem>- {subreddits.filter(s => s !== 'all').map(s => (- <SelectItem key={s} value={s}>r/{s}</SelectItem>- ))}- </SelectContent>- </Select>- <Select value={sort} onValueChange={setSort}>- <SelectTrigger className="w-full sm:w-52">- <SelectValue />- </SelectTrigger>- <SelectContent>- {SORT_OPTIONS.map(o => (- <SelectItem key={o.value} value={o.value}>{o.label}</SelectItem>- ))}- </SelectContent>- </Select>- </div>- </MainCard>-- {/* Posts table */}- <MainCard content={false}>- <Table>- <TableHeader>- <TableRow>- <TableHead className="w-8">#</TableHead>- <TableHead>Post</TableHead>- <TableHead className="w-24">Type</TableHead>- <TableHead className="text-right w-24">Karma</TableHead>- <TableHead className="text-right w-28">Comments</TableHead>- <TableHead className="text-right w-20">Upvote %</TableHead>- <TableHead className="text-right w-28">Date</TableHead>- <TableHead className="w-8" />- </TableRow>- </TableHeader>- <TableBody>- {filtered.length === 0 ? (- <TableRow>- <TableCell colSpan={8} className="text-center text-muted-foreground py-12">- No posts match the current filters- </TableCell>- </TableRow>- ) : (- filtered.map((post, i) => (- <TableRow key={post.id}>- <TableCell className="text-xs text-muted-foreground">{i + 1}</TableCell>- <TableCell>- <div className="max-w-md">- <p className="text-sm font-medium leading-snug line-clamp-2">{post.title}</p>- <div className="flex items-center gap-2 mt-0.5">- <span className="text-xs text-muted-foreground">{post.subredditPrefixed}</span>- {post.flair && (- <Badge variant="outline" className="text-[10px] px-1 py-0 h-4">- {post.flair}- </Badge>- )}- {post.isNsfw && (- <Badge className="text-[10px] px-1 py-0 h-4 bg-red-100 text-red-700 border-red-200">- NSFW- </Badge>- )}- </div>- </div>- </TableCell>- <TableCell>- <div className="flex items-center gap-1.5 text-xs text-muted-foreground">- <MediaTypeIcon type={post.mediaType} />- <span>{MEDIA_TYPE_LABELS[post.mediaType] || post.mediaType}</span>- </div>- </TableCell>- <TableCell className="text-right text-sm font-semibold tabular-nums text-orange-500">- {fmtNum(post.score)}- </TableCell>- <TableCell className="text-right text-sm tabular-nums">{fmtNum(post.numComments)}</TableCell>- <TableCell className="text-right text-sm tabular-nums">- {Math.round((post.upvoteRatio ?? 0) * 100)}%- </TableCell>- <TableCell className="text-right text-xs text-muted-foreground">- {fmtDate(post.createdAt)}- </TableCell>- <TableCell>- <a href={post.permalink} target="_blank" rel="noopener noreferrer">- <Button variant="ghost" size="icon" className="size-7">- <ExternalLink className="h-3.5 w-3.5" />- </Button>- </a>- </TableCell>- </TableRow>- ))- )}- </TableBody>- </Table>- </MainCard>+ <RedditPostFilters+ query={query} onQuery={setQuery}+ sort={sort} onSort={setSort}+ subreddit={subFilter} onSubreddit={setSubFilter} subreddits={subreddits}+ />+ <RedditPostTable posts={filtered} /></>)}</div>diff --git a/frontend/src/features/analytics/reddit/RedditPostsAll.jsx b/frontend/src/features/analytics/reddit/RedditPostsAll.jsxindex fb73d59..ecdbf8a 100644--- a/frontend/src/features/analytics/reddit/RedditPostsAll.jsx+++ b/frontend/src/features/analytics/reddit/RedditPostsAll.jsx@@ -1,339 +1,125 @@-import React, { useState, useEffect, useMemo } from 'react';-import { useNavigate } from 'react-router-dom';+import React, { useCallback, useEffect, useMemo, useState } from 'react';+import { Link } from 'react-router-dom';+import { RefreshCw, TrendingUp, MessageSquare, Award, MessagesSquare, Plus } from 'lucide-react';import { Button } from '@/components/ui/button';-import { Input } from '@/components/ui/input';-import { Badge } from '@/components/ui/badge';-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 { Spinner } from '@/components/ui/spinner';-import StatCard from '../../../components/ui/StatCard';-import MainCard from '../../../components/MainCard';+import { Skeleton } from '@/components/ui/skeleton';+import PageHeader from '@/components/PageHeader';+import MetricBox from '@/components/MetricBox';+import SurfaceBox from '@/components/SurfaceBox';+import { EmptyState } from '@/components/StateViews';import { useAppContext } from '../../../context/AppContext';import { api } from '../../../services/api';-import { fmtNum, fmtDate } from '../../../utils/formatters';-import {- Search, ExternalLink, TrendingUp, MessageSquare, FileText,- Image, Video, Link2, Award, RefreshCw,-} from 'lucide-react';--const MEDIA_TYPE_LABELS = { text: 'Text', image: 'Image', video: 'Video', link: 'Link' };-const SORT_OPTIONS = [- { value: 'score-desc', label: 'Karma (high to low)' },- { value: 'score-asc', label: 'Karma (low to high)' },- { value: 'comments-desc', label: 'Comments (most)' },- { value: 'date-desc', label: 'Newest first' },- { value: 'date-asc', label: 'Oldest first' },-];--function MediaTypeIcon({ type }) {- const props = { className: 'h-3.5 w-3.5' };- if (type === 'image') return <Image {...props} />;- if (type === 'video') return <Video {...props} />;- if (type === 'link') return <Link2 {...props} />;- return <FileText {...props} />;-}+import { fmtNum } from '../../../utils/formatters';+import { RedditPostFilters, RedditPostTable } from './redditPostTable';+import { filterAndSortRedditPosts, subredditsOf } from './redditPostUtils';+import { cn } from '@/lib/utils';export default function RedditPostsAll() {const { accounts, showToast } = useAppContext();- const navigate = useNavigate();+ const redditAccounts = useMemo(() => accounts.filter(a => a.platform === 'reddit'), [accounts]);+ const accountsById = useMemo(() => Object.fromEntries(redditAccounts.map(a => [a.id, a])), [redditAccounts]);- const redditAccounts = accounts.filter(a => a.platform === 'reddit');-- const [posts, setPosts] = useState([]);- const [loading, setLoading] = useState(false);- const [refreshing, setRefreshing] = useState(false);- const [query, setQuery] = useState('');- const [sort, setSort] = useState('score-desc');+ const [posts, setPosts] = useState([]);+ const [loading, setLoading] = useState(false);+ const [query, setQuery] = useState('');+ const [sort, setSort] = useState('score-desc');const [accountFilter, setAccountFilter] = useState('all');- const [subFilter, setSubFilter] = useState('all');+ const [subFilter, setSubFilter] = useState('all');- const loadPosts = async () => {+ const loadPosts = useCallback(async () => {if (redditAccounts.length === 0) return;setLoading(true);try {const results = await Promise.allSettled(- redditAccounts.map(acc => api.getRedditPosts(acc.id).then(data => ({- accountId: acc.id,- username: acc.username,- iconUrl: acc.iconUrl,- posts: Array.isArray(data) ? data : [],- })))+ redditAccounts.map(acc => api.getRedditPosts(acc.id).then(data => ({ acc, posts: Array.isArray(data) ? data : [] }))),);const combined = [];results.forEach(r => {if (r.status === 'fulfilled') {r.value.posts.forEach(post => combined.push({...post,- accountId: r.value.accountId,- accountUsername: r.value.username,- accountIconUrl: r.value.iconUrl,+ accountId: r.value.acc.id,+ accountUsername: r.value.acc.username,+ accountIconUrl: r.value.acc.iconUrl,}));} else {- showToast('Failed to load posts for one account: ' + r.reason?.message, 'error');+ showToast(`Couldn't load posts for one account. ${r.reason?.message || ''}`.trim(), 'error');}});setPosts(combined);- } catch (err) {- showToast('Failed to load Reddit posts: ' + err.message, 'error');} finally {setLoading(false);}- };-- useEffect(() => { loadPosts(); }, [redditAccounts.length]);+ }, [redditAccounts, showToast]);- const handleRefresh = async () => {- setRefreshing(true);- await loadPosts();- setRefreshing(false);- };-- const subreddits = useMemo(() => {- const seen = new Set();- posts.forEach(p => seen.add(p.subreddit));- return Array.from(seen).sort();- }, [posts]);-- const filtered = useMemo(() => {- let result = posts;- if (accountFilter !== 'all') result = result.filter(p => p.accountId === accountFilter);- if (subFilter !== 'all') result = result.filter(p => p.subreddit === subFilter);- if (query.trim()) {- const q = query.toLowerCase();- result = result.filter(p =>- p.title.toLowerCase().includes(q) ||- p.subreddit.toLowerCase().includes(q) ||- (p.flair || '').toLowerCase().includes(q) ||- p.accountUsername.toLowerCase().includes(q)- );- }- return [...result].sort((a, b) => {- if (sort === 'score-desc') return b.score - a.score;- if (sort === 'score-asc') return a.score - b.score;- if (sort === 'comments-desc') return b.numComments - a.numComments;- if (sort === 'date-desc') return new Date(b.createdAt) - new Date(a.createdAt);- if (sort === 'date-asc') return new Date(a.createdAt) - new Date(b.createdAt);- return 0;- });- }, [posts, query, sort, accountFilter, subFilter]);+ useEffect(() => { loadPosts(); }, [loadPosts]);+ const subreddits = useMemo(() => subredditsOf(posts), [posts]);+ const filtered = useMemo(+ () => filterAndSortRedditPosts(posts, { query, sort, subreddit: subFilter, accountId: accountFilter }),+ [posts, query, sort, subFilter, accountFilter],+ );const totals = useMemo(() => ({- posts: filtered.length,score: filtered.reduce((s, p) => s + p.score, 0),comments: filtered.reduce((s, p) => s + p.numComments, 0),}), [filtered]);+ const avg = n => filtered.length > 0 ? `${fmtNum(Math.round(n / filtered.length))} per post on average` : '';if (redditAccounts.length === 0) {return (- <div className="space-y-6">- <div>- <h1 className="text-2xl font-bold tracking-tight">Reddit Posts</h1>- <p className="text-sm text-muted-foreground mt-0.5">Posts from all connected Reddit accounts</p>- </div>- <MainCard>- <div className="flex flex-col items-center text-center py-12 gap-4">- <p className="text-sm text-muted-foreground">No Reddit accounts connected.</p>- <Button onClick={() => navigate('/accounts')}>Add Reddit Account</Button>- </div>- </MainCard>+ <div className="flex flex-col gap-6">+ <PageHeader title="Reddit posts" description="Posts from every connected Reddit account" />+ <SurfaceBox>+ <EmptyState+ icon={<MessagesSquare />}+ title="No Reddit accounts yet"+ description="Connect a Reddit account to see its posts, karma and comments here."+ action={<Button render={<Link to="/accounts?add=1" />}><Plus data-icon="inline-start" />Add an account</Button>}+ />+ </SurfaceBox></div>);}return (- <div className="space-y-6">- <div className="flex items-start justify-between gap-4">- <div>- <h1 className="text-2xl font-bold tracking-tight">Reddit Posts</h1>- <p className="text-sm text-muted-foreground mt-0.5">- {loading ? 'Loading...' : `${filtered.length} of ${posts.length} posts across ${redditAccounts.length} account${redditAccounts.length !== 1 ? 's' : ''}`}- </p>- </div>- <Button- variant="outline"- size="sm"- className="gap-2 shrink-0"- onClick={handleRefresh}- disabled={loading || refreshing}- >- <RefreshCw className={`h-3.5 w-3.5 ${refreshing ? 'animate-spin' : ''}`} />- Refresh- </Button>- </div>+ <div className="flex flex-col gap-6">+ <PageHeader+ title="Reddit posts"+ description={loading+ ? `Loading posts from ${redditAccounts.length} account${redditAccounts.length === 1 ? '' : 's'}`+ : `${filtered.length} of ${posts.length} posts across ${redditAccounts.length} account${redditAccounts.length === 1 ? '' : 's'}`}+ actions={+ <Button variant="outline" size="sm" onClick={loadPosts} disabled={loading}>+ <RefreshCw data-icon="inline-start" className={cn(loading && 'animate-spin')} />+ Refresh+ </Button>+ }+ />{loading ? (- <div className="flex items-center justify-center min-h-[40vh]">- <div className="flex flex-col items-center gap-3">- <Spinner className="size-10" />- <p className="text-sm text-muted-foreground">Loading posts from {redditAccounts.length} account{redditAccounts.length !== 1 ? 's' : ''}...</p>+ <div className="flex flex-col gap-4">+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-3">+ {[0, 1, 2].map(i => <Skeleton key={i} className="h-28 rounded-card" />)}</div>+ <Skeleton className="h-10 rounded-field" />+ <Skeleton className="h-96 rounded-card" /></div>) : (<>- {/* Summary stats */}- <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">- <StatCard icon={<TrendingUp />} label="Posts Shown" value={fmtNum(totals.posts)} subtitle={`${posts.length} total fetched`} gradient="orange" />- <StatCard icon={<Award />} label="Combined Karma" value={fmtNum(totals.score)} subtitle={filtered.length > 0 ? `Avg ${fmtNum(Math.round(totals.score / filtered.length))} per post` : ''} gradient="red" />- <StatCard icon={<MessageSquare />} label="Total Comments" value={fmtNum(totals.comments)} subtitle={filtered.length > 0 ? `Avg ${fmtNum(Math.round(totals.comments / filtered.length))} per post` : ''} gradient="blue" />+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-3">+ <MetricBox icon={<TrendingUp />} label="Posts shown" value={fmtNum(filtered.length)} subtitle={`${posts.length} fetched in total`} />+ <MetricBox icon={<Award />} label="Karma" value={fmtNum(totals.score)} subtitle={avg(totals.score)} highlight />+ <MetricBox icon={<MessageSquare />} label="Comments" value={fmtNum(totals.comments)} subtitle={avg(totals.comments)} /></div>- {/* Filters */}- <MainCard>- <div className="flex flex-col sm:flex-row gap-3">- <div className="relative flex-1">- <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />- <Input- placeholder="Search posts..."- value={query}- onChange={e => setQuery(e.target.value)}- className="pl-9"- />- </div>-- {redditAccounts.length > 1 && (- <Select- value={accountFilter}- onValueChange={setAccountFilter}- items={[- { value: 'all', label: 'All accounts' },- ...redditAccounts.map(a => ({ value: a.id, label: `u/${a.username}` })),- ]}- >- <SelectTrigger className="w-full sm:w-48">- <SelectValue placeholder="All accounts" />- </SelectTrigger>- <SelectContent>- <SelectItem value="all">All accounts</SelectItem>- {redditAccounts.map(a => (- <SelectItem key={a.id} value={a.id}>u/{a.username}</SelectItem>- ))}- </SelectContent>- </Select>- )}-- <Select- value={subFilter}- onValueChange={setSubFilter}- items={[- { value: 'all', label: 'All subreddits' },- ...subreddits.map(s => ({ value: s, label: `r/${s}` })),- ]}- >- <SelectTrigger className="w-full sm:w-48">- <SelectValue placeholder="All subreddits" />- </SelectTrigger>- <SelectContent>- <SelectItem value="all">All subreddits</SelectItem>- {subreddits.map(s => (- <SelectItem key={s} value={s}>r/{s}</SelectItem>- ))}- </SelectContent>- </Select>-- <Select value={sort} onValueChange={setSort} items={SORT_OPTIONS}>- <SelectTrigger className="w-full sm:w-52">- <SelectValue />- </SelectTrigger>- <SelectContent>- {SORT_OPTIONS.map(o => (- <SelectItem key={o.value} value={o.value}>{o.label}</SelectItem>- ))}- </SelectContent>- </Select>- </div>- </MainCard>+ <RedditPostFilters+ query={query} onQuery={setQuery}+ sort={sort} onSort={setSort}+ subreddit={subFilter} onSubreddit={setSubFilter} subreddits={subreddits}+ accountId={accountFilter} onAccount={setAccountFilter} accounts={redditAccounts}+ />- {/* Posts table */}- <MainCard content={false}>- <Table>- <TableHeader>- <TableRow>- <TableHead className="w-8">#</TableHead>- <TableHead>Post</TableHead>- {redditAccounts.length > 1 && <TableHead className="w-36">Account</TableHead>}- <TableHead className="w-24">Type</TableHead>- <TableHead className="text-right w-24">Karma</TableHead>- <TableHead className="text-right w-28">Comments</TableHead>- <TableHead className="text-right w-20">Upvote %</TableHead>- <TableHead className="text-right w-28">Date</TableHead>- <TableHead className="w-8" />- </TableRow>- </TableHeader>- <TableBody>- {filtered.length === 0 ? (- <TableRow>- <TableCell colSpan={redditAccounts.length > 1 ? 9 : 8} className="text-center text-muted-foreground py-12">- No posts match the current filters- </TableCell>- </TableRow>- ) : (- filtered.map((post, i) => (- <TableRow key={`${post.accountId}-${post.id}`}>- <TableCell className="text-xs text-muted-foreground">{i + 1}</TableCell>- <TableCell>- <div className="max-w-md">- <p className="text-sm font-medium leading-snug line-clamp-2">{post.title}</p>- <div className="flex items-center gap-2 mt-0.5">- <span className="text-xs text-muted-foreground">{post.subredditPrefixed}</span>- {post.flair && (- <Badge variant="outline" className="text-[10px] px-1 py-0 h-4">- {post.flair}- </Badge>- )}- {post.isNsfw && (- <Badge className="text-[10px] px-1 py-0 h-4 bg-red-100 text-red-700 border-red-200">- NSFW- </Badge>- )}- </div>- </div>- </TableCell>- {redditAccounts.length > 1 && (- <TableCell>- <button- onClick={() => navigate(`/reddit/${post.accountId}`)}- className="flex items-center gap-1.5 hover:underline"- >- <Avatar className="h-5 w-5 flex-shrink-0">- <AvatarImage src={post.accountIconUrl} />- <AvatarFallback className="bg-orange-500 text-white text-[0.5rem] font-bold">- {(post.accountUsername || '?').slice(0, 2).toUpperCase()}- </AvatarFallback>- </Avatar>- <span className="text-xs">u/{post.accountUsername}</span>- </button>- </TableCell>- )}- <TableCell>- <div className="flex items-center gap-1.5 text-xs text-muted-foreground">- <MediaTypeIcon type={post.mediaType} />- <span>{MEDIA_TYPE_LABELS[post.mediaType] || post.mediaType}</span>- </div>- </TableCell>- <TableCell className="text-right text-sm font-semibold tabular-nums text-orange-500">- {fmtNum(post.score)}- </TableCell>- <TableCell className="text-right text-sm tabular-nums">{fmtNum(post.numComments)}</TableCell>- <TableCell className="text-right text-sm tabular-nums">- {Math.round((post.upvoteRatio ?? 0) * 100)}%- </TableCell>- <TableCell className="text-right text-xs text-muted-foreground">- {fmtDate(post.createdAt)}- </TableCell>- <TableCell>- <a href={post.permalink} target="_blank" rel="noopener noreferrer">- <Button variant="ghost" size="icon" className="size-7">- <ExternalLink className="h-3.5 w-3.5" />- </Button>- </a>- </TableCell>- </TableRow>- ))- )}- </TableBody>- </Table>- </MainCard>+ <RedditPostTable posts={filtered} showAccount={redditAccounts.length > 1} accountsById={accountsById} /></>)}</div>diff --git a/frontend/src/features/analytics/reddit/redditPostTable.jsx b/frontend/src/features/analytics/reddit/redditPostTable.jsxnew file mode 100644index 0000000..15817b4--- /dev/null+++ b/frontend/src/features/analytics/reddit/redditPostTable.jsx@@ -0,0 +1,129 @@+import React from 'react';+import { Link } from 'react-router-dom';+import { ExternalLink, FileText, Image, Video, Link2 } from 'lucide-react';+import { Badge } from '@/components/ui/badge';+import { Button } from '@/components/ui/button';+import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';+import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';+import SearchField from '@/components/SearchField';+import SurfaceBox from '@/components/SurfaceBox';+import { EmptyState } from '@/components/StateViews';+import { AccountAvatar } from '@/components/platform';+import { MEDIA_TYPE_LABELS, REDDIT_SORT_OPTIONS } from './redditPostUtils';+import { fmtNum, fmtDate } from '../../../utils/formatters';++const MEDIA_TYPE_ICONS = { image: Image, video: Video, link: Link2, text: FileText };++function MediaTypeIcon({ type, className = 'size-3.5' }) {+ const Icon = MEDIA_TYPE_ICONS[type] || FileText;+ return <Icon className={className} />;+}++function FilterSelect({ value, onChange, items, label, className = 'w-full sm:w-48' }) {+ return (+ <Select value={value} onValueChange={onChange} items={items}>+ <SelectTrigger className={className} aria-label={label}><SelectValue /></SelectTrigger>+ <SelectContent>+ <SelectGroup>+ {items.map(item => <SelectItem key={item.value} value={item.value}>{item.label}</SelectItem>)}+ </SelectGroup>+ </SelectContent>+ </Select>+ );+}++export function RedditPostFilters({ query, onQuery, sort, onSort, subreddit, onSubreddit, subreddits, accountId, onAccount, accounts }) {+ return (+ <div className="flex flex-col gap-2 sm:flex-row sm:flex-wrap">+ <SearchField value={query} onChange={onQuery} placeholder="Search titles, subreddits and flair" className="min-w-56 flex-1" />+ {accounts && accounts.length > 1 && (+ <FilterSelect+ label="Account"+ value={accountId}+ onChange={onAccount}+ items={[{ value: 'all', label: 'All accounts' }, ...accounts.map(a => ({ value: a.id, label: `u/${a.username}` }))]}+ />+ )}+ <FilterSelect+ label="Subreddit"+ value={subreddit}+ onChange={onSubreddit}+ items={[{ value: 'all', label: 'All subreddits' }, ...subreddits.map(s => ({ value: s, label: `r/${s}` }))]}+ />+ <FilterSelect label="Sort" value={sort} onChange={onSort} items={REDDIT_SORT_OPTIONS} className="w-full sm:w-44" />+ </div>+ );+}++export function RedditPostTable({ posts, showAccount = false, accountsById = {} }) {+ if (posts.length === 0) {+ return (+ <SurfaceBox>+ <EmptyState compact icon={<FileText />} title="No posts match" description="Clear the search or pick a different subreddit." />+ </SurfaceBox>+ );+ }+ return (+ <SurfaceBox content={false} className="overflow-hidden">+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead className="w-10 text-right">#</TableHead>+ <TableHead>Post</TableHead>+ {showAccount && <TableHead className="w-40">Account</TableHead>}+ <TableHead className="w-24">Type</TableHead>+ <TableHead className="w-24 text-right">Karma</TableHead>+ <TableHead className="w-24 text-right">Comments</TableHead>+ <TableHead className="w-24 text-right">Upvoted</TableHead>+ <TableHead className="w-28 text-right">Posted</TableHead>+ <TableHead className="w-10"><span className="sr-only">Open</span></TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {posts.map((post, i) => (+ <TableRow key={`${post.accountId || ''}-${post.id}`}>+ <TableCell className="text-right font-mono text-caption text-ink-faint">{i + 1}</TableCell>+ <TableCell className="whitespace-normal">+ <div className="max-w-md">+ <p className="line-clamp-2 text-sm font-medium leading-snug text-ink">{post.title}</p>+ <div className="mt-1 flex flex-wrap items-center gap-1.5">+ <span className="text-caption text-ink-faint">{post.subredditPrefixed}</span>+ {post.flair && <Badge variant="outline">{post.flair}</Badge>}+ {post.isNsfw && <Badge variant="destructive">NSFW</Badge>}+ </div>+ </div>+ </TableCell>+ {showAccount && (+ <TableCell>+ <Link to={`/reddit/${post.accountId}`} className="flex items-center gap-2 text-small text-ink-muted hover:text-ink">+ <AccountAvatar account={accountsById[post.accountId] || { platform: 'reddit', username: post.accountUsername, iconUrl: post.accountIconUrl }} size="xs" />+ u/{post.accountUsername}+ </Link>+ </TableCell>+ )}+ <TableCell>+ <span className="flex items-center gap-1.5 text-small text-ink-muted">+ <MediaTypeIcon type={post.mediaType} />+ {MEDIA_TYPE_LABELS[post.mediaType] || post.mediaType}+ </span>+ </TableCell>+ <TableCell className="text-right font-semibold text-ink">{fmtNum(post.score)}</TableCell>+ <TableCell className="text-right text-ink-muted">{fmtNum(post.numComments)}</TableCell>+ <TableCell className="text-right text-ink-muted">{Math.round((post.upvoteRatio ?? 0) * 100)}%</TableCell>+ <TableCell className="text-right text-small text-ink-faint">{fmtDate(post.createdAt)}</TableCell>+ <TableCell>+ <Button+ variant="ghost"+ size="icon-xs"+ render={<a href={post.permalink} target="_blank" rel="noopener noreferrer" aria-label={`Open "${post.title}" on Reddit`} />}+ >+ <ExternalLink />+ </Button>+ </TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>+ </SurfaceBox>+ );+}diff --git a/frontend/src/features/analytics/reddit/redditPostUtils.js b/frontend/src/features/analytics/reddit/redditPostUtils.jsnew file mode 100644index 0000000..847cc07--- /dev/null+++ b/frontend/src/features/analytics/reddit/redditPostUtils.js@@ -0,0 +1,32 @@+import { matchesText } from '@/lib/library';++// Filtering and sorting shared by the per-account and all-accounts Reddit posts pages.++export const MEDIA_TYPE_LABELS = { text: 'Text', image: 'Image', video: 'Video', link: 'Link' };++export const REDDIT_SORT_OPTIONS = [+ { value: 'score-desc', label: 'Most karma' },+ { value: 'score-asc', label: 'Least karma' },+ { value: 'comments-desc', label: 'Most comments' },+ { value: 'date-desc', label: 'Newest first' },+ { value: 'date-asc', label: 'Oldest first' },+];++export function filterAndSortRedditPosts(posts, { query, sort, subreddit = 'all', accountId = 'all' }) {+ let result = posts;+ if (accountId !== 'all') result = result.filter(p => p.accountId === accountId);+ if (subreddit !== 'all') result = result.filter(p => p.subreddit === subreddit);+ result = result.filter(p => matchesText([p.title, p.subreddit, p.flair, p.accountUsername], query));+ return [...result].sort((a, b) => {+ if (sort === 'score-desc') return b.score - a.score;+ if (sort === 'score-asc') return a.score - b.score;+ if (sort === 'comments-desc') return b.numComments - a.numComments;+ if (sort === 'date-desc') return new Date(b.createdAt) - new Date(a.createdAt);+ if (sort === 'date-asc') return new Date(a.createdAt) - new Date(b.createdAt);+ return 0;+ });+}++export function subredditsOf(posts) {+ return [...new Set(posts.map(p => p.subreddit))].sort();+}diff --git a/frontend/src/features/analytics/reels/ReelsExplorer.jsx b/frontend/src/features/analytics/reels/ReelsExplorer.jsxindex 1553a77..e938aec 100644--- a/frontend/src/features/analytics/reels/ReelsExplorer.jsx+++ b/frontend/src/features/analytics/reels/ReelsExplorer.jsx@@ -1,44 +1,34 @@-import React, { useState, useEffect, useMemo } from 'react';+import React, { useCallback, useEffect, useMemo, useState } from 'react';+import { Link } from 'react-router-dom';+import { RefreshCw, Heart, MessageCircle, Eye, Clapperboard, Image, Film, Plus } from 'lucide-react';import { Button } from '@/components/ui/button';-import { Input } from '@/components/ui/input';import { Skeleton } from '@/components/ui/skeleton';-import { Progress } from '@/components/ui/progress';-import {- Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue,-} from '@/components/ui/select';-import { Search, RefreshCw, Heart, MessageCircle, Camera, Eye, Clapperboard, Image, Film } from 'lucide-react';-import { Empty, EmptyMedia, EmptyHeader, EmptyDescription } from '@/components/ui/empty';-import StatCard from '../../../components/ui/StatCard';-import MainCard from '../../../components/MainCard';+import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';+import PageHeader from '@/components/PageHeader';+import MetricBox from '@/components/MetricBox';+import SurfaceBox from '@/components/SurfaceBox';+import SearchField from '@/components/SearchField';+import FilterChips from '@/components/FilterChips';+import Pager from '@/components/Pager';+import MediaCard, { MediaChip } from '@/components/MediaCard';+import { EmptyState } from '@/components/StateViews';+import { InstagramIcon } from '@/components/brand/platform-icons';+import { LIKE_TIERS, filterByTier, matchesText, pageSlice } from '@/lib/library';import { useAppContext } from '../../../context/AppContext';import { api } from '../../../services/api';import { fmtNum, timeAgo } from '../../../utils/formatters';import { IG_CONTENT_TYPES, IG_CONTENT_TYPE_META, igContentTypeMeta, fmtIGViews } from '../../../utils/instagramContent';+import { cn } from '@/lib/utils';const ITEMS_PER_PAGE = 24;--const CONTENT_TYPE_FILTER = [- { label: 'All Types', value: 'all' },- ...IG_CONTENT_TYPES.map(type => ({ label: IG_CONTENT_TYPE_META[type].plural, value: type })),-];--const CONTENT_TYPE_ICONS = { reel: <Clapperboard />, post: <Image />, video: <Film /> };-const CONTENT_TYPE_GRADIENTS = { reel: 'pink', post: 'orange', video: 'purple' };--const PERFORMANCE_TIERS = [- { label: 'All Likes', value: 'all' },- { label: 'Viral (>100K)', value: 'viral', min: 100000 },- { label: 'High (10K-100K)', value: 'high', min: 10000, max: 100000 },- { label: 'Medium (1K-10K)', value: 'medium', min: 1000, max: 10000 },- { label: 'Low (<1K)', value: 'low', max: 1000 },-];+const CONTENT_TYPE_ICONS = { reel: Clapperboard, post: Image, video: Film };const SORT_OPTIONS = [- { label: 'Most Viewed', value: 'viewCount' },- { label: 'Most Liked', value: 'likeCount' },- { label: 'Most Comments', value: 'commentsCount' },- { label: 'Best Engagement', value: 'engagementRate' },- { label: 'Newest First', value: 'timestamp' },+ { value: 'viewCount', label: 'Most viewed' },+ { value: 'likeCount', label: 'Most liked' },+ { value: 'commentsCount', label: 'Most comments' },+ { value: 'engagementRate', label: 'Best engagement' },+ { value: 'timestamp', label: 'Newest first' },];function sortValue(item, field) {@@ -48,45 +38,42 @@ function sortValue(item, field) {export default function ReelsExplorer() {const { accounts, showToast } = useAppContext();- const [media, setMedia] = useState([]);- const [loading, setLoading] = useState(true);- const [search, setSearch] = useState('');- const [accountFilter, setAccountFilter] = useState('all');- const [contentTypeFilter, setContentTypeFilter] = useState('all');- const [performanceTier, setPerformanceTier] = useState('all');- const [sortField, setSortField] = useState('viewCount');- const [page, setPage] = useState(1);- const [igAccounts, setIgAccounts] = useState([]);-- useEffect(() => { loadAllMedia(); }, [accounts]);-- const loadAllMedia = async () => {+ const igAccounts = useMemo(() => accounts.filter(a => a.platform === 'instagram'), [accounts]);+ const [media, setMedia] = useState([]);+ const [loading, setLoading] = useState(true);+ const [search, setSearch] = useState('');+ const [accountFilter, setAccountFilter] = useState('all');+ const [typeFilter, setTypeFilter] = useState('all');+ const [tier, setTier] = useState('all');+ const [sortField, setSortField] = useState('viewCount');+ const [page, setPage] = useState(1);++ const loadAllMedia = useCallback(async () => {setLoading(true);try {+ const results = await Promise.allSettled(igAccounts.map(acct => api.getIGMedia(acct.id)));const all = [];- const accList = [];- for (const acct of (accounts || [])) {- if (acct.platform !== 'instagram') continue;- try {- const res = await api.getIGMedia(acct.id);- const items = res.media || [];- accList.push({ value: acct.id, label: acct.title || acct.username || 'Unknown' });- all.push(...items.map(m => ({+ results.forEach((result, i) => {+ if (result.status !== 'fulfilled') return;+ const acct = igAccounts[i];+ for (const m of result.value.media || []) {+ all.push({...m,- accountTitle: acct.title || acct.username || 'Unknown',+ accountTitle: acct.title || acct.username || 'Unknown account',accountId: acct.id,engagementRate: m.viewCount > 0 ? ((m.likeCount || 0) + (m.commentsCount || 0)) / m.viewCount * 100 : null,- })));- } catch (e) { console.warn('Failed to load media for', acct.id, e.message); }- }+ });+ }+ });setMedia(all);- setIgAccounts(accList);} catch (err) {- showToast('Failed to load content: ' + err.message, 'error');+ showToast(`Couldn't load Instagram content. ${err.message}`, 'error');} finally {setLoading(false);}- };+ }, [igAccounts, showToast]);++ useEffect(() => { loadAllMedia(); }, [loadAllMedia]);const accountMedia = useMemo(() => accountFilter === 'all' ? media : media.filter(m => m.accountId === accountFilter),@@ -110,161 +97,154 @@ export default function ReelsExplorer() {const viewsReported = IG_CONTENT_TYPES.reduce((s, t) => s + typeTotals[t].viewsReported, 0);const filtered = useMemo(() => {- let result = [...accountMedia];- if (contentTypeFilter !== 'all') result = result.filter(m => m.contentType === contentTypeFilter);- if (search.trim()) {- const q = search.toLowerCase();- result = result.filter(m => m.caption?.toLowerCase().includes(q));- }- if (performanceTier !== 'all') {- const tier = PERFORMANCE_TIERS.find(t => t.value === performanceTier);- if (tier?.min != null) result = result.filter(m => (m.likeCount || 0) >= tier.min);- if (tier?.max != null) result = result.filter(m => (m.likeCount || 0) < tier.max);- }- result.sort((a, b) => sortValue(b, sortField) - sortValue(a, sortField));- return result;- }, [accountMedia, contentTypeFilter, search, performanceTier, sortField]);+ let result = typeFilter === 'all' ? accountMedia : accountMedia.filter(m => m.contentType === typeFilter);+ result = result.filter(m => matchesText([m.caption], search));+ result = filterByTier(result, LIKE_TIERS, tier, 'likeCount');+ return [...result].sort((a, b) => sortValue(b, sortField) - sortValue(a, sortField));+ }, [accountMedia, typeFilter, search, tier, sortField]);++ const paged = pageSlice(filtered, page, ITEMS_PER_PAGE);+ const resetPage = setter => value => { setter(value); setPage(1); };++ const typeChips = [+ { value: 'all', label: 'All types', count: accountMedia.length },+ ...IG_CONTENT_TYPES.map(t => ({ value: t, label: IG_CONTENT_TYPE_META[t].plural, icon: CONTENT_TYPE_ICONS[t], count: typeTotals[t].count })),+ ];++ const header = (+ <PageHeader+ title="Instagram content"+ description={loading ? 'Loading content from your accounts' : `${fmtNum(media.length)} item${media.length === 1 ? '' : 's'} across ${igAccounts.length} account${igAccounts.length === 1 ? '' : 's'}`}+ actions={+ <Button variant="outline" size="sm" onClick={loadAllMedia} disabled={loading}>+ <RefreshCw data-icon="inline-start" className={cn(loading && 'animate-spin')} />+ Refresh+ </Button>+ }+ />+ );- const pageCount = Math.ceil(filtered.length / ITEMS_PER_PAGE);- const paged = filtered.slice((page - 1) * ITEMS_PER_PAGE, page * ITEMS_PER_PAGE);+ if (igAccounts.length === 0) {+ return (+ <div className="flex flex-col gap-6">+ {header}+ <SurfaceBox>+ <EmptyState+ icon={<InstagramIcon />}+ title="No Instagram accounts yet"+ description="Connect a Business or Creator account to browse its reels, posts and videos."+ action={<Button render={<Link to="/accounts?add=1" />}><Plus data-icon="inline-start" />Add an account</Button>}+ />+ </SurfaceBox>+ </div>+ );+ }if (loading) {return (- <div className="space-y-4">- <Skeleton className="h-8 w-48 mb-2" />- <Progress className="h-1" />- <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3">- {[...Array(8)].map((_, i) => <Skeleton key={i} className="aspect-square rounded-xl" />)}+ <div className="flex flex-col gap-6">+ {header}+ <div className="grid grid-cols-2 gap-3 xl:grid-cols-4">+ {Array.from({ length: 4 }).map((_, i) => <Skeleton key={i} className="h-24 rounded-card" />)}+ </div>+ <Skeleton className="h-10 rounded-field" />+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4 xl:grid-cols-5">+ {Array.from({ length: 10 }).map((_, i) => <Skeleton key={i} className="aspect-square rounded-card" />)}</div></div>);}return (- <div className="space-y-5">- <div className="flex items-center justify-between gap-4 flex-wrap">- <div>- <h1 className="text-2xl font-bold tracking-tight">IG Content Explorer</h1>- <p className="text-sm text-muted-foreground mt-0.5">- {media.length} item{media.length !== 1 ? 's' : ''} across {igAccounts.length} account{igAccounts.length !== 1 ? 's' : ''}- </p>- </div>- <Button variant="outline" size="sm" onClick={loadAllMedia} className="gap-2">- <RefreshCw data-icon="inline-start" /> Refresh- </Button>- </div>+ <div className="flex flex-col gap-6">+ {header}- <div className="grid grid-cols-2 xl:grid-cols-4 gap-3">- <StatCard- icon={<Eye />}- label="Total Views"- value={fmtNum(totalViews)}- subtitle={`${viewsReported} of ${accountMedia.length} items report views`}- gradient="blue"- small- />- {IG_CONTENT_TYPES.map(type => (- <StatCard- key={type}- icon={CONTENT_TYPE_ICONS[type]}- label={IG_CONTENT_TYPE_META[type].plural}- value={fmtNum(typeTotals[type].count)}- subtitle={typeTotals[type].viewsReported > 0 ? `${fmtNum(typeTotals[type].views)} views` : 'no views reported'}- gradient={CONTENT_TYPE_GRADIENTS[type]}- small- />- ))}+ <div className="grid grid-cols-2 gap-3 xl:grid-cols-4">+ <MetricBox small icon={<Eye />} label="Views" value={fmtNum(totalViews)} subtitle={`${viewsReported} of ${accountMedia.length} items report views`} highlight />+ {IG_CONTENT_TYPES.map(type => {+ const Icon = CONTENT_TYPE_ICONS[type];+ return (+ <MetricBox+ key={type}+ small+ icon={<Icon />}+ label={IG_CONTENT_TYPE_META[type].plural}+ value={fmtNum(typeTotals[type].count)}+ subtitle={typeTotals[type].viewsReported > 0 ? `${fmtNum(typeTotals[type].views)} views` : 'No views reported'}+ />+ );+ })}</div>- <MainCard>- <div className="flex flex-wrap gap-3 items-center">- <div className="relative flex-1 min-w-48">- <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />- <Input className="pl-9" placeholder="Search captions..." value={search} onChange={e => { setSearch(e.target.value); setPage(1); }} />- </div>+ <div className="flex flex-col gap-3">+ <div className="flex flex-wrap items-center gap-2">+ <SearchField value={search} onChange={resetPage(setSearch)} placeholder="Search captions" className="min-w-56 flex-1" />{igAccounts.length > 1 && (- <Select value={accountFilter} onValueChange={v => { setAccountFilter(v); setPage(1); }} items={[{ value: 'all', label: 'All Accounts' }, ...igAccounts]}>- <SelectTrigger className="w-40"><SelectValue /></SelectTrigger>+ <Select+ value={accountFilter}+ onValueChange={resetPage(setAccountFilter)}+ items={[{ value: 'all', label: 'All accounts' }, ...igAccounts.map(a => ({ value: a.id, label: a.title || a.username }))]}+ >+ <SelectTrigger className="w-44" aria-label="Account"><SelectValue /></SelectTrigger><SelectContent><SelectGroup>- <SelectItem value="all">All Accounts</SelectItem>- {igAccounts.map(a => <SelectItem key={a.value} value={a.value}>{a.label}</SelectItem>)}+ <SelectItem value="all">All accounts</SelectItem>+ {igAccounts.map(a => <SelectItem key={a.id} value={a.id}>{a.title || a.username}</SelectItem>)}</SelectGroup></SelectContent></Select>)}- <Select value={contentTypeFilter} onValueChange={v => { setContentTypeFilter(v); setPage(1); }} items={CONTENT_TYPE_FILTER}>- <SelectTrigger className="w-40"><SelectValue /></SelectTrigger>- <SelectContent><SelectGroup>{CONTENT_TYPE_FILTER.map(t => <SelectItem key={t.value} value={t.value}>{t.label}</SelectItem>)}</SelectGroup></SelectContent>- </Select>- <Select value={performanceTier} onValueChange={v => { setPerformanceTier(v); setPage(1); }} items={PERFORMANCE_TIERS}>- <SelectTrigger className="w-40"><SelectValue /></SelectTrigger>- <SelectContent><SelectGroup>{PERFORMANCE_TIERS.map(t => <SelectItem key={t.value} value={t.value}>{t.label}</SelectItem>)}</SelectGroup></SelectContent>+ <Select value={tier} onValueChange={resetPage(setTier)} items={LIKE_TIERS}>+ <SelectTrigger className="w-36" aria-label="Likes"><SelectValue /></SelectTrigger>+ <SelectContent>+ <SelectGroup>+ {LIKE_TIERS.map(t => <SelectItem key={t.value} value={t.value}>{t.label}</SelectItem>)}+ </SelectGroup>+ </SelectContent></Select><Select value={sortField} onValueChange={setSortField} items={SORT_OPTIONS}>- <SelectTrigger className="w-44"><SelectValue /></SelectTrigger>- <SelectContent><SelectGroup>{SORT_OPTIONS.map(o => <SelectItem key={o.value} value={o.value}>{o.label}</SelectItem>)}</SelectGroup></SelectContent>+ <SelectTrigger className="w-44" aria-label="Sort"><SelectValue /></SelectTrigger>+ <SelectContent>+ <SelectGroup>+ {SORT_OPTIONS.map(o => <SelectItem key={o.value} value={o.value}>{o.label}</SelectItem>)}+ </SelectGroup>+ </SelectContent></Select></div>- <p className="text-xs text-muted-foreground mt-2">Showing {paged.length} of {filtered.length} items</p>- </MainCard>-- <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 xl:grid-cols-5 gap-3">- {paged.map((m, i) => {- const meta = igContentTypeMeta(m.contentType);- const thumb = m.contentType === 'post' ? (m.thumbnailUrl || m.mediaUrl) : m.thumbnailUrl;- return (- <div- key={`${m.id}-${i}`}- className="border border-border rounded-xl overflow-hidden cursor-pointer hover:shadow-md transition-shadow bg-card group"- onClick={() => m.permalink && window.open(m.permalink, '_blank', 'noopener')}- >- <div className="relative aspect-square">- {thumb- ? <img src={thumb} className="w-full h-full object-cover" alt="" />- : <div className="w-full h-full bg-gradient-to-br from-pink-500 to-purple-600 flex items-center justify-center"><Camera className="h-8 w-8 text-white" /></div>}- <span className="absolute top-1.5 left-1.5 text-white text-[9px] font-bold px-1.5 py-0.5 rounded" style={{ background: meta.color }}>- {meta.label}- </span>- </div>- <div className="p-2.5 space-y-1.5">- {m.caption && (- <p className="text-[11px] leading-snug line-clamp-2 text-foreground/80">{m.caption}</p>- )}- <div className="flex items-center gap-3 text-[11px] text-muted-foreground">- <span className="flex items-center gap-0.5"><Eye className="h-3 w-3" />{fmtIGViews(m.viewCount)}</span>- <span className="flex items-center gap-0.5"><Heart className="h-3 w-3 text-pink-500" />{fmtNum(m.likeCount)}</span>- <span className="flex items-center gap-0.5"><MessageCircle className="h-3 w-3" />{fmtNum(m.commentsCount)}</span>- <span className="ml-auto">{timeAgo(m.timestamp)}</span>- </div>- </div>- </div>- );- })}+ <FilterChips label="Content type" options={typeChips} value={typeFilter} onChange={resetPage(setTypeFilter)} /></div>- {filtered.length === 0 && !loading && (- <MainCard>- <Empty>- <EmptyMedia><Camera className="size-10 text-muted-foreground/40" /></EmptyMedia>- <EmptyHeader>- <EmptyDescription>- {accounts?.filter(a => a.platform === 'instagram').length === 0- ? 'Add an Instagram account to explore content'- : 'No content matches your filters'}- </EmptyDescription>- </EmptyHeader>- </Empty>- </MainCard>- )}-- {pageCount > 1 && (- <div className="flex items-center justify-center gap-2">- <Button variant="outline" size="sm" onClick={() => setPage(p => Math.max(1, p - 1))} disabled={page === 1}>Previous</Button>- <span className="text-sm text-muted-foreground px-2">Page {page} of {pageCount}</span>- <Button variant="outline" size="sm" onClick={() => setPage(p => Math.min(pageCount, p + 1))} disabled={page === pageCount}>Next</Button>+ {filtered.length === 0 ? (+ <SurfaceBox>+ <EmptyState compact icon={<InstagramIcon />} title="No content matches" description="Clear the search or choose a different type or like range." />+ </SurfaceBox>+ ) : (+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4 xl:grid-cols-5">+ {paged.items.map((m, i) => {+ const meta = igContentTypeMeta(m.contentType);+ return (+ <MediaCard+ key={`${m.id}-${i}`}+ aspect="square"+ href={m.permalink}+ image={m.contentType === 'post' ? (m.thumbnailUrl || m.mediaUrl) : m.thumbnailUrl}+ title={m.caption}+ topLeft={<MediaChip>{meta.label}</MediaChip>}+ meta={+ <>+ <span className="flex items-center gap-1"><Eye />{fmtIGViews(m.viewCount)}</span>+ <span className="flex items-center gap-1"><Heart />{fmtNum(m.likeCount)}</span>+ <span className="flex items-center gap-1"><MessageCircle />{fmtNum(m.commentsCount)}</span>+ <span className="ml-auto">{timeAgo(m.timestamp)}</span>+ </>+ }+ />+ );+ })}</div>)}++ <Pager page={paged.page} pageCount={paged.pageCount} onPageChange={setPage} total={filtered.length} shown={paged.items.length} noun="items" /></div>);}diff --git a/frontend/src/features/analytics/shorts/ShortsExplorer.jsx b/frontend/src/features/analytics/shorts/ShortsExplorer.jsxindex 1b0caa8..d43d1ea 100644--- a/frontend/src/features/analytics/shorts/ShortsExplorer.jsx+++ b/frontend/src/features/analytics/shorts/ShortsExplorer.jsx@@ -1,216 +1,167 @@-import React, { useState, useEffect, useMemo } from 'react';+import React, { useMemo, useState } from 'react';+import { Link } from 'react-router-dom';+import { RefreshCw, Eye, ThumbsUp, MessageSquare, Scissors, Plus } from 'lucide-react';import { Button } from '@/components/ui/button';-import { Input } from '@/components/ui/input';-import { Badge } from '@/components/ui/badge';-import { Avatar, AvatarImage } from '@/components/ui/avatar';import { Skeleton } from '@/components/ui/skeleton';-import { Progress } from '@/components/ui/progress';-import {- Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue,-} from '@/components/ui/select';-import { Search, RefreshCw, Eye, ThumbsUp, MessageSquare, Play, Tv } from 'lucide-react';-import { Empty, EmptyMedia, EmptyHeader, EmptyTitle, EmptyDescription } from '@/components/ui/empty';-import MainCard from '../../../components/MainCard';-import { useAppContext } from '../../../context/AppContext';-import { api } from '../../../services/api';-import { fmtNum, fmtDuration, timeAgo } from '../../../utils/formatters';+import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';+import PageHeader from '@/components/PageHeader';+import SurfaceBox from '@/components/SurfaceBox';+import SearchField from '@/components/SearchField';+import FilterChips from '@/components/FilterChips';+import Pager from '@/components/Pager';+import MediaCard, { MediaChip } from '@/components/MediaCard';+import { EmptyState } from '@/components/StateViews';+import { VIEW_TIERS, filterByTier, matchesText, pageSlice } from '@/lib/library';+import { useChannelVideos } from '../videos/useChannelVideos';+import { fmtNum, fmtDuration } from '../../../utils/formatters';+import { cn } from '@/lib/utils';const ITEMS_PER_PAGE = 24;--function parseDurationToSeconds(iso) {- if (!iso || iso === 'P0D') return 0;- const m = iso.match(/PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?/);- if (!m) return 0;- return (parseInt(m[1] || 0) * 3600) + (parseInt(m[2] || 0) * 60) + parseInt(m[3] || 0);-}--const PERFORMANCE_TIERS = [- { label: 'All', value: 'all' },- { label: 'Viral (>1M)', value: 'viral', min: 1000000 },- { label: 'High (100K-1M)', value: 'high', min: 100000, max: 1000000 },- { label: 'Medium (10K-100K)', value: 'medium', min: 10000, max: 100000 },- { label: 'Low (<10K)', value: 'low', max: 10000 },-];+const SHORT_MAX_SECONDS = 60;const SORT_OPTIONS = [- { label: 'Most Viewed', field: 'viewCount' },- { label: 'Most Liked', field: 'likeCount' },- { label: 'Most Comments', field: 'commentCount' },- { label: 'Best Engagement', field: 'engagementRate' },- { label: 'Newest First', field: 'publishedAt' },+ { value: 'viewCount', label: 'Most viewed' },+ { value: 'likeCount', label: 'Most liked' },+ { value: 'commentCount', label: 'Most comments' },+ { value: 'engagementRate', label: 'Best engagement' },+ { value: 'publishedAt', label: 'Newest first' },];-export default function ShortsExplorer() {- const { accounts, showToast } = useAppContext();- const [shorts, setShorts] = useState([]);- const [loading, setLoading] = useState(true);- const [search, setSearch] = useState('');- const [channelFilter, setChannelFilter] = useState('all');- const [performanceTier, setPerformanceTier] = useState('all');- const [sortField, setSortField] = useState('viewCount');- const [page, setPage] = useState(1);- const [channels, setChannels] = useState([]);+function sortValue(item, field) {+ if (field === 'publishedAt') return new Date(item.publishedAt).getTime() || 0;+ return Number(item[field] ?? 0);+}- useEffect(() => { loadAllShorts(); }, [accounts]);+export default function ShortsExplorer() {+ const { videos, channels, loading, reload } = useChannelVideos();+ const [search, setSearch] = useState('');+ const [channelFilter, setChannelFilter] = useState('all');+ const [tier, setTier] = useState('all');+ const [sortField, setSortField] = useState('viewCount');+ const [page, setPage] = useState(1);- const loadAllShorts = async () => {- setLoading(true);- try {- const all = [];- const channelList = [];- for (const acct of (accounts || [])) {- if (acct.platform === 'instagram') continue;- try {- const res = await api.getVideos(acct.id);- const vids = res.videos || res.data?.videos || [];- const channelTitle = acct.title || 'Unknown';- channelList.push({ id: acct.id, title: channelTitle, thumbnail: acct.thumbnails?.default || '' });- const shortsOnly = vids.filter(v => {- const secs = v.durationSeconds || parseDurationToSeconds(v.duration);- return secs > 0 && secs <= 60;- });- all.push(...shortsOnly.map(v => ({- ...v,- thumbnail: v.thumbnail || v.thumbnails?.medium || v.thumbnails?.default || '',- channelTitle,- channelId: acct.id,- engagementRate: (v.viewCount || 0) > 0 ? (((v.likeCount || 0) + (v.commentCount || 0)) / v.viewCount * 100).toFixed(2) : '0.00',- durationSeconds: v.durationSeconds || parseDurationToSeconds(v.duration),- })));- } catch (e) { /* skip */ }- }- setShorts(all);- setChannels(channelList);- } catch (err) {- showToast('Failed to load Shorts: ' + err.message, 'error');- } finally {- setLoading(false);- }- };+ const shorts = useMemo(+ () => videos.filter(v => v.durationSeconds > 0 && v.durationSeconds <= SHORT_MAX_SECONDS),+ [videos],+ );const filtered = useMemo(() => {- let result = [...shorts];- if (channelFilter !== 'all') result = result.filter(v => v.channelId === channelFilter);- if (search.trim()) {- const q = search.toLowerCase();- result = result.filter(v => v.title?.toLowerCase().includes(q));- }- if (performanceTier !== 'all') {- const tier = PERFORMANCE_TIERS.find(t => t.value === performanceTier);- if (tier?.min != null) result = result.filter(v => (v.viewCount || 0) >= tier.min);- if (tier?.max != null) result = result.filter(v => (v.viewCount || 0) < tier.max);- }- result.sort((a, b) => (b[sortField] ?? 0) - (a[sortField] ?? 0));- return result;- }, [shorts, channelFilter, search, performanceTier, sortField]);+ let result = channelFilter === 'all' ? shorts : shorts.filter(v => v.channelId === channelFilter);+ result = result.filter(v => matchesText([v.title], search));+ result = filterByTier(result, VIEW_TIERS, tier, 'viewCount');+ return [...result].sort((a, b) => sortValue(b, sortField) - sortValue(a, sortField));+ }, [shorts, channelFilter, search, tier, sortField]);++ const paged = pageSlice(filtered, page, ITEMS_PER_PAGE);+ const resetPage = setter => value => { setter(value); setPage(1); };- const pageCount = Math.ceil(filtered.length / ITEMS_PER_PAGE);- const paged = filtered.slice((page - 1) * ITEMS_PER_PAGE, page * ITEMS_PER_PAGE);+ const header = (+ <PageHeader+ title="Shorts"+ description={loading ? 'Loading Shorts from your channels' : `${fmtNum(shorts.length)} Shorts across ${channels.length} channel${channels.length === 1 ? '' : 's'}`}+ actions={+ <Button variant="outline" size="sm" onClick={reload} disabled={loading}>+ <RefreshCw data-icon="inline-start" className={cn(loading && 'animate-spin')} />+ Refresh+ </Button>+ }+ />+ );if (loading) {return (- <div className="space-y-4">- <Skeleton className="h-8 w-48 mb-2" />- <Progress className="h-1" />- <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 xl:grid-cols-6 gap-3">- {[...Array(12)].map((_, i) => <Skeleton key={i} className="aspect-[9/16] rounded-xl" />)}+ <div className="flex flex-col gap-6">+ {header}+ <Skeleton className="h-10 rounded-field" />+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4 xl:grid-cols-6">+ {Array.from({ length: 12 }).map((_, i) => <Skeleton key={i} className="aspect-[9/16] rounded-card" />)}</div></div>);}- return (- <div className="space-y-5">- <div className="flex items-center justify-between gap-4 flex-wrap">- <div>- <h1 className="text-2xl font-bold tracking-tight">Shorts Explorer</h1>- <p className="text-sm text-muted-foreground mt-0.5">- {shorts.length} Shorts across {channels.length} channel{channels.length !== 1 ? 's' : ''}- </p>- </div>- <Button variant="outline" size="sm" onClick={loadAllShorts} className="gap-2">- <RefreshCw className="h-3.5 w-3.5" /> Refresh- </Button>+ if (channels.length === 0) {+ return (+ <div className="flex flex-col gap-6">+ {header}+ <SurfaceBox>+ <EmptyState+ icon={<Scissors />}+ title="No YouTube channels yet"+ description="Add a channel and its Shorts appear here, ranked by views."+ action={<Button render={<Link to="/accounts?add=1" />}><Plus data-icon="inline-start" />Add a channel</Button>}+ />+ </SurfaceBox></div>+ );+ }- {/* Filters */}- <MainCard>- <div className="flex flex-wrap gap-3 items-center">- <div className="relative flex-1 min-w-48">- <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />- <Input className="pl-9" placeholder="Search Shorts…" value={search} onChange={e => { setSearch(e.target.value); setPage(1); }} />- </div>+ return (+ <div className="flex flex-col gap-6">+ {header}++ <div className="flex flex-col gap-3">+ <div className="flex flex-wrap items-center gap-2">+ <SearchField value={search} onChange={resetPage(setSearch)} placeholder="Search Shorts" className="min-w-56 flex-1" />{channels.length > 1 && (- <Select value={channelFilter} onValueChange={v => { setChannelFilter(v); setPage(1); }}>- <SelectTrigger className="w-40"><SelectValue placeholder="All Channels" /></SelectTrigger>+ <Select+ value={channelFilter}+ onValueChange={resetPage(setChannelFilter)}+ items={[{ value: 'all', label: 'All channels' }, ...channels.map(c => ({ value: c.id, label: c.title }))]}+ >+ <SelectTrigger className="w-48" aria-label="Channel"><SelectValue /></SelectTrigger><SelectContent><SelectGroup>- <SelectItem value="all">All Channels</SelectItem>+ <SelectItem value="all">All channels</SelectItem>{channels.map(c => <SelectItem key={c.id} value={c.id}>{c.title}</SelectItem>)}</SelectGroup></SelectContent></Select>)}- <Select value={performanceTier} onValueChange={v => { setPerformanceTier(v); setPage(1); }}>- <SelectTrigger className="w-44"><SelectValue /></SelectTrigger>- <SelectContent><SelectGroup>{PERFORMANCE_TIERS.map(t => <SelectItem key={t.value} value={t.value}>{t.label}</SelectItem>)}</SelectGroup></SelectContent>- </Select>- <Select value={sortField} onValueChange={setSortField}>- <SelectTrigger className="w-44"><SelectValue /></SelectTrigger>- <SelectContent><SelectGroup>{SORT_OPTIONS.map(o => <SelectItem key={o.field} value={o.field}>{o.label}</SelectItem>)}</SelectGroup></SelectContent>+ <Select value={sortField} onValueChange={setSortField} items={SORT_OPTIONS}>+ <SelectTrigger className="w-44" aria-label="Sort"><SelectValue /></SelectTrigger>+ <SelectContent>+ <SelectGroup>+ {SORT_OPTIONS.map(o => <SelectItem key={o.value} value={o.value}>{o.label}</SelectItem>)}+ </SelectGroup>+ </SelectContent></Select></div>- <p className="text-xs text-muted-foreground mt-2">Showing {paged.length} of {filtered.length} Shorts</p>- </MainCard>-- {/* Vertical card grid */}- <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 xl:grid-cols-6 gap-3">- {paged.map((v, i) => (- <div- key={`${v.videoId}-${i}`}- className="border border-border rounded-xl overflow-hidden cursor-pointer hover:shadow-md transition-shadow bg-card"- onClick={() => window.open(`https://www.youtube.com/watch?v=${v.videoId}`, '_blank', 'noopener')}- >- <div className="relative">- {v.thumbnail- ? <img src={v.thumbnail} className="w-full aspect-[9/16] object-cover" alt="" />- : <div className="w-full aspect-[9/16] bg-muted flex items-center justify-center"><Tv className="h-6 w-6 text-muted-foreground" /></div>}- <span className="absolute top-1.5 right-1.5 flex items-center gap-0.5 bg-black/75 text-white text-[10px] font-semibold px-1.5 py-0.5 rounded">- <Eye className="h-2.5 w-2.5" />{fmtNum(v.viewCount)}- </span>- {v.durationSeconds > 0 && (- <span className="absolute bottom-1.5 right-1.5 bg-black/80 text-white text-[10px] font-semibold px-1.5 py-0.5 rounded">{fmtDuration(v.durationSeconds)}</span>- )}- </div>- <div className="p-2 space-y-1">- <p className="text-[11px] font-semibold line-clamp-2 leading-snug">{v.title}</p>- <div className="flex items-center gap-2 text-[10px] text-muted-foreground">- <span className="flex items-center gap-0.5"><ThumbsUp className="h-2.5 w-2.5" />{fmtNum(v.likeCount)}</span>- <span className="flex items-center gap-0.5"><MessageSquare className="h-2.5 w-2.5" />{fmtNum(v.commentCount)}</span>- </div>- </div>- </div>- ))}+ <FilterChips label="Views" options={VIEW_TIERS} value={tier} onChange={resetPage(setTier)} /></div>- {filtered.length === 0 && !loading && (- <MainCard>- <Empty>- <EmptyMedia><Tv className="size-10 text-muted-foreground/40" /></EmptyMedia>- <EmptyHeader>- <EmptyDescription>No Shorts found. Try adjusting filters or add a YouTube channel.</EmptyDescription>- </EmptyHeader>- </Empty>- </MainCard>- )}-- {pageCount > 1 && (- <div className="flex items-center justify-center gap-2">- <Button variant="outline" size="sm" onClick={() => setPage(p => Math.max(1, p - 1))} disabled={page === 1}>Previous</Button>- <span className="text-sm text-muted-foreground px-2">Page {page} of {pageCount}</span>- <Button variant="outline" size="sm" onClick={() => setPage(p => Math.min(pageCount, p + 1))} disabled={page === pageCount}>Next</Button>+ {filtered.length === 0 ? (+ <SurfaceBox>+ <EmptyState+ compact+ icon={<Scissors />}+ title={shorts.length === 0 ? 'No Shorts yet' : 'No Shorts match'}+ description={shorts.length === 0 ? 'Videos of 60 seconds or less appear here once your channels publish them.' : 'Clear the search or choose a different view range.'}+ />+ </SurfaceBox>+ ) : (+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4 xl:grid-cols-6">+ {paged.items.map((v, i) => (+ <MediaCard+ key={`${v.videoId}-${i}`}+ aspect="vertical"+ href={`https://www.youtube.com/shorts/${v.videoId}`}+ image={v.thumbnail}+ title={v.title}+ topRight={<MediaChip><Eye />{fmtNum(v.viewCount)}</MediaChip>}+ bottomRight={<MediaChip>{fmtDuration(v.durationSeconds)}</MediaChip>}+ meta={+ <>+ <span className="flex items-center gap-1"><ThumbsUp />{fmtNum(v.likeCount)}</span>+ <span className="flex items-center gap-1"><MessageSquare />{fmtNum(v.commentCount)}</span>+ </>+ }+ />+ ))}</div>)}++ <Pager page={paged.page} pageCount={paged.pageCount} onPageChange={setPage} total={filtered.length} shown={paged.items.length} noun="Shorts" /></div>);}diff --git a/frontend/src/features/analytics/tracked/TrackedCategory.jsx b/frontend/src/features/analytics/tracked/TrackedCategory.jsxindex 8d3e2f4..d4c6e13 100644--- a/frontend/src/features/analytics/tracked/TrackedCategory.jsx+++ b/frontend/src/features/analytics/tracked/TrackedCategory.jsx@@ -1,36 +1,49 @@-import React, { useState, useEffect, useMemo } from 'react';-import { useParams, useNavigate } from 'react-router-dom';+import React, { useEffect, useMemo, useState } from 'react';+import { Link, useParams } from 'react-router-dom';+import { CirclePlay, ExternalLink, Eye, ThumbsUp, MessageSquare, Tag, TrendingUp, MessagesSquare } from 'lucide-react';import { Button } from '@/components/ui/button';import { Badge } from '@/components/ui/badge';-import { Separator } from '@/components/ui/separator';import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';-import { Skeleton } from '@/components/ui/skeleton';-import {- Empty, EmptyHeader, EmptyMedia, EmptyTitle, EmptyDescription, EmptyContent,-} from '@/components/ui/empty';-import StatCard from '../../../components/ui/StatCard';-import MainCard from '../../../components/MainCard';-import MetricAreaChart from '../../../components/MetricAreaChart';-import ImageLightbox from '../../../components/ImageLightbox';+import PageHeader from '@/components/PageHeader';+import MetricBox from '@/components/MetricBox';+import SurfaceBox from '@/components/SurfaceBox';+import SectionHeader from '@/components/SectionHeader';+import MetricAreaChart from '@/components/MetricAreaChart';+import ImageLightbox from '@/components/ImageLightbox';+import { RankNumber } from '@/components/ListRow';+import { EmptyState, PageSkeleton } from '@/components/StateViews';+import { PlatformIcon } from '@/components/platform';+import { PLATFORM_META } from '@/lib/accounts';import { useAppContext } from '../../../context/AppContext';import { api } from '../../../services/api';import { fmtNum, fmtNumFull, fmtDate } from '../../../utils/formatters';-import { trackedViews, hasTrackedViews } from '../../../utils/trackedContent';-import {- ArrowLeft, CirclePlay, Flame, ExternalLink, Eye,- ThumbsUp, MessageSquare, Tag, TrendingUp,-} from 'lucide-react';+import { trackedViews, hasTrackedViews, isRedditItem } from '../../../utils/trackedContent';// fmtNum abbreviates only at 1000 and above, so the full value is redundant below thatfunction showsFullValue(n) {return Math.abs(Number(n) || 0) >= 1000;}+function NumberCell({ value }) {+ return (+ <TableCell className="text-right">+ <p className="font-semibold text-ink">{fmtNum(value ?? 0)}</p>+ {showsFullValue(value) && <p className="text-caption text-ink-faint">{fmtNumFull(value)}</p>}+ </TableCell>+ );+}++function OpenLink({ href, label }) {+ return (+ <Button variant="ghost" size="icon-xs" render={<a href={href} target="_blank" rel="noopener noreferrer" aria-label={label} />}>+ <ExternalLink />+ </Button>+ );+}+export default function TrackedCategory() {const { name } = useParams();- const navigate = useNavigate();const { showToast } = useAppContext();-const categoryName = decodeURIComponent(name || '');const [items, setItems] = useState([]);@@ -38,29 +51,23 @@ export default function TrackedCategory() {useEffect(() => {api.getTrackedContent()- .then(data => {- const all = Array.isArray(data) ? data : [];- setItems(all.filter(p => p.category === categoryName));- })- .catch(err => showToast(err.message, 'error'))+ .then(data => setItems((Array.isArray(data) ? data : []).filter(p => p.category === categoryName)))+ .catch(err => showToast(`Couldn't load this category. ${err.message}`, 'error')).finally(() => setLoading(false));}, [categoryName, showToast]);const ytItems = useMemo(() => items.filter(p => p.contentType === 'youtube'), [items]);- const rdItems = useMemo(() => items.filter(p => (p.contentType || 'reddit') === 'reddit'), [items]);+ const rdItems = useMemo(() => items.filter(isRedditItem), [items]);const ytStats = useMemo(() => {- const count = ytItems.length;- const views = ytItems.reduce((s, p) => s + trackedViews(p), 0);- const likes = ytItems.reduce((s, p) => s + (p.likeCount ?? 0), 0);+ const count = ytItems.length;+ const views = ytItems.reduce((s, p) => s + trackedViews(p), 0);+ const likes = ytItems.reduce((s, p) => s + (p.likeCount ?? 0), 0);const comments = ytItems.reduce((s, p) => s + (p.commentCount ?? 0), 0);return {- count,- views,- likes,- comments,- avgViews: count ? Math.round(views / count) : 0,- avgLikes: count ? Math.round(likes / count) : 0,+ count, views, likes, comments,+ avgViews: count ? Math.round(views / count) : 0,+ avgLikes: count ? Math.round(likes / count) : 0,avgComments: count ? Math.round(comments / count) : 0,likeRatio: views > 0 ? ((likes / views) * 100).toFixed(2) : '0',};@@ -68,458 +75,194 @@ export default function TrackedCategory() {// Reddit post score is karma, so it is named and labelled as karma throughoutconst rdStats = useMemo(() => {- const count = rdItems.length;- const karma = rdItems.reduce((s, p) => s + (p.score ?? 0), 0);+ const count = rdItems.length;+ const karma = rdItems.reduce((s, p) => s + (p.score ?? 0), 0);const comments = rdItems.reduce((s, p) => s + (p.numComments ?? 0), 0);const ratioSum = rdItems.reduce((s, p) => s + (p.upvoteRatio ?? 0), 0);- const views = rdItems.reduce((s, p) => s + trackedViews(p), 0);- const withViews = rdItems.filter(hasTrackedViews).length;+ const views = rdItems.reduce((s, p) => s + trackedViews(p), 0);return {- count,- karma,- comments,- views,- withViews,- avgKarma: count ? Math.round(karma / count) : 0,+ count, karma, comments, views,+ withViews: rdItems.filter(hasTrackedViews).length,+ avgKarma: count ? Math.round(karma / count) : 0,avgComments: count ? Math.round(comments / count) : 0,- avgRatio: count ? ratioSum / count : 0,+ avgRatio: count ? ratioSum / count : 0,};}, [rdItems]);const totalViews = ytStats.views + rdStats.views;- const ytChartData = useMemo(() =>- [...ytItems]- .sort((a, b) => (b.viewCount ?? 0) - (a.viewCount ?? 0))- .slice(0, 12)- .map(p => ({- name: (p.title || p.url || '').slice(0, 16),- views: p.viewCount ?? 0,- })),- [ytItems]- );+ const ytSorted = useMemo(() => [...ytItems].sort((a, b) => (b.viewCount ?? 0) - (a.viewCount ?? 0)), [ytItems]);+ const rdSorted = useMemo(() => [...rdItems].sort((a, b) => (b.score ?? 0) - (a.score ?? 0)), [rdItems]);+ const ytChartData = ytSorted.slice(0, 12).map(p => ({ name: (p.title || p.url || '').slice(0, 16), views: p.viewCount ?? 0 }));+ const rdChartData = rdSorted.slice(0, 12).map(p => ({ name: (p.title || p.url || '').slice(0, 16), karma: p.score ?? 0 }));- const rdChartData = useMemo(() =>- [...rdItems]- .sort((a, b) => (b.score ?? 0) - (a.score ?? 0))- .slice(0, 12)- .map(p => ({- name: (p.title || p.url || '').slice(0, 16),- karma: p.score ?? 0,- })),- [rdItems]- );+ const back = { to: '/tracked-content', label: 'Tracked content' };+ const split = (yt, rd) => [ytItems.length > 0 ? yt : null, rdItems.length > 0 ? rd : null].filter(Boolean).join(', ');- const medalColor = (i) =>- i === 0 ? 'text-yellow-500' : i === 1 ? 'text-slate-400' : i === 2 ? 'text-orange-400' : 'text-muted-foreground';-- if (loading) {- return (- <div className="space-y-6">- <div className="flex items-center gap-3">- <Skeleton className="h-9 w-9 rounded-md" />- <div className="space-y-1">- <Skeleton className="h-7 w-48" />- <Skeleton className="h-4 w-32" />- </div>- </div>- <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">- {[0, 1, 2, 3].map(i => <Skeleton key={i} className="h-28" />)}- </div>- <Skeleton className="h-48" />- <Skeleton className="h-64" />- </div>- );- }+ if (loading) return <PageSkeleton metrics={4} />;if (items.length === 0) {return (- <div className="space-y-6">- <div className="flex items-center gap-3">- <Button variant="ghost" size="icon" className="shrink-0" onClick={() => navigate('/tracked-content')}>- <ArrowLeft className="h-4 w-4" />- </Button>- <div>- <h1 className="text-2xl font-bold tracking-tight">{categoryName}</h1>- <p className="text-sm text-muted-foreground mt-0.5">No items in this category</p>- </div>- </div>- <MainCard>- <Empty className="py-8">- <EmptyHeader>- <EmptyMedia variant="icon">- <Tag />- </EmptyMedia>- <EmptyTitle>Nothing tracked in {categoryName}</EmptyTitle>- <EmptyDescription>- Assign this category to a Reddit post or YouTube video in Tracked Content and its analytics will appear here.- </EmptyDescription>- </EmptyHeader>- <EmptyContent>- <Button size="sm" onClick={() => navigate('/tracked-content')}>Manage Tracked Content</Button>- </EmptyContent>- </Empty>- </MainCard>+ <div className="flex flex-col gap-6">+ <PageHeader back={back} eyebrow="Category" title={categoryName} description="No items in this category" />+ <SurfaceBox>+ <EmptyState+ icon={<Tag />}+ title={`Nothing tracked in ${categoryName}`}+ description="Assign this category to a Reddit post or YouTube video in Tracked content and its analytics appear here."+ action={<Button size="sm" render={<Link to="/tracked-content" />}>Open tracked content</Button>}+ />+ </SurfaceBox></div>);}return (- <div className="space-y-6">- {/* Header */}- <div className="flex items-start gap-3">- <Button variant="ghost" size="icon" className="shrink-0 mt-0.5" onClick={() => navigate('/tracked-content')}>- <ArrowLeft className="h-4 w-4" />- </Button>- <div className="flex-1 min-w-0">- <div className="flex items-center gap-2 flex-wrap">- <h1 className="text-2xl font-bold tracking-tight">{categoryName}</h1>- <Badge variant="outline" className="text-xs border-purple-200 bg-purple-50 text-purple-700 dark:border-purple-900 dark:bg-purple-950 dark:text-purple-400">- <Tag className="h-3 w-3 mr-1" />- Category- </Badge>- </div>- <p className="text-sm text-muted-foreground mt-0.5">- {items.length} item{items.length !== 1 ? 's' : ''}- {ytItems.length > 0 && ` · ${ytItems.length} YouTube`}- {rdItems.length > 0 && ` · ${rdItems.length} Reddit`}- </p>- </div>- <Button size="sm" variant="outline" onClick={() => navigate('/tracked-content')} className="shrink-0">- Manage Content- </Button>- </div>+ <div className="flex flex-col gap-6">+ <PageHeader+ back={back}+ eyebrow="Category"+ title={categoryName}+ description={[+ `${items.length} item${items.length !== 1 ? 's' : ''}`,+ ytItems.length > 0 ? `${ytItems.length} YouTube` : null,+ rdItems.length > 0 ? `${rdItems.length} Reddit` : null,+ ].filter(Boolean).join(', ')}+ actions={<Button variant="outline" render={<Link to="/tracked-content" />}>Manage content</Button>}+ />- {/* Summary StatCards */}- <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">- <StatCard- icon={<Tag />}- label="Total Content"- value={items.length}- subtitle={[- ytItems.length > 0 ? `${ytItems.length} YouTube video${ytItems.length !== 1 ? 's' : ''}` : null,- rdItems.length > 0 ? `${rdItems.length} Reddit post${rdItems.length !== 1 ? 's' : ''}` : null,- ].filter(Boolean).join(' · ')}- gradient="purple"- />- <StatCard- icon={<Eye />}- label="Total Views"- value={totalViews > 0 ? fmtNum(totalViews) : '-'}- subtitle={- totalViews > 0- ? [- ytItems.length > 0 ? `${fmtNum(ytStats.views)} YouTube` : null,- rdItems.length > 0 ? `${fmtNum(rdStats.views)} Reddit` : null,- ].filter(Boolean).join(' · ')- : 'no views recorded yet'- }- gradient="red"- />- <StatCard- icon={<Flame />}- label="Reddit Karma"- value={rdItems.length > 0 ? fmtNum(rdStats.karma) : '-'}- subtitle={rdItems.length > 0 ? `avg ${fmtNum(rdStats.avgKarma)} per post` : 'no Reddit posts in this category'}- gradient="orange"- />- <StatCard- icon={<MessageSquare />}- label="Total Comments"- value={fmtNum(ytStats.comments + rdStats.comments)}- subtitle={[- ytItems.length > 0 ? `${fmtNum(ytStats.comments)} YouTube` : null,- rdItems.length > 0 ? `${fmtNum(rdStats.comments)} Reddit` : null,- ].filter(Boolean).join(' · ')}- gradient="blue"- />+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">+ <MetricBox icon={<Tag />} label="Items" value={items.length} subtitle={split(`${ytItems.length} YouTube video${ytItems.length !== 1 ? 's' : ''}`, `${rdItems.length} Reddit post${rdItems.length !== 1 ? 's' : ''}`)} />+ <MetricBox icon={<Eye />} label="Views" value={totalViews > 0 ? fmtNum(totalViews) : '-'} subtitle={totalViews > 0 ? split(`${fmtNum(ytStats.views)} YouTube`, `${fmtNum(rdStats.views)} Reddit`) : 'No views recorded yet'} highlight />+ <MetricBox icon={<MessagesSquare />} label="Reddit karma" value={rdItems.length > 0 ? fmtNum(rdStats.karma) : '-'} subtitle={rdItems.length > 0 ? `${fmtNum(rdStats.avgKarma)} per post on average` : 'No Reddit posts in this category'} />+ <MetricBox icon={<MessageSquare />} label="Comments" value={fmtNum(ytStats.comments + rdStats.comments)} subtitle={split(`${fmtNum(ytStats.comments)} YouTube`, `${fmtNum(rdStats.comments)} Reddit`)} /></div>- {/* YouTube section */}{ytItems.length > 0 && (- <>- <div className="flex items-center gap-3 pt-2">- <CirclePlay className="h-5 w-5 text-red-500 shrink-0" />- <h2 className="text-base font-semibold">YouTube Videos</h2>- <Separator className="flex-1" />- <span className="text-sm text-muted-foreground shrink-0">- {ytItems.length} video{ytItems.length !== 1 ? 's' : ''}- </span>+ <section className="flex flex-col gap-4">+ <SectionHeader+ className="mt-2"+ title={<span className="flex items-center gap-2"><PlatformIcon platform="youtube" className="text-ink-muted" />YouTube videos</span>}+ actions={<span className="text-small text-ink-faint">{ytItems.length} video{ytItems.length !== 1 ? 's' : ''}</span>}+ />+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">+ <MetricBox small icon={<Eye />} label="Video views" value={fmtNum(ytStats.views)} subtitle={`${fmtNum(ytStats.avgViews)} per video on average`} />+ <MetricBox small icon={<ThumbsUp />} label="Video likes" value={fmtNum(ytStats.likes)} subtitle={`${fmtNum(ytStats.avgLikes)} per video on average`} />+ <MetricBox small icon={<MessageSquare />} label="Video comments" value={fmtNum(ytStats.comments)} subtitle={`${fmtNum(ytStats.avgComments)} per video on average`} />+ <MetricBox small icon={<TrendingUp />} label="Likes per view" value={`${ytStats.likeRatio}%`} subtitle="Likes as a share of views" /></div>-- <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">- <StatCard- icon={<Eye />}- label="Video Views"- value={fmtNum(ytStats.views)}- subtitle={`avg ${fmtNum(ytStats.avgViews)} per video`}- gradient="red"- />- <StatCard- icon={<ThumbsUp />}- label="Video Likes"- value={fmtNum(ytStats.likes)}- subtitle={`avg ${fmtNum(ytStats.avgLikes)} per video`}- gradient="orange"- />- <StatCard- icon={<MessageSquare />}- label="Video Comments"- value={fmtNum(ytStats.comments)}- subtitle={`avg ${fmtNum(ytStats.avgComments)} per video`}- gradient="blue"- />- <StatCard- icon={<TrendingUp />}- label="Like-to-View Ratio"- value={ytStats.likeRatio + '%'}- subtitle="likes as share of views"- gradient="purple"- />- </div>-{ytChartData.length > 1 && (- <MainCard- title="Video Views"- subheader={`Top ${ytChartData.length} video${ytChartData.length !== 1 ? 's' : ''} in this category ranked by views`}- >- <MetricAreaChart- data={ytChartData}- dataKey="views"- label="Views"- color="#ef4444"- height={260}- />- </MainCard>+ <SurfaceBox title="Video views" subheader={`Top ${ytChartData.length} videos in this category ranked by views`}>+ <MetricAreaChart data={ytChartData} dataKey="views" label="Views" color={PLATFORM_META.youtube.series} height={260} />+ </SurfaceBox>)}-- <MainCard content={false}>+ <SurfaceBox content={false} className="overflow-hidden"><Table><TableHeader><TableRow>- <TableHead className="w-8">#</TableHead>+ <TableHead className="w-10 text-right">#</TableHead><TableHead>Video</TableHead>- <TableHead className="text-right w-32">Views</TableHead>- <TableHead className="text-right w-24">Likes</TableHead>- <TableHead className="text-right w-24">Comments</TableHead>- <TableHead className="text-right w-28">Fetched</TableHead>- <TableHead className="w-10" />+ <TableHead className="w-32 text-right">Views</TableHead>+ <TableHead className="w-24 text-right">Likes</TableHead>+ <TableHead className="w-24 text-right">Comments</TableHead>+ <TableHead className="w-28 text-right">Fetched</TableHead>+ <TableHead className="w-10"><span className="sr-only">Open</span></TableHead></TableRow></TableHeader><TableBody>- {[...ytItems]- .sort((a, b) => (b.viewCount ?? 0) - (a.viewCount ?? 0))- .map((item, i) => (- <TableRow key={item.id}>- <TableCell>- <span className={`text-xs font-bold tabular-nums ${medalColor(i)}`}>{i + 1}</span>- </TableCell>- <TableCell>- <div className="flex items-start gap-2.5">- {item.thumbnail ? (- <img- src={item.thumbnail}- alt=""- className="h-10 w-16 rounded object-cover flex-shrink-0 mt-0.5"- />- ) : (- <div className="h-10 w-16 rounded bg-red-500/10 flex items-center justify-center flex-shrink-0 mt-0.5">- <CirclePlay className="h-4 w-4 text-red-500" />- </div>- )}- <div className="min-w-0">- <p className="text-sm font-medium leading-snug line-clamp-2">- {item.title || item.url}- </p>- <div className="flex items-center gap-2 mt-0.5 flex-wrap">- {item.channelTitle && (- <span className="text-xs text-muted-foreground">{item.channelTitle}</span>- )}- {item.isShort && (- <Badge variant="outline" className="text-[10px] px-1.5 py-0">Short</Badge>- )}- {item.label && (- <span className="text-xs text-muted-foreground italic">{item.label}</span>- )}- </div>+ {ytSorted.map((item, i) => (+ <TableRow key={item.id}>+ <TableCell className="text-right"><RankNumber rank={i + 1} className="w-auto" /></TableCell>+ <TableCell className="whitespace-normal">+ <div className="flex items-start gap-3">+ {item.thumbnail ? (+ <img src={item.thumbnail} alt="" loading="lazy" className="mt-0.5 h-10 w-16 shrink-0 rounded-sm object-cover" />+ ) : (+ <span className="mt-0.5 flex h-10 w-16 shrink-0 items-center justify-center rounded-sm bg-surface-sunken text-ink-faint"><CirclePlay className="size-4" /></span>+ )}+ <div className="min-w-0">+ <p className="line-clamp-2 text-sm font-medium leading-snug text-ink">{item.title || item.url}</p>+ <div className="mt-1 flex flex-wrap items-center gap-1.5">+ {item.channelTitle && <span className="text-caption text-ink-faint">{item.channelTitle}</span>}+ {item.isShort && <Badge variant="outline">Short</Badge>}+ {item.label && <span className="text-caption text-ink-faint italic">{item.label}</span>}</div></div>- </TableCell>- <TableCell className="text-right">- <p className="text-sm font-bold tabular-nums">{fmtNum(item.viewCount ?? 0)}</p>- {showsFullValue(item.viewCount) && (- <p className="text-xs text-muted-foreground tabular-nums">{fmtNumFull(item.viewCount)}</p>- )}- </TableCell>- <TableCell className="text-right text-sm font-semibold tabular-nums text-red-500">- {fmtNum(item.likeCount ?? 0)}- </TableCell>- <TableCell className="text-right text-sm tabular-nums text-muted-foreground">- {fmtNum(item.commentCount ?? 0)}- </TableCell>- <TableCell className="text-right text-xs text-muted-foreground">- {item.lastFetchedAt ? fmtDate(item.lastFetchedAt) : '-'}- </TableCell>- <TableCell>- <a href={item.url} target="_blank" rel="noopener noreferrer">- <Button variant="ghost" size="icon" className="size-7">- <ExternalLink className="h-3.5 w-3.5" />- </Button>- </a>- </TableCell>- </TableRow>- ))}+ </div>+ </TableCell>+ <NumberCell value={item.viewCount} />+ <TableCell className="text-right text-ink-muted">{fmtNum(item.likeCount ?? 0)}</TableCell>+ <TableCell className="text-right text-ink-muted">{fmtNum(item.commentCount ?? 0)}</TableCell>+ <TableCell className="text-right text-small text-ink-faint">{item.lastFetchedAt ? fmtDate(item.lastFetchedAt) : '-'}</TableCell>+ <TableCell><OpenLink href={item.url} label={`Open "${item.title || 'video'}" on YouTube`} /></TableCell>+ </TableRow>+ ))}</TableBody></Table>- </MainCard>- </>+ </SurfaceBox>+ </section>)}- {/* Reddit section */}{rdItems.length > 0 && (- <>- <div className="flex items-center gap-3 pt-2">- <Flame className="h-5 w-5 text-orange-500 shrink-0" />- <h2 className="text-base font-semibold">Reddit Posts</h2>- <Separator className="flex-1" />- <span className="text-sm text-muted-foreground shrink-0">- {rdItems.length} post{rdItems.length !== 1 ? 's' : ''}- </span>- </div>-- <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">- <StatCard- icon={<Flame />}- label="Post Karma"- value={fmtNum(rdStats.karma)}- subtitle={`avg ${fmtNum(rdStats.avgKarma)} per post`}- gradient="orange"- />- <StatCard- icon={<Eye />}- label="Post Views"- value={rdStats.withViews > 0 ? fmtNum(rdStats.views) : '-'}- subtitle={- rdStats.withViews > 0- ? `across ${rdItems.length} post${rdItems.length !== 1 ? 's' : ''}`- : 'Reddit does not report views - add them per post'- }- gradient="teal"- />- <StatCard- icon={<MessageSquare />}- label="Post Comments"- value={fmtNum(rdStats.comments)}- subtitle={`avg ${fmtNum(rdStats.avgComments)} per post`}- gradient="blue"- />- <StatCard- icon={<TrendingUp />}- label="Avg Upvote Ratio"- value={rdStats.avgRatio > 0 ? Math.round(rdStats.avgRatio * 100) + '%' : '-'}- subtitle="upvotes as share of total votes"- gradient="green"- />+ <section className="flex flex-col gap-4">+ <SectionHeader+ className="mt-2"+ title={<span className="flex items-center gap-2"><PlatformIcon platform="reddit" className="text-ink-muted" />Reddit posts</span>}+ actions={<span className="text-small text-ink-faint">{rdItems.length} post{rdItems.length !== 1 ? 's' : ''}</span>}+ />+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">+ <MetricBox small icon={<MessagesSquare />} label="Post karma" value={fmtNum(rdStats.karma)} subtitle={`${fmtNum(rdStats.avgKarma)} per post on average`} />+ <MetricBox small icon={<Eye />} label="Post views" value={rdStats.withViews > 0 ? fmtNum(rdStats.views) : '-'} subtitle={rdStats.withViews > 0 ? `Across ${rdItems.length} post${rdItems.length !== 1 ? 's' : ''}` : 'Reddit does not report views. Add them per post.'} />+ <MetricBox small icon={<MessageSquare />} label="Post comments" value={fmtNum(rdStats.comments)} subtitle={`${fmtNum(rdStats.avgComments)} per post on average`} />+ <MetricBox small icon={<TrendingUp />} label="Average upvote ratio" value={rdStats.avgRatio > 0 ? `${Math.round(rdStats.avgRatio * 100)}%` : '-'} subtitle="Upvotes as a share of all votes" /></div>-{rdChartData.length > 1 && (- <MainCard- title="Post Karma"- subheader={`Top ${rdChartData.length} post${rdChartData.length !== 1 ? 's' : ''} in this category ranked by karma`}- >- <MetricAreaChart- data={rdChartData}- dataKey="karma"- label="Karma"- color="#f97316"- height={260}- />- </MainCard>+ <SurfaceBox title="Post karma" subheader={`Top ${rdChartData.length} posts in this category ranked by karma`}>+ <MetricAreaChart data={rdChartData} dataKey="karma" label="Karma" color={PLATFORM_META.reddit.series} height={260} />+ </SurfaceBox>)}-- <MainCard content={false}>+ <SurfaceBox content={false} className="overflow-hidden"><Table><TableHeader><TableRow>- <TableHead className="w-8">#</TableHead>+ <TableHead className="w-10 text-right">#</TableHead><TableHead>Post</TableHead>- <TableHead className="text-right w-28">Karma</TableHead>- <TableHead className="text-right w-24">Views</TableHead>- <TableHead className="text-right w-20">Upvote %</TableHead>- <TableHead className="text-right w-24">Comments</TableHead>- <TableHead className="text-right w-28">Fetched</TableHead>- <TableHead className="w-10" />+ <TableHead className="w-28 text-right">Karma</TableHead>+ <TableHead className="w-24 text-right">Views</TableHead>+ <TableHead className="w-20 text-right">Upvoted</TableHead>+ <TableHead className="w-24 text-right">Comments</TableHead>+ <TableHead className="w-28 text-right">Fetched</TableHead>+ <TableHead className="w-10"><span className="sr-only">Open</span></TableHead></TableRow></TableHeader><TableBody>- {[...rdItems]- .sort((a, b) => (b.score ?? 0) - (a.score ?? 0))- .map((item, i) => (- <TableRow key={item.id}>- <TableCell>- <span className={`text-xs font-bold tabular-nums ${medalColor(i)}`}>{i + 1}</span>- </TableCell>- <TableCell>- <div className="flex items-start gap-2.5">- {item.imageUrl && (- <ImageLightbox- src={item.imageUrl}- alt={item.title || 'Reddit post'}- className="mt-0.5"- />- )}- <div className="min-w-0">- <p className="text-sm font-medium leading-snug line-clamp-2">- {item.title || item.url}- </p>- <div className="flex items-center gap-2 mt-0.5 flex-wrap">- {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>- )}- </div>+ {rdSorted.map((item, i) => (+ <TableRow key={item.id}>+ <TableCell className="text-right"><RankNumber rank={i + 1} className="w-auto" /></TableCell>+ <TableCell className="whitespace-normal">+ <div className="flex items-start gap-3">+ {item.imageUrl && <ImageLightbox src={item.imageUrl} alt={item.title || 'Reddit post'} className="mt-0.5" />}+ <div className="min-w-0">+ <p className="line-clamp-2 text-sm font-medium leading-snug text-ink">{item.title || item.url}</p>+ <div className="mt-1 flex flex-wrap items-center gap-1.5">+ {item.subredditPrefixed && <span className="text-caption text-ink-faint">{item.subredditPrefixed}</span>}+ {item.label && <span className="text-caption text-ink-faint italic">{item.label}</span>}</div></div>- </TableCell>- <TableCell className="text-right">- <p className="text-sm font-bold tabular-nums text-orange-500">- {fmtNum(item.score ?? 0)}- </p>- {showsFullValue(item.score) && (- <p className="text-xs text-muted-foreground tabular-nums">{fmtNumFull(item.score)}</p>- )}- </TableCell>- <TableCell className="text-right text-sm tabular-nums">- {hasTrackedViews(item)- ? fmtNum(trackedViews(item))- : <span className="text-muted-foreground">-</span>}- </TableCell>- <TableCell className="text-right text-sm tabular-nums text-muted-foreground">- {(item.upvoteRatio != null && (item.score ?? 0) >= 10)- ? Math.round(item.upvoteRatio * 100) + '%'- : '-'}- </TableCell>- <TableCell className="text-right text-sm tabular-nums text-muted-foreground">- {fmtNum(item.numComments ?? 0)}- </TableCell>- <TableCell className="text-right text-xs text-muted-foreground">- {item.lastFetchedAt ? fmtDate(item.lastFetchedAt) : '-'}- </TableCell>- <TableCell>- <a href={item.permalink || item.url} target="_blank" rel="noopener noreferrer">- <Button variant="ghost" size="icon" className="size-7">- <ExternalLink className="h-3.5 w-3.5" />- </Button>- </a>- </TableCell>- </TableRow>- ))}+ </div>+ </TableCell>+ <NumberCell value={item.score} />+ <TableCell className="text-right text-ink-muted">{hasTrackedViews(item) ? fmtNum(trackedViews(item)) : '-'}</TableCell>+ <TableCell className="text-right text-ink-muted">{item.upvoteRatio != null && (item.score ?? 0) >= 10 ? `${Math.round(item.upvoteRatio * 100)}%` : '-'}</TableCell>+ <TableCell className="text-right text-ink-muted">{fmtNum(item.numComments ?? 0)}</TableCell>+ <TableCell className="text-right text-small text-ink-faint">{item.lastFetchedAt ? fmtDate(item.lastFetchedAt) : '-'}</TableCell>+ <TableCell><OpenLink href={item.permalink || item.url} label={`Open "${item.title || 'post'}" on Reddit`} /></TableCell>+ </TableRow>+ ))}</TableBody></Table>- </MainCard>- </>+ </SurfaceBox>+ </section>)}</div>);diff --git a/frontend/src/features/analytics/tracked/TrackedContent.jsx b/frontend/src/features/analytics/tracked/TrackedContent.jsxindex a6c7c01..4924cb5 100644--- a/frontend/src/features/analytics/tracked/TrackedContent.jsx+++ b/frontend/src/features/analytics/tracked/TrackedContent.jsx@@ -1,62 +1,73 @@import React, { useState, useEffect, useMemo, useCallback, useRef } from 'react';+import {+ Plus, RefreshCw, Trash2, Pencil, ExternalLink, Upload, X, Tag, Bookmark, BookmarkCheck, CirclePlay,+ MessagesSquare, Eye,+} from 'lucide-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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';+import { Select, SelectContent, SelectGroup, 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 { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '@/components/ui/dialog';+import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';import { Spinner } from '@/components/ui/spinner';-import StatCard from '../../../components/ui/StatCard';-import MainCard from '../../../components/MainCard';-import ImageLightbox from '../../../components/ImageLightbox';+import PageHeader from '@/components/PageHeader';+import MetricBox from '@/components/MetricBox';+import SurfaceBox from '@/components/SurfaceBox';+import SearchField from '@/components/SearchField';+import FilterChips from '@/components/FilterChips';+import ConfirmDialog from '@/components/ConfirmDialog';+import ImageLightbox from '@/components/ImageLightbox';+import { FieldRow } from '@/components/DetailPanel';+import { EmptyState } from '@/components/StateViews';+import { PlatformBadge } from '@/components/platform';+import { matchesText } from '@/lib/library';import { useAppContext } from '../../../context/AppContext';import { api } from '../../../services/api';import { fmtNum, fmtDate } from '../../../utils/formatters';-import { trackedViews, hasTrackedViews } from '../../../utils/trackedContent';import {- Plus, RefreshCw, Trash2, Pencil, ExternalLink, Upload, X,- Tag, Bookmark, BookmarkCheck, CirclePlay, Flame, Eye,-} from 'lucide-react';+ trackedViews, hasTrackedViews, detectContentType, isRedditItem, trackedEngagement, trackedComments,+} from '../../../utils/trackedContent';+import { cn } from '@/lib/utils';-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;-}+const MAX_IMAGE_BYTES = 10 * 1024 * 1024;-function getComments(item) {- if (item.contentType === 'youtube') return item.commentCount ?? 0;- return item.numComments ?? 0;-}+const SORT_OPTIONS = [+ { value: 'date-desc', label: 'Newest first' },+ { value: 'engagement-desc', label: 'Most likes or karma' },+ { value: 'comments-desc', label: 'Most comments' },+ { value: 'views-desc', label: 'Most views' },+];-function isRedditItem(item) {- return (item?.contentType || 'reddit') === 'reddit';+function CategoryPicker({ categories, onPick }) {+ if (categories.length === 0) return null;+ return (+ <div className="flex flex-wrap gap-1.5">+ {categories.map(c => (+ <button+ key={c}+ type="button"+ onClick={() => onPick(c)}+ className="h-6 rounded-pill border border-line px-2.5 text-caption font-medium text-ink-muted transition-colors duration-(--duration-fast) hover:bg-surface-hover hover:text-ink"+ >+ {c}+ </button>+ ))}+ </div>+ );}-const MAX_IMAGE_BYTES = 10 * 1024 * 1024;--function ContentTypeBadge({ type }) {- if (type === 'youtube') {- return (- <Badge variant="outline" className="text-[10px] border-red-200 bg-red-50 text-red-700 dark:border-red-900 dark:bg-red-950 dark:text-red-400 gap-1 px-1.5 py-0">- <CirclePlay className="h-2.5 w-2.5" />- YouTube- </Badge>- );- }+function RowAction({ label, onClick, disabled, children, href, danger }) {+ const button = href+ ? <Button variant="ghost" size="icon-xs" render={<a href={href} target="_blank" rel="noopener noreferrer" aria-label={label} />} />+ : <Button variant="ghost" size="icon-xs" onClick={onClick} disabled={disabled} aria-label={label} className={cn(danger && 'hover:bg-danger-soft hover:text-danger')} />;return (- <Badge variant="outline" className="text-[10px] border-orange-200 bg-orange-50 text-orange-700 dark:border-orange-900 dark:bg-orange-950 dark:text-orange-400 gap-1 px-1.5 py-0">- <Flame className="h-2.5 w-2.5" />- </Badge>+ <Tooltip>+ <TooltipTrigger render={button}>{children}</TooltipTrigger>+ <TooltipContent>{label}</TooltipContent>+ </Tooltip>);}@@ -68,6 +79,8 @@ export default function TrackedContent() {const [loading, setLoading] = useState(true);const [addOpen, setAddOpen] = useState(false);const [editItem, setEditItem] = useState(null);+ const [deleteItem, setDeleteItem] = useState(null);+ const [deleting, setDeleting] = useState(false);const [selected, setSelected] = useState(new Set());const [bulkCategory, setBulkCategory] = useState('');const [query, setQuery] = useState('');@@ -76,7 +89,6 @@ export default function TrackedContent() {const [sort, setSort] = useState('date-desc');const [refreshingIds, setRefreshingIds] = useState(new Set());- // Add dialog stateconst [addUrl, setAddUrl] = useState('');const [detectedType, setDetectedType] = useState(null);const [addAccountId, setAddAccountId] = useState(redditAccounts[0]?.id ?? 'none');@@ -84,7 +96,6 @@ export default function TrackedContent() {const [addCategory, setAddCategory] = useState('');const [adding, setAdding] = useState(false);- // Edit dialog stateconst [editLabel, setEditLabel] = useState('');const [editCategory, setEditCategory] = useState('');const [editViews, setEditViews] = useState('');@@ -100,7 +111,7 @@ export default function TrackedContent() {const data = await api.getTrackedContent();setItems(Array.isArray(data) ? data : []);} catch (err) {- showToast(err.message, 'error');+ showToast(`Couldn't load tracked content. ${err.message}`, 'error');} finally {setLoading(false);}@@ -120,73 +131,66 @@ export default function TrackedContent() {setDetectedType(detectContentType(val));}- const categories = useMemo(() => {- const seen = new Set(items.map(p => p.category).filter(Boolean));- return Array.from(seen).sort();- }, [items]);+ function resetAddForm() {+ setAddUrl(''); setDetectedType(null); setAddLabel(''); setAddCategory('');+ }++ const categories = useMemo(() => [...new Set(items.map(p => p.category).filter(Boolean))].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)- );- }+ result = result.filter(p => matchesText([p.title, p.subreddit, p.channelTitle, p.label, p.category], query));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 === 'engagement-desc') return trackedEngagement(b) - trackedEngagement(a);+ if (sort === 'comments-desc') return trackedComments(b) - trackedComments(a);if (sort === 'views-desc') return trackedViews(b) - trackedViews(a);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 stats = useMemo(() => ({+ total: items.length,+ categories: categories.length,+ youtube: items.filter(p => p.contentType === 'youtube').length,+ reddit: items.filter(p => isRedditItem(p)).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; });- }+ setSelected(prev => {+ const next = new Set(prev);+ filtered.forEach(p => (allSelected ? next.delete(p.id) : next.add(p.id)));+ return next;+ });}function toggleOne(id) {- setSelected(prev => { const n = new Set(prev); n.has(id) ? n.delete(id) : n.add(id); return n; });+ setSelected(prev => {+ const next = new Set(prev);+ if (next.has(id)) next.delete(id); else next.add(id);+ return next;+ });}- async function handleAdd() {- if (!addUrl.trim()) { showToast('Paste a URL to track', 'error'); return; }+ async function handleAdd(e) {+ e?.preventDefault();+ if (!addUrl.trim()) { showToast('Paste a Reddit post or YouTube video link to track it.', 'error'); return; }const type = detectContentType(addUrl.trim());- if (!type) { showToast('Only Reddit and YouTube URLs are supported', 'error'); return; }+ if (!type) { showToast('That link is not a Reddit post or a YouTube video. Paste one of those.', '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');+ resetAddForm();+ showToast('Now tracking this content');} catch (err) {- showToast(err.message, 'error');+ showToast(`Couldn't track that link. ${err.message}`, 'error');} finally {setAdding(false);}@@ -201,22 +205,22 @@ export default function TrackedContent() {if (imageInputRef.current) imageInputRef.current.value = '';}- // The Worker never handles binary uploads - the browser posts straight to Cloudinary with the+ // The Worker never handles binary uploads: the browser posts straight to Cloudinary with the// unsigned preset and only the returned URL is saved on the tracked itemasync function handleImageSelect(e) {const file = e.target.files?.[0];if (!file) return;if (!cloudConfig) {- showToast('Cloudinary is not configured on this server, so images cannot be uploaded', 'error');+ showToast('Image uploads need Cloudinary set up on the server. Check Settings.', 'error');return;}if (!file.type.startsWith('image/')) {- showToast('Choose an image file', 'error');+ showToast('That file is not an image. Choose a PNG, JPG or WebP file.', 'error');return;}if (file.size > MAX_IMAGE_BYTES) {- showToast(`Images must be under ${MAX_IMAGE_BYTES / 1024 / 1024}MB`, 'error');+ showToast(`That image is too large. Choose one under ${MAX_IMAGE_BYTES / 1024 / 1024}MB.`, 'error');return;}@@ -228,23 +232,24 @@ export default function TrackedContent() {const res = await fetch(`https://api.cloudinary.com/v1_1/${cloudConfig.cloudName}/image/upload`,- { method: 'POST', body: formData }+ { method: 'POST', body: formData },);const json = await res.json();if (!res.ok || !json.secure_url) {- throw new Error(json.error?.message || 'Upload failed');+ throw new Error(json.error?.message || 'Cloudinary did not return an image URL');}setEditImageUrl(json.secure_url);showToast('Image uploaded');} catch (err) {- showToast(err.message, 'error');+ showToast(`Image upload failed. ${err.message}`, 'error');} finally {setUploading(false);if (imageInputRef.current) imageInputRef.current.value = '';}}- async function handleSaveEdit() {+ async function handleSaveEdit(e) {+ e?.preventDefault();if (!editItem) return;const updates = { label: editLabel, category: editCategory };@@ -256,7 +261,7 @@ export default function TrackedContent() {} else {const views = Number(raw);if (!Number.isInteger(views) || views < 0) {- showToast('Views must be a whole number of 0 or more', 'error');+ showToast('Views must be a whole number of 0 or more.', 'error');return;}updates.manualViews = views;@@ -269,21 +274,28 @@ export default function TrackedContent() {const updated = await api.updateTrackedContent(editItem.id, updates);setItems(prev => prev.map(p => p.id === editItem.id ? updated : p));setEditItem(null);- showToast('Updated');+ showToast('Changes saved');} catch (err) {- showToast(err.message, 'error');+ showToast(`Couldn't save the changes. ${err.message}`, 'error');} finally {setSaving(false);}}- async function handleDelete(id) {+ async function handleDelete() {+ if (!deleteItem) return;+ const id = deleteItem.id;+ setDeleting(true);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; });+ setSelected(prev => { const next = new Set(prev); next.delete(id); return next; });+ setDeleteItem(null);+ showToast('Stopped tracking this content');} catch (err) {- showToast(err.message, 'error');+ showToast(`Couldn't stop tracking. ${err.message}`, 'error');+ } finally {+ setDeleting(false);}}@@ -293,547 +305,362 @@ export default function TrackedContent() {const updated = await api.refreshTrackedContent(id);setItems(prev => prev.map(p => p.id === id ? updated : p));} catch (err) {- showToast(err.message, 'error');+ showToast(`Refresh failed. ${err.message}`, 'error');} finally {- setRefreshingIds(prev => { const n = new Set(prev); n.delete(id); return n; });+ setRefreshingIds(prev => { const next = new Set(prev); next.delete(id); return next; });}}- async function handleBulkCategory() {+ async function handleBulkCategory(e) {+ e?.preventDefault();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');- }+ const ids = [...selected];+ const results = await Promise.allSettled(ids.map(id => api.updateTrackedContent(id, { category: bulkCategory.trim() })));+ const succeeded = results+ .map((r, i) => (r.status === 'fulfilled' ? { id: ids[i], data: r.value } : null))+ .filter(Boolean);+ setItems(prev => prev.map(p => succeeded.find(s => s.id === p.id)?.data ?? p));+ setSelected(new Set());+ setBulkCategory('');+ const failed = ids.length - succeeded.length;+ showToast(+ failed > 0+ ? `Category set on ${succeeded.length} item${succeeded.length !== 1 ? 's' : ''}. ${failed} could not be updated; try those again.`+ : `Category set on ${succeeded.length} item${succeeded.length !== 1 ? 's' : ''}`,+ failed > 0 ? 'warning' : 'success',+ );}+ const header = (+ <PageHeader+ title="Tracked content"+ description="Reddit posts and YouTube videos you follow, with karma, likes and comments."+ actions={+ <Button onClick={() => setAddOpen(true)}>+ <Plus data-icon="inline-start" />+ Track content+ </Button>+ }+ />+ );+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 className="flex flex-col gap-6">+ {header}+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-4">+ {[0, 1, 2, 3].map(i => <Skeleton key={i} className="h-28 rounded-card" />)}</div>- <Skeleton className="h-64" />+ <Skeleton className="h-10 rounded-field" />+ <Skeleton className="h-72 rounded-card" /></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 karma, 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>+ const typeChips = [+ { value: 'all', label: 'All', count: stats.total },+ { value: 'reddit', label: 'Reddit posts', count: stats.reddit },+ { value: 'youtube', label: 'YouTube videos', count: stats.youtube },+ ];- {/* 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={<CirclePlay />} 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" />+ return (+ <div className="flex flex-col gap-6">+ {header}++ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-4">+ <MetricBox icon={<BookmarkCheck />} label="Tracked items" value={stats.total} subtitle="Across all categories" highlight />+ <MetricBox icon={<Tag />} label="Categories" value={stats.categories} subtitle={stats.categories === 0 ? 'None assigned yet' : `${stats.categories} group${stats.categories !== 1 ? 's' : ''}`} />+ <MetricBox icon={<CirclePlay />} label="YouTube" value={stats.youtube} subtitle={stats.youtube === 0 ? 'No videos tracked' : `Video${stats.youtube !== 1 ? 's' : ''} tracked`} />+ <MetricBox icon={<MessagesSquare />} label="Reddit" value={stats.reddit} subtitle={stats.reddit === 0 ? 'No posts tracked' : `Post${stats.reddit !== 1 ? 's' : ''} tracked`} /></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>+ {items.length === 0 ? (+ <SurfaceBox>+ <EmptyState+ icon={<Bookmark />}+ title="Nothing tracked yet"+ description="Paste a Reddit post or YouTube video link to follow its karma, likes and comments."+ action={<Button onClick={() => setAddOpen(true)}><Plus data-icon="inline-start" />Track your first item</Button>}+ />+ </SurfaceBox>+ ) : (+ <>+ <div className="flex flex-col gap-3">+ <div className="flex flex-wrap items-center gap-2">+ <SearchField value={query} onChange={setQuery} placeholder="Search titles, channels, subreddits and labels" className="min-w-56 flex-1" />+ {categories.length > 0 && (+ <Select+ value={categoryFilter}+ onValueChange={setCategoryFilter}+ items={[{ value: 'all', label: 'All categories' }, ...categories.map(c => ({ value: c, label: c }))]}+ >+ <SelectTrigger className="w-44" aria-label="Category"><SelectValue /></SelectTrigger>+ <SelectContent>+ <SelectGroup>+ <SelectItem value="all">All categories</SelectItem>+ {categories.map(c => <SelectItem key={c} value={c}>{c}</SelectItem>)}+ </SelectGroup>+ </SelectContent>+ </Select>+ )}+ <Select value={sort} onValueChange={setSort} items={SORT_OPTIONS}>+ <SelectTrigger className="w-48" aria-label="Sort"><SelectValue /></SelectTrigger>+ <SelectContent>+ <SelectGroup>+ {SORT_OPTIONS.map(o => <SelectItem key={o.value} value={o.value}>{o.label}</SelectItem>)}+ </SelectGroup>+ </SelectContent>+ </Select></div>- <Button size="sm" variant="ghost" onClick={() => setSelected(new Set())}>- Clear- </Button>+ <FilterChips label="Content type" options={typeChips} value={typeFilter} onChange={setTypeFilter} /></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 }))]}+ {someSelected && (+ <form+ onSubmit={handleBulkCategory}+ className="sticky top-[calc(var(--topbar-h)+0.75rem)] z-10 flex flex-wrap items-center gap-3 rounded-card border border-brand/30 bg-surface-raised px-4 py-3 shadow-md"+ aria-label="Bulk actions">- <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>+ <span className="text-sm font-medium text-ink">{selected.size} selected</span>+ <div className="flex min-w-0 flex-1 items-center gap-2">+ <Tag className="size-4 shrink-0 text-ink-faint" />+ <Input+ placeholder="Category name"+ aria-label="Category to assign"+ value={bulkCategory}+ onChange={e => setBulkCategory(e.target.value)}+ className="h-(--control-h-sm) max-w-xs"+ />+ <Button type="submit" size="sm" disabled={!bulkCategory.trim()}>Assign category</Button>+ </div>+ <Button type="button" size="sm" variant="ghost" onClick={() => setSelected(new Set())}>Clear selection</Button>+ </form>)}- <Select- value={sort}- onValueChange={setSort}- items={[- { value: 'date-desc', label: 'Newest first' },- { value: 'engagement-desc', label: 'Likes / Karma' },- { 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 / Karma</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 / Karma</TableHead>- <TableHead className="text-right w-24">Comments</TableHead>- <TableHead className="text-right w-20">Ratio</TableHead>- <TableHead className="text-right w-28">Fetched</TableHead>- <TableHead className="w-24" />- </TableRow>- </TableHeader>- <TableBody>- {filtered.length === 0 ? (++ <SurfaceBox content={false} className="overflow-hidden">+ <Table>+ <TableHeader><TableRow>- <TableCell colSpan={9} className="text-center text-muted-foreground py-10">- No items match the current filters- </TableCell>+ <TableHead className="w-10">+ <Checkbox checked={allSelected} onCheckedChange={toggleAll} aria-label="Select all shown items" />+ </TableHead>+ <TableHead>Content</TableHead>+ <TableHead className="w-32">Category</TableHead>+ <TableHead className="w-24 text-right">Views</TableHead>+ <TableHead className="w-28 text-right">Likes or karma</TableHead>+ <TableHead className="w-24 text-right">Comments</TableHead>+ <TableHead className="w-20 text-right">Upvoted</TableHead>+ <TableHead className="w-28 text-right">Fetched</TableHead>+ <TableHead className="w-32"><span className="sr-only">Actions</span></TableHead></TableRow>- ) : (- filtered.map(item => {- const isYT = item.contentType === 'youtube';- 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" />- ) : !isYT && item.imageUrl ? (- <ImageLightbox- src={item.imageUrl}- alt={item.title || item.label || 'Reddit post'}- className="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>- )}+ </TableHeader>+ <TableBody>+ {filtered.length === 0 ? (+ <TableRow className="hover:bg-transparent">+ <TableCell colSpan={9}>+ <EmptyState compact icon={<Bookmark />} title="No items match" description="Clear the search or choose a different type or category." />+ </TableCell>+ </TableRow>+ ) : (+ filtered.map(item => {+ const isYT = item.contentType === 'youtube';+ const isRefreshing = refreshingIds.has(item.id);+ const title = item.title || item.label || item.url;+ const engagement = isYT ? item.likeCount : item.score;+ const comments = isYT ? item.commentCount : item.numComments;+ return (+ <TableRow key={item.id} data-state={selected.has(item.id) ? 'selected' : undefined}>+ <TableCell>+ <Checkbox checked={selected.has(item.id)} onCheckedChange={() => toggleOne(item.id)} aria-label={`Select ${title}`} />+ </TableCell>+ <TableCell className="whitespace-normal">+ <div className="flex max-w-sm items-start gap-3">+ {isYT && item.thumbnail ? (+ <img src={item.thumbnail} alt="" loading="lazy" className="mt-0.5 h-10 w-16 shrink-0 rounded-sm object-cover" />+ ) : !isYT && item.imageUrl ? (+ <ImageLightbox src={item.imageUrl} alt={title || 'Reddit post'} className="mt-0.5" />+ ) : null}+ <div className="min-w-0">+ <p className="line-clamp-2 text-sm font-medium leading-snug text-ink">{title}</p>+ <div className="mt-1 flex flex-wrap items-center gap-1.5">+ <PlatformBadge platform={item.contentType || 'reddit'} className="h-5" />+ <span className="text-caption text-ink-faint">{isYT ? item.channelTitle : item.subredditPrefixed}</span>+ {item.label && <span className="text-caption text-ink-faint italic">{item.label}</span>}+ {isYT && item.isShort && <Badge variant="outline">Short</Badge>}+ </div></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">- {hasTrackedViews(item) ? (- <span className={isYT ? '' : 'text-foreground'}>{fmtNum(trackedViews(item))}</span>- ) : isYT ? (- '-'- ) : (- <Button- variant="ghost"- size="sm"- className="h-6 px-1.5 text-xs font-normal text-muted-foreground gap-1"- onClick={() => openEdit(item)}- title="Reddit does not report views - enter them manually"- >- <Eye className="h-3 w-3" />- Set- </Button>- )}- </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">+ </TableCell>+ <TableCell>+ {item.category ? <Badge variant="secondary">{item.category}</Badge> : <span className="text-ink-faint">-</span>}+ </TableCell>+ <TableCell className="text-right">+ {hasTrackedViews(item) ? (+ <span className="text-ink">{fmtNum(trackedViews(item))}</span>+ ) : isYT ? (+ <span className="text-ink-faint">-</span>+ ) : (+ <Tooltip>+ <TooltipTrigger render={<Button variant="ghost" size="xs" onClick={() => openEdit(item)} />}>+ <Eye />Add+ </TooltipTrigger>+ <TooltipContent>Reddit does not report views. Enter them by hand.</TooltipContent>+ </Tooltip>+ )}+ </TableCell>+ <TableCell className="text-right font-semibold text-ink">{engagement !== undefined ? fmtNum(engagement) : '-'}</TableCell>+ <TableCell className="text-right text-ink-muted">{comments !== undefined ? fmtNum(comments) : '-'}</TableCell>+ <TableCell className="text-right text-ink-muted">+ {!isYT && item.upvoteRatio !== undefined && (item.score ?? 0) >= 10 ? `${Math.round(item.upvoteRatio * 100)}%` : '-'}+ </TableCell>+ <TableCell className="text-right text-small text-ink-faint">{item.lastFetchedAt ? fmtDate(item.lastFetchedAt) : '-'}</TableCell>+ <TableCell>+ <div className="flex items-center justify-end gap-0.5">+ <RowAction label="Refresh live data" onClick={() => handleRefresh(item.id)} disabled={isRefreshing}>+ <RefreshCw className={cn(isRefreshing && 'animate-spin')} />+ </RowAction>+ <RowAction label="Edit" onClick={() => openEdit(item)}><Pencil /></RowAction>+ <RowAction label="Open original" href={item.permalink || item.url}><ExternalLink /></RowAction>+ <RowAction label="Stop tracking" onClick={() => setDeleteItem(item)} danger><Trash2 /></RowAction>+ </div>+ </TableCell>+ </TableRow>+ );+ })+ )}+ </TableBody>+ </Table>+ </SurfaceBox>+ </>+ )}++ <Dialog open={addOpen} onOpenChange={open => { setAddOpen(open); if (!open) resetAddForm(); }}>+ <DialogContent className="sm:max-w-lg"><DialogHeader>- <DialogTitle>Track Content</DialogTitle>+ <DialogTitle>Track content</DialogTitle>+ <DialogDescription>Paste a Reddit post or a YouTube video or Shorts link.</DialogDescription></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>+ <form id="track-form" onSubmit={handleAdd} className="flex flex-col gap-5">+ <FieldRow label="Link" htmlFor="track-url">+ <Input id="track-url" className="h-(--control-h-lg)" placeholder="https://" value={addUrl} onChange={e => handleUrlChange(e.target.value)} autoFocus />{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 className="flex items-center gap-1.5 text-caption text-success">+ <PlatformBadge platform={detectedType} className="h-5" />+ {detectedType === 'youtube' ? 'YouTube video found' : 'Reddit post found'}</p>- )}- </div>+ ) : addUrl.trim() ? (+ <p className="text-caption text-danger">Error: only Reddit posts and YouTube videos can be tracked.</p>+ ) : null}+ </FieldRow>{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>+ <FieldRow label="Fetch with account" hint="A session cookie helps Reddit accept requests from the server." htmlFor="track-account"><Selectvalue={addAccountId}onValueChange={setAddAccountId}- items={[- { value: 'none', label: 'No cookie (public posts only)' },- ...redditAccounts.map(a => ({ value: a.id, label: `u/${a.username}` })),- ]}+ items={[{ value: 'none', label: 'No account (public posts only)' }, ...redditAccounts.map(a => ({ value: a.id, label: `u/${a.username}` }))]}>- <SelectTrigger>- <SelectValue />- </SelectTrigger>+ <SelectTrigger id="track-account" className="w-full"><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>- ))}+ <SelectGroup>+ <SelectItem value="none">No account (public posts only)</SelectItem>+ {redditAccounts.map(a => <SelectItem key={a.id} value={a.id}>u/{a.username}</SelectItem>)}+ </SelectGroup></SelectContent></Select>- <p className="text-xs text-muted-foreground">- A session cookie improves access from datacenter IPs- </p>- </div>+ </FieldRow>)}- <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 className="grid grid-cols-1 gap-5 sm:grid-cols-2">+ <FieldRow label="Label" hint="Optional" htmlFor="track-label">+ <Input id="track-label" placeholder="Launch teaser" value={addLabel} onChange={e => setAddLabel(e.target.value)} />+ </FieldRow>+ <FieldRow label="Category" hint="Optional" htmlFor="track-category">+ <Input id="track-category" placeholder="Campaign A" value={addCategory} onChange={e => setAddCategory(e.target.value)} />+ <CategoryPicker categories={categories} onPick={setAddCategory} />+ </FieldRow></div>- </div>+ </form><DialogFooter><Button variant="outline" onClick={() => setAddOpen(false)} disabled={adding}>Cancel</Button>- <Button onClick={handleAdd} disabled={adding || !addUrl.trim() || !detectedType}>- {adding ? 'Fetching...' : 'Track'}+ <Button type="submit" form="track-form" disabled={adding || !addUrl.trim() || !detectedType}>+ {adding && <Spinner className="size-4" />}+ {adding ? 'Fetching details' : 'Track'}</Button></DialogFooter></DialogContent></Dialog>- {/* Edit dialog */}- <Dialog open={!!editItem} onOpenChange={v => !v && setEditItem(null)}>- <DialogContent className="max-w-sm">+ <Dialog open={!!editItem} onOpenChange={open => !open && setEditItem(null)}>+ <DialogContent className="sm:max-w-md"><DialogHeader><DialogTitle>Edit tracked item</DialogTitle>+ <DialogDescription className="line-clamp-2">{editItem?.title || editItem?.url}</DialogDescription></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>+ <form id="edit-tracked-form" onSubmit={handleSaveEdit} className="flex flex-col gap-5">+ <FieldRow label="Label" htmlFor="edit-label">+ <Input id="edit-label" value={editLabel} onChange={e => setEditLabel(e.target.value)} placeholder="Launch teaser" />+ </FieldRow>+ <FieldRow label="Category" htmlFor="edit-category">+ <Input id="edit-category" value={editCategory} onChange={e => setEditCategory(e.target.value)} placeholder="Campaign A" />+ <CategoryPicker categories={categories} onPick={setEditCategory} />+ </FieldRow>+{editItem && isRedditItem(editItem) && (- <div className="space-y-1.5">- <label className="text-sm font-medium">- Views <span className="text-muted-foreground font-normal">(optional)</span>- </label>- <Input- type="number"- min="0"- step="1"- inputMode="numeric"- value={editViews}- onChange={e => setEditViews(e.target.value)}- placeholder="e.g. 12500"- />- <p className="text-xs text-muted-foreground">- Reddit does not report view counts through its API. Copy the number from the post- insights page to include it in your totals. Leave empty to remove it.- </p>- </div>+ <FieldRow+ label="Views"+ hint="Reddit does not report views through its API. Copy the number from the post's insights page. Leave empty to remove it."+ htmlFor="edit-views"+ >+ <Input id="edit-views" type="number" min="0" step="1" inputMode="numeric" value={editViews} onChange={e => setEditViews(e.target.value)} placeholder="12500" />+ </FieldRow>)}{editItem && isRedditItem(editItem) && (- <div className="flex flex-col gap-1.5">- <label className="text-sm font-medium">- Image <span className="text-muted-foreground font-normal">(optional)</span>- </label>-- <input- ref={imageInputRef}- type="file"- accept="image/*"- onChange={handleImageSelect}- className="hidden"- />-+ <FieldRow+ label="Image"+ hint={cloudConfig+ ? 'Reddit posts have no thumbnail in the public API. Upload a screenshot to recognise the post at a glance.'+ : 'Image uploads need Cloudinary set up on the server. Check Settings.'}+ >+ <input ref={imageInputRef} type="file" accept="image/*" onChange={handleImageSelect} className="hidden" aria-label="Choose an image" />{editImageUrl ? (- <div className="flex items-center gap-3 rounded-lg border border-border p-2">- <ImageLightbox- src={editImageUrl}- alt={editItem.title || 'Reddit post'}- thumbClassName="size-14"- />- <div className="flex-1 min-w-0">- <p className="text-xs text-muted-foreground">- Click the image to view it full size- </p>- </div>- <Button- variant="ghost"- size="icon"- className="size-7 shrink-0"- onClick={() => setEditImageUrl(null)}- title="Remove image"- disabled={uploading}- >- <X className="h-3.5 w-3.5" />+ <div className="flex items-center gap-3 rounded-control border border-line p-2">+ <ImageLightbox src={editImageUrl} alt={editItem.title || 'Reddit post'} thumbClassName="size-14" />+ <p className="min-w-0 flex-1 text-caption text-ink-faint">Select the image to view it full size.</p>+ <Button variant="ghost" size="icon-xs" onClick={() => setEditImageUrl(null)} disabled={uploading} aria-label="Remove image">+ <X /></Button></div>) : (- <Button- variant="outline"- size="sm"- className="justify-start gap-2"- onClick={() => imageInputRef.current?.click()}- disabled={uploading || !cloudConfig}- >- {uploading ? <Spinner /> : <Upload className="h-3.5 w-3.5" />}- {uploading ? 'Uploading...' : 'Upload image'}+ <Button type="button" variant="outline" className="justify-start" onClick={() => imageInputRef.current?.click()} disabled={uploading || !cloudConfig}>+ {uploading ? <Spinner className="size-4" /> : <Upload data-icon="inline-start" />}+ {uploading ? 'Uploading image' : 'Upload image'}</Button>)}-- <p className="text-xs text-muted-foreground">- {cloudConfig- ? 'Reddit posts have no thumbnail in the public API. Upload a screenshot to recognise the post at a glance.'- : 'Image uploads need Cloudinary configured on the server. Check Settings.'}- </p>- </div>+ </FieldRow>)}- </div>+ </form><DialogFooter><Button variant="outline" onClick={() => setEditItem(null)} disabled={saving}>Cancel</Button>- <Button onClick={handleSaveEdit} disabled={saving}>{saving ? 'Saving...' : 'Save'}</Button>+ <Button type="submit" form="edit-tracked-form" disabled={saving || uploading}>+ {saving && <Spinner className="size-4" />}+ {saving ? 'Saving' : 'Save changes'}+ </Button></DialogFooter></DialogContent></Dialog>++ <ConfirmDialog+ open={!!deleteItem}+ onOpenChange={open => { if (!open) setDeleteItem(null); }}+ title="Stop tracking this content?"+ description={deleteItem ? `"${deleteItem.title || deleteItem.label || deleteItem.url}" and its saved views, image and category are removed from Twiligent. The original post or video is not affected.` : ''}+ confirmLabel="Stop tracking"+ onConfirm={handleDelete}+ busy={deleting}+ hold+ /></div>);}diff --git a/frontend/src/features/analytics/videos/VideoExplorer.jsx b/frontend/src/features/analytics/videos/VideoExplorer.jsxindex ec0f31b..4b44c6d 100644--- a/frontend/src/features/analytics/videos/VideoExplorer.jsx+++ b/frontend/src/features/analytics/videos/VideoExplorer.jsx@@ -1,364 +1,280 @@-import React, { useState, useEffect, useMemo } from 'react';+import React, { useMemo, useState } from 'react';+import { Link } from 'react-router-dom';+import {+ RefreshCw, List, LayoutGrid, ThumbsUp, MessageSquare, Play, Eye, PlaySquare, ArrowUp, ArrowDown, Plus,+} from 'lucide-react';import { Button } from '@/components/ui/button';-import { Input } from '@/components/ui/input';import { Badge } from '@/components/ui/badge';-import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';-import { Skeleton } from '@/components/ui/skeleton';-import { Progress } from '@/components/ui/progress';import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';-import {- Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue,-} from '@/components/ui/select';-import { ScrollArea } from '@/components/ui/scroll-area';-import {- Search, RefreshCw, List, LayoutGrid, ExternalLink, ThumbsUp, MessageSquare,- Play, Eye, Tv,-} from 'lucide-react';-import { Empty, EmptyMedia, EmptyHeader, EmptyTitle, EmptyDescription } from '@/components/ui/empty';-import StatCard from '../../../components/ui/StatCard';-import MainCard from '../../../components/MainCard';-import { useAppContext } from '../../../context/AppContext';-import { api } from '../../../services/api';+import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';+import { Skeleton } from '@/components/ui/skeleton';+import PageHeader from '@/components/PageHeader';+import MetricBox from '@/components/MetricBox';+import SurfaceBox from '@/components/SurfaceBox';+import SearchField from '@/components/SearchField';+import FilterChips from '@/components/FilterChips';+import Pager from '@/components/Pager';+import MediaCard, { MediaChip } from '@/components/MediaCard';+import { EmptyState } from '@/components/StateViews';+import { VIEW_TIERS, filterByTier, matchesText, pageSlice } from '@/lib/library';+import { useChannelVideos } from './useChannelVideos';import { fmtNum, fmtDate, fmtDuration, fmtPercent, timeAgo } from '../../../utils/formatters';import { cn } from '@/lib/utils';const ITEMS_PER_PAGE = 25;+const watchUrl = id => `https://www.youtube.com/watch?v=${id}`;+const LAYOUTS = [{ value: 'table', label: 'List', Icon: List }, { value: 'grid', label: 'Grid', Icon: LayoutGrid }];-function parseDurationToSeconds(iso) {- if (!iso || iso === 'P0D') return 0;- const m = iso.match(/PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?/);- if (!m) return 0;- return (parseInt(m[1] || 0) * 3600) + (parseInt(m[2] || 0) * 60) + parseInt(m[3] || 0);-}--const PERFORMANCE_TIERS = [- { label: 'All', value: 'all' },- { label: 'Viral (>1M)', value: 'viral', min: 1000000 },- { label: 'High (100K-1M)', value: 'high', min: 100000, max: 1000000 },- { label: 'Medium (10K-100K)', value: 'medium', min: 10000, max: 100000 },- { label: 'Low (<10K)', value: 'low', max: 10000 },-];--function SortButton({ field, label, sortField, sortOrder, onSort }) {- const active = sortField === field;+function SortHeader({ field, label, sort, onSort, align = 'left' }) {+ const active = sort.field === field;+ const Arrow = sort.order === 'asc' ? ArrowUp : ArrowDown;return (<button+ type="button"onClick={() => onSort(field)}- className={cn('flex items-center gap-1 text-xs font-medium hover:text-foreground transition-colors', active ? 'text-foreground' : 'text-muted-foreground')}+ aria-sort={active ? (sort.order === 'asc' ? 'ascending' : 'descending') : undefined}+ className={cn(+ 'inline-flex items-center gap-1 rounded-sm transition-colors hover:text-ink',+ align === 'right' && 'flex-row-reverse',+ active ? 'text-ink' : 'text-ink-muted',+ )}>{label}- <span className="text-[10px]">{active ? (sortOrder === 'asc' ? '↑' : '↓') : ''}</span>+ <Arrow className={cn('size-3', !active && 'invisible')} /></button>);}export default function VideoExplorer() {- const { accounts, showToast } = useAppContext();- const [videos, setVideos] = useState([]);- const [loading, setLoading] = useState(true);- const [search, setSearch] = useState('');- const [channelFilter, setChannelFilter] = useState('all');- const [performanceTier, setPerformanceTier] = useState('all');- const [sortField, setSortField] = useState('viewCount');- const [sortOrder, setSortOrder] = useState('desc');- const [viewMode, setViewMode] = useState('table');- const [page, setPage] = useState(1);- const [channels, setChannels] = useState([]);+ const { videos, channels, loading, reload } = useChannelVideos();+ const [search, setSearch] = useState('');+ const [channelFilter, setChannelFilter] = useState('all');+ const [tier, setTier] = useState('all');+ const [sort, setSort] = useState({ field: 'viewCount', order: 'desc' });+ const [viewMode, setViewMode] = useState('table');+ const [page, setPage] = useState(1);- useEffect(() => { loadAllVideos(); }, [accounts]);-- const loadAllVideos = async () => {- setLoading(true);- try {- const allVids = [];- const channelList = [];- for (const acct of (accounts || [])) {- if (acct.platform === 'instagram') continue;- try {- const res = await api.getVideos(acct.id);- const vids = res.videos || res.data?.videos || [];- const channelTitle = acct.title || acct.channelTitle || 'Unknown';- channelList.push({ id: acct.id, title: channelTitle, thumbnail: acct.thumbnails?.default || acct.thumbnailUrl || '' });- allVids.push(...vids.map(v => ({- ...v,- thumbnail: v.thumbnail || v.thumbnails?.medium || v.thumbnails?.high || v.thumbnails?.default || '',- channelTitle,- channelId: acct.id,- engagementRate: (v.viewCount || 0) > 0 ? (((v.likeCount || 0) + (v.commentCount || 0)) / v.viewCount * 100).toFixed(2) : '0.00',- durationSeconds: v.durationSeconds || parseDurationToSeconds(v.duration),- })));- } catch (e) { /* skip failed channels */ }- }- setVideos(allVids);- setChannels(channelList);- } catch (err) {- showToast('Failed to load videos: ' + err.message, 'error');- } finally {- setLoading(false);- }- };-- const filteredVideos = useMemo(() => {- let result = [...videos];- if (channelFilter !== 'all') result = result.filter(v => v.channelId === channelFilter);- if (search.trim()) {- const q = search.toLowerCase();- result = result.filter(v => v.title?.toLowerCase().includes(q) || (v.tags || []).some(t => t.toLowerCase().includes(q)));- }- if (performanceTier !== 'all') {- const tier = PERFORMANCE_TIERS.find(t => t.value === performanceTier);- if (tier?.min != null) result = result.filter(v => (v.viewCount || 0) >= tier.min);- if (tier?.max != null) result = result.filter(v => (v.viewCount || 0) < tier.max);- }- result.sort((a, b) => {- const aVal = a[sortField] ?? 0, bVal = b[sortField] ?? 0;- if (typeof aVal === 'string') return sortOrder === 'asc' ? aVal.localeCompare(bVal) : bVal.localeCompare(aVal);- return sortOrder === 'asc' ? aVal - bVal : bVal - aVal;+ const filtered = useMemo(() => {+ let result = channelFilter === 'all' ? videos : videos.filter(v => v.channelId === channelFilter);+ result = result.filter(v => matchesText([v.title, ...(v.tags || [])], search));+ result = filterByTier(result, VIEW_TIERS, tier, 'viewCount');+ const dir = sort.order === 'asc' ? 1 : -1;+ return [...result].sort((a, b) => {+ const av = a[sort.field] ?? 0;+ const bv = b[sort.field] ?? 0;+ if (typeof av === 'string' && typeof bv === 'string') return av.localeCompare(bv) * dir;+ return (Number(av) - Number(bv)) * dir;});- return result;- }, [videos, channelFilter, search, performanceTier, sortField, sortOrder]);+ }, [videos, channelFilter, search, tier, sort]);++ const paged = pageSlice(filtered, page, ITEMS_PER_PAGE);- const pageCount = Math.ceil(filteredVideos.length / ITEMS_PER_PAGE);- const paginatedVideos = filteredVideos.slice((page - 1) * ITEMS_PER_PAGE, page * ITEMS_PER_PAGE);+ const stats = useMemo(() => {+ const sum = key => filtered.reduce((s, v) => s + (v[key] || 0), 0);+ const views = sum('viewCount');+ return {+ total: filtered.length,+ views,+ likes: sum('likeCount'),+ comments: sum('commentCount'),+ avgViews: filtered.length ? Math.round(views / filtered.length) : 0,+ };+ }, [filtered]);- const handleSort = (field) => {- if (sortField === field) setSortOrder(prev => prev === 'asc' ? 'desc' : 'asc');- else { setSortField(field); setSortOrder('desc'); }+ const resetPage = setter => value => { setter(value); setPage(1); };+ const handleSort = field => {+ setSort(prev => prev.field === field ? { field, order: prev.order === 'asc' ? 'desc' : 'asc' } : { field, order: 'desc' });};- const stats = useMemo(() => ({- total: filteredVideos.length,- totalViews: filteredVideos.reduce((s, v) => s + (v.viewCount || 0), 0),- totalLikes: filteredVideos.reduce((s, v) => s + (v.likeCount || 0), 0),- totalComments: filteredVideos.reduce((s, v) => s + (v.commentCount || 0), 0),- avgViews: filteredVideos.length > 0 ? Math.round(filteredVideos.reduce((s, v) => s + (v.viewCount || 0), 0) / filteredVideos.length) : 0,- }), [filteredVideos]);+ const header = (+ <PageHeader+ title="Videos"+ description={loading ? 'Loading videos from your channels' : `${fmtNum(videos.length)} videos across ${channels.length} channel${channels.length === 1 ? '' : 's'}`}+ actions={+ <Button variant="outline" size="sm" onClick={reload} disabled={loading}>+ <RefreshCw data-icon="inline-start" className={cn(loading && 'animate-spin')} />+ Refresh+ </Button>+ }+ />+ );if (loading) {return (- <div className="space-y-4">- <div>- <Skeleton className="h-8 w-48 mb-2" />- <Progress className="h-1" />- </div>- <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-3">- {[...Array(6)].map((_, i) => <Skeleton key={i} className="h-44 rounded-xl" />)}+ <div className="flex flex-col gap-6">+ {header}+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 xl:grid-cols-5">+ {Array.from({ length: 5 }).map((_, i) => <Skeleton key={i} className="h-24 rounded-card" />)}</div>+ <Skeleton className="h-10 rounded-pill" />+ <Skeleton className="h-96 rounded-card" /></div>);}- return (- <div className="space-y-5">- {/* Header */}- <div className="flex items-center justify-between gap-4 flex-wrap">- <div>- <h1 className="text-2xl font-bold tracking-tight">Video Explorer</h1>- <p className="text-sm text-muted-foreground mt-0.5">- {videos.length} total videos across {channels.length} channel{channels.length !== 1 ? 's' : ''}- </p>- </div>- <Button variant="outline" size="sm" onClick={loadAllVideos} className="gap-2">- <RefreshCw className="h-3.5 w-3.5" /> Refresh- </Button>+ if (channels.length === 0) {+ return (+ <div className="flex flex-col gap-6">+ {header}+ <SurfaceBox>+ <EmptyState+ icon={<PlaySquare />}+ title="No YouTube channels yet"+ description="Add a channel to browse and compare its videos here."+ action={<Button render={<Link to="/accounts?add=1" />}><Plus data-icon="inline-start" />Add a channel</Button>}+ />+ </SurfaceBox></div>+ );+ }++ return (+ <div className="flex flex-col gap-6">+ {header}- {/* Stats */}- <div className="grid grid-cols-2 sm:grid-cols-3 xl:grid-cols-5 gap-3">- {[- { icon: <Play />, label: 'Videos', value: fmtNum(stats.total), gradient: 'blue' },- { icon: <Eye />, label: 'Total Views', value: fmtNum(stats.totalViews), gradient: 'red' },- { icon: <ThumbsUp />, label: 'Total Likes', value: fmtNum(stats.totalLikes), gradient: 'green' },- { icon: <MessageSquare />, label: 'Comments', value: fmtNum(stats.totalComments), gradient: 'orange' },- { icon: <Eye />, label: 'Avg Views', value: fmtNum(stats.avgViews), gradient: 'purple' },- ].map((s, i) => <StatCard key={i} {...s} small />)}+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 xl:grid-cols-5">+ <MetricBox small icon={<Play />} label="Videos" value={fmtNum(stats.total)} />+ <MetricBox small icon={<Eye />} label="Views" value={fmtNum(stats.views)} highlight />+ <MetricBox small icon={<ThumbsUp />} label="Likes" value={fmtNum(stats.likes)} />+ <MetricBox small icon={<MessageSquare />} label="Comments" value={fmtNum(stats.comments)} />+ <MetricBox small icon={<Eye />} label="Average views" value={fmtNum(stats.avgViews)} /></div>- {/* Filters */}- <MainCard>- <div className="flex flex-wrap gap-3 items-center">- <div className="relative flex-1 min-w-48">- <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />- <Input- className="pl-9"- placeholder="Search by title or tag…"- value={search}- onChange={e => { setSearch(e.target.value); setPage(1); }}- />- </div>- <Select value={channelFilter} onValueChange={v => { setChannelFilter(v); setPage(1); }}>- <SelectTrigger className="w-44">- <SelectValue placeholder="All Channels" />- </SelectTrigger>- <SelectContent>- <SelectGroup>- <SelectItem value="all">All Channels ({channels.length})</SelectItem>- {channels.map(c => (- <SelectItem key={c.id} value={c.id}>- <div className="flex items-center gap-2">- {c.thumbnail && <Avatar className="size-4"><AvatarImage src={c.thumbnail} /></Avatar>}- <span className="truncate max-w-28">{c.title}</span>- </div>- </SelectItem>- ))}- </SelectGroup>- </SelectContent>- </Select>- <Select value={performanceTier} onValueChange={v => { setPerformanceTier(v); setPage(1); }}>- <SelectTrigger className="w-44">- <SelectValue placeholder="Performance" />- </SelectTrigger>- <SelectContent>- <SelectGroup>- {PERFORMANCE_TIERS.map(t => <SelectItem key={t.value} value={t.value}>{t.label}</SelectItem>)}- </SelectGroup>- </SelectContent>- </Select>- <div className="flex border border-border rounded-md overflow-hidden">- <button- onClick={() => setViewMode('table')}- className={cn('px-3 py-1.5 transition-colors', viewMode === 'table' ? 'bg-primary text-primary-foreground' : 'bg-background hover:bg-muted')}+ <div className="flex flex-col gap-3">+ <div className="flex flex-wrap items-center gap-2">+ <SearchField+ value={search}+ onChange={resetPage(setSearch)}+ placeholder="Search titles and tags"+ className="min-w-56 flex-1"+ />+ {channels.length > 1 && (+ <Select+ value={channelFilter}+ onValueChange={resetPage(setChannelFilter)}+ items={[{ value: 'all', label: 'All channels' }, ...channels.map(c => ({ value: c.id, label: c.title }))]}>- <List className="h-4 w-4" />- </button>- <button- onClick={() => setViewMode('grid')}- className={cn('px-3 py-1.5 transition-colors', viewMode === 'grid' ? 'bg-primary text-primary-foreground' : 'bg-background hover:bg-muted')}- >- <LayoutGrid className="h-4 w-4" />- </button>+ <SelectTrigger className="w-48" aria-label="Channel"><SelectValue /></SelectTrigger>+ <SelectContent>+ <SelectGroup>+ <SelectItem value="all">All channels</SelectItem>+ {channels.map(c => <SelectItem key={c.id} value={c.id}>{c.title}</SelectItem>)}+ </SelectGroup>+ </SelectContent>+ </Select>+ )}+ <div role="radiogroup" aria-label="Layout" className="flex h-(--control-h-lg) items-center gap-0.5 rounded-field border border-line-control p-1">+ {LAYOUTS.map(layout => {+ const { value, label, Icon } = layout;+ return (+ <button+ key={value}+ type="button"+ role="radio"+ aria-checked={viewMode === value}+ aria-label={`${label} layout`}+ onClick={() => setViewMode(value)}+ className={cn(+ 'flex size-8 items-center justify-center rounded-[8px] transition-colors',+ viewMode === value ? 'bg-surface-selected text-ink' : 'text-ink-muted hover:text-ink',+ )}+ >+ <Icon className="size-4 stroke-[1.75]" />+ </button>+ );+ })}</div></div>- <p className="text-xs text-muted-foreground mt-2">- Showing {paginatedVideos.length} of {filteredVideos.length} videos- </p>- </MainCard>+ <FilterChips label="Views" options={VIEW_TIERS} value={tier} onChange={resetPage(setTier)} />+ </div>- {/* Table view */}- {viewMode === 'table' && (- <MainCard content={false}>- <ScrollArea className="h-[600px]">- <Table>- <TableHeader className="sticky top-0 bg-background z-10">- <TableRow>- <TableHead className="w-10">#</TableHead>- <TableHead className="w-16" />- <TableHead><SortButton field="title" label="Video" sortField={sortField} sortOrder={sortOrder} onSort={handleSort} /></TableHead>- {channels.length > 1 && <TableHead>Channel</TableHead>}- <TableHead className="text-right"><SortButton field="viewCount" label="Views" sortField={sortField} sortOrder={sortOrder} onSort={handleSort} /></TableHead>- <TableHead className="text-right"><SortButton field="likeCount" label="Likes" sortField={sortField} sortOrder={sortOrder} onSort={handleSort} /></TableHead>- <TableHead className="text-right"><SortButton field="commentCount" label="Comments" sortField={sortField} sortOrder={sortOrder} onSort={handleSort} /></TableHead>- <TableHead className="text-right"><SortButton field="engagementRate" label="Eng%" sortField={sortField} sortOrder={sortOrder} onSort={handleSort} /></TableHead>- <TableHead className="text-right"><SortButton field="durationSeconds" label="Duration" sortField={sortField} sortOrder={sortOrder} onSort={handleSort} /></TableHead>- <TableHead className="text-right"><SortButton field="publishedAt" label="Published" sortField={sortField} sortOrder={sortOrder} onSort={handleSort} /></TableHead>- <TableHead className="w-10" />+ {filtered.length === 0 ? (+ <SurfaceBox>+ <EmptyState+ compact+ icon={<PlaySquare />}+ title="No videos match"+ description="Clear the search or choose a different view range."+ action={<Button variant="outline" size="sm" onClick={() => { setSearch(''); setTier('all'); setChannelFilter('all'); setPage(1); }}>Clear filters</Button>}+ />+ </SurfaceBox>+ ) : viewMode === 'table' ? (+ <SurfaceBox content={false} className="overflow-hidden">+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead className="w-10 text-right">#</TableHead>+ <TableHead><SortHeader field="title" label="Video" sort={sort} onSort={handleSort} /></TableHead>+ {channels.length > 1 && <TableHead>Channel</TableHead>}+ <TableHead className="text-right"><SortHeader field="viewCount" label="Views" sort={sort} onSort={handleSort} align="right" /></TableHead>+ <TableHead className="text-right"><SortHeader field="likeCount" label="Likes" sort={sort} onSort={handleSort} align="right" /></TableHead>+ <TableHead className="text-right"><SortHeader field="commentCount" label="Comments" sort={sort} onSort={handleSort} align="right" /></TableHead>+ <TableHead className="text-right"><SortHeader field="engagementRate" label="Engagement" sort={sort} onSort={handleSort} align="right" /></TableHead>+ <TableHead className="text-right"><SortHeader field="durationSeconds" label="Length" sort={sort} onSort={handleSort} align="right" /></TableHead>+ <TableHead className="text-right"><SortHeader field="publishedAt" label="Published" sort={sort} onSort={handleSort} align="right" /></TableHead>+ <TableHead className="w-10"><span className="sr-only">Watch</span></TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {paged.items.map((v, i) => (+ <TableRow key={`${v.videoId}-${i}`}>+ <TableCell className="text-right font-mono text-caption text-ink-faint">{paged.offset + i + 1}</TableCell>+ <TableCell>+ <div className="flex items-center gap-3">+ {v.thumbnail+ ? <img src={v.thumbnail} alt="" loading="lazy" className="h-9 w-16 shrink-0 rounded-sm object-cover" />+ : <span className="h-9 w-16 shrink-0 rounded-sm bg-surface-sunken" />}+ <a href={watchUrl(v.videoId)} target="_blank" rel="noopener noreferrer" className="max-w-[18rem] truncate text-sm font-medium text-ink hover:underline">+ {v.title}+ </a>+ </div>+ </TableCell>+ {channels.length > 1 && <TableCell className="max-w-36 truncate text-small text-ink-muted">{v.channelTitle}</TableCell>}+ <TableCell className="text-right font-semibold text-ink">{fmtNum(v.viewCount)}</TableCell>+ <TableCell className="text-right text-ink-muted">{fmtNum(v.likeCount)}</TableCell>+ <TableCell className="text-right text-ink-muted">{fmtNum(v.commentCount)}</TableCell>+ <TableCell className="text-right">+ <Badge variant={parseFloat(v.engagementRate) > 5 ? 'success' : 'secondary'}>{fmtPercent(v.engagementRate)}</Badge>+ </TableCell>+ <TableCell className="text-right text-ink-muted">{fmtDuration(v.durationSeconds)}</TableCell>+ <TableCell className="text-right text-small text-ink-faint">{fmtDate(v.publishedAt)}</TableCell>+ <TableCell>+ <Tooltip>+ <TooltipTrigger render={<Button variant="ghost" size="icon-xs" render={<a href={watchUrl(v.videoId)} target="_blank" rel="noopener noreferrer" aria-label={`Watch ${v.title} on YouTube`} />} />}>+ <Play />+ </TooltipTrigger>+ <TooltipContent>Watch on YouTube</TooltipContent>+ </Tooltip>+ </TableCell></TableRow>- </TableHeader>- <TableBody>- {paginatedVideos.map((v, i) => (- <TableRow- key={`${v.videoId}-${i}`}- className="cursor-pointer"- onClick={() => window.open(`https://www.youtube.com/watch?v=${v.videoId}`, '_blank', 'noopener')}- >- <TableCell className="text-xs text-muted-foreground">{(page - 1) * ITEMS_PER_PAGE + i + 1}</TableCell>- <TableCell>- {v.thumbnail && (- <img src={v.thumbnail} className="w-16 h-9 object-cover rounded" alt="" />- )}- </TableCell>- <TableCell>- <p className="text-sm font-medium max-w-[280px] truncate">{v.title}</p>- </TableCell>- {channels.length > 1 && (- <TableCell>- <Badge variant="outline" className="text-xs max-w-28 truncate">{v.channelTitle}</Badge>- </TableCell>- )}- <TableCell className="text-right text-sm font-semibold">{fmtNum(v.viewCount)}</TableCell>- <TableCell className="text-right text-sm">{fmtNum(v.likeCount)}</TableCell>- <TableCell className="text-right text-sm">{fmtNum(v.commentCount)}</TableCell>- <TableCell className="text-right">- <Badge variant="outline" className={cn('text-xs', parseFloat(v.engagementRate) > 5 ? 'border-green-200 bg-green-50 text-green-700' : '')}>- {fmtPercent(v.engagementRate)}- </Badge>- </TableCell>- <TableCell className="text-right text-sm">{fmtDuration(v.durationSeconds)}</TableCell>- <TableCell className="text-right text-xs text-muted-foreground">{fmtDate(v.publishedAt)}</TableCell>- <TableCell>- <Tooltip>- <TooltipTrigger render={<Button variant="ghost" size="icon" className="size-7 text-red-500 hover:text-red-600 hover:bg-red-50" onClick={e => { e.stopPropagation(); window.open(`https://www.youtube.com/watch?v=${v.videoId}`, '_blank', 'noopener'); }} />}>- <Play />- </TooltipTrigger>- <TooltipContent>Watch on YouTube</TooltipContent>- </Tooltip>- </TableCell>- </TableRow>- ))}- </TableBody>- </Table>- </ScrollArea>- </MainCard>- )}-- {/* Grid view */}- {viewMode === 'grid' && (- <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 xl:grid-cols-4 gap-4">- {paginatedVideos.map((v, i) => (- <div+ ))}+ </TableBody>+ </Table>+ </SurfaceBox>+ ) : (+ <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 md:grid-cols-3 xl:grid-cols-4">+ {paged.items.map((v, i) => (+ <MediaCardkey={`${v.videoId}-${i}`}- className="border border-border rounded-xl overflow-hidden cursor-pointer hover:shadow-md transition-shadow bg-card group"- onClick={() => window.open(`https://www.youtube.com/watch?v=${v.videoId}`, '_blank', 'noopener')}- >- <div className="relative">- {v.thumbnail- ? <img src={v.thumbnail} className="w-full aspect-video object-cover" alt="" />- : <div className="w-full aspect-video bg-muted flex items-center justify-center"><Tv className="h-8 w-8 text-muted-foreground" /></div>}- {v.durationSeconds > 0 && (- <span className="absolute bottom-1.5 right-1.5 bg-black/80 text-white text-[10px] font-semibold px-1.5 py-0.5 rounded">{fmtDuration(v.durationSeconds)}</span>- )}- <span className="absolute top-1.5 right-1.5 flex items-center gap-1 bg-black/75 text-white text-[10px] font-semibold px-1.5 py-0.5 rounded">- <Eye className="h-2.5 w-2.5" />{fmtNum(v.viewCount)}- </span>- </div>- <div className="p-3 space-y-1.5">- <p className="text-xs font-semibold leading-snug line-clamp-2">{v.title}</p>- {channels.length > 1 && <p className="text-[10px] text-muted-foreground">{v.channelTitle}</p>}- <div className="flex items-center gap-3 text-muted-foreground text-[11px]">- <span className="flex items-center gap-0.5"><ThumbsUp className="h-2.5 w-2.5" />{fmtNum(v.likeCount)}</span>- <span className="flex items-center gap-0.5"><MessageSquare className="h-2.5 w-2.5" />{fmtNum(v.commentCount)}</span>- <span className="ml-auto">{timeAgo(v.publishedAt)}</span>- </div>- </div>- </div>+ href={watchUrl(v.videoId)}+ image={v.thumbnail}+ title={v.title}+ topRight={<MediaChip><Eye />{fmtNum(v.viewCount)}</MediaChip>}+ bottomRight={v.durationSeconds > 0 && <MediaChip>{fmtDuration(v.durationSeconds)}</MediaChip>}+ meta={+ <>+ <span className="flex items-center gap-1"><ThumbsUp />{fmtNum(v.likeCount)}</span>+ <span className="flex items-center gap-1"><MessageSquare />{fmtNum(v.commentCount)}</span>+ <span className="ml-auto">{channels.length > 1 ? v.channelTitle : timeAgo(v.publishedAt)}</span>+ </>+ }+ />))}</div>)}- {/* Empty state */}- {filteredVideos.length === 0 && !loading && (- <MainCard>- <Empty>- <EmptyMedia><Tv className="size-10 text-muted-foreground/40" /></EmptyMedia>- <EmptyHeader>- <EmptyTitle>No videos found</EmptyTitle>- <EmptyDescription>- {accounts?.length === 0 ? 'Add a channel first to explore videos' : 'Try adjusting your filters'}- </EmptyDescription>- </EmptyHeader>- </Empty>- </MainCard>- )}-- {/* Pagination */}- {pageCount > 1 && (- <div className="flex items-center justify-center gap-2">- <Button variant="outline" size="sm" onClick={() => setPage(p => Math.max(1, p - 1))} disabled={page === 1}>Previous</Button>- <span className="text-sm text-muted-foreground px-2">Page {page} of {pageCount}</span>- <Button variant="outline" size="sm" onClick={() => setPage(p => Math.min(pageCount, p + 1))} disabled={page === pageCount}>Next</Button>- </div>- )}+ <Pager page={paged.page} pageCount={paged.pageCount} onPageChange={setPage} total={filtered.length} shown={paged.items.length} noun="videos" /></div>);}diff --git a/frontend/src/features/analytics/videos/useChannelVideos.js b/frontend/src/features/analytics/videos/useChannelVideos.jsnew file mode 100644index 0000000..42615dc--- /dev/null+++ b/frontend/src/features/analytics/videos/useChannelVideos.js@@ -0,0 +1,50 @@+import { useCallback, useEffect, useState } from 'react';+import { api } from '../../../services/api';+import { useAppContext } from '../../../context/AppContext';+import { platformOf } from '@/lib/accounts';+import { engagementPercent, parseIsoDuration } from '@/lib/library';++// Loads every video from every YouTube channel. Shared by the Videos and Shorts pages.+export function useChannelVideos() {+ const { accounts, showToast } = useAppContext();+ const [videos, setVideos] = useState([]);+ const [channels, setChannels] = useState([]);+ const [loading, setLoading] = useState(true);++ const load = useCallback(async () => {+ setLoading(true);+ try {+ const channelAccounts = (accounts || []).filter(a => platformOf(a) === 'youtube');+ const results = await Promise.allSettled(channelAccounts.map(a => api.getVideos(a.id)));+ const allVideos = [];+ const channelList = [];+ results.forEach((result, i) => {+ if (result.status !== 'fulfilled') return;+ const acct = channelAccounts[i];+ const res = result.value;+ const channelTitle = acct.title || acct.channelTitle || 'Unknown channel';+ channelList.push({ id: acct.id, title: channelTitle, account: acct });+ for (const v of res.videos || res.data?.videos || []) {+ allVideos.push({+ ...v,+ thumbnail: v.thumbnail || v.thumbnails?.medium || v.thumbnails?.high || v.thumbnails?.default || '',+ channelTitle,+ channelId: acct.id,+ engagementRate: engagementPercent(v.viewCount, v.likeCount, v.commentCount),+ durationSeconds: v.durationSeconds || parseIsoDuration(v.duration),+ });+ }+ });+ setVideos(allVideos);+ setChannels(channelList);+ } catch (err) {+ showToast(`Couldn't load videos. ${err.message}`, 'error');+ } finally {+ setLoading(false);+ }+ }, [accounts, showToast]);++ useEffect(() => { load(); }, [load]);++ return { videos, channels, loading, reload: load };+}diff --git a/frontend/src/features/publishing/UploadContent.jsx b/frontend/src/features/publishing/UploadContent.jsxindex 8ea8ad0..31faea0 100644--- a/frontend/src/features/publishing/UploadContent.jsx+++ b/frontend/src/features/publishing/UploadContent.jsx@@ -1,81 +1,163 @@import React, { useState, useEffect, useRef } from 'react';+import { Link } from 'react-router-dom';+import {+ Upload, Image as ImageIcon, Film, BookOpen, Trash2, CheckCircle2, AlertCircle, Calendar, Send, X, Plus,+ Copy, Square, UserPlus, MapPin, AtSign, Music, Clock, FolderUp, ExternalLink, Pencil, RefreshCw, Info, Camera,+} from 'lucide-react';import { Button } from '@/components/ui/button';import { Input } from '@/components/ui/input';-import { Label } from '@/components/ui/label';import { Badge } from '@/components/ui/badge';import { Textarea } from '@/components/ui/textarea';-import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';import { Progress } from '@/components/ui/progress';import { Alert, AlertDescription } from '@/components/ui/alert';-import { Separator } from '@/components/ui/separator';import { Switch } from '@/components/ui/switch';import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';-import {- AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent,- AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle,-} from '@/components/ui/alert-dialog';-import {- Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue,-} from '@/components/ui/select';+import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';import { Spinner } from '@/components/ui/spinner';-import {- Table, TableBody, TableCell, TableHead, TableHeader, TableRow,-} from '@/components/ui/table';+import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';-import {- Upload, Camera, Image as ImageIcon, Film, BookOpen, Trash2,- CheckCircle2, AlertCircle, Calendar, Send, X, Plus, Copy, Square,- UserPlus, MapPin, AtSign, Music, Clock, FolderUp,- ExternalLink, Pencil, Trash,-} from 'lucide-react';-import MainCard from '../../components/MainCard';+import PageHeader from '@/components/PageHeader';+import SurfaceBox from '@/components/SurfaceBox';+import DetailPanel, { FieldRow } from '@/components/DetailPanel';+import FilterChips from '@/components/FilterChips';+import ConfirmDialog from '@/components/ConfirmDialog';+import { EmptyState } from '@/components/StateViews';+import { AccountAvatar } from '@/components/platform';+import { InstagramIcon } from '@/components/brand/platform-icons';import { useAppContext } from '../../context/AppContext';import { api } from '../../services/api';import { cn } from '@/lib/utils';const BULK_INTERVAL_OPTIONS = [- { value: 720, label: 'Every 12 Hours' },- { value: 1440, label: 'Once a Day' },- { value: 2880, label: 'Every 2 Days' },- { value: 4320, label: 'Every 3 Days' },- { value: 10080, label: 'Once a Week' },+ { value: 720, label: 'Every 12 hours' },+ { value: 1440, label: 'Once a day' },+ { value: 2880, label: 'Every 2 days' },+ { value: 4320, label: 'Every 3 days' },+ { value: 10080, label: 'Once a week' },];const CONTENT_TYPES = [- { value: 'IMAGE', label: 'Photo', icon: ImageIcon, color: '#F58529', accept: 'image/jpeg', desc: 'JPEG, 4:5 to 1.91:1, max 8MB' },- { value: 'REELS', label: 'Reel', icon: Film, color: '#DD2A7B', accept: 'video/mp4,video/quicktime', desc: 'MP4/MOV 9:16, 3s-15min, max 300MB' },- { value: 'STORIES', label: 'Story', icon: BookOpen, color: '#8134AF', accept: 'image/jpeg,video/mp4,video/quicktime', desc: 'Image or video, 9:16, max 60s' },+ { value: 'IMAGE', label: 'Photo', icon: ImageIcon, accept: 'image/jpeg', desc: 'JPEG, 4:5 to 1.91:1, up to 8MB' },+ { value: 'REELS', label: 'Reel', icon: Film, accept: 'video/mp4,video/quicktime', desc: 'MP4 or MOV, 9:16, 3 seconds to 15 minutes, up to 300MB' },+ { value: 'STORIES', label: 'Story', icon: BookOpen, accept: 'image/jpeg,video/mp4,video/quicktime', desc: 'Image or video, 9:16, up to 60 seconds' },];-const PUBLISH_STEPS = ['Select Media', 'Configure', 'Upload & Publish'];--const STATUS_CHIP_MAP = {- published: { label: 'Published', cls: 'bg-green-50 border-green-200 text-green-700' },- failed: { label: 'Failed', cls: 'bg-red-50 border-red-200 text-red-700' },- publishing: { label: 'Publishing…', cls: 'bg-orange-50 border-orange-200 text-orange-700' },- pending: { label: 'Pending', cls: 'bg-amber-50 border-amber-200 text-amber-700' },+const POST_STATUS = {+ published: { label: 'Published', variant: 'success' },+ failed: { label: 'Failed', variant: 'destructive' },+ publishing: { label: 'Publishing', variant: 'info' },+ pending: { label: 'Pending', variant: 'warning' },};-const BULK_STATUS_MAP = {- pending: { label: 'Pending', cls: 'bg-muted text-muted-foreground' },- uploading: { label: 'Uploading…', cls: 'bg-blue-50 border-blue-200 text-blue-700' },- creating: { label: 'Creating…', cls: 'bg-pink-50 border-pink-200 text-pink-700' },- processing: { label: 'Processing…', cls: 'bg-purple-50 border-purple-200 text-purple-700' },- publishing: { label: 'Publishing…', cls: 'bg-orange-50 border-orange-200 text-orange-700' },- scheduling: { label: 'Scheduling…', cls: 'bg-orange-50 border-orange-200 text-orange-700' },- done: { label: 'Published', cls: 'bg-green-50 border-green-200 text-green-700' },- scheduled: { label: 'Scheduled', cls: 'bg-amber-50 border-amber-200 text-amber-700' },- error: { label: 'Failed', cls: 'bg-red-50 border-red-200 text-red-700' },+const BULK_STATUS = {+ pending: { label: 'Pending', variant: 'secondary' },+ uploading: { label: 'Uploading', variant: 'info' },+ creating: { label: 'Creating', variant: 'info' },+ processing: { label: 'Processing', variant: 'info' },+ publishing: { label: 'Publishing', variant: 'info' },+ scheduling: { label: 'Scheduling', variant: 'info' },+ done: { label: 'Published', variant: 'success' },+ scheduled: { label: 'Scheduled', variant: 'warning' },+ error: { label: 'Failed', variant: 'destructive' },};-function StatusBadge({ status }) {- const s = STATUS_CHIP_MAP[status] || STATUS_CHIP_MAP.pending;- return <span className={cn('inline-flex items-center px-2 py-0.5 rounded-full text-xs font-semibold border', s.cls)}>{s.label}</span>;+const ACTIVE_BULK = ['uploading', 'creating', 'processing', 'publishing', 'scheduling'];+const CAPTION_LIMIT = 2200;++function StatusBadge({ status, map }) {+ const s = map[status] || Object.values(map)[0];+ return <Badge variant={s.variant}>{s.label}</Badge>;+}++function IconInput({ icon, ...props }) {+ const Icon = icon;+ return (+ <div className="relative">+ <Icon className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 stroke-[1.75] text-ink-faint" />+ <Input className="pl-9" {...props} />+ </div>+ );+}++function AccountSelect({ accounts, value, onChange, disabled }) {+ const selected = accounts.find(a => a.id === value);+ return (+ <Select value={value} onValueChange={onChange} disabled={disabled}>+ <SelectTrigger className="h-(--control-h-lg) w-full" aria-label="Instagram account">+ {selected ? (+ <span className="flex min-w-0 items-center gap-2">+ <AccountAvatar account={selected} size="xs" />+ <span className="truncate text-sm">{selected.title || selected.username}</span>+ {selected.username && <span className="shrink-0 text-caption text-ink-faint">@{selected.username}</span>}+ </span>+ ) : (+ <SelectValue placeholder="Choose an account" />+ )}+ </SelectTrigger>+ <SelectContent>+ <SelectGroup>+ {accounts.map(a => (+ <SelectItem key={a.id} value={a.id}>+ <span className="flex items-center gap-2">+ <AccountAvatar account={a} size="xs" />+ <span className="truncate text-sm font-medium">{a.title || a.username}</span>+ {a.username && <span className="shrink-0 text-caption text-ink-faint">@{a.username}</span>}+ </span>+ </SelectItem>+ ))}+ </SelectGroup>+ </SelectContent>+ </Select>+ );+}++function TypePicker({ value, onChange, disabled }) {+ return (+ <div role="radiogroup" aria-label="Content type" className="grid grid-cols-3 gap-2">+ {CONTENT_TYPES.map(t => {+ const Icon = t.icon;+ const active = value === t.value;+ return (+ <button+ key={t.value}+ type="button"+ role="radio"+ aria-checked={active}+ disabled={disabled}+ onClick={() => onChange(t.value)}+ className={cn(+ 'flex flex-col items-center gap-1.5 rounded-field border px-2 py-3 text-center transition-colors duration-(--duration-fast)',+ 'focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring disabled:cursor-not-allowed disabled:opacity-50',+ active ? 'border-brand bg-brand-soft/50 text-brand-text' : 'border-line-control text-ink-muted hover:bg-surface-hover hover:text-ink',+ )}+ >+ <Icon className="size-5 stroke-[1.75]" />+ <span className="text-small font-semibold">{t.label}</span>+ </button>+ );+ })}+ </div>+ );+}++function ScheduleToggle({ scheduled, onChange, disabled, nowLabel = 'Publish now', laterLabel = 'Schedule' }) {+ return (+ <Tabs value={scheduled ? 'later' : 'now'} onValueChange={v => onChange(v === 'later')}>+ <TabsList variant="segmented" className="w-full">+ <TabsTrigger value="now" disabled={disabled}><Send />{nowLabel}</TabsTrigger>+ <TabsTrigger value="later" disabled={disabled}><Calendar />{laterLabel}</TabsTrigger>+ </TabsList>+ </Tabs>+ );}-function BulkStatusBadge({ status }) {- const s = BULK_STATUS_MAP[status] || BULK_STATUS_MAP.pending;- return <span className={cn('inline-flex items-center px-2 py-0.5 rounded-full text-xs font-semibold border', s.cls)}>{s.label}</span>;+function SummaryRow({ label, children }) {+ return (+ <div className="flex items-center justify-between gap-3 text-small">+ <span className="text-ink-faint">{label}</span>+ <span className="min-w-0 truncate font-medium text-ink">{children}</span>+ </div>+ );}export default function UploadContent() {@@ -110,8 +192,9 @@ export default function UploadContent() {const [editTime, setEditTime] = useState('');const [savingEdit, setSavingEdit] = useState(false);- const [confirmDeleteId, setConfirmDeleteId] = useState(null);+ const [pendingDelete, setPendingDelete] = useState(null);const [confirmDeleteAll, setConfirmDeleteAll] = useState(false);+ const [deleting, setDeleting] = useState(false);const [activeStep, setActiveStep] = useState(0);const [uploading, setUploading] = useState(false);@@ -140,7 +223,6 @@ export default function UploadContent() {const [bulkStartTime, setBulkStartTime] = useState('');const [bulkInterval, setBulkInterval] = useState(1440);const [bulkProcessing, setBulkProcessing] = useState(false);- const [bulkCancelled, setBulkCancelled] = useState(false);useEffect(() => {const ig = (accounts || []).filter(a => a.platform === 'instagram');@@ -154,24 +236,28 @@ export default function UploadContent() {try {const res = await api.getScheduledPosts();if (res.success) setScheduledPosts(res.posts || []);- } catch { }+ } catch {+ // The schedule list is secondary; publishing still works without it+ }};const loadCloudinaryConfig = async () => {try {const res = await api.getCloudinaryConfig();if (res.success) setCloudConfig(res);- } catch { }+ } catch {+ // A missing config is shown as an alert on the page+ }};- const handleFileSelect = (e) => {+ const handleFileSelect = e => {const f = e.target.files?.[0];if (!f) return;setFile(f);setFilePreview(URL.createObjectURL(f));};- const handleCoverSelect = (e) => {+ const handleCoverSelect = e => {const f = e.target.files?.[0];if (!f) return;setCoverFile(f);@@ -190,8 +276,8 @@ export default function UploadContent() {setScheduleDate(''); setScheduleTime('');};- const uploadToCloudinary = async (fileToUpload) => {- if (!cloudConfig) throw new Error('Cloudinary not configured. Go to Settings.');+ const uploadToCloudinary = async fileToUpload => {+ if (!cloudConfig) throw new Error('Cloudinary is not set up on the server. Check Settings.');const formData = new FormData();formData.append('file', fileToUpload);formData.append('upload_preset', cloudConfig.uploadPreset);@@ -203,7 +289,7 @@ export default function UploadContent() {if (xhr.status >= 200 && xhr.status < 300) { resolve(JSON.parse(xhr.responseText).secure_url); }else { try { reject(new Error(JSON.parse(xhr.responseText).error?.message || 'Upload failed')); } catch { reject(new Error('Upload failed')); } }});- xhr.addEventListener('error', () => reject(new Error('Network error')));+ xhr.addEventListener('error', () => reject(new Error('The upload lost its network connection. Check your connection and try again.')));xhr.open('POST', `https://api.cloudinary.com/v1_1/${cloudConfig.cloudName}/${resourceType}/upload`);xhr.send(formData);});@@ -214,77 +300,76 @@ export default function UploadContent() {await new Promise(r => setTimeout(r, 3000));try {const status = await api.getIGContainerStatus(containerId, accountId);- setStatusMessage(`Processing: ${status.statusCode || 'IN_PROGRESS'}…`);+ setStatusMessage(`Instagram status: ${status.statusCode || 'IN_PROGRESS'}`);if (status.statusCode === 'FINISHED' || status.statusCode === 'PUBLISHED') return true;if (status.statusCode === 'ERROR') throw new Error('Container processing failed: ' + (status.status || 'Unknown'));if (status.statusCode === 'EXPIRED') throw new Error('Container expired');} catch (err) { if (err.message.includes('processing failed') || err.message.includes('expired')) throw err; }}- throw new Error('Timed out waiting for media processing');+ throw new Error('Instagram took too long to process the media. Try again in a few minutes.');};- const parseUserTags = (str) => str.split(',').map(s => {+ const parseUserTags = str => str.split(',').map(s => {const parts = s.trim().replace(/^@/, '').split(/\s+/);return { username: parts[0], x: parts[1] ? parseFloat(parts[1]) : 0.5, y: parts[2] ? parseFloat(parts[2]) : 0.5 };}).filter(t => t.username);const handlePublish = async () => {- if (!selectedAccount || !file || !contentType) { showToast('Select account, content type, and file', 'error'); return; }- if (!cloudConfig) { showToast('Cloudinary not configured', 'error'); return; }+ if (!selectedAccount || !file || !contentType) { showToast('Choose an account, a content type and a file before publishing.', 'error'); return; }+ if (!cloudConfig) { showToast('Cloudinary is not set up on the server. Check Settings.', 'error'); return; }if (scheduleMode) {- if (!scheduleDate || !scheduleTime) { showToast('Set schedule date and time', 'error'); return; }+ if (!scheduleDate || !scheduleTime) { showToast('Set a date and time for the scheduled post.', 'error'); return; }const scheduledAt = new Date(`${scheduleDate}T${scheduleTime}`);- if (scheduledAt <= new Date()) { showToast('Scheduled time must be in the future', 'error'); return; }+ if (scheduledAt <= new Date()) { showToast('Pick a time in the future.', 'error'); return; }setUploading(true); setPublishStatus('uploading-cloudinary'); setActiveStep(2);try {const mediaUrl = await uploadToCloudinary(file);let coverUrl = null;- if (coverFile && contentType === 'REELS') { setStatusMessage('Uploading cover…'); coverUrl = await uploadToCloudinary(coverFile); }- setPublishStatus('scheduling'); setStatusMessage('Saving scheduled post…');+ if (coverFile && contentType === 'REELS') { setStatusMessage('Uploading cover'); coverUrl = await uploadToCloudinary(coverFile); }+ setPublishStatus('scheduling'); setStatusMessage('Saving the scheduled post');const res = await api.createScheduledPost({accountId: selectedAccount, platform: 'instagram', mediaType: contentType, mediaUrl, caption: caption || '',coverUrl: coverUrl || null, shareToFeed: contentType === 'REELS' ? shareToFeed : true,collaborators: collaborators ? collaborators.split(',').map(s => s.trim()).filter(Boolean) : [],- audioName: audioName || '', thumbOffset: thumbOffset ? parseInt(thumbOffset) : null,+ audioName: audioName || '', thumbOffset: thumbOffset ? parseInt(thumbOffset, 10) : null,locationId: locationId || '', userTags: userTags ? parseUserTags(userTags) : [],altText: (contentType === 'IMAGE' && altText) ? altText : '', scheduledAt: scheduledAt.toISOString(),});if (!res.success) throw new Error(res.message || 'Failed to schedule');setPublishStatus('scheduled'); setStatusMessage(`Scheduled for ${scheduledAt.toLocaleString()}`);- showToast('Post scheduled!'); loadScheduledPosts();- } catch (err) { setPublishStatus('error'); setStatusMessage(err.message); showToast('Schedule failed: ' + err.message, 'error'); }+ showToast('Post scheduled'); loadScheduledPosts();+ } catch (err) { setPublishStatus('error'); setStatusMessage(err.message); showToast(`Scheduling failed. ${err.message}`, 'error'); }finally { setUploading(false); }return;}- setUploading(true); setPublishStatus('uploading-cloudinary'); setStatusMessage('Uploading to CDN…'); setActiveStep(2);+ setUploading(true); setPublishStatus('uploading-cloudinary'); setStatusMessage('Uploading media'); setActiveStep(2);try {const mediaUrl = await uploadToCloudinary(file);let coverUrl = null;- if (coverFile && contentType === 'REELS') { setStatusMessage('Uploading cover…'); coverUrl = await uploadToCloudinary(coverFile); }- setPublishStatus('creating-container'); setStatusMessage('Creating Instagram container…');+ if (coverFile && contentType === 'REELS') { setStatusMessage('Uploading cover'); coverUrl = await uploadToCloudinary(coverFile); }+ setPublishStatus('creating-container'); setStatusMessage('Creating the Instagram media container');const containerRes = await api.createIGContainer(selectedAccount, {mediaType: contentType, mediaUrl, caption: caption || undefined, coverUrl: coverUrl || undefined,shareToFeed: contentType === 'REELS' ? shareToFeed : undefined,collaborators: collaborators ? collaborators.split(',').map(s => s.trim()).filter(Boolean) : undefined,- audioName: audioName || undefined, thumbOffset: thumbOffset ? parseInt(thumbOffset) : undefined,+ audioName: audioName || undefined, thumbOffset: thumbOffset ? parseInt(thumbOffset, 10) : undefined,locationId: locationId || undefined, userTags: userTags ? parseUserTags(userTags) : undefined,altText: (contentType === 'IMAGE' && altText) ? altText : undefined,});if (!containerRes.success || !containerRes.containerId) throw new Error(containerRes.message || 'Failed to create container');- if (contentType === 'REELS' || contentType === 'STORIES') { setPublishStatus('processing'); setStatusMessage('Instagram is processing…'); await waitForContainer(containerRes.containerId, selectedAccount); }+ if (contentType === 'REELS' || contentType === 'STORIES') { setPublishStatus('processing'); setStatusMessage('Instagram is processing the media'); await waitForContainer(containerRes.containerId, selectedAccount); }else { await new Promise(r => setTimeout(r, 2000)); }- setPublishStatus('publishing'); setStatusMessage('Publishing to Instagram…');+ setPublishStatus('publishing'); setStatusMessage('Publishing to Instagram');const publishRes = await api.publishIGContainer(selectedAccount, containerRes.containerId);if (!publishRes.success || !publishRes.mediaId) throw new Error(publishRes.message || 'Publish failed');- setPublishStatus('done'); setPublishedMediaId(publishRes.mediaId); setStatusMessage('Published successfully!');- showToast('Content published to Instagram!');- } catch (err) { setPublishStatus('error'); setStatusMessage(err.message); showToast('Publish failed: ' + err.message, 'error'); }+ setPublishStatus('done'); setPublishedMediaId(publishRes.mediaId); setStatusMessage('Published');+ showToast('Published to Instagram');+ } catch (err) { setPublishStatus('error'); setStatusMessage(err.message); showToast(`Publishing failed. ${err.message}`, 'error'); }finally { setUploading(false); }};- // Bulk upload- const handleBulkFilesSelect = (e) => {+ const handleBulkFilesSelect = e => {const files = Array.from(e.target.files || []);if (!files.length) return;const newItems = files.map(f => ({ id: ++bulkIdCounter.current, file: f, preview: URL.createObjectURL(f), caption: '', status: 'pending', progress: 0, error: null, mediaId: null }));@@ -296,7 +381,7 @@ export default function UploadContent() {if (bulkFileInputRef.current) bulkFileInputRef.current.value = '';};- const removeBulkFile = (id) => {+ const removeBulkFile = id => {setBulkFiles(prev => { const item = prev.find(f => f.id === id); if (item?.preview) URL.revokeObjectURL(item.preview); return prev.filter(f => f.id !== id); });};@@ -304,15 +389,15 @@ export default function UploadContent() {const applySharedCaption = () => { if (!bulkSharedCaption) return; setBulkFiles(prev => prev.map(f => f.status === 'pending' ? { ...f, caption: bulkSharedCaption } : f)); };- const clearBulkFiles = () => { bulkFiles.forEach(f => { if (f.preview) URL.revokeObjectURL(f.preview); }); setBulkFiles([]); setBulkProcessing(false); setBulkCancelled(false); bulkCancelRef.current = false; };+ const clearBulkFiles = () => { bulkFiles.forEach(f => { if (f.preview) URL.revokeObjectURL(f.preview); }); setBulkFiles([]); setBulkProcessing(false); bulkCancelRef.current = false; };const handleBulkProcess = async () => {- if (!bulkAccount || bulkFiles.length === 0 || !bulkContentType) { showToast('Select account, type, and files', 'error'); return; }- if (!cloudConfig) { showToast('Cloudinary not configured', 'error'); return; }- if (bulkScheduleMode && (!bulkStartDate || !bulkStartTime)) { showToast('Set start date and time', 'error'); return; }+ if (!bulkAccount || bulkFiles.length === 0 || !bulkContentType) { showToast('Choose an account, a content type and at least one file.', 'error'); return; }+ if (!cloudConfig) { showToast('Cloudinary is not set up on the server. Check Settings.', 'error'); return; }+ if (bulkScheduleMode && (!bulkStartDate || !bulkStartTime)) { showToast('Set a start date and time for the schedule.', 'error'); return; }const baseTime = bulkScheduleMode ? new Date(`${bulkStartDate}T${bulkStartTime}`) : null;- if (baseTime && baseTime <= new Date()) { showToast('Start time must be in the future', 'error'); return; }- setBulkProcessing(true); setBulkCancelled(false); bulkCancelRef.current = false;+ if (baseTime && baseTime <= new Date()) { showToast('Pick a start time in the future.', 'error'); return; }+ setBulkProcessing(true); bulkCancelRef.current = false;const pendingFiles = bulkFiles.filter(f => f.status === 'pending');let scheduleOffset = 0, successCount = 0, failCount = 0;for (let i = 0; i < pendingFiles.length; i++) {@@ -326,7 +411,7 @@ export default function UploadContent() {const mediaUrl = await new Promise((resolve, reject) => {xhr.upload.addEventListener('progress', e => { if (e.lengthComputable) setBulkFiles(prev => prev.map(f => f.id === item.id ? { ...f, progress: Math.round(e.loaded / e.total * 100) } : f)); });xhr.addEventListener('load', () => { if (xhr.status >= 200 && xhr.status < 300) resolve(JSON.parse(xhr.responseText).secure_url); else reject(new Error('Upload failed')); });- xhr.addEventListener('error', () => reject(new Error('Network error')));+ xhr.addEventListener('error', () => reject(new Error('The upload lost its network connection')));xhr.open('POST', `https://api.cloudinary.com/v1_1/${cloudConfig.cloudName}/${rtype}/upload`); xhr.send(formData);});if (bulkCancelRef.current) break;@@ -357,21 +442,26 @@ export default function UploadContent() {if (i < pendingFiles.length - 1 && !bulkCancelRef.current) await new Promise(r => setTimeout(r, 2000));}setBulkProcessing(false);- if (bulkCancelRef.current) { showToast('Bulk upload cancelled', 'warning'); }- else { showToast(`Bulk complete: ${successCount} succeeded, ${failCount} failed`, successCount > 0 ? 'success' : 'error'); if (bulkScheduleMode) loadScheduledPosts(); }+ if (bulkCancelRef.current) { showToast('Bulk upload stopped. Files already processed keep their status.', 'warning'); }+ else { showToast(`Bulk upload finished: ${successCount} succeeded, ${failCount} failed`, successCount > 0 ? 'success' : 'error'); if (bulkScheduleMode) loadScheduledPosts(); }};- const handleDeleteScheduled = async (id) => {- try { await api.deleteScheduledPost(id); showToast('Post removed'); setConfirmDeleteId(null); loadScheduledPosts(); }- catch (err) { showToast('Delete failed: ' + err.message, 'error'); setConfirmDeleteId(null); }+ const handleDeleteScheduled = async () => {+ if (!pendingDelete) return;+ setDeleting(true);+ try { await api.deleteScheduledPost(pendingDelete.id); showToast(pendingDelete.status === 'published' ? 'Record removed' : 'Scheduled post deleted'); loadScheduledPosts(); }+ catch (err) { showToast(`Couldn't delete the post. ${err.message}`, 'error'); }+ finally { setDeleting(false); setPendingDelete(null); }};const handleDeleteAll = async () => {- try { const res = await api.deleteAllScheduledPosts(); showToast(`Deleted ${res.deleted} post(s)`); setConfirmDeleteAll(false); loadScheduledPosts(); }- catch (err) { showToast('Delete all failed: ' + err.message, 'error'); setConfirmDeleteAll(false); }+ setDeleting(true);+ try { const res = await api.deleteAllScheduledPosts(); showToast(`Deleted ${res.deleted} post${res.deleted === 1 ? '' : 's'}`); loadScheduledPosts(); }+ catch (err) { showToast(`Couldn't delete the posts. ${err.message}`, 'error'); }+ finally { setDeleting(false); setConfirmDeleteAll(false); }};- const startEditPost = (post) => {+ const startEditPost = post => {setEditingPostId(post.id); setEditCaption(post.caption || '');const dt = new Date(post.scheduledAt);setEditDate(`${dt.getFullYear()}-${String(dt.getMonth() + 1).padStart(2, '0')}-${String(dt.getDate()).padStart(2, '0')}`);@@ -380,21 +470,22 @@ export default function UploadContent() {const cancelEdit = () => { setEditingPostId(null); setEditCaption(''); setEditDate(''); setEditTime(''); };const handleSaveEdit = async () => {- if (!editingPostId || !editDate || !editTime) { showToast('Set date and time', 'error'); return; }+ if (!editingPostId || !editDate || !editTime) { showToast('Set a date and time.', 'error'); return; }const scheduledAt = new Date(`${editDate}T${editTime}`);- if (scheduledAt <= new Date()) { showToast('Scheduled time must be in the future', 'error'); return; }+ if (scheduledAt <= new Date()) { showToast('Pick a time in the future.', 'error'); return; }setSavingEdit(true);try {const res = await api.updateScheduledPost(editingPostId, { caption: editCaption, scheduledAt: scheduledAt.toISOString() });if (!res.success) throw new Error(res.message || 'Update failed');- showToast('Post updated & synced'); cancelEdit(); loadScheduledPosts();- } catch (err) { showToast('Update failed: ' + err.message, 'error'); }+ showToast('Scheduled post updated'); cancelEdit(); loadScheduledPosts();+ } catch (err) { showToast(`Couldn't update the post. ${err.message}`, 'error'); }finally { setSavingEdit(false); }};- const canProceed = () => { if (activeStep === 0) return !!file && !!contentType && !!selectedAccount; return true; };+ const canPublish = !!file && !!contentType && !!selectedAccount && !(scheduleMode && (!scheduleDate || !scheduleTime));const selectedAcct = igAccounts.find(a => a.id === selectedAccount);const selectedType = CONTENT_TYPES.find(t => t.value === contentType);+ const bulkType = CONTENT_TYPES.find(t => t.value === bulkContentType);const bulkStats = {total: bulkFiles.length,@@ -402,698 +493,608 @@ export default function UploadContent() {done: bulkFiles.filter(f => f.status === 'done').length,scheduled: bulkFiles.filter(f => f.status === 'scheduled').length,errors: bulkFiles.filter(f => f.status === 'error').length,- active: bulkFiles.filter(f => ['uploading','creating','processing','publishing','scheduling'].includes(f.status)).length,};- const fmtLocalDate = (iso) => iso ? new Date(iso).toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' }) : '-';-- const sPostsCounts = {- all: scheduledPosts.length,- pending: scheduledPosts.filter(p => p.status === 'pending').length,- publishing: scheduledPosts.filter(p => p.status === 'publishing').length,- published: scheduledPosts.filter(p => p.status === 'published').length,- failed: scheduledPosts.filter(p => p.status === 'failed').length,- };- const filteredScheduled = scheduledPosts.filter(p => statusFilter === 'all' || p.status === statusFilter).sort((a, b) => new Date(b.scheduledAt) - new Date(a.scheduledAt));+ const fmtLocalDate = iso => iso ? new Date(iso).toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' }) : '-';+ const today = new Date().toISOString().split('T')[0];++ const statusChips = [+ { value: 'all', label: 'All', count: scheduledPosts.length },+ { value: 'pending', label: 'Pending', count: scheduledPosts.filter(p => p.status === 'pending').length },+ { value: 'publishing', label: 'Publishing', count: scheduledPosts.filter(p => p.status === 'publishing').length },+ { value: 'published', label: 'Published', count: scheduledPosts.filter(p => p.status === 'published').length },+ { value: 'failed', label: 'Failed', count: scheduledPosts.filter(p => p.status === 'failed').length },+ ];+ const filteredScheduled = scheduledPosts+ .filter(p => statusFilter === 'all' || p.status === statusFilter)+ .sort((a, b) => new Date(b.scheduledAt) - new Date(a.scheduledAt));++ const intervalText = bulkInterval >= 1440 ? `${bulkInterval / 1440} day${bulkInterval > 1440 ? 's' : ''}` : `${bulkInterval / 60} hours`;++ if (igAccounts.length === 0) {+ return (+ <div className="flex flex-col gap-6">+ <PageHeader title="Publish" description="Post and schedule photos, Reels and Stories to Instagram." />+ <SurfaceBox>+ <EmptyState+ icon={<InstagramIcon />}+ title="Connect an Instagram account to publish"+ description="Publishing works with Instagram Business and Creator accounts. YouTube publishing is not available yet."+ action={<Button render={<Link to="/accounts?add=1" />}><Plus data-icon="inline-start" />Add an account</Button>}+ />+ </SurfaceBox>+ </div>+ );+ }return (- <div className="space-y-5">- {/* Header */}- <div className="flex items-center justify-between gap-4 flex-wrap">- <div className="flex items-center gap-2">- <Upload className="h-7 w-7 text-pink-500" />- <h1 className="text-2xl font-bold tracking-tight">Upload Content</h1>- </div>- {publishStatus === 'done' && uploadMode === 'single' && (- <Button size="sm" onClick={resetAll} style={{ background: 'linear-gradient(135deg, #F58529, #DD2A7B, #8134AF)' }} className="text-white">Upload Another</Button>+ <div className="flex flex-col gap-6">+ <PageHeader+ title="Publish"+ description="Post and schedule photos, Reels and Stories to Instagram."+ actions={publishStatus === 'done' && uploadMode === 'single' && (+ <Button onClick={resetAll}><Plus data-icon="inline-start" />Publish another</Button>)}- </div>+ />- {igAccounts.length === 0 && (- <Alert><AlertDescription>No Instagram accounts found. Add an account in the Accounts section first.</AlertDescription></Alert>- )}{!cloudConfig && (- <Alert><AlertDescription><strong>Cloudinary CDN required</strong> - Configure it in <strong>Settings</strong> to enable uploads.</AlertDescription></Alert>+ <Alert variant="warning">+ <AlertCircle />+ <AlertDescription>+ Uploads need Cloudinary, which is not set up on the server. Instagram only accepts media from a public URL. Set the Cloudinary environment variables, then check the status in <Link to="/settings" className="font-semibold underline">Settings</Link>.+ </AlertDescription>+ </Alert>)}- {/* Mode Tabs */}- <Tabs value={uploadMode} onValueChange={setUploadMode}>+ <Tabs value={uploadMode} onValueChange={setUploadMode} className="gap-6"><TabsList>- <TabsTrigger value="single" className="gap-2"><Upload className="h-4 w-4" />Single Upload</TabsTrigger>- <TabsTrigger value="bulk" className="gap-2">- <FolderUp className="h-4 w-4" />- Bulk Upload- {bulkFiles.length > 0 && <span className="ml-1 bg-amber-500 text-white text-[10px] font-bold px-1.5 py-0.5 rounded-full">{bulkFiles.length}</span>}+ <TabsTrigger value="single"><Upload />Single post</TabsTrigger>+ <TabsTrigger value="bulk">+ <FolderUp />Bulk upload+ {bulkFiles.length > 0 && <Badge variant="solid" className="h-4 px-1.5">{bulkFiles.length}</Badge>}</TabsTrigger></TabsList>- {/* ===== SINGLE UPLOAD ===== */}- <TabsContent value="single" className="mt-4">- {/* Stepper */}- <div className="flex items-center gap-2 mb-6">- {PUBLISH_STEPS.map((label, i) => (- <React.Fragment key={label}>- <div className={cn('flex items-center gap-2 text-sm font-medium', i === activeStep ? 'text-foreground' : i < activeStep ? 'text-primary' : 'text-muted-foreground')}>- <span className={cn('h-7 w-7 rounded-full flex items-center justify-center text-xs font-bold border-2', i === activeStep ? 'border-primary bg-primary text-primary-foreground' : i < activeStep ? 'border-primary bg-primary text-primary-foreground' : 'border-muted-foreground/30')}>{i + 1}</span>- <span className="hidden sm:block">{label}</span>- </div>- {i < PUBLISH_STEPS.length - 1 && <div className={cn('flex-1 h-0.5 rounded', i < activeStep ? 'bg-primary' : 'bg-border')} />}- </React.Fragment>- ))}- </div>-- {/* Step 0: Select Media */}- {activeStep === 0 && (- <div className="space-y-4">- <div className="grid grid-cols-1 md:grid-cols-2 gap-4">- {/* Platform & Account */}- <MainCard title="Platform & Account">- <div className="space-y-3">- <div className="flex items-center gap-2 flex-wrap">- <span className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-bold text-white" style={{ background: 'linear-gradient(135deg, #F58529, #DD2A7B, #8134AF, #515BD4)' }}>- <Camera className="h-3 w-3" /> Instagram- </span>- <span className="text-xs text-muted-foreground">YouTube coming soon</span>- </div>- <Select value={selectedAccount} onValueChange={setSelectedAccount}>- <SelectTrigger>- {selectedAcct ? (- <div className="flex items-center gap-2 min-w-0">- <Avatar className="size-5 shrink-0"><AvatarImage src={selectedAcct.profilePictureUrl || selectedAcct.thumbnailUrl} /><AvatarFallback className="text-[9px] bg-gradient-to-br from-pink-500 to-purple-600 text-white">{(selectedAcct.title || selectedAcct.username || '?')[0].toUpperCase()}</AvatarFallback></Avatar>- <span className="text-sm truncate">{selectedAcct.title || selectedAcct.username}</span>- {selectedAcct.username && <span className="text-xs text-muted-foreground shrink-0">@{selectedAcct.username}</span>}- </div>- ) : (- <SelectValue placeholder="Select account…" />- )}- </SelectTrigger>- <SelectContent>- <SelectGroup>- {igAccounts.map(a => (- <SelectItem key={a.id} value={a.id}>- <div className="flex items-center gap-2">- <Avatar className="size-5 shrink-0"><AvatarImage src={a.profilePictureUrl || a.thumbnailUrl} /><AvatarFallback className="text-[9px] bg-gradient-to-br from-pink-500 to-purple-600 text-white">{(a.title || a.username || '?')[0].toUpperCase()}</AvatarFallback></Avatar>- <span className="text-sm font-medium truncate">{a.title || a.username}</span>- {a.username && <span className="text-xs text-muted-foreground shrink-0">@{a.username}</span>}- </div>- </SelectItem>- ))}- </SelectGroup>- </SelectContent>- </Select>- </div>- </MainCard>-- {/* Content Type */}- <MainCard title="Content Type">- <div className="grid grid-cols-3 gap-2">- {CONTENT_TYPES.map(t => {- const Icon = t.icon;- return (- <button key={t.value} onClick={() => { setContentType(t.value); clearFile(); }}- className={cn('flex flex-col items-center gap-1.5 p-3 rounded-lg border-2 cursor-pointer transition-all text-center', contentType === t.value ? 'border-current' : 'border-border hover:border-muted-foreground/50')}- style={{ borderColor: contentType === t.value ? t.color : undefined, background: contentType === t.value ? `${t.color}15` : undefined }}>- <Icon className="h-5 w-5" style={{ color: t.color }} />- <span className="text-xs font-semibold">{t.label}</span>- </button>- );- })}- </div>- {selectedType && <p className="text-xs text-muted-foreground mt-2">{selectedType.desc}</p>}- </MainCard>- </div>-- {/* File Upload */}- <MainCard title="Select File">- {!file ? (- <button onClick={() => contentType && fileInputRef.current?.click()}- className={cn('w-full border-2 border-dashed rounded-xl p-10 text-center transition-all', contentType ? 'cursor-pointer hover:border-pink-500 hover:bg-pink-500/5 border-border' : 'cursor-not-allowed border-border opacity-50')}>- <Upload className="h-10 w-10 mx-auto text-muted-foreground mb-2" />- <p className="font-medium">{contentType ? 'Click to select file' : 'Choose a content type first'}</p>- {selectedType && <p className="text-xs text-muted-foreground mt-1">{selectedType.desc}</p>}- </button>- ) : (- <div className="flex gap-4 items-start">- <div className="relative w-48 flex-shrink-0 rounded-lg overflow-hidden">- {file.type.startsWith('video/') ? (- <video src={filePreview} controls muted className="w-full max-h-64 object-contain bg-black rounded-lg" />- ) : (- <img src={filePreview} className="w-full max-h-64 object-contain rounded-lg bg-muted" alt="" />- )}- <button onClick={clearFile} className="absolute top-1.5 right-1.5 h-6 w-6 rounded-full bg-black/70 text-white flex items-center justify-center hover:bg-red-500 transition-colors"><X className="h-3 w-3" /></button>- </div>- <div>- <p className="font-semibold">{file.name}</p>- <p className="text-sm text-muted-foreground">{(file.size / (1024 * 1024)).toFixed(2)} MB · {file.type}</p>- <span className="inline-block mt-2 px-2 py-0.5 rounded text-xs font-semibold border" style={{ borderColor: `${selectedType?.color}50`, color: selectedType?.color, background: `${selectedType?.color}15` }}>{selectedType?.label}</span>- </div>- </div>- )}- <input ref={fileInputRef} type="file" hidden accept={selectedType?.accept || '*'} onChange={handleFileSelect} />- </MainCard>-- <div className="flex justify-end">- <Button disabled={!canProceed()} onClick={() => setActiveStep(1)} style={{ background: 'linear-gradient(135deg, #F58529, #DD2A7B, #8134AF)' }} className="text-white px-6">Next: Configure Settings</Button>- </div>- </div>- )}-- {/* Step 1: Configure */}- {activeStep === 1 && (- <div className="space-y-4">- <div className="grid grid-cols-1 md:grid-cols-3 gap-4">- {/* Caption & Details */}- <div className="md:col-span-2">- <MainCard title="Caption & Details">- <div className="space-y-3">- <div>- <Textarea value={caption} onChange={e => setCaption(e.target.value)} placeholder="Write your caption… #hashtags @mentions" rows={4} />- <p className="text-xs text-muted-foreground mt-1">{caption.length}/2,200 characters</p>- </div>- {contentType === 'IMAGE' && (- <div className="relative"><ImageIcon className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" /><Input className="pl-9" value={altText} onChange={e => setAltText(e.target.value)} placeholder="Alt text for accessibility" /></div>- )}- <div className="relative"><UserPlus className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" /><Input className="pl-9" value={collaborators} onChange={e => setCollaborators(e.target.value)} placeholder="Collaborators (username1, username2)" /></div>- <div className="relative"><AtSign className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" /><Input className="pl-9" value={userTags} onChange={e => setUserTags(e.target.value)} placeholder="Tag users (@username1, @username2)" /></div>- <div className="relative"><MapPin className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" /><Input className="pl-9" value={locationId} onChange={e => setLocationId(e.target.value)} placeholder="Location ID (Facebook Page ID)" /></div>- </div>- </MainCard>- </div>-- {/* Settings & Summary */}- <MainCard title={contentType === 'REELS' ? 'Reel Settings' : 'Post Settings'}>- <div className="space-y-3">- {contentType === 'REELS' && (- <>- <div className="flex items-center justify-between">- <Label className="text-sm">Share to Feed</Label>- <Switch checked={shareToFeed} onCheckedChange={setShareToFeed} />- </div>- <div className="relative"><Music className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" /><Input className="pl-9" value={audioName} onChange={e => setAudioName(e.target.value)} placeholder="Audio name (optional)" /></div>- <div className="relative"><Clock className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" /><Input className="pl-9 " type="number" value={thumbOffset} onChange={e => setThumbOffset(e.target.value)} placeholder="Thumbnail offset (ms)" /></div>- <div>- <Label className="text-sm font-medium mb-1.5 block">Cover Image (optional)</Label>- {!coverFile ? (- <Button variant="outline" size="sm" onClick={() => coverInputRef.current?.click()} className="gap-2"><Camera className="h-3.5 w-3.5" />Select Cover</Button>- ) : (- <div className="flex items-center gap-2">- <img src={coverPreview} className="h-10 w-10 rounded object-cover" alt="" />- <span className="text-xs flex-1 truncate">{coverFile.name}</span>- <Button variant="ghost" size="icon" className="h-6 w-6" onClick={clearCover}><X className="h-3 w-3" /></Button>- </div>- )}- <input ref={coverInputRef} type="file" hidden accept="image/jpeg" onChange={handleCoverSelect} />- </div>- </>- )}- <Separator />- <div className="text-xs text-muted-foreground space-y-1">- <p>Account: <strong className="text-foreground">{selectedAcct?.title || selectedAcct?.username || '-'}</strong></p>- <p>Type: <strong style={{ color: selectedType?.color }}>{selectedType?.label}</strong></p>- <p>File: <strong className="text-foreground">{file?.name || '-'}</strong></p>- <p>Size: <strong className="text-foreground">{file ? `${(file.size / (1024 * 1024)).toFixed(2)} MB` : '-'}</strong></p>- {scheduleMode && scheduleDate && scheduleTime && <p>Schedule: <strong className="text-amber-600">{new Date(`${scheduleDate}T${scheduleTime}`).toLocaleString()}</strong></p>}- </div>- </div>- </MainCard>- </div>-- {/* Schedule */}- <MainCard>- <div className="flex items-center justify-between mb-3">- <div className="flex items-center gap-2"><Calendar className="h-5 w-5 text-amber-500" /><h3 className="font-semibold">Schedule for Later</h3></div>- <div className="flex items-center gap-2"><Label className="text-sm">{scheduleMode ? 'Scheduled' : 'Publish Now'}</Label><Switch checked={scheduleMode} onCheckedChange={setScheduleMode} /></div>- </div>- {scheduleMode && (- <div className="space-y-3">- <div className="flex gap-3 flex-wrap">- <Input type="date" value={scheduleDate} onChange={e => setScheduleDate(e.target.value)} min={new Date().toISOString().split('T')[0]} className="w-44" />- <Input type="time" value={scheduleTime} onChange={e => setScheduleTime(e.target.value)} className="w-36" />- {scheduleDate && scheduleTime && (- <span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-semibold bg-amber-50 border border-amber-200 text-amber-700">- <Calendar className="h-3 w-3" />{new Date(`${scheduleDate}T${scheduleTime}`).toLocaleString()}- </span>- )}- </div>- <Alert><AlertDescription><strong>Cloud Scheduling.</strong> Your file is uploaded to Cloudinary now. With <strong>GitHub Actions</strong> configured, posts publish even when your PC is off.</AlertDescription></Alert>- </div>- )}- </MainCard>-- <div className="flex justify-between">- <Button variant="outline" onClick={() => setActiveStep(0)}>Back</Button>- <Button onClick={handlePublish} disabled={uploading || (scheduleMode && (!scheduleDate || !scheduleTime))}- style={{ background: scheduleMode ? 'linear-gradient(135deg, #F58529, #FF6B35)' : 'linear-gradient(135deg, #F58529, #DD2A7B, #8134AF)' }} className="text-white gap-2 px-6">- {uploading ? <Spinner /> : (scheduleMode ? <Calendar data-icon="inline-start" /> : <Send data-icon="inline-start" />)}- {scheduleMode ? 'Schedule Post' : 'Upload & Publish Now'}- </Button>- </div>- </div>- )}-- {/* Step 2: Progress */}- {activeStep === 2 && (- <MainCard>- <div className="flex flex-col items-center text-center py-8 gap-3">+ <TabsContent value="single">+ {activeStep === 2 ? (+ <SurfaceBox>+ <div role="status" className="flex flex-col items-center gap-3 py-10 text-center">{publishStatus === 'uploading-cloudinary' && (<>- <Upload className="h-14 w-14 text-blue-500" />- <h3 className="text-lg font-bold">Uploading to CDN…</h3>- <div className="w-72"><Progress value={uploadProgress} className="h-2" /></div>- <p className="text-sm text-muted-foreground">{uploadProgress}% uploaded</p>- </>- )}- {(publishStatus === 'creating-container' || publishStatus === 'publishing' || publishStatus === 'scheduling') && (- <>- <Spinner className="size-12" />- <h3 className="text-lg font-bold">{publishStatus === 'creating-container' ? 'Creating Instagram Container…' : publishStatus === 'scheduling' ? 'Saving Schedule…' : 'Publishing…'}</h3>- <p className="text-sm text-muted-foreground">{statusMessage}</p>+ <Upload className="size-10 stroke-[1.5] text-ink-muted" />+ <h2 className="font-heading text-section font-semibold text-ink">Uploading media</h2>+ <Progress value={uploadProgress} className="w-72 max-w-full" aria-label="Upload progress" />+ <p className="text-small text-ink-muted tabular-nums">{uploadProgress}% uploaded</p></>)}- {publishStatus === 'processing' && (+ {['creating-container', 'publishing', 'scheduling', 'processing'].includes(publishStatus) && (<>- <Spinner className="size-12" />- <h3 className="text-lg font-bold">Processing Media…</h3>- <p className="text-sm text-muted-foreground">{statusMessage}</p>- <p className="text-xs text-muted-foreground">This may take a minute for videos</p>+ <Spinner className="size-10 text-brand" />+ <h2 className="font-heading text-section font-semibold text-ink">+ {publishStatus === 'creating-container' ? 'Preparing the post' : publishStatus === 'scheduling' ? 'Saving the schedule' : publishStatus === 'processing' ? 'Instagram is processing the media' : 'Publishing'}+ </h2>+ <p className="text-small text-ink-muted">{statusMessage}</p>+ {publishStatus === 'processing' && <p className="text-caption text-ink-faint">Videos can take a minute.</p>}</>)}{publishStatus === 'done' && (<>- <CheckCircle2 className="h-16 w-16 text-green-500" />- <h3 className="text-xl font-bold text-green-600">Published Successfully!</h3>- <p className="text-sm text-muted-foreground">Your {selectedType?.label?.toLowerCase()} is now live on Instagram.</p>- {publishedMediaId && <Badge variant="outline">Media ID: {publishedMediaId}</Badge>}- <div className="flex gap-2 mt-2">- <Button onClick={resetAll} style={{ background: 'linear-gradient(135deg, #F58529, #DD2A7B, #8134AF)' }} className="text-white">Upload Another</Button>- {selectedAcct?.username && <Button variant="outline" onClick={() => window.open(`https://instagram.com/${selectedAcct.username}`, '_blank')} className="gap-2"><Camera className="h-4 w-4" />View Profile</Button>}+ <span className="flex size-12 items-center justify-center rounded-full bg-success-soft text-success"><CheckCircle2 className="size-6" /></span>+ <h2 className="font-heading text-page-title font-semibold text-ink">Published</h2>+ <p className="text-sm text-ink-muted">Your {selectedType?.label?.toLowerCase()} is live on Instagram.</p>+ {publishedMediaId && <Badge variant="outline" className="font-mono">Media ID {publishedMediaId}</Badge>}+ <div className="mt-2 flex gap-2">+ <Button onClick={resetAll}><Plus data-icon="inline-start" />Publish another</Button>+ {selectedAcct?.username && (+ <Button variant="outline" render={<a href={`https://instagram.com/${selectedAcct.username}`} target="_blank" rel="noopener noreferrer" />}>+ <ExternalLink data-icon="inline-start" />View profile+ </Button>+ )}</div></>)}{publishStatus === 'scheduled' && (<>- <Calendar className="h-16 w-16 text-amber-500" />- <h3 className="text-xl font-bold text-amber-600">Post Scheduled!</h3>- <p className="text-sm text-muted-foreground">Your {selectedType?.label?.toLowerCase()} has been scheduled.</p>- <p className="font-semibold">{statusMessage}</p>- <Alert className="max-w-sm text-left"><AlertDescription>Your post is synced and will auto-publish at the scheduled time. With <strong>GitHub Actions</strong> it publishes even when your PC is off.</AlertDescription></Alert>- <div className="flex gap-2 mt-2">- <Button onClick={resetAll} style={{ background: 'linear-gradient(135deg, #F58529, #FF6B35)' }} className="text-white">Schedule Another</Button>- </div>+ <span className="flex size-12 items-center justify-center rounded-full bg-warning-soft text-warning"><Calendar className="size-6" /></span>+ <h2 className="font-heading text-page-title font-semibold text-ink">Post scheduled</h2>+ <p className="text-sm text-ink-muted">{statusMessage}</p>+ <p className="max-w-md text-small text-ink-faint">The server publishes it at that time, even when this browser is closed.</p>+ <Button onClick={resetAll} className="mt-2"><Plus data-icon="inline-start" />Schedule another</Button></>)}{publishStatus === 'error' && (<>- <AlertCircle className="h-16 w-16 text-red-500" />- <h3 className="text-xl font-bold text-red-600">{scheduleMode ? 'Schedule Failed' : 'Publish Failed'}</h3>- <p className="text-sm text-muted-foreground max-w-md">{statusMessage}</p>- <div className="flex gap-2 mt-2">- <Button onClick={() => { setActiveStep(1); setPublishStatus(''); }} style={{ background: 'linear-gradient(135deg, #F58529, #DD2A7B, #8134AF)' }} className="text-white">Try Again</Button>- <Button variant="outline" onClick={resetAll}>Start Over</Button>+ <span className="flex size-12 items-center justify-center rounded-full bg-danger-soft text-danger"><AlertCircle className="size-6" /></span>+ <h2 className="font-heading text-page-title font-semibold text-ink"><span className="sr-only">Error: </span>{scheduleMode ? 'Scheduling failed' : 'Publishing failed'}</h2>+ <p className="max-w-md text-sm text-ink-muted">{statusMessage}</p>+ <div className="mt-2 flex gap-2">+ <Button onClick={() => { setActiveStep(0); setPublishStatus(''); }}>Try again</Button>+ <Button variant="outline" onClick={resetAll}>Start over</Button></div></>)}</div>- </MainCard>- )}- </TabsContent>-- {/* ===== BULK UPLOAD ===== */}- <TabsContent value="bulk" className="mt-4">- <div className="space-y-4">- <div className="grid grid-cols-1 md:grid-cols-2 gap-4">- {/* Account & Type */}- <MainCard title="Account & Type">- <div className="space-y-3">- {(() => {- const bulkAcct = igAccounts.find(a => a.id === bulkAccount);- return (- <Select value={bulkAccount} onValueChange={setBulkAccount} disabled={bulkProcessing}>- <SelectTrigger>- {bulkAcct ? (- <div className="flex items-center gap-2 min-w-0">- <Avatar className="size-5 shrink-0"><AvatarImage src={bulkAcct.profilePictureUrl || bulkAcct.thumbnailUrl} /><AvatarFallback className="text-[9px] bg-gradient-to-br from-pink-500 to-purple-600 text-white">{(bulkAcct.title || bulkAcct.username || '?')[0].toUpperCase()}</AvatarFallback></Avatar>- <span className="text-sm truncate">{bulkAcct.title || bulkAcct.username}</span>- {bulkAcct.username && <span className="text-xs text-muted-foreground shrink-0">@{bulkAcct.username}</span>}- </div>+ </SurfaceBox>+ ) : (+ <div className="grid grid-cols-1 gap-6 lg:grid-cols-[minmax(0,1fr)_28rem]">+ <div className="flex min-w-0 flex-col gap-4">+ <SurfaceBox title="Media" subheader={selectedType ? selectedType.desc : 'Choose what you are posting, then add the file.'}>+ <div className="flex flex-col gap-4">+ <TypePicker value={contentType} onChange={v => { setContentType(v); clearFile(); }} />+ {!file ? (+ <button+ type="button"+ onClick={() => contentType && fileInputRef.current?.click()}+ disabled={!contentType}+ className={cn(+ 'flex w-full flex-col items-center gap-2 rounded-card border border-dashed p-10 text-center transition-colors duration-(--duration-fast)',+ 'focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring',+ contentType ? 'border-line-strong/50 hover:border-brand hover:bg-brand-soft/30' : 'cursor-not-allowed border-line opacity-60',+ )}+ >+ <Upload className="size-8 stroke-[1.5] text-ink-faint" />+ <span className="text-sm font-medium text-ink">{contentType ? 'Choose a file' : 'Choose a content type first'}</span>+ {selectedType && <span className="text-caption text-ink-faint">{selectedType.desc}</span>}+ </button>+ ) : (+ <div className="flex flex-col gap-4 sm:flex-row sm:items-start">+ <div className="relative w-full shrink-0 overflow-hidden rounded-control bg-surface-sunken sm:w-52">+ {file.type.startsWith('video/') ? (+ <video src={filePreview} controls muted className="max-h-72 w-full bg-black object-contain" />) : (- <SelectValue placeholder="Select account…" />+ <img src={filePreview} alt="Selected media preview" className="max-h-72 w-full object-contain" />)}- </SelectTrigger>- <SelectContent>- <SelectGroup>- {igAccounts.map(a => (- <SelectItem key={a.id} value={a.id}>- <div className="flex items-center gap-2">- <Avatar className="size-5 shrink-0"><AvatarImage src={a.profilePictureUrl || a.thumbnailUrl} /><AvatarFallback className="text-[9px] bg-gradient-to-br from-pink-500 to-purple-600 text-white">{(a.title || a.username || '?')[0].toUpperCase()}</AvatarFallback></Avatar>- <span className="text-sm font-medium truncate">{a.title || a.username}</span>- {a.username && <span className="text-xs text-muted-foreground shrink-0">@{a.username}</span>}- </div>- </SelectItem>- ))}- </SelectGroup>- </SelectContent>- </Select>- );- })()}- <div className="grid grid-cols-3 gap-2">- {CONTENT_TYPES.map(t => {- const Icon = t.icon;- return (- <button key={t.value} onClick={() => !bulkProcessing && setBulkContentType(t.value)}- className={cn('flex flex-col items-center gap-1 p-2.5 rounded-lg border-2 transition-all text-center', bulkProcessing && 'opacity-50 cursor-not-allowed', bulkContentType === t.value ? 'border-current' : 'border-border hover:border-muted-foreground/50')}- style={{ borderColor: bulkContentType === t.value ? t.color : undefined, background: bulkContentType === t.value ? `${t.color}15` : undefined }}>- <Icon className="h-4 w-4" style={{ color: t.color }} />- <span className="text-[11px] font-semibold">{t.label}</span>- </button>- );- })}+ <button+ type="button"+ onClick={clearFile}+ aria-label="Remove file"+ className="absolute top-2 right-2 flex size-7 items-center justify-center rounded-full bg-[#0C0809]/75 text-white transition-colors hover:bg-brand"+ >+ <X className="size-3.5" />+ </button>+ </div>+ <div className="min-w-0">+ <p className="truncate text-sm font-semibold text-ink">{file.name}</p>+ <p className="text-small text-ink-muted">{(file.size / (1024 * 1024)).toFixed(2)} MB, {file.type}</p>+ <Badge variant="default" className="mt-2">{selectedType?.label}</Badge>+ </div>+ </div>+ )}+ <input ref={fileInputRef} type="file" hidden accept={selectedType?.accept || '*'} onChange={handleFileSelect} aria-label="Media file" />+ </div>+ </SurfaceBox>++ <SurfaceBox title="Caption">+ <Textarea+ value={caption}+ onChange={e => setCaption(e.target.value)}+ placeholder="Write a caption. Add #hashtags and @mentions."+ rows={7}+ maxLength={CAPTION_LIMIT}+ aria-label="Caption"+ className="min-h-40 border-0 bg-transparent px-0 text-base leading-6 shadow-none hover:border-0 focus-visible:outline-none md:text-base"+ />+ <p className={cn('mt-2 text-right text-caption tabular-nums', caption.length > CAPTION_LIMIT * 0.9 ? 'text-warning' : 'text-ink-faint')}>+ {caption.length.toLocaleString()} / {CAPTION_LIMIT.toLocaleString()}+ </p>+ </SurfaceBox>+ </div>++ <DetailPanel+ title="Post settings"+ footer={+ <Button size="lg" className="w-full" onClick={handlePublish} disabled={uploading || !canPublish}>+ {uploading ? <Spinner className="size-4" /> : scheduleMode ? <Calendar data-icon="inline-start" /> : <Send data-icon="inline-start" />}+ {scheduleMode ? 'Schedule post' : 'Publish now'}+ </Button>+ }+ >+ <FieldRow label="Account">+ <AccountSelect accounts={igAccounts} value={selectedAccount} onChange={setSelectedAccount} />+ </FieldRow>++ {contentType === 'IMAGE' && (+ <FieldRow label="Alt text" hint="Describes the photo for people using screen readers." htmlFor="alt-text">+ <IconInput id="alt-text" icon={ImageIcon} value={altText} onChange={e => setAltText(e.target.value)} placeholder="A short description of the photo" />+ </FieldRow>+ )}+ <FieldRow label="Collaborators" hint="Separate usernames with commas." htmlFor="collaborators">+ <IconInput id="collaborators" icon={UserPlus} value={collaborators} onChange={e => setCollaborators(e.target.value)} placeholder="username1, username2" />+ </FieldRow>+ <FieldRow label="Tagged people" hint="Separate with commas. Add x and y after a name to position the tag." htmlFor="user-tags">+ <IconInput id="user-tags" icon={AtSign} value={userTags} onChange={e => setUserTags(e.target.value)} placeholder="@username1, @username2" />+ </FieldRow>+ <FieldRow label="Location" hint="The Facebook Page ID of the place." htmlFor="location-id">+ <IconInput id="location-id" icon={MapPin} value={locationId} onChange={e => setLocationId(e.target.value)} placeholder="Location ID" />+ </FieldRow>++ {contentType === 'REELS' && (+ <div className="flex flex-col gap-5 border-t border-divider pt-5">+ <div className="flex items-center justify-between gap-3">+ <div>+ <p className="text-sm font-medium text-ink">Share to feed</p>+ <p className="text-caption text-ink-faint">Show the Reel on the profile grid as well.</p>+ </div>+ <Switch checked={shareToFeed} onCheckedChange={setShareToFeed} aria-label="Share to feed" />+ </div>+ <FieldRow label="Audio name" hint="Optional" htmlFor="audio-name">+ <IconInput id="audio-name" icon={Music} value={audioName} onChange={e => setAudioName(e.target.value)} placeholder="Original audio" />+ </FieldRow>+ <FieldRow label="Thumbnail offset" hint="Milliseconds into the video to use as the thumbnail." htmlFor="thumb-offset">+ <IconInput id="thumb-offset" icon={Clock} type="number" min="0" value={thumbOffset} onChange={e => setThumbOffset(e.target.value)} placeholder="0" />+ </FieldRow>+ <FieldRow label="Cover image" hint="Optional JPEG.">+ {!coverFile ? (+ <Button variant="outline" onClick={() => coverInputRef.current?.click()} className="justify-start">+ <Camera data-icon="inline-start" />Choose a cover+ </Button>+ ) : (+ <div className="flex items-center gap-3 rounded-control border border-line p-2">+ <img src={coverPreview} alt="Cover preview" className="size-10 rounded-sm object-cover" />+ <span className="min-w-0 flex-1 truncate text-small text-ink">{coverFile.name}</span>+ <Button variant="ghost" size="icon-xs" onClick={clearCover} aria-label="Remove cover"><X /></Button>+ </div>+ )}+ <input ref={coverInputRef} type="file" hidden accept="image/jpeg" onChange={handleCoverSelect} aria-label="Cover image" />+ </FieldRow></div>+ )}++ <div className="flex flex-col gap-4 border-t border-divider pt-5">+ <FieldRow label="When">+ <ScheduleToggle scheduled={scheduleMode} onChange={setScheduleMode} />+ </FieldRow>+ {scheduleMode && (+ <div className="grid grid-cols-2 gap-2">+ <Input type="date" value={scheduleDate} onChange={e => setScheduleDate(e.target.value)} min={today} aria-label="Schedule date" />+ <Input type="time" value={scheduleTime} onChange={e => setScheduleTime(e.target.value)} aria-label="Schedule time" />+ </div>+ )}</div>- </MainCard>- {/* Shared Settings */}- <MainCard title="Shared Settings">- <div className="space-y-3">+ <div className="flex flex-col gap-2 rounded-control bg-surface-sunken/60 p-3">+ <SummaryRow label="Account">{selectedAcct ? `@${selectedAcct.username || selectedAcct.title}` : '-'}</SummaryRow>+ <SummaryRow label="Type">{selectedType?.label || '-'}</SummaryRow>+ <SummaryRow label="File">{file ? `${(file.size / (1024 * 1024)).toFixed(1)} MB` : '-'}</SummaryRow>+ <SummaryRow label="Goes live">+ {scheduleMode ? (scheduleDate && scheduleTime ? new Date(`${scheduleDate}T${scheduleTime}`).toLocaleString() : 'Pick a time') : 'Right away'}+ </SummaryRow>+ </div>+ </DetailPanel>+ </div>+ )}+ </TabsContent>++ <TabsContent value="bulk">+ <div className="grid grid-cols-1 gap-6 lg:grid-cols-[minmax(0,1fr)_28rem]">+ <div className="flex min-w-0 flex-col gap-4">+ <SurfaceBox+ title={`Files${bulkFiles.length ? ` (${bulkFiles.length})` : ''}`}+ subheader={bulkType?.desc}+ secondary={<div className="flex gap-2">- <Textarea value={bulkSharedCaption} onChange={e => setBulkSharedCaption(e.target.value)} placeholder="Shared caption for all files…" rows={2} disabled={bulkProcessing} className="flex-1" />- <Tooltip>- <TooltipTrigger render={<Button variant="outline" size="icon" onClick={applySharedCaption} disabled={!bulkSharedCaption || bulkProcessing} />}>- <Copy />- </TooltipTrigger>- <TooltipContent>Apply to all pending</TooltipContent>- </Tooltip>+ {bulkFiles.length > 0 && !bulkProcessing && (+ <Button size="sm" variant="ghost" onClick={clearBulkFiles} className="hover:bg-danger-soft hover:text-danger">+ <Trash2 data-icon="inline-start" />Clear all+ </Button>+ )}+ <Button size="sm" variant="outline" onClick={() => bulkFileInputRef.current?.click()} disabled={bulkProcessing}>+ <Plus data-icon="inline-start" />Add files+ </Button>+ </div>+ }+ >+ <input ref={bulkFileInputRef} type="file" hidden multiple accept={bulkType?.accept || '*'} onChange={handleBulkFilesSelect} aria-label="Files to upload" />+ {bulkFiles.length === 0 ? (+ <button+ type="button"+ onClick={() => bulkFileInputRef.current?.click()}+ className="flex w-full flex-col items-center gap-2 rounded-card border border-dashed border-line-strong/50 p-10 text-center transition-colors duration-(--duration-fast) hover:border-brand hover:bg-brand-soft/30 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring"+ >+ <FolderUp className="size-8 stroke-[1.5] text-ink-faint" />+ <span className="text-sm font-medium text-ink">Choose several files</span>+ <span className="text-caption text-ink-faint">Each file becomes its own post, published or scheduled in order.</span>+ </button>+ ) : (+ <ul className="flex max-h-[34rem] flex-col gap-2 overflow-y-auto pr-1">+ {bulkFiles.map((item, idx) => {+ const isActive = ACTIVE_BULK.includes(item.status);+ return (+ <li key={item.id} className={cn('flex items-start gap-3 rounded-field border p-3', isActive ? 'border-brand/40 bg-brand-soft/20' : 'border-line')}>+ <div className="relative size-14 shrink-0 overflow-hidden rounded-control bg-surface-sunken">+ {item.file.type.startsWith('video/')+ ? <video src={item.preview} muted className="size-full object-cover" />+ : <img src={item.preview} alt="" className="size-full object-cover" />}+ <span className="absolute top-0.5 left-0.5 rounded-sm bg-[#0C0809]/75 px-1 font-mono text-[0.5625rem] font-semibold text-white">{idx + 1}</span>+ </div>+ <div className="min-w-0 flex-1">+ <div className="mb-1 flex items-center gap-2">+ <span className="truncate text-sm font-medium text-ink">{item.file.name}</span>+ <span className="shrink-0 text-caption text-ink-faint">{(item.file.size / (1024 * 1024)).toFixed(1)} MB</span>+ </div>+ {item.status === 'pending' ? (+ <Textarea value={item.caption} onChange={e => updateBulkFileCaption(item.id, e.target.value)} placeholder={`Caption for file ${idx + 1}`} rows={1} className="min-h-9 text-small" aria-label={`Caption for file ${idx + 1}`} />+ ) : (+ <p className="truncate text-caption text-ink-muted">{item.caption || 'No caption'}</p>+ )}+ {item.status === 'uploading' && <Progress value={item.progress} className="mt-1.5" aria-label={`Upload progress for file ${idx + 1}`} />}+ {item.error && <p className="mt-1 text-caption text-danger">Error: {item.error}</p>}+ {item.mediaId && <p className="mt-1 font-mono text-caption text-success">Media ID {item.mediaId}</p>}+ </div>+ <div className="flex shrink-0 items-center gap-1.5">+ {isActive && <Spinner className="size-3.5 text-brand" />}+ <StatusBadge status={item.status} map={BULK_STATUS} />+ {item.status === 'pending' && !bulkProcessing && (+ <Button variant="ghost" size="icon-xs" onClick={() => removeBulkFile(item.id)} aria-label={`Remove ${item.file.name}`}><X /></Button>+ )}+ </div>+ </li>+ );+ })}+ </ul>+ )}+ </SurfaceBox>++ {(bulkProcessing || bulkStats.done > 0 || bulkStats.scheduled > 0 || bulkStats.errors > 0) && (+ <SurfaceBox title={bulkProcessing ? 'Working through the files' : 'Results'}>+ <div className="flex flex-wrap gap-1.5">+ <Badge variant="outline">{bulkStats.total} total</Badge>+ {bulkStats.done > 0 && <Badge variant="success"><CheckCircle2 />{bulkStats.done} published</Badge>}+ {bulkStats.scheduled > 0 && <Badge variant="warning"><Calendar />{bulkStats.scheduled} scheduled</Badge>}+ {bulkStats.errors > 0 && <Badge variant="destructive"><AlertCircle />{bulkStats.errors} failed</Badge>}+ {bulkStats.pending > 0 && <Badge variant="secondary">{bulkStats.pending} pending</Badge>}</div>- <div className="relative"><UserPlus className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" /><Input className="pl-9" value={bulkCollaborators} onChange={e => setBulkCollaborators(e.target.value)} placeholder="Collaborators (all posts)" disabled={bulkProcessing} /></div>- <div className="relative"><AtSign className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" /><Input className="pl-9" value={bulkUserTags} onChange={e => setBulkUserTags(e.target.value)} placeholder="Tag users (all posts)" disabled={bulkProcessing} /></div>- {bulkContentType === 'REELS' && (- <div className="flex items-center justify-between"><Label className="text-sm">Share Reels to Feed</Label><Switch checked={bulkShareToFeed} onCheckedChange={setBulkShareToFeed} disabled={bulkProcessing} /></div>+ {bulkProcessing && (+ <Progress value={((bulkStats.done + bulkStats.scheduled + bulkStats.errors) / Math.max(1, bulkStats.total)) * 100} className="mt-3" aria-label="Overall progress" />)}- </div>- </MainCard>+ </SurfaceBox>+ )}</div>- {/* File Picker */}- <MainCard>- <div className="flex items-center justify-between mb-3">- <div className="flex items-center gap-2"><FolderUp className="h-5 w-5 text-pink-500" /><h3 className="font-semibold">Files ({bulkFiles.length})</h3></div>+ <DetailPanel+ title="Bulk settings"+ footer={bulkProcessing ? (+ <Button variant="destructive" size="lg" className="w-full" onClick={() => { bulkCancelRef.current = true; }}>+ <Square data-icon="inline-start" />Stop after this file+ </Button>+ ) : (+ <Button size="lg" className="w-full" onClick={handleBulkProcess} disabled={bulkStats.pending === 0 || !bulkAccount || !bulkContentType}>+ {bulkScheduleMode ? <Calendar data-icon="inline-start" /> : <Send data-icon="inline-start" />}+ {bulkScheduleMode ? `Schedule ${bulkStats.pending} post${bulkStats.pending === 1 ? '' : 's'}` : `Publish ${bulkStats.pending} post${bulkStats.pending === 1 ? '' : 's'} now`}+ </Button>+ )}+ >+ <FieldRow label="Account">+ <AccountSelect accounts={igAccounts} value={bulkAccount} onChange={setBulkAccount} disabled={bulkProcessing} />+ </FieldRow>+ <FieldRow label="Content type">+ <TypePicker value={bulkContentType} onChange={setBulkContentType} disabled={bulkProcessing} />+ </FieldRow>+ <FieldRow label="Shared caption" hint="Copies this caption onto every pending file." htmlFor="bulk-caption"><div className="flex gap-2">- {bulkFiles.length > 0 && !bulkProcessing && (- <Button size="sm" variant="outline" onClick={clearBulkFiles} className="gap-1.5 text-red-500 border-red-200 hover:bg-red-50"><Trash2 className="h-3.5 w-3.5" />Clear All</Button>- )}- <Button size="sm" onClick={() => bulkFileInputRef.current?.click()} disabled={bulkProcessing} style={{ background: 'linear-gradient(135deg, #F58529, #DD2A7B, #8134AF)' }} className="text-white gap-1.5"><Plus className="h-3.5 w-3.5" />Add Files</Button>+ <Textarea id="bulk-caption" value={bulkSharedCaption} onChange={e => setBulkSharedCaption(e.target.value)} placeholder="Caption for all files" rows={2} disabled={bulkProcessing} className="flex-1" />+ <Tooltip>+ <TooltipTrigger render={<Button variant="outline" size="icon" onClick={applySharedCaption} disabled={!bulkSharedCaption || bulkProcessing} aria-label="Apply caption to all pending files" />}>+ <Copy />+ </TooltipTrigger>+ <TooltipContent>Apply to all pending files</TooltipContent>+ </Tooltip></div>- </div>- <input ref={bulkFileInputRef} type="file" hidden multiple accept={CONTENT_TYPES.find(t => t.value === bulkContentType)?.accept || '*'} onChange={handleBulkFilesSelect} />-- {bulkFiles.length === 0 ? (- <button onClick={() => bulkFileInputRef.current?.click()} className="w-full border-2 border-dashed border-border rounded-xl p-8 text-center cursor-pointer hover:border-pink-500 hover:bg-pink-500/5 transition-all">- <FolderUp className="h-10 w-10 mx-auto text-muted-foreground mb-2" />- <p className="font-medium">Click to select multiple files</p>- <p className="text-xs text-muted-foreground mt-1">Select multiple videos or images at once</p>- </button>- ) : (- <div className="space-y-2 max-h-[480px] overflow-y-auto pr-1">- {bulkFiles.map((item, idx) => {- const isActive = ['uploading','creating','processing','publishing','scheduling'].includes(item.status);- return (- <div key={item.id} className={cn('flex items-start gap-3 p-3 rounded-lg border transition-all', isActive ? 'bg-card/50' : 'bg-muted/20 border-border')}>- <div className="w-14 h-14 flex-shrink-0 rounded-lg overflow-hidden bg-muted relative">- {item.file.type.startsWith('video/') ? <video src={item.preview} muted className="w-full h-full object-cover" /> : <img src={item.preview} className="w-full h-full object-cover" alt="" />}- <span className="absolute top-0.5 left-0.5 bg-black/70 text-white text-[9px] font-bold px-1 rounded">#{idx + 1}</span>- {item.status === 'uploading' && <div className="absolute bottom-0 left-0 right-0 h-1 bg-black/40"><div className="h-full bg-gradient-to-r from-orange-500 to-pink-500 transition-all" style={{ width: `${item.progress}%` }} /></div>}- </div>- <div className="flex-1 min-w-0">- <div className="flex items-center gap-2 mb-1">- <span className="text-sm font-semibold truncate">{item.file.name}</span>- <span className="text-xs text-muted-foreground shrink-0">{(item.file.size / (1024 * 1024)).toFixed(1)} MB</span>- </div>- {item.status === 'pending' ? (- <Textarea value={item.caption} onChange={e => updateBulkFileCaption(item.id, e.target.value)} placeholder={`Caption for file #${idx + 1}…`} rows={1} className="text-xs" />- ) : (- <p className="text-xs text-muted-foreground">{item.caption || '(no caption)'}</p>- )}- {item.status === 'uploading' && <Progress value={item.progress} className="h-1 mt-1" />}- {item.error && <p className="text-xs text-red-500 mt-0.5">{item.error}</p>}- {item.mediaId && <p className="text-xs text-green-600 mt-0.5">Media ID: {item.mediaId}</p>}- </div>- <div className="flex items-center gap-1.5 flex-shrink-0">- {isActive && <Spinner />}- <BulkStatusBadge status={item.status} />- {item.status === 'pending' && !bulkProcessing && (- <Button variant="ghost" size="icon" className="h-6 w-6 text-muted-foreground hover:text-red-500" onClick={() => removeBulkFile(item.id)}><X className="h-3 w-3" /></Button>- )}- </div>- </div>- );- })}+ </FieldRow>+ <FieldRow label="Collaborators" hint="Applied to every post." htmlFor="bulk-collaborators">+ <IconInput id="bulk-collaborators" icon={UserPlus} value={bulkCollaborators} onChange={e => setBulkCollaborators(e.target.value)} placeholder="username1, username2" disabled={bulkProcessing} />+ </FieldRow>+ <FieldRow label="Tagged people" hint="Applied to every post." htmlFor="bulk-tags">+ <IconInput id="bulk-tags" icon={AtSign} value={bulkUserTags} onChange={e => setBulkUserTags(e.target.value)} placeholder="@username1, @username2" disabled={bulkProcessing} />+ </FieldRow>+ <FieldRow label="Location" hint="Facebook Page ID, applied to every post." htmlFor="bulk-location">+ <IconInput id="bulk-location" icon={MapPin} value={bulkLocationId} onChange={e => setBulkLocationId(e.target.value)} placeholder="Location ID" disabled={bulkProcessing} />+ </FieldRow>+ {bulkContentType === 'REELS' && (+ <div className="flex items-center justify-between gap-3">+ <p className="text-sm font-medium text-ink">Share Reels to feed</p>+ <Switch checked={bulkShareToFeed} onCheckedChange={setBulkShareToFeed} disabled={bulkProcessing} aria-label="Share Reels to feed" /></div>)}- </MainCard>- {/* Bulk Schedule */}- <MainCard>- <div className="flex items-center justify-between mb-3">- <div className="flex items-center gap-2"><Calendar className="h-5 w-5 text-amber-500" /><h3 className="font-semibold">Bulk Schedule</h3></div>- <div className="flex items-center gap-2"><Label className="text-sm">{bulkScheduleMode ? 'Schedule All' : 'Publish All Now'}</Label><Switch checked={bulkScheduleMode} onCheckedChange={setBulkScheduleMode} disabled={bulkProcessing} /></div>- </div>- {bulkScheduleMode && (- <div className="space-y-3">- <div className="flex gap-3 flex-wrap">- <Input type="date" value={bulkStartDate} onChange={e => setBulkStartDate(e.target.value)} min={new Date().toISOString().split('T')[0]} className="w-44" disabled={bulkProcessing} />- <Input type="time" value={bulkStartTime} onChange={e => setBulkStartTime(e.target.value)} className="w-36" disabled={bulkProcessing} />- <Select value={String(bulkInterval)} onValueChange={v => setBulkInterval(Number(v))} disabled={bulkProcessing}>- <SelectTrigger className="w-48">- <span className="flex flex-1 text-left text-sm">- {BULK_INTERVAL_OPTIONS.find(o => o.value === bulkInterval)?.label}- </span>- </SelectTrigger>+ <div className="flex flex-col gap-4 border-t border-divider pt-5">+ <FieldRow label="When">+ <ScheduleToggle scheduled={bulkScheduleMode} onChange={setBulkScheduleMode} disabled={bulkProcessing} nowLabel="Publish all now" laterLabel="Spread out" />+ </FieldRow>+ {bulkScheduleMode ? (+ <>+ <div className="grid grid-cols-2 gap-2">+ <Input type="date" value={bulkStartDate} onChange={e => setBulkStartDate(e.target.value)} min={today} disabled={bulkProcessing} aria-label="Start date" />+ <Input type="time" value={bulkStartTime} onChange={e => setBulkStartTime(e.target.value)} disabled={bulkProcessing} aria-label="Start time" />+ </div>+ <Select value={String(bulkInterval)} onValueChange={v => setBulkInterval(Number(v))} disabled={bulkProcessing} items={BULK_INTERVAL_OPTIONS.map(o => ({ value: String(o.value), label: o.label }))}>+ <SelectTrigger className="w-full" aria-label="Interval"><SelectValue /></SelectTrigger><SelectContent><SelectGroup>- {BULK_INTERVAL_OPTIONS.map(o => (- <SelectItem key={o.value} value={String(o.value)}>{o.label}</SelectItem>- ))}+ {BULK_INTERVAL_OPTIONS.map(o => <SelectItem key={o.value} value={String(o.value)}>{o.label}</SelectItem>)}</SelectGroup></SelectContent></Select>- </div>- {bulkStartDate && bulkStartTime && bulkStats.pending > 0 && (- <Alert><AlertDescription>- <strong>Schedule Preview:</strong> {bulkStats.pending} files starting at <strong>{new Date(`${bulkStartDate}T${bulkStartTime}`).toLocaleString()}</strong>,- spaced <strong>{bulkInterval >= 1440 ? `${bulkInterval / 1440} day${bulkInterval > 1440 ? 's' : ''}` : `${bulkInterval / 60} hr${bulkInterval > 60 ? 's' : ''}`}</strong> apart.- Last post at <strong>{new Date(new Date(`${bulkStartDate}T${bulkStartTime}`).getTime() + (bulkStats.pending - 1) * bulkInterval * 60000).toLocaleString()}</strong>.- </AlertDescription></Alert>- )}- </div>- )}- {!bulkScheduleMode && bulkStats.pending > 0 && (- <Alert className="mt-2"><AlertDescription><strong>Immediate publish:</strong> {bulkStats.pending} files will be uploaded and published one-by-one. Rate limit: 100 posts/24hr.</AlertDescription></Alert>- )}- </MainCard>-- {/* Progress summary */}- {(bulkProcessing || bulkStats.done > 0 || bulkStats.scheduled > 0 || bulkStats.errors > 0) && (- <MainCard title={bulkProcessing ? 'Processing…' : 'Results'}>- <div className="flex gap-2 flex-wrap mb-3">- <Badge variant="outline">{bulkStats.total} Total</Badge>- {bulkStats.done > 0 && <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-semibold bg-green-50 border border-green-200 text-green-700"><CheckCircle2 className="h-3 w-3" />{bulkStats.done} Published</span>}- {bulkStats.scheduled > 0 && <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-semibold bg-amber-50 border border-amber-200 text-amber-700"><Calendar className="h-3 w-3" />{bulkStats.scheduled} Scheduled</span>}- {bulkStats.errors > 0 && <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-semibold bg-red-50 border border-red-200 text-red-700"><AlertCircle className="h-3 w-3" />{bulkStats.errors} Failed</span>}- {bulkStats.pending > 0 && <Badge variant="secondary">{bulkStats.pending} Pending</Badge>}- </div>- {bulkProcessing && <Progress value={((bulkStats.done + bulkStats.scheduled + bulkStats.errors) / bulkStats.total) * 100} className="h-2" />}- </MainCard>- )}-- <div className="flex justify-end">- {bulkProcessing ? (- <Button variant="destructive" onClick={() => { bulkCancelRef.current = true; setBulkCancelled(true); }} className="gap-2 px-6"><Square className="h-4 w-4" />Cancel</Button>- ) : (- <Button onClick={handleBulkProcess} disabled={bulkStats.pending === 0 || !bulkAccount || !bulkContentType}- style={{ background: bulkScheduleMode ? 'linear-gradient(135deg, #F58529, #FF6B35)' : 'linear-gradient(135deg, #F58529, #DD2A7B, #8134AF)' }} className="text-white gap-2 px-6">- {bulkScheduleMode ? <Calendar className="h-4 w-4" /> : <Send className="h-4 w-4" />}- {bulkScheduleMode ? `Schedule ${bulkStats.pending} Posts` : `Publish ${bulkStats.pending} Posts Now`}- </Button>- )}- </div>+ {bulkStartDate && bulkStartTime && bulkStats.pending > 0 && (+ <Alert variant="info">+ <Info />+ <AlertDescription>+ {bulkStats.pending} posts from {new Date(`${bulkStartDate}T${bulkStartTime}`).toLocaleString()}, {intervalText} apart. The last one goes out {new Date(new Date(`${bulkStartDate}T${bulkStartTime}`).getTime() + (bulkStats.pending - 1) * bulkInterval * 60000).toLocaleString()}.+ </AlertDescription>+ </Alert>+ )}+ </>+ ) : bulkStats.pending > 0 && (+ <Alert>+ <Info />+ <AlertDescription>{bulkStats.pending} files upload and publish one at a time. Instagram allows 100 posts per account every 24 hours.</AlertDescription>+ </Alert>+ )}+ </div>+ </DetailPanel></div></TabsContent></Tabs>- {/* Scheduled Posts Table */}{scheduledPosts.length > 0 && (- <MainCard content={false}>- <div className="px-5 py-4 flex items-center justify-between flex-wrap gap-2">- <div className="flex items-center gap-2"><Calendar className="h-5 w-5 text-amber-500" /><h3 className="font-bold">Scheduled Posts</h3></div>+ <section className="flex flex-col gap-3">+ <div className="flex flex-wrap items-end justify-between gap-3">+ <div>+ <h2 className="font-heading text-section font-semibold text-ink">Scheduled posts</h2>+ <p className="text-small text-ink-muted">Posts waiting to go out, and the history of ones that already did.</p>+ </div><div className="flex gap-2">- <Button size="sm" variant="ghost" onClick={loadScheduledPosts} className="gap-1.5 text-muted-foreground"><Calendar className="h-3.5 w-3.5" />Refresh</Button>- <Button size="sm" variant="outline" onClick={() => setConfirmDeleteAll(true)} className="gap-1.5 text-red-500 border-red-200 hover:bg-red-50"><Trash className="h-3.5 w-3.5" />Delete All</Button>+ <Button size="sm" variant="ghost" onClick={loadScheduledPosts}><RefreshCw data-icon="inline-start" />Refresh</Button>+ <Button size="sm" variant="outline" onClick={() => setConfirmDeleteAll(true)} className="hover:bg-danger-soft hover:text-danger"><Trash2 data-icon="inline-start" />Delete all</Button></div></div>- <Separator />- <div className="px-5 py-3 flex gap-2 flex-wrap">- {[- { label: 'Total', value: sPostsCounts.all, color: 'default', filter: 'all' },- { label: 'Pending', value: sPostsCounts.pending, cls: 'bg-amber-50 border-amber-200 text-amber-700', filter: 'pending' },- { label: 'Publishing', value: sPostsCounts.publishing, cls: 'bg-orange-50 border-orange-200 text-orange-700', filter: 'publishing' },- { label: 'Published', value: sPostsCounts.published, cls: 'bg-green-50 border-green-200 text-green-700', filter: 'published' },- { label: 'Failed', value: sPostsCounts.failed, cls: 'bg-red-50 border-red-200 text-red-700', filter: 'failed' },- ].map(s => (- <button key={s.filter} onClick={() => setStatusFilter(s.filter)}- className={cn('inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-semibold border cursor-pointer transition-all', statusFilter === s.filter ? (s.cls || 'bg-muted text-foreground border-border') : 'bg-muted/30 text-muted-foreground border-transparent hover:border-border')}>- {s.label}: {s.value}- </button>- ))}- </div>- <Separator />- <Table>- <TableHeader>- <TableRow>- <TableHead className="w-8">#</TableHead>- <TableHead>Account</TableHead>- <TableHead>Type</TableHead>- <TableHead className="min-w-48">Caption</TableHead>- <TableHead className="min-w-40">Scheduled At</TableHead>- <TableHead className="min-w-40">Published At</TableHead>- <TableHead>Status</TableHead>- <TableHead className="min-w-40">Error</TableHead>- <TableHead className="text-right">Actions</TableHead>- </TableRow>- </TableHeader>- <TableBody>- {filteredScheduled.map((post, idx) => {- const acct = igAccounts.find(a => a.id === post.accountId);- const typeInfo = CONTENT_TYPES.find(t => t.value === post.mediaType);- const Icon = typeInfo?.icon || ImageIcon;- const isEditing = editingPostId === post.id;- const canEdit = post.status === 'pending' || post.status === 'scheduled';- const isPastDue = post.status === 'pending' && new Date(post.scheduledAt) < new Date();- return (- <React.Fragment key={post.id}>- <TableRow className={isEditing ? 'bg-amber-50/50' : ''}>- <TableCell className="text-xs text-muted-foreground">{idx + 1}</TableCell>- <TableCell>- <div className="flex items-center gap-1.5">- <Avatar className="h-6 w-6"><AvatarImage src={acct?.profilePictureUrl} /><AvatarFallback className="text-[9px] bg-gradient-to-br from-pink-500 to-purple-600 text-white">{(acct?.username || '?')[0].toUpperCase()}</AvatarFallback></Avatar>- <span className="text-xs font-semibold whitespace-nowrap">{acct?.username ? `@${acct.username}` : post.accountId}</span>- </div>- </TableCell>- <TableCell>- <div className="flex items-center gap-1" style={{ color: typeInfo?.color || '#888' }}>- <Icon className="h-3.5 w-3.5" />- <span className="text-xs font-semibold">{typeInfo?.label || post.mediaType}</span>- </div>- </TableCell>- <TableCell>- <Tooltip>- <TooltipTrigger render={<p className="text-xs max-w-48 truncate cursor-default text-muted-foreground" />}>- {post.caption || '(no caption)'}- </TooltipTrigger>- <TooltipContent>{post.caption || '(no caption)'}</TooltipContent>- </Tooltip>- </TableCell>- <TableCell>- <span className={cn('text-xs whitespace-nowrap', isPastDue ? 'text-orange-500' : 'text-muted-foreground')}>{fmtLocalDate(post.scheduledAt)}</span>- {isPastDue && <p className="text-[10px] text-orange-500">overdue</p>}- </TableCell>- <TableCell>- <div className="flex items-center gap-1">- <span className={cn('text-xs whitespace-nowrap', post.publishedAt ? 'text-green-600' : 'text-muted-foreground')}>{fmtLocalDate(post.publishedAt)}</span>- {post.publishedMediaId && <Tooltip><TooltipTrigger><ExternalLink className="h-3 w-3 text-green-500/50" /></TooltipTrigger><TooltipContent>Media ID: {post.publishedMediaId}</TooltipContent></Tooltip>}- </div>- </TableCell>- <TableCell><StatusBadge status={post.status} /></TableCell>- <TableCell>- {post.error ? (- <Tooltip><TooltipTrigger render={<p className="text-xs max-w-40 truncate text-red-500 cursor-help" />}>{post.error}</TooltipTrigger><TooltipContent>{post.error}</TooltipContent></Tooltip>- ) : <span className="text-muted-foreground text-xs">-</span>}- </TableCell>- <TableCell className="text-right whitespace-nowrap">- {canEdit && !isEditing && <Tooltip><TooltipTrigger render={<Button variant="ghost" size="icon" className="size-7 text-muted-foreground hover:text-amber-500" onClick={() => startEditPost(post)} />}><Pencil /></TooltipTrigger><TooltipContent>Edit</TooltipContent></Tooltip>}- {isEditing && <Button variant="ghost" size="icon" className="size-7 text-amber-500" onClick={cancelEdit}><X /></Button>}- {post.status !== 'publishing' && <Tooltip><TooltipTrigger render={<Button variant="ghost" size="icon" className="size-7 text-muted-foreground hover:text-red-500" onClick={() => post.status === 'published' ? setConfirmDeleteId(post.id) : handleDeleteScheduled(post.id)} />}><Trash2 /></TooltipTrigger><TooltipContent>{post.status === 'published' ? 'Remove from records' : 'Delete'}</TooltipContent></Tooltip>}- </TableCell>- </TableRow>- {isEditing && (- <TableRow>- <TableCell colSpan={9} className="p-0">- <div className="p-4 bg-amber-50/30 border-t border-amber-200/50 space-y-3">- <Textarea value={editCaption} onChange={e => setEditCaption(e.target.value)} label="Caption" rows={3} />- <p className="text-xs text-muted-foreground">{editCaption.length}/2,200 characters</p>- <div className="flex gap-3 flex-wrap">- <Input type="date" value={editDate} onChange={e => setEditDate(e.target.value)} min={new Date().toISOString().split('T')[0]} className="w-44" />- <Input type="time" value={editTime} onChange={e => setEditTime(e.target.value)} className="w-36" />- {editDate && editTime && <span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-semibold bg-amber-50 border border-amber-200 text-amber-700"><Calendar className="h-3 w-3" />{new Date(`${editDate}T${editTime}`).toLocaleString()}</span>}- </div>- <div className="flex gap-2 justify-end">- <Button size="sm" variant="outline" onClick={cancelEdit}>Cancel</Button>- <Button size="sm" onClick={handleSaveEdit} disabled={savingEdit} className="gap-1.5" style={{ background: 'linear-gradient(135deg, #F58529, #FF6B35)' }}>- {savingEdit ? <Spinner /> : <CheckCircle2 data-icon="inline-start" />}- {savingEdit ? 'Saving…' : 'Save & Sync'}- </Button>- </div>- </div>+ <FilterChips label="Status" options={statusChips} value={statusFilter} onChange={setStatusFilter} />+ <SurfaceBox content={false} className="overflow-hidden">+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead className="w-10 text-right">#</TableHead>+ <TableHead>Account</TableHead>+ <TableHead>Type</TableHead>+ <TableHead className="min-w-48">Caption</TableHead>+ <TableHead className="min-w-40">Scheduled for</TableHead>+ <TableHead className="min-w-40">Published</TableHead>+ <TableHead>Status</TableHead>+ <TableHead className="min-w-40">Error</TableHead>+ <TableHead className="text-right"><span className="sr-only">Actions</span></TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {filteredScheduled.map((post, idx) => {+ const acct = igAccounts.find(a => a.id === post.accountId);+ const typeInfo = CONTENT_TYPES.find(t => t.value === post.mediaType);+ const TypeIcon = typeInfo?.icon || ImageIcon;+ const isEditing = editingPostId === post.id;+ const canEdit = post.status === 'pending' || post.status === 'scheduled';+ const isPastDue = post.status === 'pending' && new Date(post.scheduledAt) < new Date();+ return (+ <React.Fragment key={post.id}>+ <TableRow data-state={isEditing ? 'selected' : undefined}>+ <TableCell className="text-right font-mono text-caption text-ink-faint">{idx + 1}</TableCell>+ <TableCell>+ <span className="flex items-center gap-2">+ {acct && <AccountAvatar account={acct} size="xs" />}+ <span className="text-small font-medium text-ink">{acct?.username ? `@${acct.username}` : post.accountId}</span>+ </span>+ </TableCell>+ <TableCell>+ <span className="flex items-center gap-1.5 text-small text-ink-muted"><TypeIcon className="size-3.5" />{typeInfo?.label || post.mediaType}</span>+ </TableCell>+ <TableCell>+ <Tooltip>+ <TooltipTrigger render={<p className="max-w-48 cursor-default truncate text-small text-ink-muted" />}>{post.caption || 'No caption'}</TooltipTrigger>+ <TooltipContent className="max-w-sm">{post.caption || 'No caption'}</TooltipContent>+ </Tooltip>+ </TableCell>+ <TableCell>+ <span className={cn('text-small', isPastDue ? 'text-warning' : 'text-ink-muted')}>{fmtLocalDate(post.scheduledAt)}</span>+ {isPastDue && <p className="text-caption text-warning">Overdue</p>}+ </TableCell>+ <TableCell>+ <span className="flex items-center gap-1 text-small text-ink-muted">+ {fmtLocalDate(post.publishedAt)}+ {post.publishedMediaId && (+ <Tooltip>+ <TooltipTrigger render={<span className="text-success" />}><CheckCircle2 className="size-3.5" /></TooltipTrigger>+ <TooltipContent>Media ID {post.publishedMediaId}</TooltipContent>+ </Tooltip>+ )}+ </span>+ </TableCell>+ <TableCell><StatusBadge status={post.status} map={POST_STATUS} /></TableCell>+ <TableCell>+ {post.error ? (+ <Tooltip>+ <TooltipTrigger render={<p className="max-w-40 cursor-help truncate text-small text-danger" />}>{post.error}</TooltipTrigger>+ <TooltipContent className="max-w-sm">{post.error}</TooltipContent>+ </Tooltip>+ ) : <span className="text-ink-faint">-</span>}+ </TableCell>+ <TableCell className="text-right whitespace-nowrap">+ {canEdit && !isEditing && (+ <Tooltip>+ <TooltipTrigger render={<Button variant="ghost" size="icon-xs" onClick={() => startEditPost(post)} aria-label="Edit scheduled post" />}><Pencil /></TooltipTrigger>+ <TooltipContent>Edit</TooltipContent>+ </Tooltip>+ )}+ {isEditing && <Button variant="ghost" size="icon-xs" onClick={cancelEdit} aria-label="Cancel editing"><X /></Button>}+ {post.status !== 'publishing' && (+ <Tooltip>+ <TooltipTrigger render={<Button variant="ghost" size="icon-xs" onClick={() => setPendingDelete(post)} aria-label={post.status === 'published' ? 'Remove record' : 'Delete scheduled post'} className="hover:bg-danger-soft hover:text-danger" />}><Trash2 /></TooltipTrigger>+ <TooltipContent>{post.status === 'published' ? 'Remove record' : 'Delete'}</TooltipContent>+ </Tooltip>+ )}</TableCell></TableRow>- )}- </React.Fragment>- );- })}- {filteredScheduled.length === 0 && (- <TableRow><TableCell colSpan={9} className="text-center text-muted-foreground py-8">No posts with status "{statusFilter}"</TableCell></TableRow>- )}- </TableBody>- </Table>- </MainCard>+ {isEditing && (+ <TableRow className="hover:bg-transparent">+ <TableCell colSpan={9} className="whitespace-normal bg-surface-sunken/40 p-0">+ <div className="flex flex-col gap-3 p-4">+ <Textarea value={editCaption} onChange={e => setEditCaption(e.target.value)} rows={3} aria-label="Caption" maxLength={CAPTION_LIMIT} />+ <p className="text-caption text-ink-faint tabular-nums">{editCaption.length.toLocaleString()} / {CAPTION_LIMIT.toLocaleString()}</p>+ <div className="flex flex-wrap gap-2">+ <Input type="date" value={editDate} onChange={e => setEditDate(e.target.value)} min={today} className="w-44" aria-label="Date" />+ <Input type="time" value={editTime} onChange={e => setEditTime(e.target.value)} className="w-36" aria-label="Time" />+ </div>+ <div className="flex justify-end gap-2">+ <Button size="sm" variant="outline" onClick={cancelEdit}>Cancel</Button>+ <Button size="sm" onClick={handleSaveEdit} disabled={savingEdit}>+ {savingEdit ? <Spinner className="size-3.5" /> : <CheckCircle2 data-icon="inline-start" />}+ {savingEdit ? 'Saving' : 'Save changes'}+ </Button>+ </div>+ </div>+ </TableCell>+ </TableRow>+ )}+ </React.Fragment>+ );+ })}+ {filteredScheduled.length === 0 && (+ <TableRow className="hover:bg-transparent">+ <TableCell colSpan={9}>+ <EmptyState compact icon={<Calendar />} title={`No ${statusFilter} posts`} description="Choose a different status to see other posts." />+ </TableCell>+ </TableRow>+ )}+ </TableBody>+ </Table>+ </SurfaceBox>+ </section>)}- {/* API Info */}- <MainCard>- <p className="text-xs text-muted-foreground"><strong>How it works:</strong> Files are uploaded to Cloudinary CDN first (Instagram needs public URLs), then a media container is created, processed, and published. Rate limit: 100 posts/24hr per account.</p>- <div className="flex gap-2 mt-3 flex-wrap">- {[{ label: 'JPEG Photos', color: '#F58529' }, { label: 'MP4/MOV Reels', color: '#DD2A7B' }, { label: 'Stories', color: '#8134AF' }, { label: 'Max 300MB videos', color: undefined }, { label: 'instagram_business_content_publish required', color: undefined }].map(c => (- <span key={c.label} className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs border" style={{ borderColor: c.color ? `${c.color}40` : undefined, color: c.color }}>{c.label}</span>- ))}- </div>- </MainCard>-- {/* Delete All confirmation */}- <AlertDialog open={confirmDeleteAll} onOpenChange={setConfirmDeleteAll}>- <AlertDialogContent>- <AlertDialogHeader>- <AlertDialogTitle>Delete all scheduled posts?</AlertDialogTitle>- <AlertDialogDescription>- This removes every post from your records (pending, published, and failed) and syncs to GitHub.- Posts already <strong>published to Instagram remain live</strong> - only local records are deleted.- </AlertDialogDescription>- </AlertDialogHeader>- <AlertDialogFooter>- <AlertDialogCancel>Cancel</AlertDialogCancel>- <AlertDialogAction variant="destructive" onClick={handleDeleteAll}>- <Trash data-icon="inline-start" />Delete All & Sync- </AlertDialogAction>- </AlertDialogFooter>- </AlertDialogContent>- </AlertDialog>-- {/* Confirm remove published post */}- <AlertDialog open={!!confirmDeleteId} onOpenChange={v => !v && setConfirmDeleteId(null)}>- <AlertDialogContent>- <AlertDialogHeader>- <AlertDialogTitle>Remove published post?</AlertDialogTitle>- <AlertDialogDescription>- This removes the entry from your records and syncs to GitHub.- The post will <strong>remain live on Instagram</strong> - only local records are removed.- </AlertDialogDescription>- </AlertDialogHeader>- <AlertDialogFooter>- <AlertDialogCancel>Cancel</AlertDialogCancel>- <AlertDialogAction variant="destructive" onClick={() => handleDeleteScheduled(confirmDeleteId)}>- Remove Record- </AlertDialogAction>- </AlertDialogFooter>- </AlertDialogContent>- </AlertDialog>+ <p className="text-caption text-ink-faint">+ Files upload to Cloudinary first because Instagram needs a public URL. Twiligent then creates an Instagram media container, waits for processing, and publishes it. Publishing needs the instagram_business_content_publish permission. Instagram allows 100 posts per account every 24 hours.+ </p>++ <ConfirmDialog+ open={confirmDeleteAll}+ onOpenChange={setConfirmDeleteAll}+ title="Delete all scheduled posts?"+ description="Every record is removed: pending, published and failed. Pending posts will not go out. Posts already on Instagram stay live; only Twiligent's records are deleted. Posts that are publishing right now are kept."+ confirmLabel="Delete all"+ onConfirm={handleDeleteAll}+ busy={deleting}+ hold+ />++ <ConfirmDialog+ open={!!pendingDelete}+ onOpenChange={open => { if (!open) setPendingDelete(null); }}+ title={pendingDelete?.status === 'published' ? 'Remove this record?' : 'Delete this scheduled post?'}+ description={pendingDelete?.status === 'published'+ ? 'The post stays live on Instagram. Only the record in Twiligent is removed.'+ : 'It will not be published. The uploaded media stays in Cloudinary.'}+ confirmLabel={pendingDelete?.status === 'published' ? 'Remove' : 'Delete'}+ onConfirm={handleDeleteScheduled}+ busy={deleting}+ hold+ /></div>);}diff --git a/frontend/src/features/settings/Settings.jsx b/frontend/src/features/settings/Settings.jsxindex 0d2368e..b26c9c6 100644--- a/frontend/src/features/settings/Settings.jsx+++ b/frontend/src/features/settings/Settings.jsx@@ -1,82 +1,131 @@-import React, { useState, useEffect } from 'react';+import React, { useEffect, useState } from 'react';+import { useTheme } from 'next-themes';+import {+ RefreshCw, CheckCircle2, Info, AlertTriangle, ExternalLink, Copy, Check, Save, Sun, Moon, Monitor, Activity,+} from 'lucide-react';import { Button } from '@/components/ui/button';import { Input } from '@/components/ui/input';-import { Label } from '@/components/ui/label';import { Alert, AlertDescription } from '@/components/ui/alert';-import { Separator } from '@/components/ui/separator';-import { Skeleton } from '@/components/ui/skeleton';import { Badge } from '@/components/ui/badge';-import {- RefreshCw, CheckCircle2, Info, AlertTriangle, ShieldCheck, GitBranch,- Key, ExternalLink, Copy, Check, Save,-} from 'lucide-react';-import MainCard from '../../components/MainCard';+import { Skeleton } from '@/components/ui/skeleton';+import { Spinner } from '@/components/ui/spinner';+import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';+import PageHeader from '@/components/PageHeader';+import SurfaceBox from '@/components/SurfaceBox';+import { FieldRow } from '@/components/DetailPanel';import { useAppContext } from '../../context/AppContext';import { api } from '../../services/api';+import { cn } from '@/lib/utils';++const PAT_STEPS = [+ { title: 'Open GitHub settings', body: <>On github.com, open your profile menu (top right) and choose <strong>Settings</strong>.</> },+ { title: 'Open developer settings', body: <>At the bottom of the left sidebar, choose <strong>Developer settings</strong>.</> },+ { title: 'Create a fine-grained token', body: <>Choose <strong>Personal access tokens</strong>, then <strong>Fine-grained tokens</strong>, then <strong>Generate new token</strong>. Fine-grained tokens let you pick exact permissions.</> },+ { title: 'Name the token and pick the repository', body: <>Use a clear name such as <em>twiligent-actions</em>, an expiry of 90 days or less, and <em>Only select repositories</em> with this project selected.</> },+ { title: 'Set permissions', body: <>Under Repository permissions, enable <Badge variant="secondary">Actions: read and write</Badge> <Badge variant="secondary">Secrets: read and write</Badge> <Badge variant="secondary">Contents: read-only</Badge></> },+ { title: 'Copy the token now', body: <>Choose <strong>Generate token</strong>. GitHub shows it once, so copy it into a password manager straight away. A lost token has to be generated again.</> },+ { title: 'Add it as an Actions secret', body: 'In the repository, open Settings, then Secrets and variables, then Actions, then New repository secret. Name it exactly:', code: 'GITHUB_PAT' },+];++const LINKS = [+ { label: 'GitHub settings', href: 'https://github.com/settings/profile' },+ { label: 'GitHub fine-grained tokens', href: 'https://github.com/settings/tokens?type=beta' },+ { label: 'Cloudinary console', href: 'https://cloudinary.com/console' },+ { label: 'Google Cloud credentials', href: 'https://console.cloud.google.com/apis/credentials' },+ { label: 'Meta app dashboard', href: 'https://developers.facebook.com/apps' },+ { label: 'Cloudflare dashboard', href: 'https://dash.cloudflare.com' },+];++const STACK = ['React', 'shadcn/ui', 'Tailwind CSS', 'Hono', 'Supabase', 'Cloudflare', 'YouTube Data API', 'Instagram Graph API'];function CopyButton({ text }) {const [copied, setCopied] = useState(false);- const handleCopy = () => {- navigator.clipboard.writeText(text);- setCopied(true);- setTimeout(() => setCopied(false), 2000);+ const handleCopy = async () => {+ try {+ await navigator.clipboard.writeText(text);+ setCopied(true);+ setTimeout(() => setCopied(false), 2000);+ } catch {+ setCopied(false);+ }};return (- <button- onClick={handleCopy}- className="inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs bg-muted hover:bg-muted/70 border border-border transition-colors"- >- {copied ? <Check className="h-3 w-3 text-green-600" /> : <Copy className="h-3 w-3" />}+ <Button variant="ghost" size="xs" onClick={handleCopy} aria-label={copied ? 'Copied' : `Copy ${text}`}>+ {copied ? <Check className="text-success" /> : <Copy />}{copied ? 'Copied' : 'Copy'}- </button>+ </Button>);}-function StepBadge({ n }) {+function SettingsSection({ id, title, description, children }) {return (- <span className="inline-flex items-center justify-center w-5 h-5 rounded-full bg-primary text-primary-foreground text-xs font-bold flex-shrink-0">- {n}- </span>+ <section aria-labelledby={id} className="grid grid-cols-1 gap-4 border-t border-line pt-8 first:border-t-0 first:pt-0 lg:grid-cols-[16rem_1fr] lg:gap-10">+ <div className="flex flex-col gap-1">+ <h2 id={id} className="font-heading text-section font-semibold text-ink">{title}</h2>+ {description && <p className="text-small text-ink-muted">{description}</p>}+ </div>+ <div className="flex min-w-0 flex-col gap-4">{children}</div>+ </section>);}-export default function Settings() {- const { showToast, refreshAll } = useAppContext();-- const [serverStatus, setServerStatus] = useState(null);- const [testing, setTesting] = useState(false);- const [testResult, setTestResult] = useState(null);- const [loading, setLoading] = useState(true);-- const [ghPat, setGhPat] = useState('');- const [ghRepoOwner, setGhRepoOwner] = useState('');- const [ghRepoName, setGhRepoName] = useState('');- const [ghBranch, setGhBranch] = useState('main');- const [ghPatSet, setGhPatSet] = useState(false);- const [ghSaving, setGhSaving] = useState(false);-- useEffect(() => { loadStatus(); }, []);+function StatusRow({ label, ok, hint }) {+ return (+ <div className="flex items-center justify-between gap-4 px-4 py-3">+ <div className="min-w-0">+ <p className="text-sm font-medium text-ink">{label}</p>+ {hint && <p className="text-caption text-ink-faint">{hint}</p>}+ </div>+ {ok ? (+ <Badge variant="success"><CheckCircle2 />Configured</Badge>+ ) : (+ <Badge variant="warning"><AlertTriangle />Not set</Badge>+ )}+ </div>+ );+}- const loadStatus = async () => {- setLoading(true);- try {- const [keys, gh] = await Promise.all([api.getKeys(), api.getGithubSettings()]);- setServerStatus(keys);- setGhRepoOwner(gh.repoOwner || '');- setGhRepoName(gh.repoName || '');- setGhBranch(gh.branch || 'main');- setGhPatSet(gh.patSet || false);- } catch {+export default function Settings() {+ const { showToast, refreshAll, loading: refreshingAll } = useAppContext();+ const { theme, setTheme } = useTheme();++ const [serverStatus, setServerStatus] = useState(null);+ const [testing, setTesting] = useState(false);+ const [testResult, setTestResult] = useState(null);+ const [loading, setLoading] = useState(true);++ const [ghPat, setGhPat] = useState('');+ const [ghRepoOwner, setGhRepoOwner] = useState('');+ const [ghRepoName, setGhRepoName] = useState('');+ const [ghBranch, setGhBranch] = useState('main');+ const [ghPatSet, setGhPatSet] = useState(false);+ const [ghSaving, setGhSaving] = useState(false);++ useEffect(() => {+ let cancelled = false;+ (async () => {try {- const keys = await api.getKeys();+ const [keys, gh] = await Promise.all([api.getKeys(), api.getGithubSettings()]);+ if (cancelled) return;setServerStatus(keys);- } catch { /* non-critical */ }- } finally {- setLoading(false);- }- };-- const handleSaveGithub = async () => {+ setGhRepoOwner(gh.repoOwner || '');+ setGhRepoName(gh.repoName || '');+ setGhBranch(gh.branch || 'main');+ setGhPatSet(gh.patSet || false);+ } catch {+ try {+ const keys = await api.getKeys();+ if (!cancelled) setServerStatus(keys);+ } catch { /* status is informational; the page still renders */ }+ } finally {+ if (!cancelled) setLoading(false);+ }+ })();+ return () => { cancelled = true; };+ }, []);++ const handleSaveGithub = async e => {+ e.preventDefault();setGhSaving(true);try {await api.saveGithubSettings({ pat: ghPat || undefined, repoOwner: ghRepoOwner, repoName: ghRepoName, branch: ghBranch });@@ -84,379 +133,202 @@ export default function Settings() {if (ghPat) setGhPatSet(true);setGhPat('');} catch (err) {- showToast('Failed to save: ' + err.message, 'error');+ showToast(`Couldn't save GitHub settings. ${err.message}`, 'error');} finally {setGhSaving(false);}};const handleTest = async () => {- setTesting(true); setTestResult(null);+ setTesting(true);+ setTestResult(null);try {const res = await api.health();- setTestResult({ success: res.status === 'ok', message: res.status === 'ok' ? 'API connection successful!' : 'Unexpected status.' });+ setTestResult(res.status === 'ok'+ ? { success: true, message: 'The API is reachable and healthy.' }+ : { success: false, message: `The API answered with status "${res.status}". Check the Worker logs.` });} catch (err) {- setTestResult({ success: false, message: 'Connection failed: ' + err.message });- } finally { setTesting(false); }+ setTestResult({ success: false, message: `The API could not be reached: ${err.message}. Check VITE_API_URL and that the Worker is deployed.` });+ } finally {+ setTesting(false);+ }};if (loading) {return (- <div className="space-y-4">- {[1, 2, 3].map(i => <Skeleton key={i} className="h-48 w-full rounded-xl" />)}+ <div className="flex flex-col gap-8">+ <PageHeader title="Settings" description="Appearance, connections and setup guides" />+ {[0, 1, 2].map(i => <Skeleton key={i} className="h-40 rounded-card" />)}</div>);}return (- <div className="space-y-6">- <div>- <h1 className="text-2xl font-bold tracking-tight">Settings</h1>- <p className="text-sm text-muted-foreground mt-0.5">Platform configuration and guides</p>- </div>-- <div className="grid grid-cols-1 xl:grid-cols-3 gap-6">- <div className="xl:col-span-2 space-y-4">-- {/* Server-managed keys status */}- <MainCard title="Server API Keys">- <div className="space-y-3">- <div className="flex items-start gap-3 p-3 rounded-lg bg-muted/50 border border-border">- <ShieldCheck className="h-5 w-5 text-primary mt-0.5 flex-shrink-0" />- <div className="space-y-1">- <p className="text-sm font-medium">All API keys are managed by the server</p>- <p className="text-sm text-muted-foreground">- YouTube, Instagram, and Cloudinary credentials are set as environment variables by the administrator and shared across all users.- </p>- </div>- </div>- {serverStatus && (- <div className="grid grid-cols-3 gap-2">- {[- { label: 'YouTube', ok: serverStatus.youtube?.configured },- { label: 'Instagram', ok: serverStatus.instagram?.configured },- { label: 'Cloudinary', ok: serverStatus.cloudinary?.configured },- ].map(({ label, ok }) => (- <div key={label} className="flex items-center gap-2 p-2 rounded-md border border-border bg-card">- {ok- ? <CheckCircle2 className="h-4 w-4 text-green-500 flex-shrink-0" />- : <AlertTriangle className="h-4 w-4 text-amber-500 flex-shrink-0" />}- <div>- <p className="text-xs font-medium">{label}</p>- <p className="text-xs text-muted-foreground">{ok ? 'Configured' : 'Not set'}</p>- </div>- </div>- ))}- </div>- )}- </div>- </MainCard>-- {/* GitHub credentials */}- <MainCard title="GitHub Integration">- <div className="space-y-4">- <div className="flex items-start gap-3 p-3 rounded-lg bg-muted/50 border border-border">- <GitBranch className="h-5 w-5 text-foreground mt-0.5 flex-shrink-0" />- <div className="space-y-1">- <p className="text-sm font-medium">Connect your GitHub repository</p>- <p className="text-sm text-muted-foreground">- Used for GitHub Actions-based scheduled publishing. The PAT lets the scheduler- trigger workflows in your repository.- </p>- </div>- </div>-- <div className="grid grid-cols-2 gap-3">- <div className="space-y-1.5">- <Label htmlFor="gh-owner" className="text-xs">Repository owner</Label>- <Input- id="gh-owner"- placeholder="spacesdrive"- value={ghRepoOwner}- onChange={e => setGhRepoOwner(e.target.value)}- className="h-8 text-sm"- />- </div>- <div className="space-y-1.5">- <Label htmlFor="gh-repo" className="text-xs">Repository name</Label>- <Input- id="gh-repo"- placeholder="twiligent"- value={ghRepoName}- onChange={e => setGhRepoName(e.target.value)}- className="h-8 text-sm"- />- </div>- </div>-- <div className="space-y-1.5">- <Label htmlFor="gh-branch" className="text-xs">Branch</Label>- <Input- id="gh-branch"- placeholder="main"- value={ghBranch}- onChange={e => setGhBranch(e.target.value)}- className="h-8 text-sm"- />+ <div className="flex flex-col gap-8">+ <PageHeader title="Settings" description="Appearance, connections and setup guides" />++ <div className="flex flex-col gap-8">+ <SettingsSection id="appearance" title="Appearance" description="Choose a theme or follow your system setting.">+ <SurfaceBox>+ <FieldRow label="Theme" hint="Dusk is the dark theme, Paper the light one.">+ <Tabs value={theme ?? 'system'} onValueChange={setTheme}>+ <TabsList variant="segmented" className="w-full sm:w-fit">+ <TabsTrigger value="light"><Sun />Light</TabsTrigger>+ <TabsTrigger value="dark"><Moon />Dark</TabsTrigger>+ <TabsTrigger value="system"><Monitor />System</TabsTrigger>+ </TabsList>+ </Tabs>+ </FieldRow>+ </SurfaceBox>+ </SettingsSection>++ <SettingsSection+ id="server-keys"+ title="Server API keys"+ description="YouTube, Instagram and Cloudinary credentials are environment variables on the server, shared by everyone on this instance."+ >+ <SurfaceBox content={false} className="divide-y divide-divider">+ <StatusRow label="YouTube" hint="Channel and video analytics" ok={serverStatus?.youtube?.configured} />+ <StatusRow label="Instagram" hint="Account connection and publishing" ok={serverStatus?.instagram?.configured} />+ <StatusRow label="Cloudinary" hint="Media hosting for publishing" ok={serverStatus?.cloudinary?.configured} />+ </SurfaceBox>+ <div className="flex flex-wrap items-center gap-2">+ <Button variant="outline" onClick={handleTest} disabled={testing}>+ {testing ? <Spinner className="size-4" /> : <Activity data-icon="inline-start" />}+ {testing ? 'Checking API' : 'Check API health'}+ </Button>+ <Button variant="outline" onClick={refreshAll} disabled={refreshingAll}>+ <RefreshCw data-icon="inline-start" className={cn(refreshingAll && 'animate-spin')} />+ {refreshingAll ? 'Refreshing accounts' : 'Refresh all accounts'}+ </Button>+ </div>+ {testResult && (+ <Alert variant={testResult.success ? 'success' : 'destructive'}>+ {testResult.success ? <CheckCircle2 /> : <AlertTriangle />}+ <AlertDescription>{testResult.success ? '' : 'Error: '}{testResult.message}</AlertDescription>+ </Alert>+ )}+ </SettingsSection>++ <SettingsSection+ id="github"+ title="GitHub"+ description="Used for scheduled publishing through GitHub Actions. The token lets the scheduler trigger workflows in your repository."+ >+ <SurfaceBox>+ <form className="flex flex-col gap-5" onSubmit={handleSaveGithub}>+ <div className="grid grid-cols-1 gap-5 sm:grid-cols-2">+ <FieldRow label="Repository owner" htmlFor="gh-owner">+ <Input id="gh-owner" placeholder="owner" value={ghRepoOwner} onChange={e => setGhRepoOwner(e.target.value)} autoComplete="off" />+ </FieldRow>+ <FieldRow label="Repository name" htmlFor="gh-repo">+ <Input id="gh-repo" placeholder="twiligent" value={ghRepoName} onChange={e => setGhRepoName(e.target.value)} autoComplete="off" />+ </FieldRow></div>-- <div className="space-y-1.5">- <Label htmlFor="gh-pat" className="text-xs">- Personal Access Token- {ghPatSet && (- <Badge variant="secondary" className="ml-2 text-xs font-normal">- <CheckCircle2 className="h-3 w-3 mr-1 text-green-500" />saved- </Badge>- )}- </Label>+ <FieldRow label="Branch" htmlFor="gh-branch">+ <Input id="gh-branch" placeholder="main" value={ghBranch} onChange={e => setGhBranch(e.target.value)} autoComplete="off" className="sm:max-w-xs" />+ </FieldRow>+ <FieldRow+ label={<span className="flex items-center gap-2">Personal access token{ghPatSet && <Badge variant="success"><CheckCircle2 />Saved</Badge>}</span>}+ hint="Leave blank to keep the saved token. The guide below explains how to create one."+ htmlFor="gh-pat"+ ><Inputid="gh-pat"type="password"- placeholder={ghPatSet ? 'Enter new token to replace saved one' : 'github_pat_...'}+ placeholder={ghPatSet ? 'Enter a new token to replace the saved one' : 'github_pat_...'}value={ghPat}onChange={e => setGhPat(e.target.value)}- className="h-8 text-sm font-mono"+ autoComplete="off"+ className="font-mono"/>- <p className="text-xs text-muted-foreground">Leave blank to keep the existing token. See the guide below for how to create one.</p>- </div>-- <Button size="sm" className="gap-2" onClick={handleSaveGithub} disabled={ghSaving}>- {ghSaving ? <RefreshCw className="h-3.5 w-3.5 animate-spin" /> : <Save className="h-3.5 w-3.5" />}- Save GitHub Settings- </Button>- </div>- </MainCard>-- {/* GitHub guide */}- <MainCard title="GitHub Personal Access Token">- <div className="space-y-4">- <div className="flex items-start gap-3 p-3 rounded-lg bg-muted/50 border border-border">- <GitBranch className="h-5 w-5 text-foreground mt-0.5 flex-shrink-0" />- <div className="space-y-1">- <p className="text-sm font-medium">What is a GitHub PAT and why do you need it?</p>- <p className="text-sm text-muted-foreground">- A Personal Access Token lets external services (like this app or a CI workflow) interact with- your GitHub repositories on your behalf. In Twiligent it is used for GitHub Actions-based- scheduled publishing when deploying via Cloudflare Workers.- </p>- </div>+ </FieldRow>+ <div>+ <Button type="submit" disabled={ghSaving}>+ {ghSaving ? <Spinner className="size-4" /> : <Save data-icon="inline-start" />}+ {ghSaving ? 'Saving' : 'Save GitHub settings'}+ </Button></div>-- <div className="space-y-3">- <p className="text-sm font-semibold">How to create a GitHub PAT (step-by-step)</p>-- <div className="space-y-3">- <div className="flex items-start gap-3">- <StepBadge n={1} />- <div className="space-y-1 pt-0.5">- <p className="text-sm font-medium">Open GitHub Settings</p>- <p className="text-sm text-muted-foreground">- Go to <strong>github.com</strong>, click your profile photo (top-right), then click{' '}- <strong>Settings</strong>.- </p>- </div>- </div>-- <div className="flex items-start gap-3">- <StepBadge n={2} />- <div className="space-y-1 pt-0.5">- <p className="text-sm font-medium">Go to Developer Settings</p>- <p className="text-sm text-muted-foreground">- Scroll to the very bottom of the left sidebar and click{' '}- <strong>Developer settings</strong>.- </p>- </div>- </div>-- <div className="flex items-start gap-3">- <StepBadge n={3} />- <div className="space-y-1 pt-0.5">- <p className="text-sm font-medium">Create a Fine-grained token</p>- <p className="text-sm text-muted-foreground">- Click <strong>Personal access tokens</strong> then{' '}- <strong>Fine-grained tokens</strong> then{' '}- <strong>Generate new token</strong>.- Fine-grained tokens are safer than classic tokens because you choose exact permissions.- </p>- </div>- </div>-- <div className="flex items-start gap-3">- <StepBadge n={4} />- <div className="space-y-1 pt-0.5">- <p className="text-sm font-medium">Set token details</p>- <ul className="space-y-1 text-sm text-muted-foreground list-disc list-inside">- <li><strong className="text-foreground">Token name:</strong> give it a clear name like <em>twiligent-actions</em></li>- <li><strong className="text-foreground">Expiration:</strong> pick 90 days or custom (you can always regenerate)</li>- <li><strong className="text-foreground">Repository access:</strong> select <em>Only select repositories</em>, then choose the repo</li>- </ul>- </div>- </div>-- <div className="flex items-start gap-3">- <StepBadge n={5} />- <div className="space-y-1 pt-0.5">- <p className="text-sm font-medium">Set permissions</p>- <p className="text-sm text-muted-foreground">- Under <strong>Repository permissions</strong>, enable:- </p>- <div className="flex flex-wrap gap-1.5 mt-1">- {['Actions: Read and write', 'Secrets: Read and write', 'Contents: Read-only'].map(p => (- <Badge key={p} variant="secondary" className="text-xs font-normal">{p}</Badge>- ))}+ </form>+ </SurfaceBox>++ <SurfaceBox title="Create a GitHub personal access token" subheader="A token lets this app and its workflow act on your repository on your behalf.">+ <ol className="flex flex-col gap-4">+ {PAT_STEPS.map((step, i) => (+ <li key={step.title} className="flex gap-3">+ <span className="flex size-6 shrink-0 items-center justify-center rounded-full bg-surface-sunken font-mono text-caption font-medium text-ink-muted">{i + 1}</span>+ <div className="flex min-w-0 flex-col gap-1 pt-0.5">+ <p className="text-sm font-medium text-ink">{step.title}</p>+ <div className="text-sm text-ink-muted [&_strong]:font-semibold [&_strong]:text-ink">{step.body}</div>+ {step.code && (+ <div className="mt-1.5 flex items-center gap-2 rounded-control border border-line bg-surface-sunken px-3 py-1.5">+ <code className="flex-1 font-mono text-small text-ink">{step.code}</code>+ <CopyButton text={step.code} /></div>- </div>+ )}</div>-- <div className="flex items-start gap-3">- <StepBadge n={6} />- <div className="space-y-1 pt-0.5">- <p className="text-sm font-medium">Copy the token immediately</p>- <p className="text-sm text-muted-foreground">- Click <strong>Generate token</strong>. GitHub shows the token once only.- Copy it right away and store it somewhere safe (like a password manager).- If you lose it you must generate a new one.- </p>- </div>- </div>-- <div className="flex items-start gap-3">- <StepBadge n={7} />- <div className="space-y-1 pt-0.5">- <p className="text-sm font-medium">Add it as a GitHub Actions secret</p>- <p className="text-sm text-muted-foreground">- In your repository, go to <strong>Settings</strong> then <strong>Secrets and variables</strong>{' '}- then <strong>Actions</strong> then <strong>New repository secret</strong>.- Name it exactly:- </p>- <div className="flex items-center gap-2 mt-1.5 font-mono text-xs bg-muted px-3 py-2 rounded-md border border-border">- <Key className="h-3.5 w-3.5 text-muted-foreground flex-shrink-0" />- <span className="flex-1">GITHUB_PAT</span>- <CopyButton text="GITHUB_PAT" />- </div>- </div>- </div>- </div>-- <Alert>- <Info className="h-4 w-4" />- <AlertDescription className="text-xs">- Never share your token in code, commit it to git, or paste it in a public place.- If a token is accidentally exposed, go to GitHub and delete it immediately, then generate a new one.- </AlertDescription>- </Alert>- </div>+ </li>+ ))}+ </ol>+ <Alert variant="warning" className="mt-5">+ <AlertTriangle />+ <AlertDescription>+ Never put a token in code, a commit or a public place. If one is exposed, delete it on GitHub straight away and generate a new one.+ </AlertDescription>+ </Alert>+ </SurfaceBox>+ </SettingsSection>++ <SettingsSection id="platforms" title="Platform requirements" description="What each platform needs before it can be added.">+ <SurfaceBox content={false} className="divide-y divide-divider">+ <div className="flex flex-col gap-1 px-5 py-4">+ <p className="text-sm font-medium text-ink">YouTube</p>+ <p className="text-sm text-ink-muted">Add a channel link or @handle in Accounts. The API key is already set on the server.</p></div>- </MainCard>-- {/* Platform requirements */}- <MainCard title="Platform Requirements">- <div className="space-y-4">- <div>- <p className="text-sm font-semibold mb-2">YouTube</p>- <p className="text-sm text-muted-foreground">- Just add a channel URL or @handle in <strong>Manage Accounts</strong>. The API key is already configured by the server.- </p>- </div>- <Separator />- <div>- <p className="text-sm font-semibold mb-2">Instagram</p>- <ol className="space-y-2 text-sm text-muted-foreground list-decimal list-inside">- <li>Your account must be a <strong className="text-foreground">Business</strong> or <strong className="text-foreground">Creator</strong> professional account</li>- <li>Go to <strong className="text-foreground">Manage Accounts</strong> then Add Account then Instagram</li>- <li>Click <strong className="text-foreground">Connect with Instagram</strong> and you will log in directly on Instagram</li>- <li>Grant the requested permissions and you will be redirected back automatically</li>- </ol>- <Alert className="mt-3">- <AlertTriangle className="h-4 w-4" />- <AlertDescription className="text-xs">- In development mode, only <strong>test users</strong> added in the Facebook App Dashboard can connect. Your Instagram account must be added as a tester there first.- </AlertDescription>- </Alert>- </div>- <Separator />- <div>- <p className="text-sm font-semibold mb-2">Cloudinary (Instagram uploads)</p>- <p className="text-sm text-muted-foreground">- Instagram requires all media to be hosted at a public URL before publishing. Cloudinary handles this automatically.- The cloud name and upload preset are configured server-side. No action needed from you.- </p>- </div>+ <div className="flex flex-col gap-2 px-5 py-4">+ <p className="text-sm font-medium text-ink">Instagram</p>+ <ol className="flex list-decimal flex-col gap-1 pl-5 text-sm text-ink-muted marker:text-ink-faint">+ <li>The account must be an Instagram Business or Creator account.</li>+ <li>In Accounts, choose Add account, then Instagram account.</li>+ <li>Continue to Instagram and sign in there.</li>+ <li>Approve the requested permissions. Instagram sends you back here automatically.</li>+ </ol>+ <Alert variant="info" className="mt-2">+ <Info />+ <AlertDescription>+ While the Meta app is in development mode, only test users added in the Meta app dashboard can connect. Add your Instagram account as a tester first.+ </AlertDescription>+ </Alert></div>- </MainCard>- </div>-- {/* Sidebar */}- <div className="space-y-4">- <div className="sticky top-20 space-y-4">- <MainCard title="Quick Actions">- <div className="space-y-2">- <Button variant="outline" size="sm" className="w-full gap-2 justify-start" onClick={refreshAll}>- <RefreshCw className="h-3.5 w-3.5" /> Refresh All Accounts- </Button>- <Button variant="outline" size="sm" className="w-full gap-2 justify-start" onClick={handleTest} disabled={testing}>- {testing ? <RefreshCw className="h-3.5 w-3.5 animate-spin" /> : <CheckCircle2 className="h-3.5 w-3.5" />}- Test API Health- </Button>- </div>- {testResult && (- <Alert variant={testResult.success ? 'default' : 'destructive'} className="mt-3">- {testResult.success ? <CheckCircle2 className="h-4 w-4" /> : <AlertTriangle className="h-4 w-4" />}- <AlertDescription className="text-xs">{testResult.message}</AlertDescription>- </Alert>- )}- </MainCard>-- <MainCard title="Useful Links">- <div className="space-y-2">- {[- { label: 'GitHub Settings', href: 'https://github.com/settings/profile' },- { label: 'GitHub Fine-grained tokens', href: 'https://github.com/settings/tokens?type=beta' },- { label: 'Cloudinary Dashboard', href: 'https://cloudinary.com/console' },- { label: 'Google Cloud Console', href: 'https://console.cloud.google.com/apis/credentials' },- { label: 'Facebook App Dashboard', href: 'https://developers.facebook.com/apps' },- { label: 'Cloudflare Dashboard', href: 'https://dash.cloudflare.com' },- ].map(({ label, href }) => (- <a- key={label}- href={href}- target="_blank"- rel="noreferrer"- className="flex items-center justify-between gap-2 text-xs text-muted-foreground hover:text-foreground transition-colors py-1"- >- {label}- <ExternalLink className="h-3 w-3 flex-shrink-0" />- </a>- ))}- </div>- </MainCard>-- <MainCard title="About">- <div className="space-y-3">- <p className="text-xs text-muted-foreground leading-relaxed">- Twiligent is a comprehensive analytics tool for tracking YouTube and Instagram performance.- </p>- <Separator />- <div className="flex flex-wrap gap-1.5">- {[- { label: 'React', color: 'bg-sky-100 text-sky-700 border-sky-200 dark:bg-sky-900/30 dark:text-sky-400 dark:border-sky-800' },- { label: 'shadcn/ui', color: 'bg-zinc-100 text-zinc-700 border-zinc-200 dark:bg-zinc-800 dark:text-zinc-300 dark:border-zinc-700' },- { label: 'Tailwind v4', color: 'bg-cyan-100 text-cyan-700 border-cyan-200 dark:bg-cyan-900/30 dark:text-cyan-400 dark:border-cyan-800' },- { label: 'Hono', color: 'bg-orange-100 text-orange-700 border-orange-200 dark:bg-orange-900/30 dark:text-orange-400 dark:border-orange-800' },- { label: 'Supabase', color: 'bg-emerald-100 text-emerald-700 border-emerald-200 dark:bg-emerald-900/30 dark:text-emerald-400 dark:border-emerald-800' },- { label: 'Cloudflare', color: 'bg-orange-100 text-orange-700 border-orange-200 dark:bg-orange-900/30 dark:text-orange-400 dark:border-orange-800' },- { label: 'YouTube API', color: 'bg-red-100 text-red-700 border-red-200 dark:bg-red-900/30 dark:text-red-400 dark:border-red-800' },- { label: 'Instagram API', color: 'bg-pink-100 text-pink-700 border-pink-200 dark:bg-pink-900/30 dark:text-pink-400 dark:border-pink-800' },- ].map(c => (- <span key={c.label} className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium border ${c.color}`}>- {c.label}- </span>- ))}- </div>- </div>- </MainCard>+ <div className="flex flex-col gap-1 px-5 py-4">+ <p className="text-sm font-medium text-ink">Cloudinary</p>+ <p className="text-sm text-ink-muted">Instagram needs every file at a public URL before publishing. Cloudinary hosts uploads for that; its cloud name and upload preset are set on the server.</p>+ </div>+ </SurfaceBox>+ </SettingsSection>++ <SettingsSection id="links" title="Useful links">+ <SurfaceBox content={false} className="divide-y divide-divider">+ {LINKS.map(({ label, href }) => (+ <a+ key={label}+ href={href}+ target="_blank"+ rel="noreferrer"+ className="flex items-center justify-between gap-2 px-5 py-3 text-sm text-ink transition-colors duration-(--duration-fast) hover:bg-surface-hover"+ >+ {label}+ <ExternalLink className="size-4 shrink-0 text-ink-faint" />+ </a>+ ))}+ </SurfaceBox>+ </SettingsSection>++ <SettingsSection id="about" title="About Twiligent" description="Analytics and publishing for YouTube, Instagram and Reddit, run on your own infrastructure.">+ <div className="flex flex-wrap gap-1.5">+ {STACK.map(item => <Badge key={item} variant="outline">{item}</Badge>)}</div>- </div>+ </SettingsSection></div></div>);diff --git a/frontend/src/hooks/use-command-palette-shortcut.js b/frontend/src/hooks/use-command-palette-shortcut.jsnew file mode 100644index 0000000..b2301a1--- /dev/null+++ b/frontend/src/hooks/use-command-palette-shortcut.js@@ -0,0 +1,15 @@+import { useEffect } from 'react';++// Ctrl+K on Windows and Linux, Cmd+K on macOS, toggles the command palette from anywhere.+export function useCommandPaletteShortcut(setOpen) {+ useEffect(() => {+ const onKeyDown = e => {+ if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'k') {+ e.preventDefault();+ setOpen(open => !open);+ }+ };+ window.addEventListener('keydown', onKeyDown);+ return () => window.removeEventListener('keydown', onKeyDown);+ }, [setOpen]);+}diff --git a/frontend/src/index.css b/frontend/src/index.cssindex 77c6c9d..c33e241 100644--- a/frontend/src/index.css+++ b/frontend/src/index.css@@ -4,127 +4,329 @@@custom-variant dark (&:is(.dark *));-@theme inline {- --font-heading: var(--font-sans);- --font-sans: 'Inter', system-ui, -apple-system, sans-serif;- --color-sidebar-ring: var(--sidebar-ring);- --color-sidebar-border: var(--sidebar-border);- --color-sidebar-accent-foreground: var(--sidebar-accent-foreground);- --color-sidebar-accent: var(--sidebar-accent);- --color-sidebar-primary-foreground: var(--sidebar-primary-foreground);- --color-sidebar-primary: var(--sidebar-primary);- --color-sidebar-foreground: var(--sidebar-foreground);- --color-sidebar: var(--sidebar);- --color-chart-5: var(--chart-5);- --color-chart-4: var(--chart-4);- --color-chart-3: var(--chart-3);- --color-chart-2: var(--chart-2);- --color-chart-1: var(--chart-1);- --color-ring: var(--ring);- --color-input: var(--input);- --color-border: var(--border);- --color-destructive: var(--destructive);- --color-accent-foreground: var(--accent-foreground);- --color-accent: var(--accent);- --color-muted-foreground: var(--muted-foreground);- --color-muted: var(--muted);- --color-secondary-foreground: var(--secondary-foreground);- --color-secondary: var(--secondary);- --color-primary-foreground: var(--primary-foreground);- --color-primary: var(--primary);- --color-popover-foreground: var(--popover-foreground);- --color-popover: var(--popover);- --color-card-foreground: var(--card-foreground);- --color-card: var(--card);- --color-foreground: var(--foreground);- --color-background: var(--background);- --radius-sm: calc(var(--radius) * 0.6);- --radius-md: calc(var(--radius) * 0.8);- --radius-lg: var(--radius);- --radius-xl: calc(var(--radius) * 1.4);- --radius-2xl: calc(var(--radius) * 1.8);- --radius-3xl: calc(var(--radius) * 2.2);- --radius-4xl: calc(var(--radius) * 2.6);-}+/* Brand typefaces from the Twiligent brand kit (frontend/public/fonts), SIL OFL 1.1 */+@font-face { font-family: "Manrope"; font-style: normal; font-weight: 400; font-display: swap; src: url("/fonts/manrope-latin-400-normal.woff2") format("woff2"); }+@font-face { font-family: "Manrope"; font-style: normal; font-weight: 500; font-display: swap; src: url("/fonts/manrope-latin-500-normal.woff2") format("woff2"); }+@font-face { font-family: "Manrope"; font-style: normal; font-weight: 600; font-display: swap; src: url("/fonts/manrope-latin-600-normal.woff2") format("woff2"); }+@font-face { font-family: "Manrope"; font-style: normal; font-weight: 700; font-display: swap; src: url("/fonts/manrope-latin-700-normal.woff2") format("woff2"); }+@font-face { font-family: "Sora"; font-style: normal; font-weight: 600; font-display: swap; src: url("/fonts/sora-latin-600-normal.woff2") format("woff2"); }+@font-face { font-family: "Sora"; font-style: normal; font-weight: 700; font-display: swap; src: url("/fonts/sora-latin-700-normal.woff2") format("woff2"); }+@font-face { font-family: "JetBrains Mono"; font-style: normal; font-weight: 400; font-display: swap; src: url("/fonts/jetbrains-mono-latin-400-normal.woff2") format("woff2"); }+@font-face { font-family: "JetBrains Mono"; font-style: normal; font-weight: 500; font-display: swap; src: url("/fonts/jetbrains-mono-latin-500-normal.woff2") format("woff2"); }+/*+ * Design tokens. Every value traces to docs/design-reference.md:+ * colours, fonts, radii and shadows come from frontend/public/tokens.json,+ * layout and density from the measured interface reference.+ */:root {- --background: oklch(0.985 0 0);- --foreground: oklch(0.145 0 0);- --card: oklch(1 0 0);- --card-foreground: oklch(0.145 0 0);- --popover: oklch(1 0 0);- --popover-foreground: oklch(0.145 0 0);- --primary: oklch(0.546 0.245 262.881);- --primary-foreground: oklch(0.985 0 0);- --secondary: oklch(0.96 0.006 264);- --secondary-foreground: oklch(0.3 0.06 264);- --muted: oklch(0.96 0.003 264);- --muted-foreground: oklch(0.556 0.012 264);- --accent: oklch(0.96 0.006 264);- --accent-foreground: oklch(0.205 0 0);- --destructive: oklch(0.577 0.245 27.325);- --border: oklch(0.9 0.005 264);- --input: oklch(0.9 0.005 264);- --ring: oklch(0.546 0.245 262.881);- --chart-1: oklch(0.546 0.245 262.881);- --chart-2: oklch(0.624 0.185 142.5);- --chart-3: oklch(0.682 0.199 37.7);- --chart-4: oklch(0.558 0.227 304.1);- --chart-5: oklch(0.621 0.218 14.8);+ color-scheme: light;++ /* Surfaces */+ --surface: #F7F3EF;+ --surface-raised: #FFFFFF;+ --surface-sunken: #EFE8E3;+ --surface-sidebar: #F3EEE9;+ --surface-overlay: #FFFFFF;+ --surface-hover: color-mix(in oklab, var(--ink) 4%, transparent);+ --surface-selected: color-mix(in oklab, var(--ink) 6%, transparent);+ --surface-wash: color-mix(in oklab, var(--ink) 4.3%, transparent);++ /* Lines */+ --line: color-mix(in oklab, var(--ink) 8%, var(--surface));+ --line-control: color-mix(in oklab, var(--ink) 12%, var(--surface));+ --line-strong: #8C7E83;+ --divider: color-mix(in oklab, var(--ink) 7%, var(--surface));++ /* Text */+ --ink: #140E10;+ --ink-muted: #5F5357;+ --ink-faint: #6A6565;+ --ink-inverse: #FFFFFF;++ /* Brand accent */+ --brand: #C11F2F;+ --brand-hover: #9A1423;+ --brand-soft: #FBE7E8;+ --brand-text: #B01C2B;+ --on-brand: #FFFFFF;+ --afterglow: #E8A33D;++ /* Status */+ --success: #1E7349;+ --success-soft: #E2F3E9;+ --warning: #7F4C00;+ --warning-soft: #FCEFD9;+ --danger: #B01C2B;+ --danger-soft: #FBE7E8;+ --info: #2C5A99;+ --info-soft: #E5EDF8;++ --focus-ring: #C11F2F;++ /* Data visualisation, in the brand series order */+ --chart-1: #C11F2F;+ --chart-2: #5F5357;+ --chart-3: #B5761A;+ --chart-4: #2C5A99;+ --chart-5: #5E0B14;++ /* Elevation */+ --shadow-sm: 0 1px 2px #140e100f, 0 1px 3px #140e1014;+ --shadow-md: 0 4px 12px #140e1014, 0 1px 3px #140e100f;+ --shadow-lg: 0 16px 40px #140e101f;++ --fold-gradient: linear-gradient(120deg, #C11F2F 0%, #C11F2F 35%, #9A1423 70%, #5E0B14 100%);++ /* Shape */--radius: 0.625rem;- --sidebar: oklch(1 0 0);- --sidebar-foreground: oklch(0.145 0 0);- --sidebar-primary: oklch(0.546 0.245 262.881);- --sidebar-primary-foreground: oklch(0.985 0 0);- --sidebar-accent: oklch(0.96 0.006 264);- --sidebar-accent-foreground: oklch(0.205 0 0);- --sidebar-border: oklch(0.9 0.005 264);- --sidebar-ring: oklch(0.546 0.245 262.881);+ --radius-row: 10px;+ --radius-control: 10px;+ --radius-field: 12px;+ --radius-card: 16px;+ --radius-panel: 24px;+ --radius-dialog: 24px;+ --radius-pill: 999px;++ /* Layout */+ --sidebar-w: 16rem;+ --topbar-h: 3.125rem;+ --content-max: 80rem;+ --control-h: 2.25rem;+ --control-h-sm: 2rem;+ --control-h-lg: 2.5rem;+ --nav-row-h: 2rem;++ /* Motion */+ --duration-fast: 75ms;+ --duration-base: 150ms;+ --duration-overlay: 200ms;+ --duration-fold: 220ms;+ --duration-slow: 320ms;+ --ease-fold: cubic-bezier(0.2, 0.8, 0.2, 1);+ --ease-standard: cubic-bezier(0.4, 0, 0.2, 1);++ /* shadcn/ui contract, mapped onto the tokens above */+ --background: var(--surface);+ --foreground: var(--ink);+ --card: var(--surface-raised);+ --card-foreground: var(--ink);+ --popover: var(--surface-overlay);+ --popover-foreground: var(--ink);+ --primary: var(--brand);+ --primary-foreground: var(--on-brand);+ --secondary: var(--surface-sunken);+ --secondary-foreground: var(--ink);+ --muted: var(--surface-sunken);+ --muted-foreground: var(--ink-muted);+ --accent: var(--surface-selected);+ --accent-foreground: var(--ink);+ --destructive: var(--danger);+ --border: var(--line);+ --input: var(--line-strong);+ --ring: var(--focus-ring);+ --sidebar: var(--surface-sidebar);+ --sidebar-foreground: var(--ink);+ --sidebar-primary: var(--brand);+ --sidebar-primary-foreground: var(--on-brand);+ --sidebar-accent: var(--surface-selected);+ --sidebar-accent-foreground: var(--ink);+ --sidebar-border: var(--line);+ --sidebar-ring: var(--focus-ring);}.dark {- --background: oklch(0.13 0.012 264);- --foreground: oklch(0.985 0 0);- --card: oklch(0.175 0.013 264);- --card-foreground: oklch(0.985 0 0);- --popover: oklch(0.175 0.013 264);- --popover-foreground: oklch(0.985 0 0);- --primary: oklch(0.614 0.245 262.881);- --primary-foreground: oklch(0.1 0.01 264);- --secondary: oklch(0.24 0.015 264);- --secondary-foreground: oklch(0.985 0 0);- --muted: oklch(0.22 0.012 264);- --muted-foreground: oklch(0.65 0.01 264);- --accent: oklch(0.24 0.015 264);- --accent-foreground: oklch(0.985 0 0);- --destructive: oklch(0.704 0.191 22.216);- --border: oklch(1 0 0 / 10%);- --input: oklch(1 0 0 / 15%);- --ring: oklch(0.614 0.245 262.881);- --chart-1: oklch(0.614 0.245 262.881);- --chart-2: oklch(0.624 0.185 142.5);- --chart-3: oklch(0.682 0.199 37.7);- --chart-4: oklch(0.558 0.227 304.1);- --chart-5: oklch(0.621 0.218 14.8);- --sidebar: oklch(0.175 0.013 264);- --sidebar-foreground: oklch(0.985 0 0);- --sidebar-primary: oklch(0.614 0.245 262.881);- --sidebar-primary-foreground: oklch(0.985 0 0);- --sidebar-accent: oklch(0.24 0.015 264);- --sidebar-accent-foreground: oklch(0.985 0 0);- --sidebar-border: oklch(1 0 0 / 10%);- --sidebar-ring: oklch(0.614 0.245 262.881);+ color-scheme: dark;++ --surface: #140E10;+ --surface-raised: #1F1719;+ --surface-sunken: #0C0809;+ --surface-sidebar: #1A1214;+ --surface-overlay: #1F1719;++ --line-strong: #86777C;++ --ink: #F5EFEB;+ --ink-muted: #B8ABAF;+ --ink-faint: #97918F;+ --ink-inverse: #140E10;++ --brand: #C11F2F;+ --brand-hover: #D93444;+ --brand-soft: #3A1419;+ --brand-text: #FF7A82;+ --on-brand: #FFFFFF;++ --success: #5FCB95;+ --success-soft: #12301F;+ --warning: #F2B65E;+ --warning-soft: #3A2A12;+ --danger: #FF7A82;+ --danger-soft: #3A1419;+ --info: #8DB3EC;+ --info-soft: #16243A;++ --focus-ring: #FF7A82;++ --chart-1: #D93444;+ --chart-2: #B8ABAF;+ --chart-3: #E8A33D;+ --chart-4: #8DB3EC;+ --chart-5: #B4626E;++ --shadow-sm: 0 1px 2px #00000066;+ --shadow-md: 0 4px 16px #00000080;+ --shadow-lg: 0 16px 48px #000000a6;+}++@theme inline {+ --font-sans: "Manrope", system-ui, -apple-system, "Segoe UI", sans-serif;+ --font-heading: "Sora", "Manrope", system-ui, sans-serif;+ --font-display: "Sora", "Manrope", system-ui, sans-serif;+ --font-mono: "JetBrains Mono", ui-monospace, "SF Mono", Menlo, monospace;++ --text-display: 1.75rem;+ --text-display--line-height: 2.25rem;+ --text-display--letter-spacing: -0.02em;+ --text-page-title: 1.5rem;+ --text-page-title--line-height: 1.875rem;+ --text-page-title--letter-spacing: -0.015em;+ --text-section: 1rem;+ --text-section--line-height: 1.5rem;+ --text-section--letter-spacing: -0.01em;+ --text-body: 0.875rem;+ --text-body--line-height: 1.25rem;+ --text-small: 0.8125rem;+ --text-small--line-height: 1.21875rem;+ --text-caption: 0.75rem;+ --text-caption--line-height: 1rem;++ --color-background: var(--background);+ --color-foreground: var(--foreground);+ --color-card: var(--card);+ --color-card-foreground: var(--card-foreground);+ --color-popover: var(--popover);+ --color-popover-foreground: var(--popover-foreground);+ --color-primary: var(--primary);+ --color-primary-foreground: var(--primary-foreground);+ --color-secondary: var(--secondary);+ --color-secondary-foreground: var(--secondary-foreground);+ --color-muted: var(--muted);+ --color-muted-foreground: var(--muted-foreground);+ --color-accent: var(--accent);+ --color-accent-foreground: var(--accent-foreground);+ --color-destructive: var(--destructive);+ --color-border: var(--border);+ --color-input: var(--input);+ --color-ring: var(--ring);+ --color-chart-1: var(--chart-1);+ --color-chart-2: var(--chart-2);+ --color-chart-3: var(--chart-3);+ --color-chart-4: var(--chart-4);+ --color-chart-5: var(--chart-5);+ --color-sidebar: var(--sidebar);+ --color-sidebar-foreground: var(--sidebar-foreground);+ --color-sidebar-primary: var(--sidebar-primary);+ --color-sidebar-primary-foreground: var(--sidebar-primary-foreground);+ --color-sidebar-accent: var(--sidebar-accent);+ --color-sidebar-accent-foreground: var(--sidebar-accent-foreground);+ --color-sidebar-border: var(--sidebar-border);+ --color-sidebar-ring: var(--sidebar-ring);++ --color-surface: var(--surface);+ --color-surface-raised: var(--surface-raised);+ --color-surface-sunken: var(--surface-sunken);+ --color-surface-hover: var(--surface-hover);+ --color-surface-selected: var(--surface-selected);+ --color-surface-wash: var(--surface-wash);+ --color-line: var(--line);+ --color-line-strong: var(--line-strong);+ --color-line-control: var(--line-control);+ --color-divider: var(--divider);+ --color-ink: var(--ink);+ --color-ink-muted: var(--ink-muted);+ --color-ink-faint: var(--ink-faint);+ --color-ink-inverse: var(--ink-inverse);+ --color-brand: var(--brand);+ --color-brand-hover: var(--brand-hover);+ --color-brand-soft: var(--brand-soft);+ --color-brand-text: var(--brand-text);+ --color-on-brand: var(--on-brand);+ --color-afterglow: var(--afterglow);+ --color-success: var(--success);+ --color-success-soft: var(--success-soft);+ --color-warning: var(--warning);+ --color-warning-soft: var(--warning-soft);+ --color-danger: var(--danger);+ --color-danger-soft: var(--danger-soft);+ --color-info: var(--info);+ --color-info-soft: var(--info-soft);++ --radius-sm: 6px;+ --radius-md: var(--radius-control);+ --radius-lg: 12px;+ --radius-xl: var(--radius-card);+ --radius-2xl: var(--radius-dialog);+ --radius-3xl: 24px;+ --radius-4xl: var(--radius-pill);+ --radius-row: var(--radius-row);+ --radius-control: var(--radius-control);+ --radius-field: var(--radius-field);+ --radius-card: var(--radius-card);+ --radius-panel: var(--radius-panel);+ --radius-dialog: var(--radius-dialog);+ --radius-pill: var(--radius-pill);++ --shadow-sm: var(--shadow-sm);+ --shadow-md: var(--shadow-md);+ --shadow-lg: var(--shadow-lg);++ --ease-fold: var(--ease-fold);+ --ease-standard: var(--ease-standard);++ --animate-fold-in: fold-in var(--duration-fold) var(--ease-fold) both;+}++@keyframes fold-in {+ from { opacity: 0; transform: translate(-4px, 7px); }+ to { opacity: 1; transform: none; }}@layer base {* {@apply border-border outline-ring/50;}- body {- @apply bg-background text-foreground;- }html {@apply font-sans;+ -webkit-font-smoothing: antialiased;+ -moz-osx-font-smoothing: grayscale;+ text-rendering: optimizeLegibility;+ }+ body {+ background-color: var(--surface);+ color: var(--ink);+ font-size: var(--text-body);+ line-height: var(--text-body--line-height);+ }+ h1, h2, h3 {+ font-family: var(--font-heading);+ font-weight: 600;+ }+ :focus-visible {+ outline: 2px solid var(--focus-ring);+ outline-offset: 2px;+ }+ ::selection {+ background: var(--brand-soft);+ color: var(--ink);+ }+ @media (prefers-reduced-motion: reduce) {+ *, *::before, *::after {+ animation-duration: 1ms !important;+ animation-iteration-count: 1 !important;+ transition-duration: 1ms !important;+ scroll-behavior: auto !important;+ }}}@@ -136,4 +338,17 @@.scrollbar-hide::-webkit-scrollbar {display: none;}+ .tabular {+ font-variant-numeric: tabular-nums;+ }+ .eyebrow {+ font-size: 0.75rem;+ line-height: 1rem;+ font-weight: 700;+ letter-spacing: 0.12em;+ text-transform: uppercase;+ }+ .fold-band {+ background-image: var(--fold-gradient);+ }}diff --git a/frontend/src/layout/Header.jsx b/frontend/src/layout/Header.jsxindex 961f436..36b6627 100644--- a/frontend/src/layout/Header.jsx+++ b/frontend/src/layout/Header.jsx@@ -1,119 +1,76 @@import React from 'react';-import { useNavigate, useLocation } from 'react-router-dom';+import { useLocation } from 'react-router-dom';+import { useTheme } from 'next-themes';+import { RefreshCw, Sun, Moon, Search } from 'lucide-react';import { SidebarTrigger } from '@/components/ui/sidebar';import { Button } from '@/components/ui/button';-import { Avatar, AvatarFallback } from '@/components/ui/avatar';-import {- Breadcrumb, BreadcrumbItem, BreadcrumbLink,- BreadcrumbList, BreadcrumbPage, BreadcrumbSeparator,-} from '@/components/ui/breadcrumb';import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';-import { RefreshCw, Settings, Sun, Moon, LogOut } from 'lucide-react';-import { useTheme } from 'next-themes';+import { routeTitle } from './navigation';import { useAppContext } from '../context/AppContext';-import { useAuth } from '../context/AuthContext';import { cn } from '@/lib/utils';-const BREADCRUMB_MAP = {- '/': { label: 'Overview', parent: null },- '/videos': { label: 'All Videos', parent: 'Analytics' },- '/shorts': { label: 'Shorts', parent: 'Analytics' },- '/reels': { label: 'IG Content', parent: 'Analytics' },- '/upload': { label: 'Publish', parent: 'Publishing' },- '/accounts': { label: 'Accounts', parent: 'Management' },- '/settings': { label: 'Settings', parent: 'Management' },-};--export default function AppHeader() {- const navigate = useNavigate();+export default function TopBar({ onOpenPalette }) {const location = useLocation();- const { loading, refreshAll } = useAppContext();+ const { loading, refreshAll, accounts } = useAppContext();const { resolvedTheme, setTheme } = useTheme();- const { user, signOut } = useAuth();const isDark = resolvedTheme === 'dark';-- let crumb = BREADCRUMB_MAP[location.pathname];- if (!crumb && location.pathname.startsWith('/channel/')) {- crumb = { label: 'Channel Analytics', parent: 'Analytics' };- } else if (!crumb && location.pathname.startsWith('/instagram/')) {- crumb = { label: 'Instagram Analytics', parent: 'Analytics' };- }-- async function handleSignOut() {- await signOut();- navigate('/login');- }-- const emailInitial = user?.email?.[0]?.toUpperCase() ?? 'T';+ const title = routeTitle(location.pathname);return (- <header className="flex h-14 shrink-0 items-center gap-2 border-b border-border bg-background/95 backdrop-blur px-4">- <SidebarTrigger className="-ml-1" />-- {/* Breadcrumbs */}- {crumb && (- <Breadcrumb className="flex-1">- <BreadcrumbList>- <BreadcrumbItem>- <BreadcrumbLink- onClick={() => navigate('/')}- className="cursor-pointer text-xs"- >- Dashboard- </BreadcrumbLink>- </BreadcrumbItem>- {crumb.parent && (- <>- <BreadcrumbSeparator />- <BreadcrumbItem>- <BreadcrumbPage className="text-xs text-muted-foreground">- {crumb.parent}- </BreadcrumbPage>- </BreadcrumbItem>- </>- )}- <BreadcrumbSeparator />- <BreadcrumbItem>- <BreadcrumbPage className="text-xs font-semibold">{crumb.label}</BreadcrumbPage>- </BreadcrumbItem>- </BreadcrumbList>- </Breadcrumb>+ <header className="sticky top-0 z-20 flex h-(--topbar-h) shrink-0 items-center gap-2 border-b border-line bg-surface/85 px-3 backdrop-blur-md sm:px-4">+ <SidebarTrigger className="text-ink-muted" />+ {title && (+ <nav aria-label="Breadcrumb" className="flex min-w-0 items-center gap-1.5 text-small">+ {title.parent && (+ <>+ <span className="hidden truncate text-ink-faint sm:inline">{title.parent}</span>+ <span className="hidden text-ink-faint sm:inline" aria-hidden="true">/</span>+ </>+ )}+ <span className="truncate font-medium text-ink" aria-current="page">{title.label}</span>+ </nav>)}<div className="ml-auto flex items-center gap-1"><Tooltip>- <TooltipTrigger render={<Button variant="ghost" size="icon" className="size-8" onClick={refreshAll} disabled={loading} />}>- <RefreshCw className={cn(loading && 'animate-spin')} />- </TooltipTrigger>- <TooltipContent>Refresh all accounts</TooltipContent>- </Tooltip>-- <Tooltip>- <TooltipTrigger render={<Button variant="ghost" size="icon" className="size-8" onClick={() => setTheme(isDark ? 'light' : 'dark')} />}>- {isDark ? <Sun /> : <Moon />}+ <TooltipTrigger render={<Button variant="ghost" size="icon-sm" onClick={onOpenPalette} aria-label="Search" className="md:hidden" />}>+ <Search /></TooltipTrigger>- <TooltipContent>{isDark ? 'Light mode' : 'Dark mode'}</TooltipContent>+ <TooltipContent>Search</TooltipContent></Tooltip><Tooltip>- <TooltipTrigger render={<Button variant="ghost" size="icon" className="size-8" onClick={() => navigate('/settings')} />}>- <Settings />+ <TooltipTrigger+ render={+ <Button+ variant="ghost"+ size="icon-sm"+ onClick={refreshAll}+ disabled={loading || accounts.length === 0}+ aria-label="Refresh all accounts"+ />+ }+ >+ <RefreshCw className={cn(loading && 'animate-spin')} /></TooltipTrigger>- <TooltipContent>Settings</TooltipContent>+ <TooltipContent>{loading ? 'Refreshing accounts' : 'Refresh all accounts'}</TooltipContent></Tooltip><Tooltip>- <TooltipTrigger render={<Button variant="ghost" size="icon" className="size-8" onClick={handleSignOut} />}>- <LogOut />+ <TooltipTrigger+ render={+ <Button+ variant="ghost"+ size="icon-sm"+ onClick={() => setTheme(isDark ? 'light' : 'dark')}+ aria-label={isDark ? 'Switch to light theme' : 'Switch to dark theme'}+ />+ }+ >+ {isDark ? <Sun /> : <Moon />}</TooltipTrigger>- <TooltipContent>Sign out ({user?.email})</TooltipContent>+ <TooltipContent>{isDark ? 'Light theme' : 'Dark theme'}</TooltipContent></Tooltip>-- <Avatar className="size-8 ml-1">- <AvatarFallback className="bg-primary text-primary-foreground text-xs font-bold">- {emailInitial}- </AvatarFallback>- </Avatar></div></header>);diff --git a/frontend/src/layout/Sidebar.jsx b/frontend/src/layout/Sidebar.jsxindex 18f82af..8f604b6 100644--- a/frontend/src/layout/Sidebar.jsx+++ b/frontend/src/layout/Sidebar.jsx@@ -1,148 +1,97 @@-import React, { useState, useEffect } from 'react';-import { useNavigate, useLocation } from 'react-router-dom';+import React from 'react';+import { Link, useLocation, useNavigate } from 'react-router-dom';+import { useTheme } from 'next-themes';+import { Search, Tag, Settings, LogOut, Sun, Moon, Monitor, ChevronsUpDown } from 'lucide-react';import {- Sidebar, SidebarContent, SidebarFooter, SidebarGroup,- SidebarGroupLabel, SidebarHeader, SidebarMenu, SidebarMenuButton,- SidebarMenuItem, SidebarSeparator,+ Sidebar, SidebarContent, SidebarFooter, SidebarGroup, SidebarGroupLabel, SidebarHeader,+ SidebarMenu, SidebarMenuButton, SidebarMenuItem, useSidebar,} from '@/components/ui/sidebar';-import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';import {- LayoutDashboard, PlaySquare, Scissors, Camera,- Upload, Users, Settings, Flame, Bookmark, Tag,-} from 'lucide-react';-+ DropdownMenu, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuLabel,+ DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuSeparator, DropdownMenuTrigger,+} from '@/components/ui/dropdown-menu';+import { Avatar, AvatarFallback } from '@/components/ui/avatar';+import { Logo } from '@/components/brand/Logo';+import { AccountAvatar } from '@/components/platform';+import { accountName, accountPath } from '@/lib/accounts';+import { NAV_GROUPS, isNavActive } from './navigation';import { useAppContext } from '../context/AppContext';-import { api } from '../services/api';+import { useAuth } from '../context/AuthContext';-const NAV_GROUPS = [- {- label: 'Analytics',- items: [- { path: '/', label: 'Overview', icon: LayoutDashboard },- { path: '/videos', label: 'All Videos', icon: PlaySquare },- { path: '/shorts', label: 'Shorts', icon: Scissors },- { path: '/reels', label: 'IG Content', icon: Camera },- { path: '/reddit-posts', label: 'Reddit Posts', icon: Flame },- { path: '/tracked-content', label: 'Tracked Content', icon: Bookmark },- ],- },- {- label: 'Publishing',- items: [- { path: '/upload', label: 'Publish', icon: Upload },- ],- },- {- label: 'Management',- items: [- { path: '/accounts', label: 'Accounts', icon: Users },- { path: '/settings', label: 'Settings', icon: Settings },- ],- },-];+const isMac = typeof navigator !== 'undefined' && /Mac|iPhone|iPad/.test(navigator.platform);-export default function AppSidebar() {- const navigate = useNavigate();+export default function AppSidebar({ categories, onOpenPalette, onSignOut }) {const location = useLocation();const { accounts } = useAppContext();+ const { setOpenMobile } = useSidebar();- const [categories, setCategories] = useState([]);-- useEffect(() => {- api.getTrackedContent()- .then(data => {- const all = Array.isArray(data) ? data : [];- const cats = [...new Set(all.map(p => p.category).filter(Boolean))].sort();- setCategories(cats);- })- .catch(() => {});- }, []);-- const isActive = (path) => {- if (path === '/') return location.pathname === '/';- return location.pathname.startsWith(path);- };+ const nav = (path, label, children, tooltip = label) => (+ <SidebarMenuButton+ isActive={isNavActive(path, location.pathname)}+ tooltip={tooltip}+ render={<Link to={path} onClick={() => setOpenMobile(false)} />}+ >+ {children}+ </SidebarMenuButton>+ );return (- <Sidebar collapsible="icon" className="border-r border-border">- {/* Header */}- <SidebarHeader className="border-b border-border">+ <Sidebar collapsible="icon" className="border-r border-line">+ <SidebarHeader className="gap-3 px-3 pt-4 pb-2">+ <Link+ to="/"+ aria-label="Twiligent overview"+ className="flex h-8 items-center rounded-row px-1 group-data-[collapsible=icon]:justify-center group-data-[collapsible=icon]:px-0"+ >+ <Logo className="h-6 group-data-[collapsible=icon]:hidden" />+ <Logo variant="mark" className="hidden h-6 group-data-[collapsible=icon]:block" />+ </Link><SidebarMenu><SidebarMenuItem><SidebarMenuButton- size="lg"- className="cursor-default hover:bg-transparent active:bg-transparent"+ tooltip="Search"+ onClick={onOpenPalette}+ className="border border-line bg-surface-raised text-ink-faint hover:text-ink group-data-[collapsible=icon]:border-0 group-data-[collapsible=icon]:bg-transparent">- <img src="/logo.png" alt="Twiligent" className="size-8 object-contain shrink-0" />- <div className="flex flex-col leading-tight min-w-0">- <span className="font-bold text-sm truncate">Twiligent</span>- <span className="text-xs text-muted-foreground truncate">Analytics</span>- </div>+ <Search className="size-4!" />+ <span className="flex-1">Search</span>+ <kbd className="font-mono text-caption text-ink-faint group-data-[collapsible=icon]:hidden">{isMac ? 'Cmd K' : 'Ctrl K'}</kbd></SidebarMenuButton></SidebarMenuItem></SidebarMenu></SidebarHeader>- {/* Nav groups */}- <SidebarContent>- {NAV_GROUPS.map((group, gi) => (- <SidebarGroup key={gi}>+ <SidebarContent className="gap-1 px-1">+ {NAV_GROUPS.map(group => (+ <SidebarGroup key={group.label} className="py-1"><SidebarGroupLabel>{group.label}</SidebarGroupLabel>- <SidebarMenu>- {group.items.map((item) => {+ <SidebarMenu className="gap-0.5">+ {group.items.map(item => {const Icon = item.icon;- const active = isActive(item.path);return (<SidebarMenuItem key={item.path}>- <SidebarMenuButton- isActive={active}- onClick={() => navigate(item.path)}- tooltip={item.label}- >- <Icon />- <span>{item.label}</span>- </SidebarMenuButton>+ {nav(item.path, item.label, <><Icon /><span>{item.label}</span></>)}</SidebarMenuItem>);})}</SidebarMenu>- {gi < NAV_GROUPS.length - 1 && <SidebarSeparator className="mt-2" />}</SidebarGroup>))}- {/* Accounts quick list */}{accounts.length > 0 && (- <SidebarGroup>- <SidebarSeparator />+ <SidebarGroup className="py-1"><SidebarGroupLabel>Accounts</SidebarGroupLabel>- <SidebarMenu>- {accounts.map((acc) => {- const isIG = acc.platform === 'instagram';- const isReddit = acc.platform === 'reddit';- const path = isIG ? `/instagram/${acc.id}` : isReddit ? `/reddit/${acc.id}` : `/channel/${acc.id}`;- const initials = (acc.title || '?').slice(0, 2).toUpperCase();- const avatarBg = isIG ? '#ec4899' : isReddit ? '#f97316' : '#ef4444';+ <SidebarMenu className="gap-0.5">+ {accounts.map(account => {+ const path = accountPath(account);return (- <SidebarMenuItem key={acc.id}>- <SidebarMenuButton- isActive={location.pathname === path}- onClick={() => navigate(path)}- tooltip={acc.title}- >- <Avatar className="size-5 flex-shrink-0">- <AvatarImage- src={acc.thumbnail || acc.profilePictureUrl || acc.thumbnails?.default}- alt={acc.title}- />- <AvatarFallback- style={{ background: avatarBg }}- className="text-[0.5rem] font-bold text-white"- >- {initials}- </AvatarFallback>- </Avatar>- <span className="truncate text-sm">{acc.title}</span>- </SidebarMenuButton>+ <SidebarMenuItem key={account.id}>+ {nav(path, accountName(account), (+ <>+ <AccountAvatar account={account} size="xs" />+ <span>{accountName(account)}</span>+ </>+ ))}</SidebarMenuItem>);})}@@ -150,24 +99,15 @@ export default function AppSidebar() {</SidebarGroup>)}- {/* Categories quick list */}{categories.length > 0 && (- <SidebarGroup>- <SidebarSeparator />+ <SidebarGroup className="py-1"><SidebarGroupLabel>Categories</SidebarGroupLabel>- <SidebarMenu>- {categories.map((cat) => {- const path = `/tracked-content/category/${encodeURIComponent(cat)}`;+ <SidebarMenu className="gap-0.5">+ {categories.map(category => {+ const path = `/tracked-content/category/${encodeURIComponent(category)}`;return (- <SidebarMenuItem key={cat}>- <SidebarMenuButton- isActive={location.pathname === path}- onClick={() => navigate(path)}- tooltip={cat}- >- <Tag className="size-4 text-purple-500 flex-shrink-0" />- <span className="truncate text-sm">{cat}</span>- </SidebarMenuButton>+ <SidebarMenuItem key={category}>+ {nav(path, category, <><Tag /><span>{category}</span></>)}</SidebarMenuItem>);})}@@ -176,21 +116,51 @@ export default function AppSidebar() {)}</SidebarContent>- {/* Footer */}- <SidebarFooter className="border-t border-border p-2">- <SidebarMenu>- <SidebarMenuItem>- <SidebarMenuButton- onClick={() => navigate('/settings')}- tooltip="Settings"- className="text-muted-foreground"- >- <Settings />- <span>Settings</span>- </SidebarMenuButton>- </SidebarMenuItem>- </SidebarMenu>+ <SidebarFooter className="border-t border-line p-2">+ <UserMenu onSignOut={onSignOut} /></SidebarFooter></Sidebar>);}++function UserMenu({ onSignOut }) {+ const navigate = useNavigate();+ const { user } = useAuth();+ const { theme, setTheme } = useTheme();+ const email = user?.email ?? '';+ const initial = email[0]?.toUpperCase() ?? 'T';++ return (+ <SidebarMenu>+ <SidebarMenuItem>+ <DropdownMenu>+ <DropdownMenuTrigger+ render={<SidebarMenuButton size="lg" tooltip={email || 'Account'} className="data-popup-open:bg-surface-selected" />}+ >+ <Avatar className="size-7">+ <AvatarFallback className="bg-brand text-caption font-semibold text-on-brand">{initial}</AvatarFallback>+ </Avatar>+ <span className="flex min-w-0 flex-1 flex-col text-left">+ <span className="truncate text-sm font-medium text-ink">{email.split('@')[0] || 'Account'}</span>+ <span className="truncate text-caption font-normal text-ink-faint">{email}</span>+ </span>+ <ChevronsUpDown className="size-4! text-ink-faint" />+ </DropdownMenuTrigger>+ <DropdownMenuContent side="top" align="start" className="w-(--anchor-width) min-w-56">+ <DropdownMenuGroup>+ <DropdownMenuLabel className="text-caption text-ink-faint">Theme</DropdownMenuLabel>+ <DropdownMenuRadioGroup value={theme} onValueChange={setTheme}>+ <DropdownMenuRadioItem value="light"><Sun />Light</DropdownMenuRadioItem>+ <DropdownMenuRadioItem value="dark"><Moon />Dark</DropdownMenuRadioItem>+ <DropdownMenuRadioItem value="system"><Monitor />Match system</DropdownMenuRadioItem>+ </DropdownMenuRadioGroup>+ </DropdownMenuGroup>+ <DropdownMenuSeparator />+ <DropdownMenuItem onClick={() => navigate('/settings')}><Settings />Settings</DropdownMenuItem>+ <DropdownMenuItem onClick={onSignOut}><LogOut />Sign out</DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </SidebarMenuItem>+ </SidebarMenu>+ );+}diff --git a/frontend/src/layout/index.jsx b/frontend/src/layout/index.jsxindex 1e54bf0..cdbf722 100644--- a/frontend/src/layout/index.jsx+++ b/frontend/src/layout/index.jsx@@ -1,36 +1,66 @@-import React, { Suspense } from 'react';-import { Outlet } from 'react-router-dom';+import React, { Suspense, useCallback, useEffect, useState } from 'react';+import { Outlet, useNavigate } from 'react-router-dom';import { SidebarProvider, SidebarInset } from '@/components/ui/sidebar';+import CommandPalette from '@/components/CommandPalette';+import { useCommandPaletteShortcut } from '@/hooks/use-command-palette-shortcut';+import { PageSkeleton } from '@/components/StateViews';import AppSidebar from './Sidebar';-import AppHeader from './Header';+import TopBar from './Header';+import { useAppContext } from '../context/AppContext';+import { useAuth } from '../context/AuthContext';+import { api } from '../services/api';-function PageSkeleton() {- return (- <div className="flex-1 p-4 sm:p-6 space-y-4 animate-pulse">- <div className="h-8 w-48 rounded-md bg-muted" />- <div className="h-4 w-72 rounded-md bg-muted" />- <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-4 mt-6">- {Array.from({ length: 4 }).map((_, i) => (- <div key={i} className="h-28 rounded-xl bg-muted" />- ))}- </div>- <div className="h-64 rounded-xl bg-muted" />- </div>- );-}+export default function AppShell() {+ const navigate = useNavigate();+ const { accounts, refreshAll } = useAppContext();+ const { signOut } = useAuth();+ const [paletteOpen, setPaletteOpen] = useState(false);+ const [categories, setCategories] = useState([]);++ useCommandPaletteShortcut(setPaletteOpen);++ useEffect(() => {+ api.getTrackedContent()+ .then(data => {+ const items = Array.isArray(data) ? data : [];+ setCategories([...new Set(items.map(p => p.category).filter(Boolean))].sort());+ })+ .catch(() => {});+ }, []);++ const openPalette = useCallback(() => setPaletteOpen(true), []);+ const handleSignOut = useCallback(async () => {+ await signOut();+ navigate('/login');+ }, [signOut, navigate]);-export default function MainLayout() {return (<SidebarProvider>- <AppSidebar />- <SidebarInset>- <AppHeader />- <main className="flex-1 overflow-auto p-4 sm:p-6">- <Suspense fallback={<PageSkeleton />}>- <Outlet />- </Suspense>- </main>+ <a+ href="#main-content"+ className="sr-only focus:not-sr-only focus:fixed focus:top-3 focus:left-3 focus:z-50 focus:rounded-pill focus:bg-ink focus:px-4 focus:py-2 focus:text-sm focus:text-ink-inverse"+ >+ Skip to content+ </a>+ <AppSidebar categories={categories} onOpenPalette={openPalette} onSignOut={handleSignOut} />+ <SidebarInset className="min-w-0">+ <TopBar onOpenPalette={openPalette} />+ <div id="main-content" tabIndex={-1} className="flex-1 outline-none">+ <div className="mx-auto w-full max-w-(--content-max) px-4 py-6 sm:px-5">+ <Suspense fallback={<PageSkeleton />}>+ <Outlet />+ </Suspense>+ </div>+ </div></SidebarInset>+ <CommandPalette+ open={paletteOpen}+ onOpenChange={setPaletteOpen}+ accounts={accounts}+ categories={categories}+ onRefreshAll={refreshAll}+ onSignOut={handleSignOut}+ /></SidebarProvider>);}diff --git a/frontend/src/layout/navigation.js b/frontend/src/layout/navigation.jsnew file mode 100644index 0000000..269f4dd--- /dev/null+++ b/frontend/src/layout/navigation.js@@ -0,0 +1,53 @@+import {+ LayoutDashboard, PlaySquare, Scissors, Clapperboard, MessagesSquare, Bookmark, Send, Users, Settings,+} from 'lucide-react';++// Single source for navigation: the sidebar, top bar title and command palette all read from here.+export const NAV_GROUPS = [+ {+ label: 'Analytics',+ items: [+ { path: '/', label: 'Overview', icon: LayoutDashboard },+ { path: '/videos', label: 'Videos', icon: PlaySquare },+ { path: '/shorts', label: 'Shorts', icon: Scissors },+ { path: '/reels', label: 'Instagram content', icon: Clapperboard },+ { path: '/reddit-posts', label: 'Reddit posts', icon: MessagesSquare },+ { path: '/tracked-content', label: 'Tracked content', icon: Bookmark },+ ],+ },+ {+ label: 'Publishing',+ items: [+ { path: '/upload', label: 'Publish', icon: Send },+ ],+ },+ {+ label: 'Manage',+ items: [+ { path: '/accounts', label: 'Accounts', icon: Users },+ { path: '/settings', label: 'Settings', icon: Settings },+ ],+ },+];++const DETAIL_ROUTES = [+ { prefix: '/channel/', label: 'YouTube channel', parent: 'Analytics' },+ { prefix: '/instagram/', label: 'Instagram account', parent: 'Analytics' },+ { prefix: '/reddit/', label: 'Reddit account', parent: 'Analytics' },+ { prefix: '/reddit-posts/', label: 'Reddit posts', parent: 'Analytics' },+ { prefix: '/tracked-content/category/', label: 'Category', parent: 'Tracked content' },+];++export function isNavActive(path, pathname) {+ if (path === '/') return pathname === '/';+ return pathname === path || pathname.startsWith(`${path}/`);+}++export function routeTitle(pathname) {+ for (const group of NAV_GROUPS) {+ const item = group.items.find(i => i.path === pathname);+ if (item) return { label: item.label, parent: item.path === '/' ? null : group.label };+ }+ const detail = DETAIL_ROUTES.find(r => pathname.startsWith(r.prefix));+ return detail ? { label: detail.label, parent: detail.parent } : null;+}diff --git a/frontend/src/lib/accounts.js b/frontend/src/lib/accounts.jsnew file mode 100644index 0000000..1f222b2--- /dev/null+++ b/frontend/src/lib/accounts.js@@ -0,0 +1,68 @@+// Platform helpers shared by every page. Kept free of JSX and path aliases so node --test can import it.++export const PLATFORMS = ['youtube', 'instagram', 'reddit'];++export const PLATFORM_META = {+ youtube: { label: 'YouTube', audienceLabel: 'subscribers', series: 'var(--chart-1)' },+ instagram: { label: 'Instagram', audienceLabel: 'followers', series: 'var(--chart-3)' },+ reddit: { label: 'Reddit', audienceLabel: 'karma', series: 'var(--chart-4)' },+};++// Accounts saved before multi-platform support have no platform field and are YouTube channels+export function platformOf(account) {+ const p = account?.platform;+ return p === 'instagram' || p === 'reddit' ? p : 'youtube';+}++export function accountPath(account) {+ const platform = platformOf(account);+ if (platform === 'instagram') return `/instagram/${account.id}`;+ if (platform === 'reddit') return `/reddit/${account.id}`;+ return `/channel/${account.id}`;+}++export function accountName(account) {+ if (!account) return '';+ if (platformOf(account) === 'reddit') return `u/${account.username || ''}`;+ return account.title || account.username || account.channelId || '';+}++export function accountHandle(account) {+ if (!account) return '';+ const platform = platformOf(account);+ if (platform === 'instagram') return account.username ? `@${account.username}` : '';+ if (platform === 'reddit') return 'Reddit';+ return account.customUrl || account.channelId || '';+}++export function accountImage(account) {+ if (!account) return '';+ return account.thumbnail || account.profilePictureUrl || account.thumbnails?.default || account.iconUrl || '';+}++export function accountInitials(account) {+ const source = account?.title || account?.username || '?';+ return source.replace(/^u\//, '').slice(0, 2).toUpperCase();+}++export function audienceOf(account) {+ const platform = platformOf(account);+ if (platform === 'instagram') return account.followersCount || 0;+ if (platform === 'reddit') return account.totalKarma || 0;+ return account.subscriberCount || 0;+}++export function groupByPlatform(accounts) {+ const groups = { youtube: [], instagram: [], reddit: [] };+ for (const account of accounts || []) groups[platformOf(account)].push(account);+ return groups;+}++// "2 YouTube, 1 Instagram" style summary, empty platforms omitted+export function platformSummary(accounts) {+ const groups = groupByPlatform(accounts);+ return PLATFORMS+ .filter(p => groups[p].length > 0)+ .map(p => `${groups[p].length} ${PLATFORM_META[p].label}`)+ .join(', ');+}diff --git a/frontend/src/lib/accounts.test.js b/frontend/src/lib/accounts.test.jsnew file mode 100644index 0000000..1b7758a--- /dev/null+++ b/frontend/src/lib/accounts.test.js@@ -0,0 +1,42 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { platformOf, accountPath, accountName, accountHandle, accountInitials, audienceOf, platformSummary } from './accounts.js';++const yt = { id: 'y1', title: 'Studio Dusk', customUrl: '@studiodusk', subscriberCount: 1200 };+const ig = { id: 'i1', platform: 'instagram', title: 'Paper Fold', username: 'paperfold', followersCount: 800 };+const rd = { id: 'r1', platform: 'reddit', username: 'ribbon', totalKarma: 50 };++test('accounts without a platform are YouTube channels', () => {+ assert.equal(platformOf(yt), 'youtube');+ assert.equal(platformOf(ig), 'instagram');+ assert.equal(platformOf(rd), 'reddit');+});++test('each platform routes to its own analytics page', () => {+ assert.equal(accountPath(yt), '/channel/y1');+ assert.equal(accountPath(ig), '/instagram/i1');+ assert.equal(accountPath(rd), '/reddit/r1');+});++test('names and handles follow each platform convention', () => {+ assert.equal(accountName(rd), 'u/ribbon');+ assert.equal(accountName(ig), 'Paper Fold');+ assert.equal(accountHandle(ig), '@paperfold');+ assert.equal(accountHandle(yt), '@studiodusk');+ assert.equal(accountHandle(rd), 'Reddit');+});++test('initials come from the title or username', () => {+ assert.equal(accountInitials(yt), 'ST');+ assert.equal(accountInitials({ title: 'u/ribbon' }), 'RI');+ assert.equal(accountInitials({}), '?');+});++test('audience uses subscribers, followers or karma', () => {+ assert.deepEqual([yt, ig, rd].map(audienceOf), [1200, 800, 50]);+});++test('the platform summary lists only platforms that have accounts', () => {+ assert.equal(platformSummary([yt, ig, { ...ig, id: 'i2' }]), '1 YouTube, 2 Instagram');+ assert.equal(platformSummary([]), '');+});diff --git a/frontend/src/lib/chart.js b/frontend/src/lib/chart.jsnew file mode 100644index 0000000..6f61690--- /dev/null+++ b/frontend/src/lib/chart.js@@ -0,0 +1,34 @@+// Shared Recharts styling. Series follow the brand data-visualisation order; values are CSS variables+// so charts switch with the theme.++export const SERIES = {+ primary: 'var(--chart-1)',+ neutral: 'var(--chart-2)',+ warm: 'var(--chart-3)',+ cool: 'var(--chart-4)',+ deep: 'var(--chart-5)',+};++export const SERIES_ORDER = [SERIES.primary, SERIES.neutral, SERIES.warm, SERIES.cool, SERIES.deep];++export const seriesAt = index => SERIES_ORDER[index % SERIES_ORDER.length];++export const axisTick = { fill: 'var(--ink-faint)', fontSize: 11, fontFamily: 'var(--font-sans)' };++export const axisProps = { tick: axisTick, axisLine: false, tickLine: false };++export const gridProps = { strokeDasharray: '3 3', stroke: 'var(--divider)' };++export const tooltipStyle = {+ background: 'var(--surface-overlay)',+ border: '1px solid var(--line)',+ borderRadius: 10,+ boxShadow: 'var(--shadow-md)',+ color: 'var(--ink)',+ fontSize: 12,+ padding: '8px 10px',+};++export const tooltipCursor = { fill: 'var(--surface-hover)' };++export const legendStyle = { fontSize: 12, color: 'var(--ink-muted)' };diff --git a/frontend/src/lib/commandSearch.js b/frontend/src/lib/commandSearch.jsnew file mode 100644index 0000000..6e9e354--- /dev/null+++ b/frontend/src/lib/commandSearch.js@@ -0,0 +1,40 @@+// Ranking for the command palette. Pure so it can be unit tested without a DOM.++function normalize(text) {+ return String(text || '').toLowerCase().normalize('NFKD').replace(/[̀-ͯ]/g, '').trim();+}++// Higher is better; 0 means no match. Every query word must appear in the label or keywords.+export function scoreCommand(command, query) {+ const q = normalize(query);+ if (!q) return 1;+ const label = normalize(command.label);+ const haystack = `${label} ${normalize(command.group)} ${(command.keywords || []).map(normalize).join(' ')}`;+ const words = q.split(/\s+/);+ if (!words.every(w => haystack.includes(w))) return 0;+ if (label === q) return 100;+ if (label.startsWith(q)) return 80;+ if (label.split(/\s+/).some(part => part.startsWith(words[0]))) return 60;+ if (label.includes(q)) return 40;+ return 20;+}++export function filterCommands(commands, query, limit = 50) {+ return commands+ .map((command, index) => ({ command, index, score: scoreCommand(command, query) }))+ .filter(entry => entry.score > 0)+ .sort((a, b) => b.score - a.score || a.index - b.index)+ .slice(0, limit)+ .map(entry => entry.command);+}++// Groups in first-seen order so the palette keeps a stable layout while typing+export function groupCommands(commands) {+ const groups = new Map();+ for (const command of commands) {+ const key = command.group || 'Other';+ if (!groups.has(key)) groups.set(key, []);+ groups.get(key).push(command);+ }+ return [...groups.entries()].map(([group, items]) => ({ group, items }));+}diff --git a/frontend/src/lib/commandSearch.test.js b/frontend/src/lib/commandSearch.test.jsnew file mode 100644index 0000000..2200771--- /dev/null+++ b/frontend/src/lib/commandSearch.test.js@@ -0,0 +1,45 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { scoreCommand, filterCommands, groupCommands } from './commandSearch.js';++const commands = [+ { id: 'overview', group: 'Pages', label: 'Overview', keywords: ['Analytics'] },+ { id: 'videos', group: 'Pages', label: 'Videos', keywords: ['Analytics'] },+ { id: 'reddit-posts', group: 'Pages', label: 'Reddit posts', keywords: ['Analytics'] },+ { id: 'acct', group: 'Accounts', label: 'Daily Café Vlogs', keywords: ['YouTube', 'cafevlogs'] },+ { id: 'theme-dark', group: 'Theme', label: 'Use dark theme', keywords: ['appearance', 'dusk'] },+];++test('an empty query keeps every command in its original order', () => {+ assert.deepEqual(filterCommands(commands, '').map(c => c.id), commands.map(c => c.id));+});++test('exact and prefix label matches rank above keyword matches', () => {+ const ids = filterCommands(commands, 'vid').map(c => c.id);+ assert.equal(ids[0], 'videos');+ assert.ok(scoreCommand(commands[1], 'videos') > scoreCommand(commands[1], 'vid'));+});++test('keywords and groups are searchable', () => {+ assert.deepEqual(filterCommands(commands, 'dusk').map(c => c.id), ['theme-dark']);+ assert.deepEqual(filterCommands(commands, 'youtube').map(c => c.id), ['acct']);+});++test('every word in the query must match', () => {+ assert.deepEqual(filterCommands(commands, 'reddit posts').map(c => c.id), ['reddit-posts']);+ assert.deepEqual(filterCommands(commands, 'reddit videos'), []);+});++test('matching ignores case and accents', () => {+ assert.deepEqual(filterCommands(commands, 'CAFE').map(c => c.id), ['acct']);+});++test('the result limit is respected', () => {+ assert.equal(filterCommands(commands, 'a', 2).length, 2);+});++test('groups keep first-seen order', () => {+ const groups = groupCommands(filterCommands(commands, ''));+ assert.deepEqual(groups.map(g => g.group), ['Pages', 'Accounts', 'Theme']);+ assert.equal(groups[0].items.length, 3);+});diff --git a/frontend/src/lib/holdProgress.js b/frontend/src/lib/holdProgress.jsnew file mode 100644index 0000000..3061182--- /dev/null+++ b/frontend/src/lib/holdProgress.js@@ -0,0 +1,57 @@+// Timing core for hold-to-confirm. The clock and frame scheduler are injected so tests can drive time.++export const DEFAULT_HOLD_MS = 1200;++export function createHoldController({+ duration = DEFAULT_HOLD_MS,+ onProgress = () => {},+ onComplete = () => {},+ now = () => performance.now(),+ requestFrame = cb => requestAnimationFrame(cb),+ cancelFrame = id => cancelAnimationFrame(id),+} = {}) {+ let startedAt = null;+ let frame = null;+ let done = false;++ function tick() {+ if (startedAt === null) return;+ const progress = Math.min(1, (now() - startedAt) / duration);+ onProgress(progress);+ if (progress >= 1) {+ startedAt = null;+ frame = null;+ done = true;+ onComplete();+ return;+ }+ frame = requestFrame(tick);+ }++ return {+ start() {+ if (startedAt !== null || done) return;+ startedAt = now();+ onProgress(0);+ frame = requestFrame(tick);+ },+ // Releasing early resets progress; nothing fires+ cancel() {+ if (frame !== null) cancelFrame(frame);+ frame = null;+ if (startedAt !== null) onProgress(0);+ startedAt = null;+ },+ reset() {+ this.cancel();+ done = false;+ onProgress(0);+ },+ get holding() {+ return startedAt !== null;+ },+ get completed() {+ return done;+ },+ };+}diff --git a/frontend/src/lib/holdProgress.test.js b/frontend/src/lib/holdProgress.test.jsnew file mode 100644index 0000000..25e19a4--- /dev/null+++ b/frontend/src/lib/holdProgress.test.js@@ -0,0 +1,82 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { createHoldController } from './holdProgress.js';++// A manual clock and frame queue so timing can be stepped deterministically+function harness(duration = 1000) {+ let now = 0;+ let queue = [];+ const progress = [];+ let completed = 0;+ const controller = createHoldController({+ duration,+ now: () => now,+ requestFrame: cb => { queue.push(cb); return queue.length; },+ cancelFrame: () => { queue = []; },+ onProgress: p => progress.push(p),+ onComplete: () => { completed++; },+ });+ const advance = ms => {+ now += ms;+ const pending = queue;+ queue = [];+ pending.forEach(cb => cb());+ };+ return { controller, advance, progress, get completed() { return completed; } };+}++test('a full hold confirms exactly once', () => {+ const h = harness(1000);+ h.controller.start();+ h.advance(400);+ h.advance(400);+ assert.equal(h.completed, 0);+ h.advance(400);+ assert.equal(h.completed, 1);+ assert.equal(h.progress.at(-1), 1);+ h.advance(400);+ assert.equal(h.completed, 1, 'no further ticks after completion');+});++test('releasing early cancels and resets progress', () => {+ const h = harness(1000);+ h.controller.start();+ h.advance(500);+ h.controller.cancel();+ assert.equal(h.progress.at(-1), 0);+ h.advance(2000);+ assert.equal(h.completed, 0);+ assert.equal(h.controller.holding, false);+});++test('a quick click never confirms', () => {+ const h = harness(1200);+ h.controller.start();+ h.advance(16);+ h.controller.cancel();+ h.advance(5000);+ assert.equal(h.completed, 0);+});++test('starting twice does not restart the timer', () => {+ const h = harness(1000);+ h.controller.start();+ h.advance(600);+ h.controller.start();+ h.advance(500);+ assert.equal(h.completed, 1);+});++test('a completed controller ignores new holds until reset', () => {+ const h = harness(100);+ h.controller.start();+ h.advance(150);+ assert.equal(h.controller.completed, true);+ h.controller.start();+ h.advance(150);+ assert.equal(h.completed, 1);+ h.controller.reset();+ h.controller.start();+ h.advance(150);+ assert.equal(h.completed, 2);+});diff --git a/frontend/src/lib/icons.test.js b/frontend/src/lib/icons.test.jsnew file mode 100644index 0000000..3861714--- /dev/null+++ b/frontend/src/lib/icons.test.js@@ -0,0 +1,31 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { readdirSync, readFileSync, statSync } from 'node:fs';+import { join, dirname } from 'node:path';+import { fileURLToPath } from 'node:url';+import * as lucide from 'lucide-react';++const SRC = join(dirname(fileURLToPath(import.meta.url)), '..');++function sourceFiles(dir) {+ return readdirSync(dir).flatMap(name => {+ const path = join(dir, name);+ if (statSync(path).isDirectory()) return sourceFiles(path);+ return /\.(jsx?|tsx?)$/.test(name) && !name.endsWith('.test.js') ? [path] : [];+ });+}++// A renamed or removed icon renders as an empty box at runtime, so every imported name must exist+test('every Lucide icon imported in src exists in lucide-react', () => {+ const missing = [];+ for (const file of sourceFiles(SRC)) {+ const text = readFileSync(file, 'utf8');+ for (const match of text.matchAll(/import\s*\{([^}]+)\}\s*from\s*['"]lucide-react['"]/g)) {+ for (const raw of match[1].split(',')) {+ const name = raw.trim().split(/\s+as\s+/)[0].trim();+ if (name && !(name in lucide)) missing.push(`${name} in ${file.slice(SRC.length + 1)}`);+ }+ }+ }+ assert.deepEqual(missing, []);+});diff --git a/frontend/src/lib/library.js b/frontend/src/lib/library.jsnew file mode 100644index 0000000..f49eafd--- /dev/null+++ b/frontend/src/lib/library.js@@ -0,0 +1,58 @@+// Filtering, sorting and paging shared by the content library pages. Pure, no JSX.++export function parseIsoDuration(iso) {+ if (!iso || iso === 'P0D') return 0;+ const m = iso.match(/PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?/);+ if (!m) return 0;+ return (parseInt(m[1] || 0, 10) * 3600) + (parseInt(m[2] || 0, 10) * 60) + parseInt(m[3] || 0, 10);+}++// (likes + comments) / views as a percentage string, matching the backend's two-decimal format+export function engagementPercent(views, likes, comments) {+ return (views || 0) > 0 ? (((likes || 0) + (comments || 0)) / views * 100).toFixed(2) : '0.00';+}++export const VIEW_TIERS = [+ { label: 'Any views', value: 'all' },+ { label: 'Over 1M', value: 'viral', min: 1000000 },+ { label: '100K to 1M', value: 'high', min: 100000, max: 1000000 },+ { label: '10K to 100K', value: 'medium', min: 10000, max: 100000 },+ { label: 'Under 10K', value: 'low', max: 10000 },+];++export const LIKE_TIERS = [+ { label: 'Any likes', value: 'all' },+ { label: 'Over 100K', value: 'viral', min: 100000 },+ { label: '10K to 100K', value: 'high', min: 10000, max: 100000 },+ { label: '1K to 10K', value: 'medium', min: 1000, max: 10000 },+ { label: 'Under 1K', value: 'low', max: 1000 },+];++export function filterByTier(items, tiers, tierValue, field) {+ if (tierValue === 'all') return items;+ const tier = tiers.find(t => t.value === tierValue);+ if (!tier) return items;+ return items.filter(item => {+ const n = item[field] || 0;+ if (tier.min != null && n < tier.min) return false;+ if (tier.max != null && n >= tier.max) return false;+ return true;+ });+}++export function pageSlice(items, page, perPage) {+ const pageCount = Math.max(1, Math.ceil(items.length / perPage));+ const current = Math.min(Math.max(1, page), pageCount);+ return {+ items: items.slice((current - 1) * perPage, current * perPage),+ page: current,+ pageCount,+ offset: (current - 1) * perPage,+ };+}++export function matchesText(values, query) {+ const q = query.trim().toLowerCase();+ if (!q) return true;+ return values.some(v => typeof v === 'string' && v.toLowerCase().includes(q));+}diff --git a/frontend/src/lib/library.test.js b/frontend/src/lib/library.test.jsnew file mode 100644index 0000000..996713a--- /dev/null+++ b/frontend/src/lib/library.test.js@@ -0,0 +1,42 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { parseIsoDuration, engagementPercent, filterByTier, VIEW_TIERS, LIKE_TIERS, pageSlice, matchesText } from './library.js';++test('ISO 8601 durations convert to seconds', () => {+ assert.equal(parseIsoDuration('PT1H2M3S'), 3723);+ assert.equal(parseIsoDuration('PT45S'), 45);+ assert.equal(parseIsoDuration('PT10M'), 600);+ assert.equal(parseIsoDuration('P0D'), 0);+ assert.equal(parseIsoDuration(undefined), 0);+});++test('engagement is likes plus comments over views, as a two-decimal string', () => {+ assert.equal(engagementPercent(1000, 40, 10), '5.00');+ assert.equal(engagementPercent(0, 40, 10), '0.00');+});++test('view tiers have inclusive minimums and exclusive maximums', () => {+ const items = [{ viewCount: 9999 }, { viewCount: 10000 }, { viewCount: 100000 }, { viewCount: 2000000 }];+ assert.deepEqual(filterByTier(items, VIEW_TIERS, 'medium', 'viewCount').map(i => i.viewCount), [10000]);+ assert.deepEqual(filterByTier(items, VIEW_TIERS, 'low', 'viewCount').map(i => i.viewCount), [9999]);+ assert.deepEqual(filterByTier(items, VIEW_TIERS, 'viral', 'viewCount').map(i => i.viewCount), [2000000]);+ assert.equal(filterByTier(items, VIEW_TIERS, 'all', 'viewCount').length, 4);+});++test('like tiers filter on likes', () => {+ const items = [{ likeCount: 500 }, { likeCount: 5000 }];+ assert.deepEqual(filterByTier(items, LIKE_TIERS, 'medium', 'likeCount').map(i => i.likeCount), [5000]);+});++test('pages clamp to the valid range', () => {+ const items = Array.from({ length: 30 }, (_, i) => i);+ assert.deepEqual(pageSlice(items, 2, 25), { items: [25, 26, 27, 28, 29], page: 2, pageCount: 2, offset: 25 });+ assert.equal(pageSlice(items, 9, 25).page, 2);+ assert.equal(pageSlice([], 1, 25).pageCount, 1);+});++test('text matching is case-insensitive and skips empty values', () => {+ assert.equal(matchesText(['Morning Routine', undefined], 'routine'), true);+ assert.equal(matchesText(['Morning Routine'], 'evening'), false);+ assert.equal(matchesText([], ' '), true);+});diff --git a/frontend/src/pages/Login.jsx b/frontend/src/pages/Login.jsxindex 8d423c0..9a3a81d 100644--- a/frontend/src/pages/Login.jsx+++ b/frontend/src/pages/Login.jsx@@ -4,8 +4,9 @@ import { toast } from 'sonner';import { useAuth } from '../context/AuthContext';import { Button } from '@/components/ui/button';import { Input } from '@/components/ui/input';-import { Label } from '@/components/ui/label';-import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';+import { Spinner } from '@/components/ui/spinner';+import { FieldRow } from '@/components/DetailPanel';+import { Logo } from '@/components/brand/Logo';export default function Login() {const { signIn, signUp } = useAuth();@@ -14,95 +15,106 @@ export default function Login() {const [email, setEmail] = useState('');const [password, setPassword] = useState('');const [loading, setLoading] = useState(false);+ const isLogin = mode === 'login';async function handleSubmit(e) {e.preventDefault();setLoading(true);try {- if (mode === 'login') {+ if (isLogin) {const { error } = await signIn(email, password);if (error) throw error;navigate('/');} else {const { error } = await signUp(email, password);if (error) throw error;- toast.success('Account created! Sign in now.');+ toast.success('Account created. Sign in to continue.');setMode('login');}} catch (err) {- toast.error(err.message);+ toast.error(isLogin ? `Couldn't sign in. ${err.message}` : `Couldn't create the account. ${err.message}`);} finally {setLoading(false);}}return (- <div className="min-h-screen flex items-center justify-center bg-background p-4">- <div className="w-full max-w-sm">- <div className="mb-8 text-center">- <h1 className="text-2xl font-bold tracking-tight">Twiligent</h1>- <p className="text-sm text-muted-foreground mt-1">Social media analytics & publishing</p>- </div>+ <div className="grid min-h-svh bg-surface lg:grid-cols-[minmax(0,1fr)_minmax(0,1.1fr)]">+ <main className="flex flex-col px-6 py-8 sm:px-10">+ <Logo className="h-7" />+ <div className="flex flex-1 items-center justify-center py-12">+ <div className="flex w-full max-w-sm animate-fold-in flex-col gap-8">+ <div className="flex flex-col gap-2">+ <h1 className="font-heading text-page-title font-semibold tracking-[-0.015em] text-ink">+ {isLogin ? 'Sign in to Twiligent' : 'Create your account'}+ </h1>+ <p className="text-sm text-ink-muted">+ {isLogin+ ? 'Analytics and publishing for your channels, in one place.'+ : 'Use an email and a password of at least 6 characters.'}+ </p>+ </div>- <Card>- <CardHeader className="pb-4">- <CardTitle className="text-lg">- {mode === 'login' ? 'Sign in' : 'Create account'}- </CardTitle>- <CardDescription>- {mode === 'login'- ? 'Enter your credentials to access your dashboard'- : 'Fill in your details to get started'}- </CardDescription>- </CardHeader>- <CardContent>- <form onSubmit={handleSubmit} className="space-y-4">- <div className="space-y-2">- <Label htmlFor="email">Email</Label>+ <form onSubmit={handleSubmit} className="flex flex-col gap-5">+ <FieldRow label="Email" htmlFor="email"><Inputid="email"type="email"+ className="h-(--control-h-lg)"placeholder="[email protected]"value={email}onChange={e => setEmail(e.target.value)}requiredautoComplete="email"+ autoFocus/>- </div>- <div className="space-y-2">- <Label htmlFor="password">Password</Label>+ </FieldRow>+ <FieldRow label="Password" htmlFor="password"><Inputid="password"type="password"- placeholder="••••••••"+ className="h-(--control-h-lg)"value={password}onChange={e => setPassword(e.target.value)}requiredminLength={6}- autoComplete={mode === 'login' ? 'current-password' : 'new-password'}+ autoComplete={isLogin ? 'current-password' : 'new-password'}/>- </div>- <Button type="submit" className="w-full" disabled={loading}>- {loading- ? 'Please wait...'- : mode === 'login' ? 'Sign in' : 'Create account'}+ </FieldRow>+ <Button type="submit" size="lg" className="mt-1 w-full" disabled={loading}>+ {loading && <Spinner className="size-4" />}+ {loading ? (isLogin ? 'Signing in' : 'Creating account') : (isLogin ? 'Sign in' : 'Create account')}</Button></form>- <div className="mt-4 text-center">+ <p className="text-center text-sm text-ink-muted">+ {isLogin ? 'New to Twiligent?' : 'Already have an account?'}{' '}<buttontype="button"- onClick={() => setMode(mode === 'login' ? 'signup' : 'login')}- className="text-sm text-muted-foreground hover:text-foreground transition-colors"+ onClick={() => setMode(isLogin ? 'signup' : 'login')}+ className="rounded-sm font-medium text-brand-text underline-offset-4 hover:underline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring">- {mode === 'login'- ? "Don't have an account? Sign up"- : 'Already have an account? Sign in'}+ {isLogin ? 'Create an account' : 'Sign in'}</button>- </div>- </CardContent>- </Card>- </div>+ </p>+ </div>+ </div>+ </main>++ <aside aria-hidden="true" className="relative hidden overflow-hidden fold-band lg:block">+ <img+ src="/Logos/twiligent-mark-white.svg"+ alt=""+ className="absolute -right-24 -bottom-28 w-[70%] max-w-[44rem] opacity-[0.14] select-none"+ draggable={false}+ />+ <div className="relative flex h-full flex-col justify-end gap-3 p-12 text-white">+ <p className="eyebrow text-white/80">Twiligent</p>+ <p className="max-w-md font-heading text-[2.75rem] leading-[3.125rem] font-semibold tracking-[-0.025em]">+ Clarity from many sources, folded into one picture.+ </p>+ </div>+ </aside></div>);}diff --git a/frontend/src/utils/instagramContent.js b/frontend/src/utils/instagramContent.jsindex c74b24e..a4d8ebe 100644--- a/frontend/src/utils/instagramContent.js+++ b/frontend/src/utils/instagramContent.js@@ -2,10 +2,11 @@ import { fmtNum } from './formatters';export const IG_CONTENT_TYPES = ['reel', 'post', 'video'];+// Colours are brand chart series so they follow the themeexport const IG_CONTENT_TYPE_META = {- reel: { label: 'Reel', plural: 'Reels', color: '#DD2A7B' },- post: { label: 'Post', plural: 'Posts', color: '#F58529' },- video: { label: 'Video', plural: 'Videos', color: '#8134AF' },+ reel: { label: 'Reel', plural: 'Reels', color: 'var(--chart-1)' },+ post: { label: 'Post', plural: 'Posts', color: 'var(--chart-3)' },+ video: { label: 'Video', plural: 'Videos', color: 'var(--chart-4)' },};export function igContentTypeMeta(type) {diff --git a/frontend/src/utils/trackedContent.js b/frontend/src/utils/trackedContent.jsindex 3705706..07b307f 100644--- a/frontend/src/utils/trackedContent.js+++ b/frontend/src/utils/trackedContent.js@@ -13,3 +13,23 @@ export function hasTrackedViews(item) {if (item.contentType === 'youtube') return item.viewCount !== undefined && item.viewCount !== null;return item.manualViews !== undefined && item.manualViews !== null;}++export 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;+}++export function isRedditItem(item) {+ return (item?.contentType || 'reddit') === 'reddit';+}++// YouTube likes and Reddit karma play the same role, so lists sort and total them together+export function trackedEngagement(item) {+ return item.contentType === 'youtube' ? (item.likeCount ?? 0) : (item.score ?? 0);+}++export function trackedComments(item) {+ return item.contentType === 'youtube' ? (item.commentCount ?? 0) : (item.numComments ?? 0);+}