'use client';

import { useState, useEffect, useCallback } from 'react';
import axios from 'axios';
import Link from 'next/link';

// ─── Types ──────────────────────────────────────────────────────────
interface NicheCluster {
    id?: number;
    name: string;
    keywords: string | string[];
    titles?: string | string[];
    sample_titles?: string | string[];
    channels?: string | string[];
    sample_channels?: string | string[];
    score: number;
    session_count?: number;
    item_count?: number;
    last_seen?: string;
    history?: number[]; // score trend for sparkline
}

interface Anomaly {
    id: string;
    title: string;
    thumbnailUrl: string;
    subs: number;
    views_now: number;
    views_48h: number;
    velocity_pct: number;
    note?: string;
}

interface EmbryoCluster {
    name: string;
    keywords: string[];
    titles: string[];
    channels: string[];
    score: number;
    members: { title: string; channel: string; views: number; subs: number; ratio: number; thumbnail: string; videoId: string; channelId: string }[];
}

interface FamilyTree {
    niche: string;
    parent: string[];
    channels: { id: string; title: string; subs: number; thumbnail: string }[];
    siblings: string[];
    children: string[];
}

interface WhiteSpaceResult {
    niche: string;
    whiteSpaceScore: number;
    demandScore: number;
    supplyScore: number;
    label: string;
    verdict: string;
    data: { avgViews: number; totalVideoResults: number; totalChannels: number; avgTopChannelSubs: number };
}

// ─── Helpers ──────────────────────────────────────────────────────────
const fmt = (n: number) =>
    n >= 1_000_000 ? (n / 1_000_000).toFixed(1) + 'M' :
        n >= 1_000 ? (n / 1_000).toFixed(1) + 'K' : String(n);

const scoreColor = (s: number) =>
    s >= 75 ? '#22c55e' : s >= 55 ? '#eab308' : s >= 35 ? '#f97316' : '#ef4444';

const keywordList = (v: string | string[] | undefined): string[] => {
    if (!v) return [];
    if (Array.isArray(v)) return v;
    return v.split(',').map(k => k.trim()).filter(Boolean);
};

const titleList = (v: string | string[] | undefined): string[] => {
    if (!v) return [];
    if (Array.isArray(v)) return v;
    return v.split('|').map(t => t.trim()).filter(Boolean);
};

// ─── Sparkline ──────────────────────────────────────────────────────────────
function Sparkline({ data, color = '#22c55e' }: { data: number[]; color?: string }) {
    if (!data || data.length < 2) return null;
    const max = Math.max(...data), min = Math.min(...data);
    const range = max - min || 1;
    const w = 56, h = 18;
    const pts = data.map((v, i) => `${(i / (data.length - 1)) * w},${h - ((v - min) / range) * h}`).join(' ');
    const lastY = h - ((data[data.length - 1] - min) / range) * h;
    return (
        <svg width={w} height={h} className="overflow-visible flex-shrink-0">
            <polyline points={pts} fill="none" stroke={color} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
            <circle cx={(data.length - 1) / (data.length - 1) * w} cy={lastY} r="2.5" fill={color} />
        </svg>
    );
}


