'use client';

import { useState, useEffect } from 'react';
import { useParams, useRouter } from 'next/navigation';
import axios from 'axios';
import Link from 'next/link';

// ---- Types ----
interface Video {
    id: string;
    title: string;
    thumbnail: string;
    publishedAt: string;
    views: number;
    likes: number;
    comments: number;
    engRate: number;
    duration: number;
    isShort: boolean;
    isOutperformer: boolean;
    outperformRatio: number;
}

interface ChannelData {
    id: string;
    title: string;
    description: string;
    customUrl: string;
    publishedAt: string;
    country: string;
    thumbnail: string;
    banner: string;
    keywords: string;
    totalViews: number;
    totalSubs: number;
    totalVideos: number;
    avgViewsPerVideo: number;
    viewsPerSub: number;
    topVideoViews: number;
    topics: string[];
    uploadFrequencyDays: number;
    uploadFrequencyLabel: string;
    geographyTier: string;
    geographyLabel: string;
}

interface CommentAnalysis {
    sentiment: string;
    sentimentScore: number;
    painPoints: string[];
    commonQuestions: string[];
    videoIdeas: { title: string; reason: string }[];
    audienceProfile: string;
    topInsight: string;
    commentCount: number;
    videoTitle: string;
}

interface RiskFlag { type: string; severity: 'High' | 'Medium' | 'Low'; detail: string; }
interface TrendPersistence { score: number; label: string; rationale: string; followUpRatio: number; followUpCount: number; outperformerPct: number; }
interface PackagingAnalyzer { titlePatternTag: string; titlePatternExplanation: string; thumbnailStrategy: string; hookPosition: string; hookType: string; packagingTemplate: string; ctaStyle: string; }
interface FormatDNA { videoLength: string; pacing: string; onScreenText: string; topicAngle: string; postingContext: string; replicableElements: string[]; creatorPlaybook: string; }
interface ChannelAI { trendPersistence?: TrendPersistence; riskFlags?: RiskFlag[]; packagingAnalyzer?: PackagingAnalyzer; formatDNA?: FormatDNA; error?: string; }

