Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.
refactor: migrate VideoExplorer and ShortsExplorer to shadcn/ui components
valzor4ed9b922ef91
diff --git a/frontend/src/features/analytics/shorts/ShortsExplorer.jsx b/frontend/src/features/analytics/shorts/ShortsExplorer.jsxindex cfe5fbb..affa444 100644--- a/frontend/src/features/analytics/shorts/ShortsExplorer.jsx+++ b/frontend/src/features/analytics/shorts/ShortsExplorer.jsx@@ -1,267 +1,216 @@import React, { useState, useEffect, useMemo } from '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 {- Box, Typography, Grid, TextField, InputAdornment,- Select, MenuItem, FormControl, InputLabel, Chip,- LinearProgress, Avatar, Button, Pagination, Skeleton,-} from '@mui/material';-import {- Search, Visibility, ThumbUp as ThumbUpIcon, Comment as CommentIcon,- PlayCircleOutline, YouTube,-} from '@mui/icons-material';+ 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 { GREY } from '../../../themes/index';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 },+ { 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 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' },+ { 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' },];-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);-}-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([]);-- useEffect(() => { loadAllShorts(); }, [accounts]);-- const loadAllShorts = async () => {- setLoading(true);+ 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([]);++ useEffect(() => { loadAllShorts(); }, [accounts]);++ const loadAllShorts = async () => {+ setLoading(true);+ try {+ const all = [];+ const channelList = [];+ for (const acct of (accounts || [])) {+ if (acct.platform === 'instagram') continue;try {- const allShorts = [];- 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 || '' });- for (const v of vids) {- const dur = v.durationSeconds || parseDurationToSeconds(v.duration);- if (dur > 0 && dur <= 60) {- const views = v.viewCount || 0;- allShorts.push({- ...v,- thumbnail: v.thumbnail || v.thumbnails?.medium || v.thumbnails?.high || v.thumbnails?.default || '',- channelTitle,- channelId: acct.id,- durationSeconds: dur,- engagementRate: views > 0 ? (((v.likeCount || 0) + (v.commentCount || 0)) / views * 100).toFixed(2) : '0.00',- });- }- }- } catch (e) { /* skip */ }- }- setShorts(allShorts);- setChannels(channelList);- } catch (err) {- showToast('Failed to load shorts: ' + err.message, 'error');- } finally {- setLoading(false);- }- };-- const filteredShorts = 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) || (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 = sortField === 'publishedAt' ? new Date(a[sortField] || 0).getTime() : (parseFloat(a[sortField]) || 0);- const bVal = sortField === 'publishedAt' ? new Date(b[sortField] || 0).getTime() : (parseFloat(b[sortField]) || 0);- return bVal - aVal;- });- return result;- }, [shorts, channelFilter, search, performanceTier, sortField]);-- const pageCount = Math.ceil(filteredShorts.length / ITEMS_PER_PAGE);- const paginatedShorts = filteredShorts.slice((page - 1) * ITEMS_PER_PAGE, page * ITEMS_PER_PAGE);-- const stats = useMemo(() => ({- total: filteredShorts.length,- totalViews: filteredShorts.reduce((s, v) => s + (v.viewCount || 0), 0),- totalLikes: filteredShorts.reduce((s, v) => s + (v.likeCount || 0), 0),- avgViews: filteredShorts.length > 0 ? Math.round(filteredShorts.reduce((s, v) => s + (v.viewCount || 0), 0) / filteredShorts.length) : 0,- }), [filteredShorts]);-- if (loading) {- return (- <Box>- <Typography variant="h4" sx={{ mb: 3 }}>Shorts Explorer</Typography>- <LinearProgress sx={{ mb: 3, borderRadius: 1 }} />- <Grid container spacing={2}>- {[...Array(8)].map((_, i) => <Grid size={{ xs: 6, sm: 4, md: 3, lg: 2 }} key={i}><Skeleton variant="rounded" height={300} sx={{ borderRadius: 2 }} /></Grid>)}- </Grid>- </Box>- );+ 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 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]);- return (- <Box>- <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3, flexWrap: 'wrap', gap: 2 }}>- <Box>- <Typography variant="h4">Shorts Explorer</Typography>- <Typography variant="body2" color="text.secondary" sx={{ mt: 0.25 }}>- {shorts.length} shorts across {channels.length} channels- </Typography>- </Box>- <Button variant="contained" onClick={loadAllShorts} size="small">Refresh</Button>- </Box>-- {/* Summary */}- <Grid container spacing={2} sx={{ mb: 3 }}>- {[- { label: 'Shorts', value: fmtNum(stats.total) },- { label: 'Total Views', value: fmtNum(stats.totalViews) },- { label: 'Total Likes', value: fmtNum(stats.totalLikes) },- { label: 'Avg Views', value: fmtNum(stats.avgViews) },- ].map((s, i) => (- <Grid key={i} size={{ xs: 6, sm: 3 }}>- <MainCard sx={{ textAlign: 'center' }}>- <Typography variant="caption" color="text.secondary" sx={{ display: 'block' }}>{s.label}</Typography>- <Typography variant="h5" sx={{ fontWeight: 700, mt: 0.5 }}>{s.value}</Typography>- </MainCard>- </Grid>- ))}- </Grid>-- {/* Filters */}- <MainCard sx={{ mb: 2.5 }}>- <Grid container spacing={2} alignItems="center">- <Grid size={{ xs: 12, sm: 3 }}>- <TextField fullWidth size="small" placeholder="Search shorts…"- value={search} onChange={e => { setSearch(e.target.value); setPage(1); }}- slotProps={{ input: { startAdornment: <InputAdornment position="start"><Search sx={{ color: 'text.secondary', fontSize: 18 }} /></InputAdornment> } }}- />- </Grid>- <Grid size={{ xs: 6, sm: 3 }}>- <FormControl fullWidth size="small">- <InputLabel>Channel</InputLabel>- <Select value={channelFilter} label="Channel" onChange={e => { setChannelFilter(e.target.value); setPage(1); }}>- <MenuItem value="all">All Channels ({channels.length})</MenuItem>- {channels.map(c => (- <MenuItem key={c.id} value={c.id}>- <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>- {c.thumbnail && <Avatar src={c.thumbnail} sx={{ width: 18, height: 18 }} />}- {c.title}- </Box>- </MenuItem>- ))}- </Select>- </FormControl>- </Grid>- <Grid size={{ xs: 6, sm: 3 }}>- <FormControl fullWidth size="small">- <InputLabel>Performance</InputLabel>- <Select value={performanceTier} label="Performance" onChange={e => { setPerformanceTier(e.target.value); setPage(1); }}>- {PERFORMANCE_TIERS.map(t => <MenuItem key={t.value} value={t.value}>{t.label}</MenuItem>)}- </Select>- </FormControl>- </Grid>- <Grid size={{ xs: 12, sm: 3 }}>- <FormControl fullWidth size="small">- <InputLabel>Sort By</InputLabel>- <Select value={sortField} label="Sort By" onChange={e => { setSortField(e.target.value); setPage(1); }}>- {SORT_OPTIONS.map(s => <MenuItem key={s.field} value={s.field}>{s.label}</MenuItem>)}- </Select>- </FormControl>- </Grid>- </Grid>- <Typography variant="caption" color="text.secondary" sx={{ display: 'block', mt: 1.5 }}>- Showing {paginatedShorts.length} of {filteredShorts.length} shorts- </Typography>- </MainCard>-- {/* Grid */}- <Grid container spacing={2}>- {paginatedShorts.map((v, i) => (- <Grid size={{ xs: 6, sm: 4, md: 3, lg: 2 }} key={`${v.videoId}-${i}`}>- <MainCard- content={false}- sx={{ cursor: 'pointer', overflow: 'hidden', transition: 'box-shadow 0.2s', '&:hover': { boxShadow: '0 6px 20px rgba(0,0,0,0.12)' } }}- onClick={() => window.open(`https://www.youtube.com/shorts/${v.videoId}`, '_blank', 'noopener')}- >- <Box sx={{ position: 'relative' }}>- <Box component="img" src={v.thumbnail}- sx={{ width: '100%', aspectRatio: '9/16', objectFit: 'cover', display: 'block', bgcolor: GREY[200] }}- onError={e => { e.target.style.display = 'none'; }}- />- <Chip icon={<Visibility sx={{ fontSize: '12px !important', color: '#fff !important' }} />}- label={fmtNum(v.viewCount)} size="small"- sx={{ position: 'absolute', top: 6, right: 6, bgcolor: 'rgba(0,0,0,0.75)', color: '#fff', fontSize: '0.68rem', fontWeight: 600, height: 20 }} />- <Chip label={fmtDuration(v.durationSeconds)} size="small"- sx={{ position: 'absolute', bottom: 6, right: 6, bgcolor: 'rgba(0,0,0,0.8)', color: '#fff', fontSize: '0.68rem', fontWeight: 600, height: 20 }} />- </Box>- <Box sx={{ p: 1.5 }}>- <Typography variant="body2" sx={{ fontWeight: 600, mb: 0.5, fontSize: '0.75rem', display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden', lineHeight: 1.4 }}>- {v.title}- </Typography>- {channels.length > 1 && (- <Typography variant="caption" color="text.secondary" sx={{ display: 'block', mb: 0.5 }}>{v.channelTitle}</Typography>- )}- <Box sx={{ display: 'flex', gap: 1, alignItems: 'center', color: 'text.secondary', fontSize: '0.7rem' }}>- <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.3 }}><ThumbUpIcon sx={{ fontSize: 11 }} />{fmtNum(v.likeCount)}</Box>- <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.3 }}><CommentIcon sx={{ fontSize: 11 }} />{fmtNum(v.commentCount)}</Box>- <Typography variant="caption" sx={{ ml: 'auto', fontSize: '0.65rem' }}>{timeAgo(v.publishedAt)}</Typography>- </Box>- </Box>- </MainCard>- </Grid>- ))}- </Grid>-- {filteredShorts.length === 0 && !loading && (- <MainCard>- <Box sx={{ textAlign: 'center', py: 6 }}>- <YouTube sx={{ fontSize: 56, color: GREY[300], mb: 2 }} />- <Typography variant="h5" color="text.secondary">No shorts found</Typography>- <Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>- {accounts?.length === 0 ? 'Add a channel first' : 'Try adjusting your filters'}- </Typography>- </Box>- </MainCard>- )}+ const pageCount = Math.ceil(filtered.length / ITEMS_PER_PAGE);+ const paged = filtered.slice((page - 1) * ITEMS_PER_PAGE, page * ITEMS_PER_PAGE);- {pageCount > 1 && (- <Box sx={{ display: 'flex', justifyContent: 'center', mt: 3 }}>- <Pagination count={pageCount} page={page} onChange={(_, p) => setPage(p)} shape="rounded" size="large" />- </Box>- )}- </Box>+ 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>+ </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>+ </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>+ {channels.length > 1 && (+ <Select value={channelFilter} onValueChange={v => { setChannelFilter(v); setPage(1); }}>+ <SelectTrigger className="w-40"><SelectValue placeholder="All Channels" /></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>+ )}+ <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>+ </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>+ ))}+ </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>+ </div>+ )}+ </div>+ );}diff --git a/frontend/src/features/analytics/videos/VideoExplorer.jsx b/frontend/src/features/analytics/videos/VideoExplorer.jsxindex e06d673..919401b 100644--- a/frontend/src/features/analytics/videos/VideoExplorer.jsx+++ b/frontend/src/features/analytics/videos/VideoExplorer.jsx@@ -1,313 +1,364 @@import React, { useState, useEffect, useMemo } from '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 {- Box, Typography, Grid, TextField, InputAdornment,- Select, MenuItem, FormControl, InputLabel, Chip, IconButton, Tooltip,- LinearProgress, Table, TableBody, TableCell, TableContainer, TableHead,- TableRow, Avatar, Button, ToggleButton, ToggleButtonGroup, Pagination,- Skeleton, TableSortLabel,-} from '@mui/material';+ Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue,+} from '@/components/ui/select';+import { ScrollArea } from '@/components/ui/scroll-area';import {- Search, Visibility, ThumbUp, Comment,- ViewList, ViewModule, PlayCircleOutline, YouTube,-} from '@mui/icons-material';-import MainCard from '../../../components/MainCard';+ 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 { fmtNum, fmtDate, fmtDuration, fmtPercent, timeAgo } from '../../../utils/formatters';-import { PRIMARY, GREY } from '../../../themes/index';+import { cn } from '@/lib/utils';const ITEMS_PER_PAGE = 25;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);+ 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 },+ { 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;+ return (+ <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')}+ >+ {label}+ <span className="text-[10px]">{active ? (sortOrder === 'asc' ? '↑' : '↓') : ''}</span>+ </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 { 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([]);- useEffect(() => { loadAllVideos(); }, [accounts]);+ useEffect(() => { loadAllVideos(); }, [accounts]);- const loadAllVideos = async () => {- setLoading(true);+ const loadAllVideos = async () => {+ setLoading(true);+ try {+ const allVids = [];+ const channelList = [];+ for (const acct of (accounts || [])) {+ if (acct.platform === 'instagram') continue;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 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;- });- return result;- }, [videos, channelFilter, search, performanceTier, sortField, sortOrder]);+ 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;+ });+ return result;+ }, [videos, channelFilter, search, performanceTier, sortField, sortOrder]);- const pageCount = Math.ceil(filteredVideos.length / ITEMS_PER_PAGE);- const paginatedVideos = filteredVideos.slice((page - 1) * ITEMS_PER_PAGE, 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 handleSort = (field) => {- if (sortField === field) setSortOrder(prev => prev === 'asc' ? 'desc' : 'asc');- else { setSortField(field); setSortOrder('desc'); }- };+ const handleSort = (field) => {+ if (sortField === field) setSortOrder(prev => prev === 'asc' ? 'desc' : 'asc');+ else { setSortField(field); setSortOrder('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]);-- if (loading) {- return (- <Box>- <Typography variant="h4" sx={{ mb: 3 }}>Video Explorer</Typography>- <LinearProgress sx={{ mb: 3, borderRadius: 1 }} />- <Grid container spacing={2.5}>- {[...Array(6)].map((_, i) => <Grid size={{ xs: 12, sm: 6, md: 4 }} key={i}><Skeleton variant="rounded" height={180} sx={{ borderRadius: 2 }} /></Grid>)}- </Grid>- </Box>- );- }+ 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]);+ if (loading) {return (- <Box>- {/* Header */}- <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3, flexWrap: 'wrap', gap: 2 }}>- <Box>- <Typography variant="h4">Video Explorer</Typography>- <Typography variant="body2" color="text.secondary" sx={{ mt: 0.25 }}>- {videos.length} total videos across {channels.length} channels- </Typography>- </Box>- <Button variant="contained" onClick={loadAllVideos} size="small">Refresh</Button>- </Box>+ <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>+ </div>+ );+ }- {/* Summary */}- <Grid container spacing={2} sx={{ mb: 3 }}>- {[- { label: 'Videos', value: fmtNum(stats.total), gradient: 'blue' },- { label: 'Total Views', value: fmtNum(stats.totalViews), gradient: 'red' },- { label: 'Total Likes', value: fmtNum(stats.totalLikes), gradient: 'green' },- { label: 'Total Comments', value: fmtNum(stats.totalComments), gradient: 'orange' },- { label: 'Avg Views', value: fmtNum(stats.avgViews), gradient: 'purple' },- ].map((s, i) => (- <Grid key={i} size={{ xs: 6, sm: 4, md: 2.4 }}>- <MainCard sx={{ textAlign: 'center' }}>- <Typography variant="caption" color="text.secondary" sx={{ display: 'block' }}>{s.label}</Typography>- <Typography variant="h5" sx={{ fontWeight: 700, mt: 0.5 }}>{s.value}</Typography>- </MainCard>- </Grid>- ))}- </Grid>+ 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>+ </div>- {/* Filters */}- <MainCard sx={{ mb: 2.5 }}>- <Grid container spacing={2} alignItems="center">- <Grid size={{ xs: 12, sm: 4 }}>- <TextField fullWidth size="small" placeholder="Search by title or tag…"- value={search} onChange={e => { setSearch(e.target.value); setPage(1); }}- slotProps={{ input: { startAdornment: <InputAdornment position="start"><Search sx={{ color: 'text.secondary', fontSize: 18 }} /></InputAdornment> } }}- />- </Grid>- <Grid size={{ xs: 6, sm: 3 }}>- <FormControl fullWidth size="small">- <InputLabel>Channel</InputLabel>- <Select value={channelFilter} label="Channel" onChange={e => { setChannelFilter(e.target.value); setPage(1); }}>- <MenuItem value="all">All Channels ({channels.length})</MenuItem>- {channels.map(c => (- <MenuItem key={c.id} value={c.id}>- <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>- {c.thumbnail && <Avatar src={c.thumbnail} sx={{ width: 18, height: 18 }} />}- {c.title}- </Box>- </MenuItem>- ))}- </Select>- </FormControl>- </Grid>- <Grid size={{ xs: 6, sm: 3 }}>- <FormControl fullWidth size="small">- <InputLabel>Performance</InputLabel>- <Select value={performanceTier} label="Performance" onChange={e => { setPerformanceTier(e.target.value); setPage(1); }}>- {PERFORMANCE_TIERS.map(t => <MenuItem key={t.value} value={t.value}>{t.label}</MenuItem>)}- </Select>- </FormControl>- </Grid>- <Grid size={{ xs: 12, sm: 2 }}>- <ToggleButtonGroup value={viewMode} exclusive onChange={(_, v) => v && setViewMode(v)} size="small" fullWidth>- <ToggleButton value="table"><ViewList /></ToggleButton>- <ToggleButton value="grid"><ViewModule /></ToggleButton>- </ToggleButtonGroup>- </Grid>- </Grid>- <Typography variant="caption" color="text.secondary" sx={{ display: 'block', mt: 1.5 }}>- Showing {paginatedVideos.length} of {filteredVideos.length} videos- </Typography>- </MainCard>+ {/* 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>- {/* Table */}- {viewMode === 'table' && (- <MainCard content={false}>- <TableContainer sx={{ maxHeight: 680 }}>- <Table size="small" stickyHeader>- <TableHead>- <TableRow>- <TableCell sx={{ width: 40 }}>#</TableCell>- <TableCell sx={{ width: 70 }} />- <TableCell><TableSortLabel active={sortField === 'title'} direction={sortField === 'title' ? sortOrder : 'asc'} onClick={() => handleSort('title')}>Video</TableSortLabel></TableCell>- {channels.length > 1 && <TableCell>Channel</TableCell>}- <TableCell align="right"><TableSortLabel active={sortField === 'viewCount'} direction={sortField === 'viewCount' ? sortOrder : 'desc'} onClick={() => handleSort('viewCount')}>Views</TableSortLabel></TableCell>- <TableCell align="right"><TableSortLabel active={sortField === 'likeCount'} direction={sortField === 'likeCount' ? sortOrder : 'desc'} onClick={() => handleSort('likeCount')}>Likes</TableSortLabel></TableCell>- <TableCell align="right"><TableSortLabel active={sortField === 'commentCount'} direction={sortField === 'commentCount' ? sortOrder : 'desc'} onClick={() => handleSort('commentCount')}>Comments</TableSortLabel></TableCell>- <TableCell align="right"><TableSortLabel active={sortField === 'engagementRate'} direction={sortField === 'engagementRate' ? sortOrder : 'desc'} onClick={() => handleSort('engagementRate')}>Engagement</TableSortLabel></TableCell>- <TableCell align="right"><TableSortLabel active={sortField === 'durationSeconds'} direction={sortField === 'durationSeconds' ? sortOrder : 'desc'} onClick={() => handleSort('durationSeconds')}>Duration</TableSortLabel></TableCell>- <TableCell align="right"><TableSortLabel active={sortField === 'publishedAt'} direction={sortField === 'publishedAt' ? sortOrder : 'desc'} onClick={() => handleSort('publishedAt')}>Published</TableSortLabel></TableCell>- <TableCell align="center" sx={{ width: 52 }} />- </TableRow>- </TableHead>- <TableBody>- {paginatedVideos.map((v, i) => (- <TableRow key={`${v.videoId}-${i}`} hover sx={{ cursor: 'pointer' }} onClick={() => window.open(`https://www.youtube.com/watch?v=${v.videoId}`, '_blank', 'noopener')}>- <TableCell><Typography variant="body2" color="text.secondary">{(page - 1) * ITEMS_PER_PAGE + i + 1}</Typography></TableCell>- <TableCell>{v.thumbnail && <Box component="img" src={v.thumbnail} sx={{ width: 60, height: 34, borderRadius: 1, objectFit: 'cover', display: 'block' }} />}</TableCell>- <TableCell><Typography variant="body2" sx={{ fontWeight: 500, maxWidth: 280, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{v.title}</Typography></TableCell>- {channels.length > 1 && <TableCell><Chip label={v.channelTitle} size="small" variant="outlined" sx={{ fontSize: '0.7rem', maxWidth: 120 }} /></TableCell>}- <TableCell align="right"><Typography variant="body2" sx={{ fontWeight: 600 }}>{fmtNum(v.viewCount)}</Typography></TableCell>- <TableCell align="right"><Typography variant="body2">{fmtNum(v.likeCount)}</Typography></TableCell>- <TableCell align="right"><Typography variant="body2">{fmtNum(v.commentCount)}</Typography></TableCell>- <TableCell align="right">- <Chip label={fmtPercent(v.engagementRate)} size="small"- sx={{ bgcolor: parseFloat(v.engagementRate) > 5 ? '#f6ffed' : GREY[100], color: parseFloat(v.engagementRate) > 5 ? '#389e0d' : 'text.secondary', fontWeight: 600, fontSize: '0.68rem', height: 20 }} />- </TableCell>- <TableCell align="right"><Typography variant="body2">{fmtDuration(v.durationSeconds)}</Typography></TableCell>- <TableCell align="right"><Typography variant="caption" color="text.secondary">{fmtDate(v.publishedAt)}</Typography></TableCell>- <TableCell align="center">- <Tooltip title="Watch on YouTube">- <IconButton size="small" onClick={e => { e.stopPropagation(); window.open(`https://www.youtube.com/watch?v=${v.videoId}`, '_blank', 'noopener'); }}- sx={{ color: '#ff4d4f', '&:hover': { bgcolor: '#fff1f0' } }}>- <PlayCircleOutline sx={{ fontSize: 16 }} />- </IconButton>- </Tooltip>- </TableCell>- </TableRow>- ))}- </TableBody>- </Table>- </TableContainer>- </MainCard>- )}+ {/* 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')}+ >+ <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>+ </div>+ </div>+ <p className="text-xs text-muted-foreground mt-2">+ Showing {paginatedVideos.length} of {filteredVideos.length} videos+ </p>+ </MainCard>- {/* Grid */}- {viewMode === 'grid' && (- <Grid container spacing={2}>- {paginatedVideos.map((v, i) => (- <Grid size={{ xs: 12, sm: 6, md: 4, lg: 3 }} key={`${v.videoId}-${i}`}>- <MainCard content={false} sx={{ cursor: 'pointer', transition: 'box-shadow 0.2s', '&:hover': { boxShadow: '0 6px 20px rgba(0,0,0,0.12)' } }}- onClick={() => window.open(`https://www.youtube.com/watch?v=${v.videoId}`, '_blank', 'noopener')}>- <Box sx={{ position: 'relative' }}>- <Box component="img" src={v.thumbnail} sx={{ width: '100%', aspectRatio: '16/9', objectFit: 'cover', display: 'block' }} />- {v.durationSeconds > 0 && (- <Chip label={fmtDuration(v.durationSeconds)} size="small"- sx={{ position: 'absolute', bottom: 6, right: 6, bgcolor: 'rgba(0,0,0,0.8)', color: '#fff', fontSize: '0.68rem', fontWeight: 600, height: 20 }} />- )}- <Chip icon={<Visibility sx={{ fontSize: '12px !important', color: '#fff !important' }} />} label={fmtNum(v.viewCount)} size="small"- sx={{ position: 'absolute', top: 6, right: 6, bgcolor: 'rgba(0,0,0,0.75)', color: '#fff', fontSize: '0.68rem', fontWeight: 600, height: 20 }} />- </Box>- <Box sx={{ p: 1.5 }}>- <Typography variant="body2" sx={{ fontWeight: 600, mb: 0.5, display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden', lineHeight: 1.4 }}>- {v.title}- </Typography>- {channels.length > 1 && <Typography variant="caption" color="text.secondary" sx={{ display: 'block', mb: 0.5 }}>{v.channelTitle}</Typography>}- <Box sx={{ display: 'flex', gap: 1.5, alignItems: 'center', color: 'text.secondary' }}>- <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.3, fontSize: '0.75rem' }}><ThumbUp sx={{ fontSize: 12 }} />{fmtNum(v.likeCount)}</Box>- <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.3, fontSize: '0.75rem' }}><Comment sx={{ fontSize: 12 }} />{fmtNum(v.commentCount)}</Box>- <Typography variant="caption" sx={{ ml: 'auto' }}>{timeAgo(v.publishedAt)}</Typography>- </Box>- </Box>- </MainCard>- </Grid>- ))}- </Grid>- )}+ {/* 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" />+ </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>+ )}- {/* Empty state */}- {filteredVideos.length === 0 && !loading && (- <MainCard>- <Box sx={{ textAlign: 'center', py: 6 }}>- <YouTube sx={{ fontSize: 56, color: GREY[300], mb: 2 }} />- <Typography variant="h5" color="text.secondary">No videos found</Typography>- <Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>- {accounts?.length === 0 ? 'Add a channel first to explore videos' : 'Try adjusting your filters'}- </Typography>- </Box>- </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+ key={`${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>+ ))}+ </div>+ )}- {/* Pagination */}- {pageCount > 1 && (- <Box sx={{ display: 'flex', justifyContent: 'center', mt: 3 }}>- <Pagination count={pageCount} page={page} onChange={(_, p) => setPage(p)} shape="rounded" size="large" />- </Box>- )}- </Box>- );+ {/* 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>+ )}+ </div>+ );}