function NicheDrawer({ niche, onClose }: { niche: string; onClose: () => void }) {
    const [tree, setTree] = useState<FamilyTree | null>(null);
    const [ws, setWs] = useState<WhiteSpaceResult | null>(null);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        setLoading(true);
        setTree(null); setWs(null);
        const q = encodeURIComponent(niche);
        Promise.all([
            axios.get(`/api/discover/family-tree?niche=${q}`).then(r => setTree(r.data.tree)).catch(() => { }),
            axios.get(`/api/discover/whitespace?niche=${q}`).then(r => setWs(r.data)).catch(() => { }),
        ]).finally(() => setLoading(false));
    }, [niche]);

    const wsColor = ws ? scoreColor(ws.whiteSpaceScore) : '#888';

    return (
        <div className="fixed inset-y-0 right-0 w-full max-w-md z-50 flex flex-col" style={{ background: '#13131a', borderLeft: '1px solid rgba(255,255,255,0.07)', boxShadow: '-20px 0 60px rgba(0,0,0,0.5)' }}>
            {/* Header */}
            <div className="flex items-center gap-3 px-5 py-4" style={{ borderBottom: '1px solid rgba(255,255,255,0.07)' }}>
                <button onClick={onClose} className="text-lg hover:text-white transition-colors" style={{ color: '#555' }}>✕</button>
                <h2 className="font-bold text-white truncate flex-1">{niche}</h2>
                <span className="text-xs px-2 py-0.5 rounded-full" style={{ background: 'rgba(124,58,237,0.2)', color: '#a78bfa' }}>Niche Intel</span>
            </div>

            <div className="flex-1 overflow-y-auto p-5 space-y-5">
                {loading && (
                    <div className="flex items-center justify-center py-16">
                        <div className="w-8 h-8 rounded-full border-2 border-purple-500/30 border-t-purple-500 animate-spin" />
                    </div>
                )}

                {/* White Space Score */}
                {ws && (
                    <div className="rounded-2xl p-4" style={{ background: '#1a1a24', border: '1px solid rgba(255,255,255,0.06)' }}>
                        <p className="text-xs font-bold uppercase tracking-wider mb-3" style={{ color: '#555' }}>⬜ White Space Score</p>
                        <div className="flex items-center gap-4 mb-3">
                            <div className="relative w-16 h-16 flex-shrink-0">
                                <svg className="w-16 h-16 -rotate-90" viewBox="0 0 64 64">
                                    <circle cx="32" cy="32" r="26" fill="none" stroke="#1e1e2c" strokeWidth="7" />
                                    <circle cx="32" cy="32" r="26" fill="none" stroke={wsColor} strokeWidth="7"
                                        strokeDasharray={`${ws.whiteSpaceScore * 1.634} 163.4`} strokeLinecap="round" />
                                </svg>
                                <span className="absolute inset-0 flex items-center justify-center text-sm font-black" style={{ color: wsColor }}>{ws.whiteSpaceScore}</span>
                            </div>
                            <div>
                                <p className="text-sm font-bold mb-0.5" style={{ color: wsColor }}>{ws.label}</p>
                                <p className="text-xs" style={{ color: '#777' }}>{ws.verdict}</p>
                            </div>
                        </div>
                        <div className="grid grid-cols-2 gap-2 text-xs">
                            {[
                                ['Demand', ws.demandScore, '#22c55e'],
                                ['Supply', ws.supplyScore, '#ef4444'],
                            ].map(([label, val, color]) => (
                                <div key={String(label)} className="rounded-xl p-3" style={{ background: '#0f0f12' }}>
                                    <p className="mb-1" style={{ color: '#555' }}>{label}</p>
                                    <div className="flex items-center gap-2">
                                        <div className="flex-1 h-1.5 rounded-full" style={{ background: '#1e1e2c' }}>
                                            <div className="h-1.5 rounded-full" style={{ width: `${val}%`, background: String(color) }} />
                                        </div>
                                        <span className="font-bold" style={{ color: String(color) }}>{val}</span>
                                    </div>
                                </div>
                            ))}
                        </div>
                        <div className="grid grid-cols-2 gap-2 mt-2 text-xs">
                            <div className="rounded-lg p-2" style={{ background: '#0f0f12' }}>
                                <p style={{ color: '#555' }}>Avg Views (Top)</p>
                                <p className="font-bold text-white">{fmt(ws.data.avgViews)}</p>
                            </div>
                            <div className="rounded-lg p-2" style={{ background: '#0f0f12' }}>
                                <p style={{ color: '#555' }}>Total Channels</p>
                                <p className="font-bold text-white">{fmt(ws.data.totalChannels)}</p>
                            </div>
                        </div>
                    </div>
                )}

                {/* Family Tree */}
                {tree && (
                    <div className="rounded-2xl p-4" style={{ background: '#1a1a24', border: '1px solid rgba(255,255,255,0.06)' }}>
                        <p className="text-xs font-bold uppercase tracking-wider mb-3" style={{ color: '#555' }}>🌳 Niche Family Tree</p>

                        {tree.parent.length > 0 && (
                            <div className="mb-3">
                                <p className="text-xs mb-1.5" style={{ color: '#666' }}>Parent Niche</p>
                                <div className="flex flex-wrap gap-1.5">
                                    {tree.parent.map((p, i) => (
                                        <span key={i} className="text-xs px-2 py-0.5 rounded-full" style={{ background: 'rgba(124,58,237,0.12)', color: '#a78bfa', border: '1px solid rgba(124,58,237,0.2)' }}>{p}</span>
                                    ))}
                                </div>
                            </div>
                        )}

                        <div className="mb-3">
                            <p className="text-xs mb-1.5" style={{ color: '#666' }}>Top Channels</p>
                            <div className="space-y-1.5">
                                {tree.channels.slice(0, 4).map((ch, i) => (
                                    <Link key={i} href={`/channel/${ch.id}`} className="flex items-center gap-2 rounded-lg p-2 hover:bg-white/5 transition-colors" style={{ textDecoration: 'none' }}>
                                        {ch.thumbnail && <img src={ch.thumbnail} className="w-6 h-6 rounded-full" alt="" />}
                                        <span className="text-xs text-white flex-1 truncate">{ch.title}</span>
                                        <span className="text-xs" style={{ color: '#555' }}>{fmt(ch.subs)}</span>
                                    </Link>
                                ))}
                            </div>
                        </div>

                        {tree.siblings.length > 0 && (
                            <div className="mb-3">
                                <p className="text-xs mb-1.5" style={{ color: '#666' }}>Sibling Niches</p>
                                <div className="flex flex-wrap gap-1.5">
                                    {tree.siblings.slice(0, 6).map((s, i) => (
                                        <span key={i} className="text-xs px-2 py-0.5 rounded-full cursor-pointer" style={{ background: '#1e1e2c', color: '#888', border: '1px solid rgba(255,255,255,0.06)' }}>{s}</span>
                                    ))}
                                </div>
                            </div>
                        )}

                        <div>
                            <p className="text-xs mb-1.5" style={{ color: '#666' }}>Sub-Niches (Children)</p>
                            <div className="flex flex-wrap gap-1.5">
                                {tree.children.slice(0, 8).map((c, i) => (
                                    <span key={i} className="text-xs px-2 py-0.5 rounded-full" style={{ background: 'rgba(34,197,94,0.08)', color: '#22c55e', border: '1px solid rgba(34,197,94,0.15)' }}>{c}</span>
                                ))}
                            </div>
                        </div>
                    </div>
                )}
            </div>
        </div>
    );
}