// ---- Helpers ----
function fmt(n: number): string {
    if (n >= 1_000_000_000) return (n / 1_000_000_000).toFixed(1) + 'B';
    if (n >= 1_000_000) return (n / 1_000_000).toFixed(1) + 'M';
    if (n >= 1_000) return (n / 1_000).toFixed(1) + 'K';
    return n.toLocaleString();
}
function fmtDuration(sec: number): string {
    if (sec <= 60) return `${sec}s`;
    const m = Math.floor(sec / 60), s = sec % 60;
    if (m < 60) return `${m}:${String(s).padStart(2, '0')}`;
    const h = Math.floor(m / 60);
    return `${h}:${String(m % 60).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
}
function timeAgo(dateStr: string): string {
    const diff = Date.now() - new Date(dateStr).getTime();
    const days = Math.floor(diff / 86400000);
    if (days < 1) return 'Today';
    if (days === 1) return 'Yesterday';
    if (days < 30) return `${days}d ago`;
    if (days < 365) return `${Math.floor(days / 30)}mo ago`;
    return `${Math.floor(days / 365)}y ago`;
}

// ---- Stat Box ----
function StatBox({ label, value, sub, accent }: { label: string; value: string; sub?: string; accent?: string }) {
    return (
        <div className="rounded-xl p-4 text-center" style={{ background: '#1a1a24', border: '1px solid rgba(255,255,255,0.06)' }}>
            <p className="text-xs uppercase font-bold mb-1 tracking-wider" style={{ color: '#555' }}>{label}</p>
            <p className="text-2xl font-mono font-extrabold" style={{ color: accent || '#fff' }}>{value}</p>
            {sub && <p className="text-xs mt-1" style={{ color: '#666' }}>{sub}</p>}
        </div>
    );
}

// ---- Sentiment Bar ----
function SentimentBar({ score, label }: { score: number; label: string }) {
    const color = score >= 70 ? '#22c55e' : score >= 40 ? '#f97316' : '#ef4444';
    return (
        <div className="flex items-center gap-3">
            <div className="flex-1 rounded-full h-2" style={{ background: '#1e1e2c' }}>
                <div className="h-2 rounded-full transition-all" style={{ width: `${score}%`, background: color }} />
            </div>
            <span className="text-xs font-bold" style={{ color }}>{label}</span>
        </div>
    );
}

// ---- Main Page ----
export default function ChannelPage() {
    const params = useParams();
    const router = useRouter();
    const channelId = params?.id as string;

    const [channel, setChannel] = useState<ChannelData | null>(null);
    const [videos, setVideos] = useState<Video[]>([]);
    const [titleKeywords, setTitleKeywords] = useState<{ word: string; count: number }[]>([]);
    const [topTags, setTopTags] = useState<{ tag: string; count: number }[]>([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState('');
    const [videoFilter, setVideoFilter] = useState<'all' | 'shorts' | 'longs' | 'outperformer'>('all');
    const [videoSort, setVideoSort] = useState<'views' | 'eng' | 'date'>('views');
    const [activeTab, setActiveTab] = useState<'videos' | 'keywords' | 'analytics' | 'ai'>('videos');

    // AI Insights state
    const [commentAnalysis, setCommentAnalysis] = useState<CommentAnalysis | null>(null);
    const [commentLoading, setCommentLoading] = useState(false);
    const [commentError, setCommentError] = useState('');
    const [channelAI, setChannelAI] = useState<ChannelAI | null>(null);
    const [channelAILoading, setChannelAILoading] = useState(false);
    const [channelAIError, setChannelAIError] = useState('');

    useEffect(() => {
        if (!channelId) return;
        setLoading(true);
        axios.get(`/api/channel/${channelId}`)
            .then(res => {
                setChannel(res.data.channel);
                setVideos(res.data.videos);
                setTitleKeywords(res.data.titleKeywords);
                setTopTags(res.data.topTags);
            })
            .catch(err => setError(err?.response?.data?.error || 'Failed to load channel data.'))
            .finally(() => setLoading(false));
    }, [channelId]);

    const analyzeComments = async () => {
        if (!channel || !videos.length) return;
        const topVideo = [...videos].filter(v => !v.isShort).sort((a, b) => b.views - a.views)[0] || videos[0];
        setCommentLoading(true);
        setCommentError('');
        try {
            const res = await axios.post('/api/analyze/comments', {
                videoId: topVideo.id,
                channelTitle: channel.title,
                videoTitle: topVideo.title,
            });
            setCommentAnalysis(res.data);
        } catch (err: any) {
            setCommentError(err?.response?.data?.error || 'Failed to analyze comments.');
        } finally {
            setCommentLoading(false);
        }
    };

    const analyzeChannel = async () => {
        if (!channel || !videos.length) return;
        setChannelAILoading(true);
        setChannelAIError('');
        const topVideo = [...videos].sort((a, b) => b.views - a.views)[0];
        try {
            const res = await axios.post('/api/analyze/channel', {
                channel: {
                    id: channel.id,
                    title: channel.title,
                    description: channel.description,
                    totalSubs: channel.totalSubs,
                    avgViewsPerVideo: channel.avgViewsPerVideo,
                },
                videos: videos.map(v => ({
                    id: v.id, title: v.title, views: v.views, publishedAt: v.publishedAt,
                    duration: v.duration, isShort: v.isShort,
                    isOutperformer: v.isOutperformer, outperformRatio: v.outperformRatio,
                })),
                topVideo: topVideo ? { id: topVideo.id, title: topVideo.title, views: topVideo.views, publishedAt: topVideo.publishedAt, duration: topVideo.duration, isShort: topVideo.isShort } : null,
            });
            setChannelAI(res.data);
        } catch (err: any) {
            setChannelAIError(err?.response?.data?.error || 'Channel analysis failed.');
        } finally {
            setChannelAILoading(false);
        }
    };


    const displayedVideos = videos
        .filter(v => {
            if (videoFilter === 'shorts') return v.isShort;
            if (videoFilter === 'longs') return !v.isShort;
            if (videoFilter === 'outperformer') return v.isOutperformer;
            return true;
        })
        .sort((a, b) => {
            if (videoSort === 'eng') return b.engRate - a.engRate;
            if (videoSort === 'date') return new Date(b.publishedAt).getTime() - new Date(a.publishedAt).getTime();
            return b.views - a.views;
        });

    if (loading) {
        return (
            <div className="min-h-screen flex items-center justify-center" style={{ backgroundColor: '#0f0f12' }}>
                <div className="text-center">
                    <div className="w-14 h-14 rounded-full border-4 border-orange-500 border-t-transparent animate-spin mx-auto mb-4" />
                    <p style={{ color: '#666' }}>Loading channel data...</p>
                </div>
            </div>
        );
    }

    if (error || !channel) {
        return (
            <div className="min-h-screen flex items-center justify-center" style={{ backgroundColor: '#0f0f12' }}>
                <div className="text-center">
                    <p className="text-red-400 text-lg mb-4">{error || 'Channel not found.'}</p>
                    <button onClick={() => router.back()} className="text-orange-400 underline">← Go Back</button>
                </div>
            </div>
        );
    }

    return (
        <div className="min-h-screen" style={{ backgroundColor: '#0f0f12', color: '#e8e8f0' }}>
            {/* ---- Banner ---- */}
            <div className="relative h-44 w-full overflow-hidden" style={{ background: channel.banner ? undefined : 'linear-gradient(135deg,#1a0a00,#2a1000,#0f0f12)' }}>
                {channel.banner && <img src={channel.banner} alt="banner" className="w-full h-full object-cover opacity-60" />}
                <div className="absolute inset-0" style={{ background: 'linear-gradient(to bottom, transparent 40%, #0f0f12 100%)' }} />
            </div>

            <div className="max-w-6xl mx-auto px-6">
                {/* ---- Channel Header ---- */}
                <div className="flex gap-5 items-end -mt-10 mb-8 relative z-10">
                    <img src={channel.thumbnail} alt={channel.title} className="w-24 h-24 rounded-full border-4 flex-shrink-0" style={{ borderColor: '#0f0f12' }} />
                    <div className="flex-1 min-w-0 pb-2">
                        <div className="flex items-center gap-3 flex-wrap">
                            <h1 className="text-3xl font-black text-white">{channel.title}</h1>
                            {channel.country && (
                                <span className="text-sm px-2.5 py-0.5 rounded-full font-medium" style={{ background: '#1e1e2c', color: '#888' }}>{channel.country}</span>
                            )}
                            {channel.geographyTier === '1' && (
                                <span className="text-xs px-2.5 py-0.5 rounded-full font-semibold" style={{ background: 'rgba(34,197,94,0.1)', color: '#22c55e', border: '1px solid rgba(34,197,94,0.2)' }}>🟢 Tier 1</span>
                            )}
                        </div>
                        {channel.customUrl && <p className="text-sm mt-0.5" style={{ color: '#555' }}>{channel.customUrl}</p>}
                        <p className="text-sm mt-1 line-clamp-2" style={{ color: '#777' }}>{channel.description}</p>
                    </div>
                    <div className="flex gap-2 flex-shrink-0 pb-2">
                        <Link href="/" className="px-4 py-2 rounded-lg text-sm font-semibold transition-all" style={{ background: '#1e1e2c', color: '#aaa', border: '1px solid rgba(255,255,255,0.08)' }}>
                            ← Back
                        </Link>
                        <a href={`https://youtube.com/channel/${channel.id}`} target="_blank" rel="noreferrer"
                            className="px-4 py-2 rounded-lg text-sm font-bold transition-all" style={{ background: '#ef4444', color: '#fff' }}>
                            Open on YouTube ↗
                        </a>
                    </div>
                </div>

                {/* ---- Stats Strip ---- */}
                <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3 mb-8">
                    <StatBox label="Subscribers" value={fmt(channel.totalSubs)} />
                    <StatBox label="Total Views" value={fmt(channel.totalViews)} />
                    <StatBox label="Total Videos" value={channel.totalVideos.toLocaleString()} />
                    <StatBox label="Avg Views/Video" value={fmt(channel.avgViewsPerVideo)} />
                    <StatBox label="Views/Sub" value={`${channel.viewsPerSub}×`} accent={channel.viewsPerSub > 50 ? '#f97316' : undefined} sub={channel.viewsPerSub > 50 ? '🔥 Viral ratio' : undefined} />
                    <StatBox
                        label="Upload Freq."
                        value={channel.uploadFrequencyLabel || 'N/A'}
                        sub={channel.uploadFrequencyDays ? `~${channel.uploadFrequencyDays}d avg` : undefined}
                        accent={channel.uploadFrequencyDays < 4 ? '#ef4444' : channel.uploadFrequencyDays < 10 ? '#f97316' : '#22c55e'}
                    />
                </div>

                {/* ---- Tabs ---- */}
                <div className="flex gap-1 mb-6 border-b" style={{ borderColor: 'rgba(255,255,255,0.07)' }}>
                    {([
                        ['videos', '🎬 Top Videos'],
                        ['keywords', '🔑 Traffic Keywords'],
                        ['analytics', '📊 Analytics'],
                        ['ai', '🤖 AI Insights'],
                    ] as const).map(([tab, label]) => (
                        <button key={tab} onClick={() => setActiveTab(tab)}
                            className="px-5 py-3 text-sm font-semibold capitalize transition-all relative"
                            style={{ color: activeTab === tab ? '#f97316' : '#666' }}>
                            {label}
                            {activeTab === tab && <span className="absolute bottom-0 left-0 right-0 h-0.5 rounded-t" style={{ background: '#f97316' }} />}
                        </button>
                    ))}
                </div>

                {/* ====================== VIDEOS TAB ====================== */}
                {activeTab === 'videos' && (
                    <>
                        <div className="flex gap-2 mb-5 flex-wrap items-center">
                            {([['all', '📺 All'], ['outperformer', '🚀 Outperformers'], ['shorts', '⚡ Shorts'], ['longs', '🎬 Long-form']] as ['all' | 'outperformer' | 'shorts' | 'longs', string][]).map(([f, label]) => (
                                <button key={f} onClick={() => setVideoFilter(f)} className="px-3 py-1.5 rounded-lg text-xs font-semibold transition-all"
                                    style={{ background: videoFilter === f ? '#f97316' : '#1e1e2c', color: videoFilter === f ? '#fff' : '#666', border: '1px solid rgba(255,255,255,0.05)' }}>
                                    {label}
                                </button>
                            ))}
                            <div style={{ flex: 1 }} />
                            <span className="text-xs" style={{ color: '#555' }}>Sort by:</span>
                            {([['views', '👁 Views'], ['eng', '💬 Engagement'], ['date', '📅 Newest']] as ['views' | 'eng' | 'date', string][]).map(([s, label]) => (
                                <button key={s} onClick={() => setVideoSort(s)} className="px-3 py-1.5 rounded-lg text-xs font-semibold transition-all"
                                    style={{ background: videoSort === s ? '#2563eb' : '#1e1e2c', color: videoSort === s ? '#fff' : '#666', border: '1px solid rgba(255,255,255,0.05)' }}>
                                    {label}
                                </button>
                            ))}
                        </div>
                        <p className="text-xs mb-4" style={{ color: '#555' }}>
                            Showing {displayedVideos.length} videos · Avg views: <span style={{ color: '#f97316' }}>{fmt(channel.avgViewsPerVideo)}</span>
                        </p>
                        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 mb-12">
                            {displayedVideos.map(v => (
                                <a key={v.id} href={`https://youtube.com/watch?v=${v.id}`} target="_blank" rel="noreferrer"
                                    className="rounded-xl overflow-hidden flex flex-col group transition-all hover:-translate-y-0.5"
                                    style={{ background: '#16161f', border: v.isOutperformer ? '1px solid rgba(249,115,22,0.4)' : '1px solid rgba(255,255,255,0.05)', boxShadow: v.isOutperformer ? '0 0 20px rgba(249,115,22,0.06)' : 'none' }}>
                                    <div className="relative">
                                        <img src={v.thumbnail} alt={v.title} className="w-full aspect-video object-cover" />
                                        <span className="absolute bottom-2 right-2 text-xs font-bold px-1.5 py-0.5 rounded" style={{ background: 'rgba(0,0,0,0.85)', color: '#fff' }}>{fmtDuration(v.duration)}</span>
                                        {v.isShort && <span className="absolute top-2 left-2 text-xs font-bold px-2 py-0.5 rounded" style={{ background: '#7c3aed', color: '#fff' }}>SHORT</span>}
                                        {v.isOutperformer && <span className="absolute top-2 right-2 text-xs font-bold px-2 py-0.5 rounded" style={{ background: '#f97316', color: '#fff' }}>{v.outperformRatio}× avg</span>}
                                    </div>
                                    <div className="p-3 flex flex-col gap-2 flex-1">
                                        <p className="text-sm font-semibold text-white line-clamp-2 leading-snug">{v.title}</p>
                                        <p className="text-xs" style={{ color: '#666' }}>{timeAgo(v.publishedAt)}</p>
                                        <div className="flex gap-3 mt-auto pt-2 border-t" style={{ borderColor: 'rgba(255,255,255,0.05)' }}>
                                            <div className="text-center"><p className="text-xs" style={{ color: '#555' }}>Views</p><p className="text-sm font-bold font-mono text-white">{fmt(v.views)}</p></div>
                                            <div className="text-center"><p className="text-xs" style={{ color: '#555' }}>Likes</p><p className="text-sm font-bold font-mono text-white">{fmt(v.likes)}</p></div>
                                            <div className="text-center"><p className="text-xs" style={{ color: '#555' }}>Eng %</p><p className="text-sm font-bold font-mono" style={{ color: v.engRate > 5 ? '#22c55e' : v.engRate > 2 ? '#f97316' : '#888' }}>{v.engRate}%</p></div>
                                            <div className="text-center ml-auto"><p className="text-xs" style={{ color: '#555' }}>Type</p><p className="text-sm font-bold" style={{ color: v.isShort ? '#a78bfa' : '#60a5fa' }}>{v.isShort ? 'Short' : 'Long'}</p></div>
                                        </div>
                                    </div>
                                </a>
                            ))}
                        </div>
                    </>
                )}

                {/* ====================== KEYWORDS TAB ====================== */}
                {activeTab === 'keywords' && (
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-8 mb-12">
                        <div>
                            <h2 className="text-lg font-bold mb-1 text-white">📝 Title Keywords</h2>
                            <p className="text-xs mb-4" style={{ color: '#666' }}>Most frequent meaningful words in top-performing video titles — what drives traffic to this channel.</p>
                            <div className="flex flex-wrap gap-2">
                                {titleKeywords.map(k => {
                                    const intensity = Math.min(k.count / (titleKeywords[0]?.count || 1), 1);
                                    return (
                                        <span key={k.word} className="px-3 py-1.5 rounded-full text-sm font-semibold"
                                            style={{ background: `rgba(249,115,22,${0.08 + intensity * 0.3})`, color: `rgb(${253 - Math.round(intensity * 50)},${160 - Math.round(intensity * 60)},${28 + Math.round(intensity * 30)})`, border: `1px solid rgba(249,115,22,${0.15 + intensity * 0.25})`, fontSize: `${11 + intensity * 5}px` }}>
                                            {k.word} <span style={{ opacity: 0.6 }}>×{k.count}</span>
                                        </span>
                                    );
                                })}
                                {titleKeywords.length === 0 && <p style={{ color: '#555' }}>No keywords found.</p>}
                            </div>
                        </div>
                        <div>
                            <h2 className="text-lg font-bold mb-1 text-white">🏷️ Video Tags</h2>
                            <p className="text-xs mb-4" style={{ color: '#666' }}>Tags used across videos — how YouTube categorizes and recommends this content.</p>
                            <div className="flex flex-wrap gap-2">
                                {topTags.map(t => (
                                    <span key={t.tag} className="px-3 py-1.5 rounded-full text-xs font-semibold" style={{ background: '#1e1e2c', color: '#60a5fa', border: '1px solid rgba(96,165,250,0.2)' }}>
                                        {t.tag} <span style={{ opacity: 0.5 }}>×{t.count}</span>
                                    </span>
                                ))}
                                {topTags.length === 0 && <p style={{ color: '#555' }}>No public tags.</p>}
                            </div>
                            {channel.keywords && (
                                <div className="mt-6">
                                    <h3 className="text-sm font-bold mb-2 text-white">⚙️ Channel-Level SEO Keywords</h3>
                                    <div className="flex flex-wrap gap-2">
                                        {channel.keywords.replace(/^"|"$/g, '').split('"').filter(k => k.trim().length > 0).map((k, i) => (
                                            <span key={i} className="px-3 py-1 rounded-full text-xs font-medium" style={{ background: '#1a2a1a', color: '#4ade80', border: '1px solid rgba(74,222,128,0.2)' }}>{k.trim()}</span>
                                        ))}
                                    </div>
                                </div>
                            )}
                        </div>
                    </div>
                )}

                {/* ====================== ANALYTICS TAB ====================== */}
                {activeTab === 'analytics' && (
                    <div className="space-y-6 mb-12">
                        <div className="rounded-2xl p-5" style={{ background: '#16161f', border: '1px solid rgba(255,255,255,0.06)' }}>
                            <h2 className="text-lg font-bold mb-4 text-white">💰 Monetization & Revenue Estimate</h2>
                            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                                {(() => {
                                    const isMonetized = channel.totalSubs >= 1000 && channel.totalViews >= 4000 * 60;
                                    const monthlyViews = channel.avgViewsPerVideo * (channel.totalVideos > 52 ? 4 : 2);
                                    return (
                                        <>
                                            <StatBox label="Likely Monetized" value={isMonetized ? '✅ Yes' : '⏳ Maybe'} accent={isMonetized ? '#22c55e' : '#f59e0b'} />
                                            <StatBox label="Est. Monthly Views" value={fmt(monthlyViews)} sub="Based on video count" />
                                            <StatBox label="Revenue (Low)" value={`$${fmt(monthlyViews / 1000 * 1)}`} sub="At $1 RPM" accent="#22c55e" />
                                            <StatBox label="Revenue (High)" value={`$${fmt(monthlyViews / 1000 * 4)}`} sub="At $4 RPM" accent="#22c55e" />
                                        </>
                                    );
                                })()}
                            </div>
                        </div>
                        <div className="rounded-2xl p-5" style={{ background: '#16161f', border: '1px solid rgba(255,255,255,0.06)' }}>
                            <h2 className="text-lg font-bold mb-1 text-white">🚀 Outperformer Analysis</h2>
                            <p className="text-xs mb-4" style={{ color: '#666' }}>Videos with &gt;3× the channel average views — the viral hits.</p>
                            {(() => {
                                const out = videos.filter(v => v.isOutperformer).sort((a, b) => b.outperformRatio - a.outperformRatio);
                                if (!out.length) return <p style={{ color: '#555' }}>No outperforming videos detected in top 50.</p>;
                                return (
                                    <div className="space-y-3">
                                        {out.slice(0, 5).map(v => (
                                            <a key={v.id} href={`https://youtube.com/watch?v=${v.id}`} target="_blank" rel="noreferrer"
                                                className="flex gap-4 items-center rounded-xl p-3 transition-all hover:opacity-90" style={{ background: '#1e1e2c' }}>
                                                <img src={v.thumbnail} alt="" className="w-24 aspect-video object-cover rounded-lg flex-shrink-0" />
                                                <div className="flex-1 min-w-0">
                                                    <p className="text-sm font-semibold text-white line-clamp-1">{v.title}</p>
                                                    <p className="text-xs mt-0.5" style={{ color: '#666' }}>{timeAgo(v.publishedAt)} · {fmtDuration(v.duration)}</p>
                                                    <div className="flex gap-4 mt-2">
                                                        <span className="text-xs font-mono font-bold text-white">{fmt(v.views)} views</span>
                                                        <span className="text-xs font-bold" style={{ color: '#f97316' }}>{v.outperformRatio}× avg</span>
                                                        <span className="text-xs" style={{ color: v.engRate > 5 ? '#22c55e' : '#888' }}>{v.engRate}% eng</span>
                                                    </div>
                                                </div>
                                            </a>
                                        ))}
                                    </div>
                                );
                            })()}
                        </div>
                        {channel.topics.length > 0 && (
                            <div className="rounded-2xl p-5" style={{ background: '#16161f', border: '1px solid rgba(255,255,255,0.06)' }}>
                                <h2 className="text-lg font-bold mb-3 text-white">🗂️ YouTube Topic Categories</h2>
                                <div className="flex flex-wrap gap-2">
                                    {channel.topics.map((t, i) => (
                                        <span key={i} className="px-3 py-1.5 rounded-full text-xs font-medium" style={{ background: '#1e1e2c', color: '#a78bfa', border: '1px solid rgba(167,139,250,0.2)' }}>
                                            {t.replace('https://en.wikipedia.org/wiki/', '').replace(/_/g, ' ')}
                                        </span>
                                    ))}
                                </div>
                            </div>
                        )}
                    </div>
                )}

                {/* ====================== AI INSIGHTS TAB ====================== */}
                {activeTab === 'ai' && (
                    <div className="space-y-6 mb-12">
                        {/* Quick data-computed cards */}
                        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                            {/* Upload Frequency */}
                            <div className="rounded-2xl p-5" style={{ background: '#16161f', border: '1px solid rgba(255,255,255,0.06)' }}>
                                <h3 className="text-sm font-bold mb-3 text-white">📅 Upload Frequency</h3>
                                <p className="text-3xl font-black mb-2" style={{ color: channel.uploadFrequencyDays < 4 ? '#ef4444' : channel.uploadFrequencyDays < 10 ? '#f97316' : '#22c55e' }}>
                                    {channel.uploadFrequencyLabel || 'N/A'}
                                </p>
                                <p className="text-xs" style={{ color: '#666' }}>
                                    {channel.uploadFrequencyDays ? `Avg ${channel.uploadFrequencyDays} days between videos` : 'Based on top 50 videos'}
                                </p>
                                <p className="text-xs mt-2" style={{ color: '#888' }}>
                                    {channel.uploadFrequencyDays < 3
                                        ? '⚠️ High posting effort required to compete'
                                        : channel.uploadFrequencyDays < 10
                                            ? '🟡 Moderate effort — weekly cadence'
                                            : '🟢 Low posting frequency — easier to compete'}
                                </p>
                            </div>

                            {/* Geography Tier */}
                            <div className="rounded-2xl p-5" style={{ background: '#16161f', border: '1px solid rgba(255,255,255,0.06)' }}>
                                <h3 className="text-sm font-bold mb-3 text-white">🌍 Audience Geography</h3>
                                <p className="text-2xl font-black mb-2" style={{ color: channel.geographyTier === '1' ? '#22c55e' : '#eab308' }}>
                                    {channel.geographyLabel || '⚪ Unknown'}
                                </p>
                                <p className="text-xs mt-2" style={{ color: '#888' }}>
                                    {channel.geographyTier === '1'
                                        ? '💰 High RPM zone: $4–$10+ per 1K views typical'
                                        : channel.geographyTier === '2'
                                            ? '🟡 Medium RPM: $1–$4 per 1K views typical'
                                            : 'RPM data unavailable for this channel'}
                                </p>
                            </div>

                            {/* Effort-to-Reward snapshot */}
                            <div className="rounded-2xl p-5" style={{ background: '#16161f', border: '1px solid rgba(255,255,255,0.06)' }}>
                                <h3 className="text-sm font-bold mb-3 text-white">⚖️ Effort-to-Reward</h3>
                                <p className="text-2xl font-black mb-1 text-white">
                                    {channel.viewsPerSub > 100 ? '🔥 Exceptional' : channel.viewsPerSub > 30 ? '✅ Strong' : channel.viewsPerSub > 5 ? '🟡 Moderate' : '🔴 Low'}
                                </p>
                                <p className="text-xs" style={{ color: '#888' }}>
                                    {channel.viewsPerSub}× views per subscriber · {channel.uploadFrequencyLabel} upload cadence
                                </p>
                                <p className="text-xs mt-2" style={{ color: '#666' }}>
                                    {channel.viewsPerSub > 50 ? 'High viral potential relative to audience size' : 'Standard engagement ratio'}
                                </p>
                            </div>
                        </div>

                        {/* ---- Trend Persistence Score (data-computed, always shown) ---- */}
                        {videos.length >= 3 && (() => {
                            const sorted = [...videos].sort((a, b) => b.views - a.views);
                            const topViral = sorted[0];
                            const byDate = [...videos].sort((a, b) => new Date(a.publishedAt).getTime() - new Date(b.publishedAt).getTime());
                            const viralIdx = byDate.findIndex(v => v.id === topViral.id);
                            const followUps = byDate.slice(viralIdx + 1, viralIdx + 4);
                            const followUpAvg = followUps.length > 0 ? followUps.reduce((s, v) => s + v.views, 0) / followUps.length : 0;
                            const followUpRatio = channel.avgViewsPerVideo > 0 ? parseFloat((followUpAvg / channel.avgViewsPerVideo).toFixed(2)) : 0;
                            const outPct = parseFloat(((videos.filter(v => v.isOutperformer).length / videos.length) * 100).toFixed(1));
                            let label: string, color: string, rationale: string, score: number;
                            if (followUpRatio >= 2 && outPct >= 20) { label = '🔥 Durable Breakout'; color = '#22c55e'; score = 90; rationale = `Follow-up videos averaged ${followUpRatio}× the channel mean — format and audience locked in.`; }
                            else if (followUpRatio >= 1.5 || outPct >= 15) { label = '✅ Building Momentum'; color = '#86efac'; score = 70; rationale = `Follow-ups at ${followUpRatio}× average. Channel is finding its footing.`; }
                            else if (followUpRatio >= 1 || outPct >= 8) { label = '🟡 Mixed Signals'; color = '#eab308'; score = 50; rationale = `Modest follow-up performance (${followUpRatio}× avg). Could be early-stage or one-off.`; }
                            else { label = '⚡ Flash Spike'; color = '#ef4444'; score = 25; rationale = `Follow-ups dropped to ${followUpRatio}× avg. Likely algorithmic test, not a format breakthrough.`; }
                            return (
                                <div className="rounded-2xl p-5" style={{ background: '#16161f', border: '1px solid rgba(255,255,255,0.06)' }}>
                                    <h2 className="text-lg font-bold mb-1 text-white">📈 Trend Persistence Score</h2>
                                    <p className="text-xs mb-4" style={{ color: '#666' }}>Does this channel&apos;s growth sustain after a viral spike, or is it a one-hit wonder?</p>
                                    <div className="flex items-center gap-5">
                                        <div className="relative w-20 h-20 flex-shrink-0">
                                            <svg className="w-20 h-20 -rotate-90" viewBox="0 0 80 80">
                                                <circle cx="40" cy="40" r="32" fill="none" stroke="#1e1e2c" strokeWidth="8" />
                                                <circle cx="40" cy="40" r="32" fill="none" stroke={color} strokeWidth="8" strokeDasharray={`${score * 2.01} 201`} strokeLinecap="round" />
                                            </svg>
                                            <span className="absolute inset-0 flex items-center justify-center text-lg font-black" style={{ color }}>{score}</span>
                                        </div>
                                        <div>
                                            <p className="text-xl font-bold mb-1" style={{ color }}>{label}</p>
                                            <p className="text-xs" style={{ color: '#888' }}>{rationale}</p>
                                            <div className="flex gap-4 mt-2">
                                                <span className="text-xs" style={{ color: '#666' }}>Follow-up ratio: <strong style={{ color: '#e8e8f0' }}>{followUpRatio}×</strong></span>
                                                <span className="text-xs" style={{ color: '#666' }}>Outperformers: <strong style={{ color: '#e8e8f0' }}>{outPct}%</strong></span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            );
                        })()}

                        {/* ---- Risk Flags (data-computed, always shown) ---- */}
                        {(() => {
                            const titles = videos.map(v => v.title.toLowerCase());
                            const compilationPhrases = ['top 10', 'top 5', 'best of', 'compilation', 'moments', 'clips', 'highlights', '#shorts'];
                            const compCount = titles.filter(t => compilationPhrases.some(p => t.includes(p))).length;
                            const shortsPct = videos.filter(v => v.isShort).length / (videos.length || 1);
                            const totalViews = videos.reduce((s, v) => s + v.views, 0);
                            const maxViews = Math.max(...videos.map(v => v.views));
                            const flags: { type: string; severity: string; sevColor: string; detail: string }[] = [];
                            if (compCount / (titles.length || 1) > 0.35) flags.push({ type: '⚠️ Compilation / Reuse Risk', severity: 'High', sevColor: '#ef4444', detail: `${Math.round(compCount / titles.length * 100)}% of videos show compilation patterns — may face copyright claims.` });
                            if (shortsPct > 0.7 && !channel.description?.match(/original|music|produced/i)) flags.push({ type: '🎵 Music-Short Dependency', severity: 'Medium', sevColor: '#f97316', detail: `${Math.round(shortsPct * 100)}% Shorts. Trending audio reliance may limit YPP monetization.` });
                            if (totalViews > 0 && maxViews / totalViews > 0.5 && videos.length >= 5) flags.push({ type: '📌 Single-Video Concentration', severity: 'Medium', sevColor: '#f97316', detail: `One video accounts for ${Math.round(maxViews / totalViews * 100)}% of all views. High dependency risk.` });
                            if (flags.length === 0) return (
                                <div className="rounded-2xl p-4 flex items-center gap-3" style={{ background: 'rgba(34,197,94,0.05)', border: '1px solid rgba(34,197,94,0.15)' }}>
                                    <span className="text-2xl">🛡️</span>
                                    <div><p className="text-sm font-bold text-green-400">No Risk Flags Detected</p><p className="text-xs" style={{ color: '#666' }}>Content patterns look sustainable.</p></div>
                                </div>
                            );
                            return (
                                <div className="rounded-2xl p-5" style={{ background: '#16161f', border: '1px solid rgba(255,255,255,0.06)' }}>
                                    <h2 className="text-lg font-bold mb-3 text-white">🚨 Risk Flags</h2>
                                    <div className="space-y-3">
                                        {flags.map((f, i) => (
                                            <div key={i} className="rounded-xl p-3 flex gap-3 items-start" style={{ background: '#1e1e2c', border: `1px solid ${f.sevColor}30` }}>
                                                <span className="text-xs font-bold px-2 py-0.5 rounded-full flex-shrink-0 mt-0.5" style={{ background: `${f.sevColor}18`, color: f.sevColor }}>{f.severity}</span>
                                                <div><p className="text-sm font-semibold text-white">{f.type}</p><p className="text-xs mt-0.5" style={{ color: '#888' }}>{f.detail}</p></div>
                                            </div>
                                        ))}
                                    </div>
                                </div>
                            );
                        })()}

                        {/* ---- Deep AI Analysis (Packaging + Format DNA) ---- */}
                        <div className="rounded-2xl p-5" style={{ background: '#16161f', border: '1px solid rgba(255,255,255,0.06)' }}>
                            <div className="flex items-start justify-between mb-4">
                                <div>
                                    <h2 className="text-lg font-bold text-white">🎬 Packaging Analyzer + Format DNA</h2>
                                    <p className="text-xs mt-1" style={{ color: '#666' }}>Gemini analyzes the top videos to extract the viral title pattern, thumbnail strategy, hook position, and a replicable creator playbook.</p>
                                </div>
                                {!channelAI && (
                                    <button onClick={analyzeChannel} disabled={channelAILoading}
                                        className="flex-shrink-0 font-bold px-5 py-2.5 rounded-xl text-sm ml-4 disabled:opacity-50"
                                        style={{ background: 'linear-gradient(135deg, #059669, #0d9488)', color: '#fff', boxShadow: channelAILoading ? 'none' : '0 0 20px rgba(5,150,105,0.2)' }}>
                                        {channelAILoading ? '⏳ Analyzing...' : '🤖 Run Analysis'}
                                    </button>
                                )}
                            </div>

                            {channelAIError && (
                                <div className="rounded-xl p-4 mb-4" style={{ background: 'rgba(239,68,68,0.08)', border: '1px solid rgba(239,68,68,0.2)' }}>
                                    <p className="text-red-400 text-sm">{channelAIError}</p>
                                </div>
                            )}

                            {channelAILoading && (
                                <div className="py-10 text-center">
                                    <div className="w-10 h-10 rounded-full border-4 border-emerald-500 border-t-transparent animate-spin mx-auto mb-4" />
                                    <p className="text-sm" style={{ color: '#666' }}>Analyzing video patterns with Gemini...</p>
                                </div>
                            )}

                            {channelAI && !channelAILoading && !channelAI.error && (
                                <div className="space-y-6">
                                    {/* Packaging Analyzer */}
                                    {channelAI.packagingAnalyzer && (
                                        <div>
                                            <p className="text-xs font-bold uppercase tracking-wider mb-3" style={{ color: '#555' }}>📦 Packaging Analyzer</p>
                                            <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                                                <div className="rounded-xl p-4" style={{ background: '#1e1e2c' }}>
                                                    <p className="text-xs font-bold mb-1" style={{ color: '#555' }}>Title Pattern</p>
                                                    <p className="text-sm font-bold text-orange-400 mb-1">{channelAI.packagingAnalyzer.titlePatternTag}</p>
                                                    <p className="text-xs" style={{ color: '#888' }}>{channelAI.packagingAnalyzer.titlePatternExplanation}</p>
                                                </div>
                                                <div className="rounded-xl p-4" style={{ background: '#1e1e2c' }}>
                                                    <p className="text-xs font-bold mb-1" style={{ color: '#555' }}>Thumbnail Strategy</p>
                                                    <p className="text-xs text-white">{channelAI.packagingAnalyzer.thumbnailStrategy}</p>
                                                </div>
                                                <div className="rounded-xl p-4" style={{ background: '#1e1e2c' }}>
                                                    <p className="text-xs font-bold mb-1" style={{ color: '#555' }}>Hook Position + Type</p>
                                                    <p className="text-sm font-bold text-blue-400 mb-0.5">{channelAI.packagingAnalyzer.hookType}</p>
                                                    <p className="text-xs" style={{ color: '#888' }}>{channelAI.packagingAnalyzer.hookPosition}</p>
                                                </div>
                                                <div className="rounded-xl p-4" style={{ background: '#1e1e2c' }}>
                                                    <p className="text-xs font-bold mb-1" style={{ color: '#555' }}>CTA Style</p>
                                                    <p className="text-xs text-white">{channelAI.packagingAnalyzer.ctaStyle}</p>
                                                </div>
                                            </div>
                                            {/* Template */}
                                            <div className="mt-3 rounded-xl p-4" style={{ background: 'rgba(249,115,22,0.06)', border: '1px solid rgba(249,115,22,0.2)' }}>
                                                <p className="text-xs font-bold text-orange-400 mb-1">📋 Replicable Title Template</p>
                                                <p className="text-sm font-mono text-white">&ldquo;{channelAI.packagingAnalyzer.packagingTemplate}&rdquo;</p>
                                            </div>
                                        </div>
                                    )}

                                    {/* Format DNA */}
                                    {channelAI.formatDNA && (
                                        <div>
                                            <p className="text-xs font-bold uppercase tracking-wider mb-3" style={{ color: '#555' }}>🧬 Format DNA</p>
                                            <div className="grid grid-cols-2 md:grid-cols-4 gap-3 mb-3">
                                                {[
                                                    { label: 'Video Length', value: channelAI.formatDNA.videoLength },
                                                    { label: 'Pacing', value: channelAI.formatDNA.pacing },
                                                    { label: 'On-Screen Text', value: channelAI.formatDNA.onScreenText },
                                                    { label: 'Topic Angle', value: channelAI.formatDNA.topicAngle },
                                                ].map((item, i) => (
                                                    <div key={i} className="rounded-xl p-3 text-center" style={{ background: '#1e1e2c' }}>
                                                        <p className="text-xs mb-1" style={{ color: '#555' }}>{item.label}</p>
                                                        <p className="text-xs font-bold text-white">{item.value}</p>
                                                    </div>
                                                ))}
                                            </div>
                                            {channelAI.formatDNA.replicableElements?.length > 0 && (
                                                <div className="mb-3">
                                                    <p className="text-xs font-bold mb-2" style={{ color: '#555' }}>✅ Replicable Elements</p>
                                                    <div className="flex flex-wrap gap-2">
                                                        {channelAI.formatDNA.replicableElements.map((el, i) => (
                                                            <span key={i} className="text-xs px-3 py-1.5 rounded-lg" style={{ background: 'rgba(34,197,94,0.08)', color: '#4ade80', border: '1px solid rgba(34,197,94,0.15)' }}>{el}</span>
                                                        ))}
                                                    </div>
                                                </div>
                                            )}
                                            <div className="rounded-xl p-4" style={{ background: 'rgba(124,58,237,0.06)', border: '1px solid rgba(124,58,237,0.2)' }}>
                                                <p className="text-xs font-bold text-purple-400 mb-1">📖 Creator Playbook</p>
                                                <p className="text-sm text-white">{channelAI.formatDNA.creatorPlaybook}</p>
                                            </div>
                                        </div>
                                    )}

                                    <button onClick={() => { setChannelAI(null); }} className="text-xs text-emerald-400 hover:text-emerald-300 underline">↺ Reanalyze</button>
                                </div>
                            )}

                            {!channelAI && !channelAILoading && !channelAIError && (
                                <div className="py-8 text-center rounded-xl" style={{ background: '#1a1a24', border: '1px dashed rgba(255,255,255,0.06)' }}>
                                    <p className="text-3xl mb-2">🧬</p>
                                    <p className="text-sm" style={{ color: '#666' }}>Click &ldquo;Run Analysis&rdquo; to extract the packaging blueprint and format DNA from this channel&apos;s top videos.</p>
                                    <p className="text-xs mt-1" style={{ color: '#444' }}>Requires GEMINI_API_KEY in your .env file.</p>
                                </div>
                            )}
                        </div>

                        {/* Comment Analyzer */}

                        <div className="rounded-2xl p-5" style={{ background: '#16161f', border: '1px solid rgba(255,255,255,0.06)' }}>
                            <div className="flex items-start justify-between mb-4">
                                <div>
                                    <h2 className="text-lg font-bold text-white">💬 Audience Comment Analyzer</h2>
                                    <p className="text-xs mt-1" style={{ color: '#666' }}>
                                        Gemini AI analyzes the top comments from this channel&apos;s most-viewed video to extract pain points, common questions, and ready-to-use video ideas.
                                    </p>
                                </div>
                                {!commentAnalysis && (
                                    <button
                                        onClick={analyzeComments}
                                        disabled={commentLoading}
                                        className="flex-shrink-0 font-bold px-5 py-2.5 rounded-xl text-sm transition-all disabled:opacity-50 ml-4"
                                        style={{ background: 'linear-gradient(135deg, #7c3aed, #4f46e5)', color: '#fff', boxShadow: commentLoading ? 'none' : '0 0 20px rgba(124,58,237,0.25)' }}
                                    >
                                        {commentLoading ? '⏳ Analyzing...' : '🤖 Analyze Comments'}
                                    </button>
                                )}
                            </div>

                            {commentError && (
                                <div className="rounded-xl p-4 mb-4" style={{ background: 'rgba(239,68,68,0.1)', border: '1px solid rgba(239,68,68,0.2)' }}>
                                    <p className="text-red-400 text-sm">{commentError}</p>
                                </div>
                            )}

                            {commentLoading && (
                                <div className="py-12 text-center">
                                    <div className="w-10 h-10 rounded-full border-4 border-purple-500 border-t-transparent animate-spin mx-auto mb-4" />
                                    <p className="text-sm" style={{ color: '#666' }}>Fetching comments + running Gemini analysis...</p>
                                </div>
                            )}

                            {commentAnalysis && !commentLoading && (
                                <div className="space-y-5">
                                    {/* Header */}
                                    <div className="rounded-xl p-3" style={{ background: '#1e1e2c' }}>
                                        <p className="text-xs" style={{ color: '#666' }}>Analyzed top <strong className="text-white">{commentAnalysis.commentCount}</strong> comments from:</p>
                                        <p className="text-sm font-semibold text-white mt-0.5 line-clamp-1">&ldquo;{commentAnalysis.videoTitle}&rdquo;</p>
                                    </div>

                                    {/* Sentiment */}
                                    <div>
                                        <p className="text-xs font-bold uppercase tracking-wider mb-2" style={{ color: '#555' }}>Audience Sentiment</p>
                                        <SentimentBar score={commentAnalysis.sentimentScore} label={commentAnalysis.sentiment} />
                                    </div>

                                    {/* Top insight */}
                                    <div className="rounded-xl p-4" style={{ background: 'rgba(249,115,22,0.06)', border: '1px solid rgba(249,115,22,0.2)' }}>
                                        <p className="text-xs font-bold text-orange-400 mb-1">🎯 Top Insight for New Creators</p>
                                        <p className="text-sm text-white">{commentAnalysis.topInsight}</p>
                                    </div>

                                    {/* Audience Profile */}
                                    <div>
                                        <p className="text-xs font-bold uppercase tracking-wider mb-2" style={{ color: '#555' }}>👥 Audience Profile</p>
                                        <p className="text-sm" style={{ color: '#aaa' }}>{commentAnalysis.audienceProfile}</p>
                                    </div>

                                    <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
                                        {/* Pain Points */}
                                        <div>
                                            <p className="text-xs font-bold uppercase tracking-wider mb-3" style={{ color: '#555' }}>😤 Pain Points</p>
                                            <div className="space-y-2">
                                                {(commentAnalysis.painPoints || []).map((p, i) => (
                                                    <div key={i} className="flex gap-2 items-start rounded-lg px-3 py-2" style={{ background: 'rgba(239,68,68,0.06)', border: '1px solid rgba(239,68,68,0.12)' }}>
                                                        <span className="text-red-400 flex-shrink-0 mt-0.5">✗</span>
                                                        <p className="text-xs text-white">{p}</p>
                                                    </div>
                                                ))}
                                            </div>
                                        </div>

                                        {/* Common Questions */}
                                        <div>
                                            <p className="text-xs font-bold uppercase tracking-wider mb-3" style={{ color: '#555' }}>❓ Common Questions</p>
                                            <div className="space-y-2">
                                                {(commentAnalysis.commonQuestions || []).map((q, i) => (
                                                    <div key={i} className="flex gap-2 items-start rounded-lg px-3 py-2" style={{ background: 'rgba(96,165,250,0.06)', border: '1px solid rgba(96,165,250,0.12)' }}>
                                                        <span className="text-blue-400 flex-shrink-0 mt-0.5">?</span>
                                                        <p className="text-xs text-white">{q}</p>
                                                    </div>
                                                ))}
                                            </div>
                                        </div>
                                    </div>

                                    {/* Video Ideas */}
                                    <div>
                                        <p className="text-xs font-bold uppercase tracking-wider mb-3" style={{ color: '#555' }}>💡 AI-Generated Video Ideas</p>
                                        <div className="space-y-3">
                                            {(commentAnalysis.videoIdeas || []).map((idea, i) => (
                                                <div key={i} className="rounded-xl p-4" style={{ background: 'rgba(34,197,94,0.05)', border: '1px solid rgba(34,197,94,0.12)' }}>
                                                    <p className="text-sm font-bold text-green-400 mb-1">{idea.title}</p>
                                                    <p className="text-xs" style={{ color: '#888' }}>{idea.reason}</p>
                                                </div>
                                            ))}
                                        </div>
                                    </div>

                                    {/* Reanalyze button */}
                                    <button onClick={analyzeComments} className="text-xs text-purple-400 hover:text-purple-300 underline">
                                        ↺ Reanalyze
                                    </button>
                                </div>
                            )}

                            {!commentAnalysis && !commentLoading && !commentError && (
                                <div className="py-8 text-center rounded-xl" style={{ background: '#1a1a24', border: '1px dashed rgba(255,255,255,0.06)' }}>
                                    <p className="text-3xl mb-2">🧠</p>
                                    <p className="text-sm" style={{ color: '#666' }}>Click &ldquo;Analyze Comments&rdquo; to extract audience insights using Gemini AI.</p>
                                    <p className="text-xs mt-1" style={{ color: '#444' }}>Requires GEMINI_API_KEY in your .env file.</p>
                                </div>
                            )}
                        </div>
                    </div>
                )}
            </div>
        </div>
    );
}