// ─── NicheCard ──────────────────────────────────────────────────────
function NicheCard({ cluster, onSelect, onSave, saved }: {
    cluster: NicheCluster;
    onSelect: (name: string) => void;
    onSave: (name: string) => void;
    saved: boolean;
}) {
    const keys = keywordList(cluster.keywords).slice(0, 4);
    const samples = titleList(cluster.sample_titles || cluster.titles).slice(0, 3);
    const sessionCount = cluster.session_count || 1;
    const history = cluster.history || [];
    const trend = history.length >= 2
        ? history[history.length - 1] > history[0] ? '↑' : history[history.length - 1] < history[0] ? '↓' : '—'
        : null;
    const trendColor = trend === '↑' ? '#22c55e' : trend === '↓' ? '#ef4444' : '#666';

    return (
        <div
            className="rounded-2xl p-4 cursor-pointer hover:scale-[1.01] transition-all flex flex-col"
            style={{ background: '#1a1a24', border: '1px solid rgba(255,255,255,0.06)' }}
        >
            <div onClick={() => onSelect(cluster.name)} className="flex-1">
                <div className="flex items-start gap-3 mb-3">
                    <div className="flex-1">
                        <p className="font-bold text-white text-sm leading-tight">{cluster.name}</p>
                        {sessionCount > 1 && (
                            <p className="text-xs mt-0.5" style={{ color: '#f97316' }}>🔥 Found in {sessionCount} regions/categories</p>
                        )}
                    </div>
                    <span className="text-xs font-bold px-2 py-0.5 rounded-full flex-shrink-0"
                        style={{ background: 'rgba(34,197,94,0.1)', color: '#22c55e' }}>
                        {Math.round(cluster.score)}
                    </span>
                </div>

                {keys.length > 0 && (
                    <div className="flex flex-wrap gap-1.5 mb-3">
                        {keys.map((k, i) => (
                            <span key={i} className="text-xs px-2 py-0.5 rounded-full" style={{ background: '#0f0f12', color: '#888' }}>{k}</span>
                        ))}
                    </div>
                )}

                {samples.length > 0 && (
                    <div className="space-y-1 mb-3">
                        {samples.map((t, i) => (
                            <p key={i} className="text-xs truncate" style={{ color: '#555' }}>“{t}”</p>
                        ))}
                    </div>
                )}
            </div>

            {/* Footer: sparkline + save button */}
            <div className="flex items-center justify-between mt-2 pt-2" style={{ borderTop: '1px solid rgba(255,255,255,0.04)' }}>
                <div className="flex items-center gap-2">
                    {history.length >= 2 && <Sparkline data={history} color={trendColor} />}
                    {trend && <span className="text-xs font-bold" style={{ color: trendColor }}>{trend}</span>}
                    {!history.length && <span className="text-xs" style={{ color: '#3b3b5c' }}>Click for intel →</span>}
                </div>
                <button
                    onClick={e => { e.stopPropagation(); onSave(cluster.name); }}
                    className="text-xs px-2 py-0.5 rounded-lg transition-all"
                    style={{
                        background: saved ? 'rgba(124,58,237,0.2)' : '#0f0f12',
                        color: saved ? '#a78bfa' : '#444',
                        border: `1px solid ${saved ? 'rgba(124,58,237,0.3)' : 'rgba(255,255,255,0.05)'}`,
                    }}
                    title={saved ? 'Saved — click to unsave' : 'Save niche'}
                >
                    {saved ? '📌 Saved' : '📌 Save'}
                </button>
            </div>
        </div>
    );
}

// ─── Main Page ──────────────────────────────────────────────────────
export default function DiscoverPage() {
    const [mounted, setMounted] = useState(false);
    const [tab, setTab] = useState<'feed' | 'anomalies' | 'embryos' | 'clusters' | 'faceless' | 'disclosed'>('feed');
    const [crawling, setCrawling] = useState(false);
    const [crawlError, setCrawlError] = useState('');
    const [lastCrawled, setLastCrawled] = useState<string | null>(null);

    const [feedResults, setFeedResults] = useState<NicheCluster[]>([]);
    const [anomalies, setAnomalies] = useState<{ tracked: Anomaly[]; fresh: Anomaly[] }>({ tracked: [], fresh: [] });
    const [embryos, setEmbryos] = useState<{ clusters: EmbryoCluster[]; raw: any[] }>({ clusters: [], raw: [] });
    const [clusters, setClusters] = useState<NicheCluster[]>([]);
    const [facelessNiches, setFacelessNiches] = useState<any[]>([]);
    const [disclosedNiches, setDisclosedNiches] = useState<any[]>([]);

    const [loadingTab, setLoadingTab] = useState(false);
    const [selectedNiche, setSelectedNiche] = useState<string | null>(null);
    const [savedNiches, setSavedNiches] = useState<Set<string>>(new Set());
    const [quotaError, setQuotaError] = useState<string | null>(null);

    // Set mounted flag + load feed + load saved niches
    useEffect(() => {
        setMounted(true);
        axios.get('/api/discover/crawl').then(r => {
            if (r.data.results?.length) {
                setFeedResults(r.data.results);
                setLastCrawled('Cached');
            }
        }).catch(() => { });
        // Load saved niche names into a Set for O(1) lookup
        axios.get('/api/niches/saved').then(r => {
            const names = (r.data.niches || []).map((n: any) => n.keyword as string);
            setSavedNiches(new Set(names));
        }).catch(() => { });
    }, []);

    const loadTabData = useCallback(async (t: typeof tab) => {
        setLoadingTab(true);
        setQuotaError(null);
        try {
            if (t === 'anomalies') {
                const r = await axios.get('/api/discover/anomalies');
                setAnomalies(r.data);
            } else if (t === 'embryos') {
                const r = await axios.get('/api/discover/embryos');
                if (r.data.quotaError) setQuotaError(r.data.quotaError);
                else setEmbryos(r.data);
            } else if (t === 'clusters') {
                const r = await axios.get('/api/discover/cluster');
                setClusters(r.data.clusters || []);
            } else if (t === 'faceless') {
                const r = await axios.get('/api/discover/faceless');
                setFacelessNiches(r.data.niches || []);
            } else if (t === 'disclosed') {
                const r = await axios.get('/api/discover/disclosed-ai');
                setDisclosedNiches(r.data.niches || []);
            }
        } catch (err: any) {
            console.error('Tab load error', err);
            if (err.response?.status === 503 && err.response?.data?.quotaExhausted) {
                setQuotaError(err.response.data.error || 'All YouTube API keys exhausted.');
            }
        } finally {
            setLoadingTab(false);
        }
    }, []);

    useEffect(() => {
        if (tab !== 'feed') loadTabData(tab);
    }, [tab, loadTabData]);

    // Save / unsave a niche
    const saveNiche = useCallback(async (name: string) => {
        if (savedNiches.has(name)) {
            await axios.delete(`/api/niches/saved?keyword=${encodeURIComponent(name)}`).catch(() => { });
            setSavedNiches(prev => { const s = new Set(prev); s.delete(name); return s; });
        } else {
            await axios.post('/api/niches/saved', { keyword: name }).catch(() => { });
            setSavedNiches(prev => new Set([...prev, name]));
        }
    }, [savedNiches]);


    const runCrawl = async () => {
        setCrawling(true);
        setCrawlError('');
        setQuotaError(null);
        try {
            const r = await axios.post('/api/discover/crawl');
            setFeedResults(r.data.results || []);
            setLastCrawled(new Date().toLocaleTimeString());
        } catch (err: any) {
            if (err.response?.status === 503 && err.response?.data?.quotaExhausted) {
                setQuotaError(err.response.data.error || 'All YouTube API keys exhausted.');
            } else {
                setCrawlError(err?.response?.data?.error || 'Crawl failed');
            }
        } finally {
            setCrawling(false);
        }
    };

    const tabs = [
        { key: 'feed', label: '🔭 Algo Feed', desc: 'YouTube is pushing' },
        { key: 'anomalies', label: '⚡ Anomalies', desc: 'Velocity spikes' },
        { key: 'embryos', label: '🌱 Embryos', desc: 'Unclaimed niches' },
        { key: 'clusters', label: '🧩 Clusters', desc: 'Topic families' },
        { key: 'faceless', label: '🤖 Faceless/AI', desc: 'No-face niches' },
        { key: 'disclosed', label: '🏷️ Disclosed AI', desc: '"Altered content" tag' },
    ] as const;


    // Don't render interactive content on server — prevents hydration mismatch
    if (!mounted) {
        return <div className="min-h-screen" style={{ backgroundColor: '#0f0f12' }} suppressHydrationWarning />;
    }

    return (
        <div className="min-h-screen" style={{ backgroundColor: '#0f0f12', color: '#e8e8f0' }} suppressHydrationWarning>
            {/* Overlay when drawer is open */}
            {selectedNiche && (
                <div className="fixed inset-0 z-40 bg-black/50 backdrop-blur-sm" onClick={() => setSelectedNiche(null)} />
            )}

            {/* Niche Drawer */}
            {selectedNiche && (
                <NicheDrawer niche={selectedNiche} onClose={() => setSelectedNiche(null)} />
            )}

            {/* Header */}
            <header className="sticky top-0 z-30" style={{ background: 'rgba(15,15,18,0.95)', borderBottom: '1px solid rgba(255,255,255,0.06)', backdropFilter: 'blur(10px)' }}>
                <div className="max-w-6xl mx-auto px-4 py-3 flex items-center gap-4">
                    <Link href="/" className="text-sm hover:text-white transition-colors" style={{ color: '#555' }}>← Search Tool</Link>
                    <div className="flex items-center gap-2 flex-1">
                        <span className="text-xl">🔭</span>
                        <h1 className="font-black text-white text-lg">Niche Radar</h1>
                        <span className="text-xs px-2 py-0.5 rounded-full ml-1" style={{ background: 'rgba(124,58,237,0.15)', color: '#a78bfa' }}>Discovery Mode</span>
                    </div>
                    <div className="flex items-center gap-3">
                        {lastCrawled && <span className="text-xs" style={{ color: '#444' }}>Last crawl: {lastCrawled}</span>}
                        <button
                            onClick={runCrawl}
                            disabled={crawling}
                            className="flex items-center gap-2 text-sm font-bold px-4 py-2 rounded-xl transition-all disabled:opacity-50"
                            style={{ background: crawling ? '#1e1e2c' : 'linear-gradient(135deg,#7c3aed,#4f46e5)', color: '#fff', boxShadow: crawling ? 'none' : '0 0 20px rgba(124,58,237,0.3)' }}
                        >
                            {crawling ? (
                                <><span className="w-3.5 h-3.5 rounded-full border-2 border-white/30 border-t-white animate-spin inline-block" /> Crawling...</>
                            ) : '🕷️ Crawl Now'}
                        </button>
                    </div>
                </div>
                {crawlError && (
                    <div className="px-4 py-2 text-xs text-red-400 border-t border-red-500/20" style={{ background: 'rgba(239,68,68,0.05)' }}>
                        ⚠️ {crawlError}
                    </div>
                )}
            </header>

            <div className="max-w-6xl mx-auto px-4 py-6">
                {quotaError && (
                    <div className="mb-6 p-4 rounded-xl text-sm border font-medium flex items-start gap-3" style={{ background: 'rgba(239,68,68,0.1)', color: '#fca5a5', borderColor: 'rgba(239,68,68,0.3)' }}>
                        <span className="text-lg">🛑</span>
                        <div>
                            <strong className="text-red-400 block mb-1">YouTube API Quota Exhausted</strong>
                            {quotaError}
                        </div>
                    </div>
                )}

                {/* Description banner */}
                <div className="rounded-2xl p-4 mb-6" style={{ background: 'linear-gradient(135deg, rgba(124,58,237,0.07), rgba(79,70,229,0.04))', border: '1px solid rgba(124,58,237,0.15)' }}>
                    <p className="text-sm" style={{ color: '#888' }}>
                        <strong className="text-white">No keyword needed. Shorts-only mode.</strong> Scans YouTube trending across <strong className="text-purple-400">all 16 categories × 4 regions</strong> and filters to videos ≤60 seconds (true Shorts). Topics appearing in multiple regions/categories score higher — those are what the algorithm is actively pushing.
                        Click any niche card to see its <strong className="text-purple-400">Family Tree</strong> + <strong className="text-green-400">White Space Score</strong>.
                    </p>
                </div>

                {/* Tabs */}
                <div className="flex gap-1 mb-6 p-1 rounded-xl" style={{ background: '#1a1a24' }}>
                    {tabs.map(t => (
                        <button
                            key={t.key}
                            onClick={() => setTab(t.key)}
                            className="flex-1 py-2.5 rounded-lg text-xs font-bold transition-all"
                            style={{
                                background: tab === t.key ? '#0f0f12' : 'transparent',
                                color: tab === t.key ? '#fff' : '#555',
                                boxShadow: tab === t.key ? '0 2px 8px rgba(0,0,0,0.3)' : 'none',
                            }}
                        >
                            {t.label}
                            <span className="block text-[10px] font-normal mt-0.5" style={{ color: tab === t.key ? '#666' : '#333' }}>{t.desc}</span>
                        </button>
                    ))}
                </div>

                {/* Tab: Algo Feed */}
                {tab === 'feed' && (
                    <div>
                        {feedResults.length === 0 && !crawling && (
                            <div className="text-center py-20" style={{ color: '#444' }}>
                                <p className="text-5xl mb-4">🕷️</p>
                                <p className="text-lg font-bold text-white mb-2">No data yet</p>
                                <p className="text-sm mb-6">Click “Crawl Now” to fetch the latest YouTube trending data across 4 regions and detect what the algorithm is pushing.</p>
                            </div>
                        )}
                        {crawling && (
                            <div className="text-center py-20">
                                <div className="w-12 h-12 rounded-full border-2 border-purple-500/30 border-t-purple-500 animate-spin mx-auto mb-4" />
                                <p className="text-sm text-white font-bold mb-1">Scanning YouTube Shorts...</p>
                                <p className="text-xs" style={{ color: '#555' }}>Fetching Shorts (≤60s) across 16 categories × 4 regions. This takes a few seconds.</p>
                            </div>
                        )}
                        {feedResults.length > 0 && !crawling && (
                            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                                {feedResults.map((c, i) => (
                                    <NicheCard key={i} cluster={c} onSelect={setSelectedNiche}
                                        onSave={saveNiche} saved={savedNiches.has(c.name)} />
                                ))}
                            </div>
                        )}
                    </div>
                )}

                {/* Tab: Anomalies */}
                {tab === 'anomalies' && (
                    <div>
                        {loadingTab ? (
                            <div className="text-center py-16"><div className="w-10 h-10 rounded-full border-2 border-orange-500/30 border-t-orange-500 animate-spin mx-auto" /></div>
                        ) : (
                            <>
                                {anomalies.tracked.length === 0 && anomalies.fresh.length === 0 && (
                                    <div className="text-center py-20" style={{ color: '#444' }}>
                                        <p className="text-5xl mb-4">⚡</p>
                                        <p className="text-lg font-bold text-white mb-2">No anomalies detected</p>
                                        <p className="text-sm">Anomaly detection needs channels in your database with 7+ days of tracking history. Use the main Search tool to add channels first.</p>
                                    </div>
                                )}
                                {anomalies.tracked.length > 0 && (
                                    <div>
                                        <p className="text-xs font-bold uppercase tracking-wider mb-3" style={{ color: '#555' }}>Tracked Channels — View Velocity Spikes</p>
                                        <div className="grid grid-cols-1 md:grid-cols-2 gap-3 mb-6">
                                            {anomalies.tracked.map((ch, i) => (
                                                <Link key={i} href={`/channel/${ch.id}`} style={{ textDecoration: 'none' }}>
                                                    <div className="rounded-2xl p-4 hover:scale-[1.01] transition-all" style={{ background: '#1a1a24', border: '1px solid rgba(249,115,22,0.2)' }}>
                                                        <div className="flex items-center gap-3 mb-2">
                                                            {ch.thumbnailUrl && <img src={ch.thumbnailUrl} className="w-10 h-10 rounded-full flex-shrink-0" alt="" />}
                                                            <div className="flex-1 min-w-0">
                                                                <p className="font-bold text-white text-sm truncate">{ch.title}</p>
                                                                <p className="text-xs" style={{ color: '#555' }}>{fmt(ch.subs)} subs</p>
                                                            </div>
                                                            <span className="text-sm font-black" style={{ color: '#f97316' }}>+{ch.velocity_pct}%</span>
                                                        </div>
                                                        <div className="flex gap-3 text-xs" style={{ color: '#555' }}>
                                                            <span>Now: {fmt(ch.views_now)}</span>
                                                            <span>48h ago: {fmt(ch.views_48h)}</span>
                                                        </div>
                                                    </div>
                                                </Link>
                                            ))}
                                        </div>
                                    </div>
                                )}
                                {anomalies.fresh.length > 0 && (
                                    <div>
                                        <p className="text-xs font-bold uppercase tracking-wider mb-3" style={{ color: '#555' }}>Fresh API Sweep — Recently Active Channels</p>
                                        <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                                            {anomalies.fresh.map((ch, i) => (
                                                <Link key={i} href={`/channel/${ch.id}`} style={{ textDecoration: 'none' }}>
                                                    <div className="rounded-2xl p-4 hover:scale-[1.01] transition-all" style={{ background: '#1a1a24', border: '1px solid rgba(255,255,255,0.06)' }}>
                                                        <div className="flex items-center gap-3">
                                                            {ch.thumbnailUrl && <img src={ch.thumbnailUrl} className="w-10 h-10 rounded-full flex-shrink-0" alt="" />}
                                                            <div className="flex-1 min-w-0">
                                                                <p className="font-bold text-white text-sm truncate">{ch.title}</p>
                                                                <p className="text-xs" style={{ color: '#555' }}>{ch.note}</p>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </Link>
                                            ))}
                                        </div>
                                    </div>
                                )}
                            </>
                        )}
                    </div>
                )}

                {/* Tab: Embryos */}
                {tab === 'embryos' && (
                    <div>
                        {loadingTab ? (
                            <div className="text-center py-16"><div className="w-10 h-10 rounded-full border-2 border-green-500/30 border-t-green-500 animate-spin mx-auto" /></div>
                        ) : embryos.clusters.length === 0 && embryos.raw.length === 0 ? (
                            <div className="text-center py-20" style={{ color: '#444' }}>
                                <p className="text-5xl mb-4">🌱</p>
                                <p className="text-lg font-bold text-white mb-2">No embryos found</p>
                                <p className="text-sm">Try refreshing — the scan rotates through different seed topics each time.</p>
                            </div>
                        ) : (
                            <div>
                                {embryos.clusters.length > 0 && (
                                    <>
                                        <p className="text-xs font-bold uppercase tracking-wider mb-3" style={{ color: '#555' }}>Clustered Embryonic Niches</p>
                                        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 mb-6">
                                            {embryos.clusters.map((cl, i) => (
                                                <div key={i} onClick={() => setSelectedNiche(cl.name)} className="rounded-2xl p-4 cursor-pointer hover:scale-[1.01] transition-all"
                                                    style={{ background: '#1a1a24', border: '1px solid rgba(34,197,94,0.15)' }}>
                                                    <div className="flex items-start gap-2 mb-2">
                                                        <p className="font-bold text-white flex-1">{cl.name || cl.keywords.slice(0, 3).join(' ')}</p>
                                                        <span className="text-xs" style={{ color: '#22c55e' }}>{cl.members?.length || 0} channels</span>
                                                    </div>
                                                    <div className="space-y-1.5">
                                                        {(cl.members || []).slice(0, 3).map((m, j) => (
                                                            <div key={j} className="flex items-center gap-2">
                                                                {m.thumbnail && <img src={m.thumbnail} className="w-6 h-6 rounded object-cover flex-shrink-0" alt="" />}
                                                                <div className="flex-1 min-w-0">
                                                                    <p className="text-xs text-white truncate">{m.title}</p>
                                                                    <p className="text-xs" style={{ color: '#555' }}>{fmt(m.subs)} subs · {fmt(m.views)} views · {m.ratio}× ratio</p>
                                                                </div>
                                                            </div>
                                                        ))}
                                                    </div>
                                                </div>
                                            ))}
                                        </div>
                                    </>
                                )}
                                {embryos.raw.length > 0 && (
                                    <>
                                        <p className="text-xs font-bold uppercase tracking-wider mb-3" style={{ color: '#555' }}>Individual Embryo Channels</p>
                                        <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                                            {embryos.raw.slice(0, 12).map((e, i) => (
                                                <Link key={i} href={`/channel/${e.channelId}`} style={{ textDecoration: 'none' }}>
                                                    <div className="rounded-xl p-3 flex gap-3 hover:scale-[1.01] transition-all" style={{ background: '#1a1a24', border: '1px solid rgba(255,255,255,0.05)' }}>
                                                        {e.thumbnail && <img src={e.thumbnail} className="w-20 h-12 rounded object-cover flex-shrink-0" alt="" />}
                                                        <div className="flex-1 min-w-0">
                                                            <p className="text-xs font-bold text-white truncate">{e.title}</p>
                                                            <p className="text-xs" style={{ color: '#888' }}>{e.channel}</p>
                                                            <div className="flex gap-3 mt-1 text-xs" style={{ color: '#555' }}>
                                                                <span>{fmt(e.subs)} subs</span>
                                                                <span className="text-orange-400 font-bold">{fmt(e.views)} views</span>
                                                                <span style={{ color: '#22c55e' }}>{e.ratio}× ratio</span>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </Link>
                                            ))}
                                        </div>
                                    </>
                                )}
                            </div>
                        )}
                    </div>
                )}

                {/* Tab: Semantic Clusters */}
                {tab === 'clusters' && (
                    <div>
                        {loadingTab ? (
                            <div className="text-center py-16"><div className="w-10 h-10 rounded-full border-2 border-blue-500/30 border-t-blue-500 animate-spin mx-auto" /></div>
                        ) : clusters.length === 0 ? (
                            <div className="text-center py-20" style={{ color: '#444' }}>
                                <p className="text-5xl mb-4">🧩</p>
                                <p className="text-lg font-bold text-white mb-2">No clusters yet</p>
                                <p className="text-sm">Run the Algo Feed crawl first — the clustering reads from the same crawled data.</p>
                            </div>
                        ) : (
                            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                                {clusters.map((cl, i) => (
                                    <NicheCard key={i} cluster={cl} onSelect={setSelectedNiche}
                                        onSave={saveNiche} saved={savedNiches.has(cl.name)} />
                                ))}
                            </div>
                        )}
                    </div>
                )}

                {/* Tab: Faceless/AI Niches */}
                {tab === 'faceless' && (
                    <div>
                        {loadingTab ? (
                            <div className="text-center py-20">
                                <div className="w-12 h-12 rounded-full border-2 border-purple-500/30 border-t-purple-500 animate-spin mx-auto mb-4" />
                                <p className="text-sm text-white font-bold mb-1">Scanning Faceless Niches...</p>
                                <p className="text-xs" style={{ color: '#555' }}>Searching 12 niche categories across YouTube Shorts. Takes ~15 seconds.</p>
                            </div>
                        ) : facelessNiches.length === 0 ? (
                            <div className="text-center py-20" style={{ color: '#444' }}>
                                <p className="text-5xl mb-4">🤖</p>
                                <p className="text-lg font-bold text-white mb-2">Click the tab to load</p>
                                <p className="text-sm">Scans 12 faceless/AI video niche categories on YouTube Shorts — no crawl needed, loads on demand.</p>
                            </div>
                        ) : (
                            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                                {facelessNiches.map((niche, i) => {
                                    const scoreColor = niche.score >= 65 ? '#22c55e' : niche.score >= 45 ? '#f97316' : '#888';
                                    const isSaved = savedNiches.has(niche.name);
                                    return (
                                        <div key={i} className="rounded-2xl p-4 flex flex-col"
                                            style={{ background: '#1a1a24', border: '1px solid rgba(255,255,255,0.06)' }}>
                                            {/* Header */}
                                            <div className="flex items-start gap-3 mb-3">
                                                {/* Score ring */}
                                                <div className="relative w-12 h-12 flex-shrink-0">
                                                    <svg className="w-12 h-12 -rotate-90" viewBox="0 0 48 48">
                                                        <circle cx="24" cy="24" r="18" fill="none" stroke="#1e1e2c" strokeWidth="5" />
                                                        <circle cx="24" cy="24" r="18" fill="none" stroke={scoreColor} strokeWidth="5"
                                                            strokeDasharray={`${niche.score * 1.131} 113.1`} strokeLinecap="round" />
                                                    </svg>
                                                    <span className="absolute inset-0 flex items-center justify-center text-xs font-black" style={{ color: scoreColor }}>{niche.score}</span>
                                                </div>
                                                <div className="flex-1 min-w-0">
                                                    <p className="font-bold text-white text-sm leading-tight">{niche.name}</p>
                                                    <span className="text-xs mt-0.5 inline-block" style={{ color: '#a78bfa' }}>{niche.viabilityLabel}</span>
                                                </div>
                                            </div>

                                            {/* Stats */}
                                            <div className="grid grid-cols-2 gap-2 mb-3">
                                                <div className="rounded-lg p-2 text-center" style={{ background: '#0f0f12' }}>
                                                    <p className="text-xs mb-0.5" style={{ color: '#555' }}>Avg Views</p>
                                                    <p className="text-sm font-bold text-white">{fmt(niche.avgViews)}</p>
                                                </div>
                                                <div className="rounded-lg p-2 text-center" style={{ background: '#0f0f12' }}>
                                                    <p className="text-xs mb-0.5" style={{ color: '#555' }}>Avg Subs</p>
                                                    <p className="text-sm font-bold text-white">{fmt(niche.avgSubs)}</p>
                                                </div>
                                            </div>

                                            {/* Why faceless */}
                                            <div className="rounded-lg p-2.5 mb-3" style={{ background: 'rgba(124,58,237,0.07)', border: '1px solid rgba(124,58,237,0.12)' }}>
                                                <p className="text-xs leading-relaxed" style={{ color: '#aaa' }}>{niche.whyFaceless}</p>
                                            </div>

                                            {/* Sample channels */}
                                            {niche.channels?.length > 0 && (
                                                <div className="space-y-1.5 mb-3">
                                                    <p className="text-xs font-bold" style={{ color: '#555' }}>SAMPLE CHANNELS</p>
                                                    {niche.channels.slice(0, 3).map((ch: any, j: number) => (
                                                        <Link key={j} href={`/channel/${ch.channelId}`} className="flex items-center gap-2 rounded-lg p-1.5 hover:bg-white/5 transition-colors" style={{ textDecoration: 'none' }}>
                                                            {ch.thumbnail && <img src={ch.thumbnail} className="w-6 h-6 rounded-full flex-shrink-0" alt="" />}
                                                            <span className="text-xs text-white truncate flex-1">{ch.channelTitle}</span>
                                                            <span className="text-xs flex-shrink-0" style={{ color: '#555' }}>{fmt(ch.subs)}</span>
                                                        </Link>
                                                    ))}
                                                </div>
                                            )}

                                            {/* Footer: save button */}
                                            <div className="mt-auto pt-2 flex justify-between items-center" style={{ borderTop: '1px solid rgba(255,255,255,0.04)' }}>
                                                <button onClick={() => setSelectedNiche(niche.name.replace(/^[^\s]+\s/, ''))}
                                                    className="text-xs" style={{ color: '#555' }}>
                                                    Family Tree + White Space →
                                                </button>
                                                <button
                                                    onClick={() => saveNiche(niche.name)}
                                                    className="text-xs px-2 py-0.5 rounded-lg transition-all"
                                                    style={{
                                                        background: isSaved ? 'rgba(124,58,237,0.2)' : '#0f0f12',
                                                        color: isSaved ? '#a78bfa' : '#444',
                                                        border: `1px solid ${isSaved ? 'rgba(124,58,237,0.3)' : 'rgba(255,255,255,0.05)'}`,
                                                    }}
                                                >
                                                    {isSaved ? '📌 Saved' : '📌 Save'}
                                                </button>
                                            </div>
                                        </div>
                                    );
                                })}
                            </div>
                        )}
                    </div>
                )}

                {/* Tab: Disclosed AI Content */}
                {tab === 'disclosed' && (
                    <div>
                        {loadingTab ? (
                            <div className="text-center py-20">
                                <div className="w-12 h-12 rounded-full border-2 border-blue-500/30 border-t-blue-500 animate-spin mx-auto mb-4" />
                                <p className="text-sm text-white font-bold mb-1">Scanning Disclosed AI Niches...</p>
                                <p className="text-xs" style={{ color: '#555' }}>Searching YouTube for heavy users of the "Altered Content" label...</p>
                            </div>
                        ) : disclosedNiches.length === 0 ? (
                            <div className="text-center py-20" style={{ color: '#444' }}>
                                <p className="text-5xl mb-4">🏷️</p>
                                <p className="text-lg font-bold text-white mb-2">Click the tab to load</p>
                                <p className="text-sm max-w-md mx-auto">Scans niches dominated by channels declaring "Altered or synthetic content" (AI generated) on YouTube Shorts.</p>
                            </div>
                        ) : (
                            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                                {disclosedNiches.map((niche, i) => {
                                    const scoreColor = niche.score >= 65 ? '#22c55e' : niche.score >= 45 ? '#f97316' : '#888';
                                    const isSaved = savedNiches.has(niche.name);
                                    return (
                                        <div key={i} className="rounded-2xl p-4 flex flex-col"
                                            style={{ background: '#1a1a2e', border: '1px solid rgba(59,130,246,0.1)' }}>
                                            {/* Header */}
                                            <div className="flex items-start gap-3 mb-3">
                                                <div className="relative w-12 h-12 flex-shrink-0">
                                                    <svg className="w-12 h-12 -rotate-90" viewBox="0 0 48 48">
                                                        <circle cx="24" cy="24" r="18" fill="none" stroke="#1e1e2c" strokeWidth="5" />
                                                        <circle cx="24" cy="24" r="18" fill="none" stroke={scoreColor} strokeWidth="5"
                                                            strokeDasharray={`${niche.score * 1.131} 113.1`} strokeLinecap="round" />
                                                    </svg>
                                                    <span className="absolute inset-0 flex items-center justify-center text-xs font-black" style={{ color: scoreColor }}>{niche.score}</span>
                                                </div>
                                                <div className="flex-1 min-w-0">
                                                    <p className="font-bold text-white text-sm leading-tight">{niche.name}</p>
                                                    <span className="text-xs mt-0.5 inline-block" style={{ color: '#60a5fa' }}>{niche.viabilityLabel}</span>
                                                </div>
                                            </div>

                                            {/* Stats */}
                                            <div className="grid grid-cols-2 gap-2 mb-3">
                                                <div className="rounded-lg p-2 text-center" style={{ background: '#0f0f12' }}>
                                                    <p className="text-xs mb-0.5" style={{ color: '#555' }}>Avg Views</p>
                                                    <p className="text-sm font-bold text-white">{fmt(niche.avgViews)}</p>
                                                </div>
                                                <div className="rounded-lg p-2 text-center" style={{ background: '#0f0f12' }}>
                                                    <p className="text-xs mb-0.5" style={{ color: '#555' }}>Avg Subs</p>
                                                    <p className="text-sm font-bold text-white">{fmt(niche.avgSubs)}</p>
                                                </div>
                                            </div>

                                            {/* AI label explainer */}
                                            <div className="rounded-lg p-2.5 mb-3" style={{ background: 'rgba(59,130,246,0.1)', border: '1px solid rgba(59,130,246,0.2)' }}>
                                                <p className="text-xs leading-relaxed" style={{ color: '#bfdbfe' }}>
                                                    <strong className="text-blue-400">🏷️ Altered Content:</strong> {niche.description}
                                                </p>
                                            </div>

                                            {/* Sample channels */}
                                            {niche.channels?.length > 0 && (
                                                <div className="space-y-1.5 mb-3">
                                                    <p className="text-xs font-bold uppercase tracking-wider" style={{ color: '#555' }}>Sample AI Channels</p>
                                                    {niche.channels.slice(0, 3).map((ch: any, j: number) => (
                                                        <Link key={j} href={`/channel/${ch.channelId}`} className="flex items-center gap-2 rounded-lg p-1.5 hover:bg-white/5 transition-colors" style={{ textDecoration: 'none' }}>
                                                            {ch.thumbnail && <img src={ch.thumbnail} className="w-6 h-6 rounded-full flex-shrink-0" alt="" />}
                                                            <span className="text-xs text-white truncate flex-1">{ch.channelTitle}</span>
                                                            <span className="text-xs flex-shrink-0" style={{ color: '#555' }}>{fmt(ch.subs)}</span>
                                                        </Link>
                                                    ))}
                                                </div>
                                            )}

                                            {/* Footer: save button */}
                                            <div className="mt-auto pt-2 flex justify-between items-center" style={{ borderTop: '1px solid rgba(255,255,255,0.04)' }}>
                                                <button onClick={() => setSelectedNiche(niche.name.replace(/^[^\s]+\s/, ''))}
                                                    className="text-xs" style={{ color: '#555' }}>
                                                    Family Tree + White Space →
                                                </button>
                                                <button
                                                    onClick={() => saveNiche(niche.name)}
                                                    className="text-xs px-2 py-0.5 rounded-lg transition-all"
                                                    style={{
                                                        background: isSaved ? 'rgba(59,130,246,0.2)' : '#0f0f12',
                                                        color: isSaved ? '#60a5fa' : '#444',
                                                        border: `1px solid ${isSaved ? 'rgba(59,130,246,0.4)' : 'rgba(255,255,255,0.05)'}`,
                                                    }}
                                                >
                                                    {isSaved ? '📌 Saved' : '📌 Save'}
                                                </button>
                                            </div>
                                        </div>
                                    );
                                })}
                            </div>
                        )}
                    </div>
                )}
            </div>
        </div>
    );
}
