'use client';

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

// ---- Types ----
interface Channel {
  id: string;
  title: string;
  description: string;
  thumbnail: string;
  publishedAt: string;
  viewCount: string;
  subscriberCount: string;
  videoCount: string;
  multiplier: number;
  engagementProxy: number;
  monetization: { isMonetized: boolean; confidence: string; reason: string };
  sponsorship: { hasSponsor: boolean; signals: string[] };
  isOneHitWonder: boolean;
  velocityScore: number;
  viewCount2dAgo?: number;
  subscriberCount2dAgo?: number;
  viewCount7dAgo?: number;
  subscriberCount7dAgo?: number;
}

interface OpportunityZone {
  isOpportunity: boolean;
  demandRatio: number;
  avgViews: number;
  avgSubs: number;
  channelCount: number;
}

type ContentFilter = 'all' | 'shorts' | 'longs';
type ViralFilter = 'none' | 'viral48h' | 'viral7d' | 'onehit';
type SortMode = 'subs' | 'views' | 'multiplier' | 'growth' | 'age' | 'velocity';
type SortDir = 'desc' | 'asc';

// ---- 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 channelAge(publishedAt: string): string {
  const months = Math.floor((Date.now() - new Date(publishedAt).getTime()) / (1000 * 60 * 60 * 24 * 30));
  if (months < 1) return '< 1mo';
  if (months < 12) return `${months}mo`;
  return `${Math.floor(months / 12)}y ${months % 12}mo`;
}

function growth48h(current: number, past?: number | null): number {
  if (!past) return 0;
  return current - past;
}

// ---- Sparkline ----
function Sparkline({ data, color = '#f97316' }: { data: number[]; color?: string }) {
  if (!data || data.length < 2) return <div className="w-20 h-7 rounded" style={{ background: '#1e1e2c' }} />;
  const max = Math.max(...data), min = Math.min(...data);
  const range = max - min || 1;
  const w = 80, h = 28;
  const stepX = w / (data.length - 1);
  const points = data.map((v, i) => `${i * stepX},${h - ((v - min) / range) * h}`).join(' ');
  const last = data[data.length - 1];
  const lastY = h - ((last - min) / range) * h;
  return (
    <svg width={w} height={h} className="overflow-visible">
      <polyline points={points} fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
      <circle cx={(data.length - 1) * stepX} cy={lastY} r="3" fill={color} />
    </svg>
  );
}

// ---- Channel Card ----
function ChannelCard({
  ch,
  isWatched,
  onToggleWatch,
}: {
  ch: Channel;
  isWatched: boolean;
  onToggleWatch: (id: string, title: string, thumbnail: string, ch: Channel) => void;
}) {
  const views = parseInt(ch.viewCount, 10);
  const subs = parseInt(ch.subscriberCount, 10);
  const sub48hGrowth = growth48h(subs, ch.subscriberCount2dAgo);
  const view7dGrowth = growth48h(views, ch.viewCount7dAgo);

  const isViral = ch.multiplier >= 30;
  const isExploding = ch.multiplier >= 100;

  // Sparkline data: 7d ago → 2d ago → now
  const sparkData = [
    ch.subscriberCount7dAgo ?? subs * 0.93,
    ch.subscriberCount2dAgo ?? subs * 0.97,
    subs,
  ];
  const sparkColor = ch.velocityScore > 5 ? '#22c55e' : ch.velocityScore > 0 ? '#f97316' : '#3b82f6';

  return (
    <Link
      href={`/channel/${ch.id}`}
      className="rounded-2xl overflow-hidden flex flex-col group transition-all hover:-translate-y-1"
      style={{
        background: '#16161f',
        border: isExploding
          ? '1px solid rgba(239,68,68,0.4)'
          : isViral
            ? '1px solid rgba(249,115,22,0.3)'
            : '1px solid rgba(255,255,255,0.05)',
        boxShadow: isExploding ? '0 4px 30px rgba(239,68,68,0.1)' : isViral ? '0 4px 20px rgba(249,115,22,0.07)' : 'none',
        textDecoration: 'none',
      }}
    >
      {/* Top accent bar */}
      <div className="h-1" style={{
        background: isExploding
          ? 'linear-gradient(90deg, #ef4444, #f97316, #eab308)'
          : isViral ? 'linear-gradient(90deg, #f97316, #ea580c)' : '#222',
      }} />

      <div className="p-4 flex flex-col gap-3 flex-1">
        {/* Header row */}
        <div className="flex gap-3 items-start">
          {ch.thumbnail
            ? <img src={ch.thumbnail} alt={ch.title} className="w-11 h-11 rounded-full flex-shrink-0" style={{ border: '2px solid rgba(255,255,255,0.08)' }} />
            : <div className="w-11 h-11 rounded-full flex items-center justify-center font-bold text-lg flex-shrink-0" style={{ background: '#2a2a38' }}>{ch.title.charAt(0)}</div>
          }
          <div className="flex-1 min-w-0">
            <h3 className="font-bold text-white text-sm truncate">{ch.title}</h3>
            <p className="text-xs mt-0.5" style={{ color: '#666' }}>{channelAge(ch.publishedAt)} · {fmt(parseInt(ch.videoCount))} videos</p>
          </div>
          {/* Watchlist toggle */}
          <button
            onClick={e => { e.preventDefault(); onToggleWatch(ch.id, ch.title, ch.thumbnail, ch); }}
            title={isWatched ? 'Remove from Watchlist' : 'Add to Watchlist'}
            className="flex-shrink-0 w-7 h-7 rounded-full flex items-center justify-center transition-all text-sm"
            style={{
              background: isWatched ? 'rgba(249,115,22,0.2)' : 'rgba(255,255,255,0.05)',
              border: isWatched ? '1px solid rgba(249,115,22,0.4)' : '1px solid rgba(255,255,255,0.1)',
            }}
          >
            {isWatched ? '★' : '☆'}
          </button>
        </div>

        {/* Badge row */}
        <div className="flex flex-wrap gap-1.5">
          {isExploding && <span className="text-xs font-bold px-2 py-0.5 rounded-full" style={{ background: 'rgba(239,68,68,0.15)', color: '#ef4444' }}>🚀 VIRAL</span>}
          {ch.isOneHitWonder && <span className="text-xs font-bold px-2 py-0.5 rounded-full" style={{ background: 'rgba(234,179,8,0.15)', color: '#eab308' }}>⚡ 1-Hit</span>}
          {ch.monetization.isMonetized && <span className="text-xs font-bold px-2 py-0.5 rounded-full" style={{ background: 'rgba(34,197,94,0.12)', color: '#22c55e' }}>💰 Monetized</span>}
          {ch.sponsorship.hasSponsor && <span className="text-xs font-bold px-2 py-0.5 rounded-full" style={{ background: 'rgba(167,139,250,0.12)', color: '#a78bfa' }}>🤝 Sponsor</span>}
          {ch.velocityScore > 3 && <span className="text-xs font-bold px-2 py-0.5 rounded-full" style={{ background: 'rgba(34,197,94,0.12)', color: '#22c55e' }}>📈 {ch.velocityScore.toFixed(1)}% vel</span>}
        </div>

        {/* Description */}
        <p className="text-xs line-clamp-2 leading-relaxed" style={{ color: '#666' }}>
          {ch.description || 'No description.'}
        </p>

        {/* Stats 2×2 */}
        <div className="grid grid-cols-2 gap-2">
          <div className="rounded-lg p-2.5 text-center" style={{ background: '#1a1a24' }}>
            <p className="text-xs font-bold uppercase tracking-wider mb-0.5" style={{ color: '#444' }}>Subscribers</p>
            <p className="text-base font-mono font-extrabold text-white">{fmt(subs)}</p>
            {sub48hGrowth > 0 && <p className="text-xs text-green-400">+{fmt(sub48hGrowth)} 48h</p>}
          </div>
          <div className="rounded-lg p-2.5 text-center" style={{ background: '#1a1a24' }}>
            <p className="text-xs font-bold uppercase tracking-wider mb-0.5" style={{ color: '#444' }}>Total Views</p>
            <p className="text-base font-mono font-extrabold text-white">{fmt(views)}</p>
            {view7dGrowth > 0 && <p className="text-xs text-blue-400">+{fmt(view7dGrowth)} 7d</p>}
          </div>
        </div>

        {/* Metrics row: Multiplier + Engagement */}
        <div className="grid grid-cols-2 gap-2">
          <div className="rounded-lg p-2.5" style={{ background: '#1a1a24' }}>
            <p className="text-xs font-bold uppercase tracking-wider mb-0.5" style={{ color: '#444' }}>Virality ×</p>
            <p className="text-base font-mono font-extrabold" style={{ color: isViral ? '#f97316' : '#9ca3af' }}>{ch.multiplier}×</p>
          </div>
          <div className="rounded-lg p-2.5" style={{ background: '#1a1a24' }}>
            <p className="text-xs font-bold uppercase tracking-wider mb-0.5" style={{ color: '#444' }}>Eng. Proxy</p>
            <p className="text-base font-mono font-extrabold" style={{ color: ch.engagementProxy > 20 ? '#22c55e' : '#9ca3af' }}>{ch.engagementProxy}%</p>
          </div>
        </div>

        {/* Sparkline + Open link */}
        <div className="flex items-end justify-between pt-2 border-t" style={{ borderColor: 'rgba(255,255,255,0.05)' }}>
          <div>
            <p className="text-xs mb-1" style={{ color: '#444' }}>7d Sub Trend</p>
            <Sparkline data={sparkData} color={sparkColor} />
          </div>
          <span className="text-xs font-semibold px-3 py-1.5 rounded-lg" style={{ background: '#ef4444', color: '#fff' }}>
            Analyze →
          </span>
        </div>
      </div>
    </Link>
  );
}

// ---- Opportunity Zone Banner ----
function OpportunityBanner({ oz }: { oz: OpportunityZone }) {
  if (!oz.isOpportunity) return null;
  return (
    <div className="rounded-2xl p-4 mb-6 flex items-center gap-4"
      style={{ background: 'linear-gradient(135deg, rgba(34,197,94,0.08), rgba(16,185,129,0.05))', border: '1px solid rgba(34,197,94,0.2)' }}>
      <span className="text-3xl flex-shrink-0">🎯</span>
      <div>
        <p className="font-bold text-green-400 text-sm">Opportunity Zone Detected!</p>
        <p className="text-xs mt-0.5" style={{ color: '#888' }}>
          This niche has a <strong className="text-white">{oz.demandRatio}× demand ratio</strong> — avg views ({fmt(oz.avgViews)}) far exceed avg subs ({fmt(oz.avgSubs)}) across {oz.channelCount} channels.
        </p>
      </div>
    </div>
  );
}

// ---- Niche AI Analysis Panel ----
interface NicheAI {
  facelessScore?: number;
  facelessLabel?: string;
  facelessReasoning?: string;
  evergreen?: boolean;
  evergreenLabel?: string;
  evergreenReasoning?: string;
  uploadFrequency?: string;
  effortLevel?: string;
  effortReasoning?: string;
  titlePatterns?: string[];
  microNiches?: { name: string; description: string; opportunity: string }[];
  nicheSummary?: string;
  geography?: { tier: string; label: string; color: string; countries: string[] };
  missingVideoIdentifier?: {
    summary: string;
    makeThisFirst: { title: string; why: string; searchabilityScore: number };
    gaps: { topic: string; demand: string; competition: string; videoIdea: string; searchabilityScore: number }[];
  };
  titleThumbnailClusters?: { cluster: string; titlePattern: string; thumbnailStyle: string; performanceMultiplier: string; exampleTitle: string }[];
  replicationDifficulty?: {
    score: number; label: string;
    dimensions: { onCameraRequired: boolean; equipmentLevel: string; specializedKnowledge: string; uniqueVoiceRequired: boolean; editingComplexity: string };
    newCreatorPath: string;
  };
  uploadFrequencyCorrelation?: { optimalFrequency: string; insight: string; fastGrowthStrategy: string };
  contentGaps?: { summary: string; gaps: { topic: string; demand: string; competition: string; videoIdea: string }[] };
  seasonality?: { pattern: string; peakMonths: string[]; lowMonths: string[]; externalTriggers: string[]; recommendation: string };
  competitorNetwork?: { archetypes: { type: string; description: string; saturated: boolean }[]; collaborationLikelihood: string; audienceOverlapClusters: string[]; blueOceanArchetype: string };
  error?: string;
}

function NicheAIPanel({ ai }: { ai: NicheAI }) {
  if (ai.error) {
    return (
      <div className="rounded-2xl p-4 mb-6" style={{ background: 'rgba(239,68,68,0.08)', border: '1px solid rgba(239,68,68,0.2)' }}>
        <p className="text-red-400 text-sm">⚠️ {ai.error}</p>
      </div>
    );
  }

  const facelessColor = (ai.facelessScore || 0) >= 70 ? '#22c55e' : (ai.facelessScore || 0) >= 40 ? '#f97316' : '#ef4444';
  const opColor = (op: string) => op === 'High' ? '#22c55e' : op === 'Medium' ? '#f97316' : '#888';

  return (
    <div className="rounded-2xl p-5 mb-6 space-y-5" style={{ background: 'linear-gradient(135deg, rgba(124,58,237,0.06), rgba(79,70,229,0.04))', border: '1px solid rgba(124,58,237,0.2)' }}>
      <div className="flex items-center gap-2 mb-1">
        <span className="text-xl">🤖</span>
        <h3 className="font-bold text-white">Gemini Niche Analysis</h3>
        {ai.geography && (
          <span className="text-xs px-2 py-0.5 rounded-full font-semibold ml-auto" style={{ background: 'rgba(34,197,94,0.1)', color: ai.geography.color, border: `1px solid ${ai.geography.color}40` }}>
            {ai.geography.label}
          </span>
        )}
      </div>

      {ai.nicheSummary && (
        <p className="text-sm" style={{ color: '#aaa' }}>{ai.nicheSummary}</p>
      )}

      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        {/* Faceless Score */}
        {ai.facelessScore !== undefined && (
          <div className="rounded-xl p-4" style={{ background: '#1a1a24' }}>
            <p className="text-xs font-bold uppercase tracking-wider mb-2" style={{ color: '#555' }}>🎭 Faceless Viability</p>
            <div className="flex items-center gap-2 mb-1">
              <div className="flex-1 rounded-full h-2" style={{ background: '#0f0f12' }}>
                <div className="h-2 rounded-full" style={{ width: `${ai.facelessScore}%`, background: facelessColor }} />
              </div>
              <span className="text-sm font-bold" style={{ color: facelessColor }}>{ai.facelessScore}/100</span>
            </div>
            <p className="text-xs font-semibold" style={{ color: facelessColor }}>{ai.facelessLabel}</p>
            <p className="text-xs mt-1" style={{ color: '#666' }}>{ai.facelessReasoning}</p>
          </div>
        )}

        {/* Evergreen */}
        {ai.evergreenLabel && (
          <div className="rounded-xl p-4" style={{ background: '#1a1a24' }}>
            <p className="text-xs font-bold uppercase tracking-wider mb-2" style={{ color: '#555' }}>🌿 Content Longevity</p>
            <p className="text-lg font-bold mb-1" style={{ color: ai.evergreen ? '#22c55e' : '#eab308' }}>{ai.evergreenLabel}</p>
            <p className="text-xs" style={{ color: '#666' }}>{ai.evergreenReasoning}</p>
          </div>
        )}

        {/* Upload Effort */}
        {ai.effortLevel && (
          <div className="rounded-xl p-4" style={{ background: '#1a1a24' }}>
            <p className="text-xs font-bold uppercase tracking-wider mb-2" style={{ color: '#555' }}>⚡ Upload Effort</p>
            <p className="text-lg font-bold mb-0.5" style={{ color: ai.effortLevel === 'Very High' ? '#ef4444' : ai.effortLevel === 'High' ? '#f97316' : ai.effortLevel === 'Medium' ? '#eab308' : '#22c55e' }}>
              {ai.effortLevel}
            </p>
            <p className="text-xs" style={{ color: '#888' }}>{ai.uploadFrequency}</p>
            <p className="text-xs mt-1" style={{ color: '#666' }}>{ai.effortReasoning}</p>
          </div>
        )}
      </div>

      {/* Title Patterns */}
      {ai.titlePatterns && ai.titlePatterns.length > 0 && (
        <div>
          <p className="text-xs font-bold uppercase tracking-wider mb-2" style={{ color: '#555' }}>🎬 Viral Title Patterns</p>
          <div className="flex flex-wrap gap-2">
            {ai.titlePatterns.map((p, i) => (
              <span key={i} className="text-xs px-3 py-1.5 rounded-lg font-medium" style={{ background: '#1a1a24', color: '#e8e8f0', border: '1px solid rgba(255,255,255,0.07)' }}>
                &ldquo;{p}&rdquo;
              </span>
            ))}
          </div>
        </div>
      )}

      {/* Micro-Niches */}
      {ai.microNiches && ai.microNiches.length > 0 && (
        <div>
          <p className="text-xs font-bold uppercase tracking-wider mb-3" style={{ color: '#555' }}>🎯 Micro-Niche Clusters</p>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-2">
            {ai.microNiches.map((n, i) => (
              <div key={i} className="rounded-xl px-4 py-3" style={{ background: '#1a1a24', border: '1px solid rgba(255,255,255,0.05)' }}>
                <div className="flex items-center justify-between gap-2 mb-0.5">
                  <p className="text-sm font-bold text-white">{n.name}</p>
                  <span className="text-xs font-semibold" style={{ color: opColor(n.opportunity) }}>{n.opportunity}</span>
                </div>
                <p className="text-xs" style={{ color: '#777' }}>{n.description}</p>
              </div>
            ))}
          </div>
        </div>
      )}
      {/* Missing Video Identifier */}
      {ai.missingVideoIdentifier && (
        <div>
          <p className="text-xs font-bold uppercase tracking-wider mb-2" style={{ color: '#555' }}>🕳️ Missing Video Identifier</p>
          <p className="text-xs mb-3" style={{ color: '#888' }}>{ai.missingVideoIdentifier.summary}</p>

          {/* Make This First */}
          {ai.missingVideoIdentifier.makeThisFirst && (
            <div className="rounded-xl p-4 mb-3" style={{ background: 'linear-gradient(135deg, rgba(34,197,94,0.08), rgba(16,185,129,0.04))', border: '1px solid rgba(34,197,94,0.25)' }}>
              <div className="flex items-center gap-2 mb-2">
                <span className="text-lg">🎯</span>
                <p className="text-xs font-bold text-green-400 uppercase tracking-wider">Make This Video First</p>
                <span className="ml-auto text-xs font-bold px-2 py-0.5 rounded-full" style={{ background: 'rgba(34,197,94,0.15)', color: '#22c55e' }}>Search Score: {ai.missingVideoIdentifier.makeThisFirst.searchabilityScore}/100</span>
              </div>
              <p className="text-base font-bold text-white mb-1">&ldquo;{ai.missingVideoIdentifier.makeThisFirst.title}&rdquo;</p>
              <p className="text-xs" style={{ color: '#888' }}>{ai.missingVideoIdentifier.makeThisFirst.why}</p>
            </div>
          )}

          <div className="space-y-2">
            {ai.missingVideoIdentifier.gaps.map((g, i) => (
              <div key={i} className="rounded-xl p-3" style={{ background: '#1a1a24', border: '1px solid rgba(255,255,255,0.05)' }}>
                <div className="flex items-center gap-2 mb-1">
                  <span className="text-xs font-bold text-white">{g.topic}</span>
                  <span className="text-xs px-1.5 py-0.5 rounded" style={{ background: 'rgba(34,197,94,0.1)', color: '#22c55e' }}>Demand: {g.demand}</span>
                  <span className="text-xs px-1.5 py-0.5 rounded" style={{ background: 'rgba(96,165,250,0.1)', color: '#60a5fa' }}>Supply: {g.competition}</span>
                  {g.searchabilityScore && <span className="ml-auto text-xs" style={{ color: '#666' }}>🔍 {g.searchabilityScore}/100</span>}
                </div>
                <p className="text-xs" style={{ color: '#888' }}>💡 &ldquo;{g.videoIdea}&rdquo;</p>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Title + Thumbnail Pattern Clusters */}
      {ai.titleThumbnailClusters && ai.titleThumbnailClusters.length > 0 && (
        <div>
          <p className="text-xs font-bold uppercase tracking-wider mb-3" style={{ color: '#555' }}>🎬 Title + Thumbnail Pattern Clusters</p>
          <div className="space-y-3">
            {ai.titleThumbnailClusters.map((c, i) => (
              <div key={i} className="rounded-xl p-4" style={{ background: '#1a1a24', border: '1px solid rgba(255,255,255,0.05)' }}>
                <div className="flex items-center gap-2 mb-2">
                  <p className="text-sm font-bold text-white">{c.cluster}</p>
                  <span className="ml-auto text-xs font-bold px-2 py-0.5 rounded-full" style={{ background: 'rgba(249,115,22,0.12)', color: '#f97316', border: '1px solid rgba(249,115,22,0.2)' }}>{c.performanceMultiplier}</span>
                </div>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-2 mb-2">
                  <div className="rounded-lg p-2" style={{ background: '#0f0f12' }}>
                    <p className="text-xs font-bold mb-0.5" style={{ color: '#555' }}>Title Template</p>
                    <p className="text-xs font-mono" style={{ color: '#e8e8f0' }}>{c.titlePattern}</p>
                  </div>
                  <div className="rounded-lg p-2" style={{ background: '#0f0f12' }}>
                    <p className="text-xs font-bold mb-0.5" style={{ color: '#555' }}>Thumbnail Style</p>
                    <p className="text-xs" style={{ color: '#aaa' }}>{c.thumbnailStyle}</p>
                  </div>
                </div>
                <div className="rounded-lg p-2" style={{ background: 'rgba(124,58,237,0.06)', border: '1px solid rgba(124,58,237,0.15)' }}>
                  <p className="text-xs font-bold text-purple-400 mb-0.5">Example for this niche:</p>
                  <p className="text-xs text-white">&ldquo;{c.exampleTitle}&rdquo;</p>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Replication Difficulty Score */}
      {ai.replicationDifficulty && (
        <div>
          <p className="text-xs font-bold uppercase tracking-wider mb-3" style={{ color: '#555' }}>🔒 Replication Difficulty Score</p>
          <div className="rounded-xl p-4" style={{ background: '#1a1a24', border: '1px solid rgba(255,255,255,0.05)' }}>
            <div className="flex items-center gap-5 mb-4">
              {(() => {
                const s = ai.replicationDifficulty!.score;
                const col = s >= 75 ? '#ef4444' : s >= 50 ? '#f97316' : s >= 25 ? '#eab308' : '#22c55e';
                return (
                  <>
                    <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={col} strokeWidth="7" strokeDasharray={`${s * 1.634} 163.4`} strokeLinecap="round" />
                      </svg>
                      <span className="absolute inset-0 flex items-center justify-center text-sm font-black" style={{ color: col }}>{s}</span>
                    </div>
                    <div>
                      <p className="text-xl font-bold" style={{ color: col }}>{ai.replicationDifficulty!.label}</p>
                      <p className="text-xs" style={{ color: '#666' }}>to replicate this niche</p>
                    </div>
                  </>
                );
              })()}
            </div>
            <div className="grid grid-cols-2 md:grid-cols-3 gap-2 mb-4">
              {[
                { label: 'On Camera', value: ai.replicationDifficulty.dimensions.onCameraRequired ? '❌ Required' : '✅ Not needed', bad: ai.replicationDifficulty.dimensions.onCameraRequired },
                { label: 'Equipment', value: ai.replicationDifficulty.dimensions.equipmentLevel, bad: ai.replicationDifficulty.dimensions.equipmentLevel.includes('Professional') },
                { label: 'Knowledge', value: ai.replicationDifficulty.dimensions.specializedKnowledge, bad: ai.replicationDifficulty.dimensions.specializedKnowledge === 'Expert' },
                { label: 'Unique Voice', value: ai.replicationDifficulty.dimensions.uniqueVoiceRequired ? '❌ Required' : '✅ Not needed', bad: ai.replicationDifficulty.dimensions.uniqueVoiceRequired },
                { label: 'Editing', value: ai.replicationDifficulty.dimensions.editingComplexity, bad: ['Advanced', 'Cinematic'].includes(ai.replicationDifficulty.dimensions.editingComplexity) },
              ].map((d, i) => (
                <div key={i} className="rounded-lg p-2 text-center" style={{ background: '#0f0f12' }}>
                  <p className="text-xs mb-0.5" style={{ color: '#555' }}>{d.label}</p>
                  <p className="text-xs font-bold" style={{ color: d.bad ? '#f97316' : '#22c55e' }}>{d.value}</p>
                </div>
              ))}
            </div>
            <div className="rounded-lg p-3" style={{ background: 'rgba(34,197,94,0.05)', border: '1px solid rgba(34,197,94,0.15)' }}>
              <p className="text-xs font-bold text-green-400 mb-1">🛤️ New Creator Entry Path</p>
              <p className="text-xs text-white">{ai.replicationDifficulty.newCreatorPath}</p>
            </div>
          </div>
        </div>
      )}

      {/* Upload Frequency vs Growth Correlation */}
      {ai.uploadFrequencyCorrelation && (
        <div>
          <p className="text-xs font-bold uppercase tracking-wider mb-2" style={{ color: '#555' }}>📈 Upload Frequency vs. Growth</p>
          <div className="rounded-xl p-4" style={{ background: '#1a1a24', border: '1px solid rgba(255,255,255,0.05)' }}>
            <div className="flex items-center gap-3 mb-3">
              <span className="text-2xl">⏰</span>
              <div>
                <p className="text-sm font-bold text-white">Optimal: {ai.uploadFrequencyCorrelation.optimalFrequency}</p>
                <p className="text-xs" style={{ color: '#666' }}>Sweet spot for this niche</p>
              </div>
            </div>
            <p className="text-xs mb-2" style={{ color: '#888' }}>{ai.uploadFrequencyCorrelation.insight}</p>
            <div className="rounded-lg p-2.5" style={{ background: 'rgba(249,115,22,0.06)', border: '1px solid rgba(249,115,22,0.15)' }}>
              <p className="text-xs font-bold text-orange-400 mb-0.5">⚡ Fast-Growth Strategy</p>
              <p className="text-xs text-white">{ai.uploadFrequencyCorrelation.fastGrowthStrategy}</p>
            </div>
          </div>
        </div>
      )}

      {/* Legacy contentGaps fallback (shown only if new missingVideoIdentifier is absent) */}
      {!ai.missingVideoIdentifier && ai.contentGaps && (
        <div>
          <p className="text-xs font-bold uppercase tracking-wider mb-2" style={{ color: '#555' }}>🕳️ Content Gap Finder</p>
          <p className="text-xs mb-3" style={{ color: '#888' }}>{ai.contentGaps.summary}</p>
          <div className="space-y-2">
            {ai.contentGaps.gaps.map((g, i) => (
              <div key={i} className="rounded-xl p-3" style={{ background: '#1a1a24', border: '1px solid rgba(255,255,255,0.05)' }}>
                <div className="flex items-center gap-2 mb-1">
                  <span className="text-xs font-bold text-white">{g.topic}</span>
                  <span className="text-xs px-1.5 py-0.5 rounded" style={{ background: 'rgba(34,197,94,0.1)', color: '#22c55e' }}>Demand: {g.demand}</span>
                  <span className="text-xs px-1.5 py-0.5 rounded" style={{ background: 'rgba(96,165,250,0.1)', color: '#60a5fa' }}>Supply: {g.competition}</span>
                </div>
                <p className="text-xs" style={{ color: '#888' }}>💡 &ldquo;{g.videoIdea}&rdquo;</p>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Seasonality */}
      {ai.seasonality && (
        <div>
          <p className="text-xs font-bold uppercase tracking-wider mb-2" style={{ color: '#555' }}>📅 Seasonality + Event Correlation</p>
          <div className="rounded-xl p-4" style={{ background: '#1a1a24', border: '1px solid rgba(255,255,255,0.05)' }}>
            <div className="flex items-start gap-4 flex-wrap mb-3">
              <div className="flex-1">
                <p className="text-sm font-bold text-white mb-0.5">{ai.seasonality.pattern}</p>
                <p className="text-xs" style={{ color: '#888' }}>{ai.seasonality.recommendation}</p>
              </div>
            </div>
            <div className="flex flex-wrap gap-3 text-xs">
              {ai.seasonality.peakMonths.length > 0 && (
                <div><p className="font-bold mb-1" style={{ color: '#22c55e' }}>📈 Peak</p>{ai.seasonality.peakMonths.map((m, i) => <span key={i} className="inline-block mr-1 px-2 py-0.5 rounded-full" style={{ background: 'rgba(34,197,94,0.1)', color: '#22c55e' }}>{m}</span>)}</div>
              )}
              {ai.seasonality.lowMonths.length > 0 && (
                <div><p className="font-bold mb-1" style={{ color: '#888' }}>📉 Low</p>{ai.seasonality.lowMonths.map((m, i) => <span key={i} className="inline-block mr-1 px-2 py-0.5 rounded-full" style={{ background: '#1e1e2c', color: '#666' }}>{m}</span>)}</div>
              )}
              {ai.seasonality.externalTriggers.length > 0 && (
                <div><p className="font-bold mb-1" style={{ color: '#f97316' }}>⚡ Triggers</p>{ai.seasonality.externalTriggers.map((t, i) => <span key={i} className="inline-block mr-1 px-2 py-0.5 rounded-full" style={{ background: 'rgba(249,115,22,0.1)', color: '#f97316' }}>{t}</span>)}</div>
              )}
            </div>
          </div>
        </div>
      )}

      {/* Competitor Network */}
      {ai.competitorNetwork && (
        <div>
          <p className="text-xs font-bold uppercase tracking-wider mb-2" style={{ color: '#555' }}>🗺️ Competitor Network Map</p>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
            <div className="rounded-xl p-4" style={{ background: '#1a1a24' }}>
              <p className="text-xs font-bold mb-2" style={{ color: '#555' }}>Channel Archetypes</p>
              <div className="space-y-2">
                {ai.competitorNetwork.archetypes.map((a, i) => (
                  <div key={i} className="flex items-center gap-2">
                    <p className="text-xs font-bold text-white flex-1">{a.type}</p>
                    <span className="text-xs px-1.5 py-0.5 rounded" style={{ background: a.saturated ? 'rgba(239,68,68,0.1)' : 'rgba(34,197,94,0.1)', color: a.saturated ? '#ef4444' : '#22c55e' }}>{a.saturated ? 'Saturated' : 'Open'}</span>
                  </div>
                ))}
              </div>
            </div>
            <div className="rounded-xl p-4" style={{ background: '#1a1a24' }}>
              <p className="text-xs font-bold mb-2" style={{ color: '#555' }}>Audience Watches Also</p>
              <div className="flex flex-wrap gap-1.5">
                {ai.competitorNetwork.audienceOverlapClusters.map((c, i) => (
                  <span key={i} className="text-xs px-2 py-0.5 rounded-full" style={{ background: '#1e1e2c', color: '#a78bfa', border: '1px solid rgba(167,139,250,0.2)' }}>{c}</span>
                ))}
              </div>
            </div>
          </div>
          <div className="mt-2 rounded-xl p-3" style={{ background: 'rgba(79,70,229,0.06)', border: '1px solid rgba(79,70,229,0.2)' }}>
            <p className="text-xs font-bold text-indigo-400 mb-0.5">🌊 Blue Ocean Opportunity</p>
            <p className="text-xs text-white">{ai.competitorNetwork.blueOceanArchetype}</p>
          </div>
        </div>
      )}
    </div>
  );
}

// ---- Watchlist Panel ----
interface WatchedChannel { id: string; title: string; thumbnail: string; addedAt: string }
function WatchlistPanel({ watchlist, onRemove }: { watchlist: WatchedChannel[]; onRemove: (id: string) => void }) {
  const [insights, setInsights] = useState<any>(null);
  const [loadingInsights, setLoadingInsights] = useState(false);

  useEffect(() => {
    if (watchlist.length === 0) return;
    setLoadingInsights(true);
    axios.get('/api/watchlist/insights')
      .then(r => setInsights(r.data))
      .catch(() => { })
      .finally(() => setLoadingInsights(false));
  }, [watchlist.length]);

  if (watchlist.length === 0) {
    return (
      <div className="py-10 text-center" style={{ color: '#555' }}>
        <p className="text-3xl mb-2">📋</p>
        <p className="text-sm">No channels saved yet. Click ☆ on any channel card.</p>
      </div>
    );
  }
  return (
    <div className="space-y-6">
      {/* Insights panel */}
      {(loadingInsights || insights) && (
        <div className="rounded-2xl p-4" style={{ background: 'linear-gradient(135deg, rgba(249,115,22,0.07), rgba(234,179,8,0.04))', border: '1px solid rgba(249,115,22,0.15)' }}>
          <p className="text-xs font-bold uppercase tracking-wider mb-3" style={{ color: '#555' }}>⚡ Weekly Growth Leaders (7-day)</p>
          {loadingInsights && <p className="text-xs" style={{ color: '#555' }}>Calculating growth...</p>}
          {insights?.topViewGrowth?.length > 0 ? (
            <div className="space-y-2">
              {insights.topViewGrowth.slice(0, 5).map((ch: any, i: number) => (
                <Link key={i} href={`/channel/${ch.id}`} className="flex items-center gap-3 rounded-xl px-3 py-2 hover:bg-white/5 transition-colors" style={{ textDecoration: 'none' }}>
                  {ch.thumbnailUrl && <img src={ch.thumbnailUrl} className="w-8 h-8 rounded-full flex-shrink-0" alt="" />}
                  <div className="flex-1 min-w-0">
                    <p className="text-sm font-semibold text-white truncate">{ch.title}</p>
                    <p className="text-xs" style={{ color: '#666' }}>+{fmt(ch.view_gain)} views this week</p>
                  </div>
                  <span className="text-xs font-black px-2 py-0.5 rounded-full flex-shrink-0"
                    style={{ background: 'rgba(249,115,22,0.15)', color: '#f97316' }}>
                    +{ch.view_growth_pct}%
                  </span>
                </Link>
              ))}
            </div>
          ) : !loadingInsights && (
            <p className="text-xs" style={{ color: '#666' }}>No growth data yet — channels need 7+ days of tracking history.</p>
          )}
        </div>
      )}

      {/* Channel list */}
      <div className="space-y-2">
        <p className="text-xs font-bold uppercase tracking-wider mb-2" style={{ color: '#555' }}>All Saved Channels</p>
        {watchlist.map(ch => (
          <div key={ch.id} className="flex items-center gap-3 rounded-xl px-4 py-3" style={{ background: '#1a1a24', border: '1px solid rgba(255,255,255,0.05)' }}>
            <img src={ch.thumbnail} alt={ch.title} className="w-9 h-9 rounded-full" />
            <div className="flex-1 min-w-0">
              <Link href={`/channel/${ch.id}`} className="text-sm font-semibold text-white hover:text-orange-400 transition-colors truncate block">{ch.title}</Link>
              <p className="text-xs" style={{ color: '#555' }}>Added {new Date(ch.addedAt).toLocaleDateString()}</p>
            </div>
            <button onClick={() => onRemove(ch.id)} className="text-xs px-2 py-1 rounded" style={{ background: 'rgba(239,68,68,0.1)', color: '#f87171' }}>Remove</button>
          </div>
        ))}
      </div>
    </div>
  );
}

// ---- Watchlist Legend ----
function FeatureLegend() {
  return (
    <div className="flex flex-wrap gap-3 text-xs mb-6 px-1">
      <span className="flex items-center gap-1.5" style={{ color: '#666' }}><span style={{ color: '#ef4444' }}>🚀</span> Views &gt; 100× Subs</span>
      <span className="flex items-center gap-1.5" style={{ color: '#666' }}><span style={{ color: '#eab308' }}>⚡</span> 1-Hit Wonder channel</span>
      <span className="flex items-center gap-1.5" style={{ color: '#666' }}><span style={{ color: '#22c55e' }}>💰</span> Likely monetized (YPP)</span>
      <span className="flex items-center gap-1.5" style={{ color: '#666' }}><span style={{ color: '#a78bfa' }}>🤝</span> Sponsor/affiliate links found</span>
      <span className="flex items-center gap-1.5" style={{ color: '#666' }}><span style={{ color: '#22c55e' }}>📈</span> Growing (velocity %)</span>
      <span className="flex items-center gap-1.5" style={{ color: '#666' }}>☆ = Add to Watchlist</span>
    </div>
  );
}

// ---- Main Page ----
export default function Home() {
  const [query, setQuery] = useState('');
  const [channels, setChannels] = useState<Channel[]>([]);
  const [opportunityZone, setOpportunityZone] = useState<OpportunityZone | null>(null);
  const [loading, setLoading] = useState(false);
  const [minSubs, setMinSubs] = useState('');
  const [maxAge, setMaxAge] = useState('');
  const [contentFilter, setContentFilter] = useState<ContentFilter>('all');
  const [viralFilter, setViralFilter] = useState<ViralFilter>('none');
  const [sortMode, setSortMode] = useState<SortMode>('views');
  const [sortDir, setSortDir] = useState<SortDir>('desc');
  const [searched, setSearched] = useState(false);
  const [activeView, setActiveView] = useState<'results' | 'watchlist'>('results');
  const [watchlist, setWatchlist] = useState<WatchedChannel[]>([]);
  const [watchlistLoading, setWatchlistLoading] = useState(false);
  const [nicheAI, setNicheAI] = useState<NicheAI | null>(null);
  const [nicheAILoading, setNicheAILoading] = useState(false);
  const [showNicheAI, setShowNicheAI] = useState(false);
  const [nicheBookmarked, setNicheBookmarked] = useState(false);


  // Load watchlist from MySQL on mount
  useEffect(() => {
    axios.get('/api/watchlist')
      .then(res => setWatchlist(res.data.watchlist || []))
      .catch(() => { }); // silently fail if DB not configured yet
  }, []);

  const toggleWatch = useCallback((id: string, title: string, thumbnail: string, ch?: Channel) => {
    const exists = watchlist.find(c => c.id === id);
    if (exists) {
      // Remove
      axios.delete(`/api/watchlist?id=${id}`)
        .then(() => setWatchlist(prev => prev.filter(c => c.id !== id)))
        .catch(err => alert('Failed to remove from watchlist'));
    } else {
      // Add — pass full channel data so it gets persisted
      const payload = {
        id,
        title,
        thumbnail,
        description: ch?.description || '',
        publishedAt: ch?.publishedAt || new Date().toISOString(),
        viewCount: ch?.viewCount || '0',
        subscriberCount: ch?.subscriberCount || '0',
        videoCount: ch?.videoCount || '0',
      };
      axios.post('/api/watchlist', payload)
        .then(() => setWatchlist(prev => [...prev, { id, title, thumbnail, addedAt: new Date().toISOString() }]))
        .catch(err => alert('Failed to add to watchlist. Make sure DB is configured.'));
    }
  }, [watchlist]);

  const removeFromWatchlist = useCallback((id: string) => {
    axios.delete(`/api/watchlist?id=${id}`)
      .then(() => setWatchlist(prev => prev.filter(c => c.id !== id)))
      .catch(() => { });
  }, []);

  const searchNiches = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!query.trim()) return;
    setLoading(true);
    setSearched(true);
    setActiveView('results');
    setNicheAI(null);
    setShowNicheAI(false);
    try {
      const res = await axios.get(`/api/search?q=${encodeURIComponent(query)}`);
      setChannels(res.data.channels || []);
      setOpportunityZone(res.data.opportunityZone || null);
    } catch {
      alert('Search failed. Check your YouTube API key in .env');
    } finally {
      setLoading(false);
    }
  };

  const handleSortClick = (mode: SortMode) => {
    if (sortMode === mode) setSortDir(d => d === 'desc' ? 'asc' : 'desc');
    else { setSortMode(mode); setSortDir('desc'); }
  };

  // Filter + sort
  const filtered = channels
    .filter(ch => {
      const subs = parseInt(ch.subscriberCount || '0', 10);
      const views = parseInt(ch.viewCount || '0', 10);
      if (minSubs && subs < parseInt(minSubs, 10)) return false;
      if (maxAge) {
        const months = Math.floor((Date.now() - new Date(ch.publishedAt).getTime()) / (1000 * 60 * 60 * 24 * 30));
        if (months > parseInt(maxAge, 10)) return false;
      }
      if (viralFilter === 'viral48h') {
        const subGrowth = growth48h(subs, ch.subscriberCount2dAgo);
        if (subGrowth < 100) return false;
      }
      if (viralFilter === 'viral7d') {
        const viewGrowth = growth48h(views, ch.viewCount7dAgo);
        if (viewGrowth < 10000) return false;
      }
      if (viralFilter === 'onehit') {
        if (!ch.isOneHitWonder) return false;
      }
      if (contentFilter === 'shorts') {
        const videoCount = parseInt(ch.videoCount || '0', 10);
        if (videoCount < 20) return false;
      }
      return true;
    })
    .sort((a, b) => {
      const aV = parseInt(a.viewCount, 10), bV = parseInt(b.viewCount, 10);
      const aS = parseInt(a.subscriberCount, 10), bS = parseInt(b.subscriberCount, 10);
      const dir = sortDir === 'desc' ? 1 : -1;
      if (sortMode === 'views') return dir * (bV - aV);
      if (sortMode === 'multiplier') return dir * (b.multiplier - a.multiplier);
      if (sortMode === 'velocity') return dir * (b.velocityScore - a.velocityScore);
      if (sortMode === 'growth') {
        const bG = growth48h(bS, b.subscriberCount2dAgo);
        const aG = growth48h(aS, a.subscriberCount2dAgo);
        return dir * (bG - aG);
      }
      if (sortMode === 'age') {
        return dir * (new Date(b.publishedAt).getTime() - new Date(a.publishedAt).getTime());
      }
      return dir * (bS - aS);
    });

  const watchedIds = new Set(watchlist.map(w => w.id));

  return (
    <div className="min-h-screen" style={{ backgroundColor: '#0f0f12', color: '#e8e8f0' }}>
      {/* ---- Header ---- */}
      <header className="relative overflow-hidden border-b border-white/5 mb-8">
        <div className="absolute inset-0 opacity-20" style={{ background: 'radial-gradient(ellipse 80% 50% at 50% -20%, rgba(239,68,68,0.5), transparent)' }} />
        {/* Top-right Discover link */}
        <div className="absolute right-6 top-4 z-10">
          <a href="/discover" className="inline-flex items-center gap-1.5 text-xs font-bold px-3 py-1.5 rounded-full transition-all hover:scale-105"
            style={{ background: 'rgba(124,58,237,0.15)', color: '#a78bfa', border: '1px solid rgba(124,58,237,0.25)' }}>
            🔭 Discover Mode
          </a>
        </div>
        <div className="relative max-w-6xl mx-auto px-6 py-10 text-center">
          <div className="inline-flex items-center gap-2 bg-red-500/10 border border-red-500/20 text-red-400 px-3 py-1 rounded-full text-xs font-medium mb-4">
            <span className="w-1.5 h-1.5 rounded-full bg-red-500 animate-pulse inline-block" />
            Live Channel Intelligence
          </div>
          <h1 className="text-5xl md:text-6xl font-black tracking-tight mb-3"
            style={{ background: 'linear-gradient(135deg, #fff 30%, #f97316)', WebkitBackgroundClip: 'text', WebkitTextFillColor: 'transparent' }}>
            Niche Finder Pro

          </h1>
          <p style={{ color: '#666' }} className="text-base max-w-md mx-auto">
            Discover exploding niches, hidden gem channels, and viral trends — before everyone else.
          </p>
        </div>
      </header>

      <main className="max-w-6xl mx-auto px-6 pb-20">
        {/* ---- Search ---- */}
        <form onSubmit={searchNiches} className="flex gap-3 mb-6 max-w-3xl mx-auto">
          <div className="flex-1 relative">
            <span className="absolute left-4 top-1/2 -translate-y-1/2 text-white/30">🔍</span>
            <input
              type="text" value={query} onChange={e => setQuery(e.target.value)}
              placeholder="Search a niche keyword (e.g. 'ASMR cooking', 'AI art')"
              className="w-full rounded-xl py-4 pl-12 pr-5 outline-none transition-all text-sm"
              style={{ background: '#1a1a24', border: '1px solid rgba(255,255,255,0.08)', color: '#e8e8f0' }}
              onFocus={e => (e.currentTarget.style.borderColor = '#f97316')}
              onBlur={e => (e.currentTarget.style.borderColor = 'rgba(255,255,255,0.08)')}
            />
          </div>
          <button type="submit" disabled={loading}
            className="font-bold px-8 py-4 rounded-xl text-white text-sm transition-all disabled:opacity-50"
            style={{ background: 'linear-gradient(135deg, #ef4444, #f97316)', boxShadow: loading ? 'none' : '0 0 20px rgba(249,115,22,0.25)' }}>
            {loading ? '⏳ Scanning...' : 'Discover →'}
          </button>
        </form>

        {/* ---- View Tabs ---- */}
        <div className="flex gap-1 mb-6 border-b" style={{ borderColor: 'rgba(255,255,255,0.06)' }}>
          <button onClick={() => setActiveView('results')}
            className="px-5 py-2.5 text-sm font-semibold relative"
            style={{ color: activeView === 'results' ? '#f97316' : '#555' }}>
            🔎 Search Results {searched && !loading && <span className="ml-1.5 text-xs px-1.5 py-0.5 rounded-full" style={{ background: '#f97316', color: '#fff' }}>{filtered.length}</span>}
            {activeView === 'results' && <span className="absolute bottom-0 left-0 right-0 h-0.5 rounded-t" style={{ background: '#f97316' }} />}
          </button>
          <button onClick={() => setActiveView('watchlist')}
            className="px-5 py-2.5 text-sm font-semibold relative"
            style={{ color: activeView === 'watchlist' ? '#f97316' : '#555' }}>
            ★ Watchlist {watchlist.length > 0 && <span className="ml-1.5 text-xs px-1.5 py-0.5 rounded-full" style={{ background: '#1e1e2c', color: '#f97316' }}>{watchlist.length}</span>}
            {activeView === 'watchlist' && <span className="absolute bottom-0 left-0 right-0 h-0.5 rounded-t" style={{ background: '#f97316' }} />}
          </button>
        </div>

        {/* ====== WATCHLIST VIEW ====== */}
        {activeView === 'watchlist' && (
          <WatchlistPanel watchlist={watchlist} onRemove={removeFromWatchlist} />
        )}

        {/* ====== SEARCH RESULTS VIEW ====== */}
        {activeView === 'results' && (
          <>
            {/* ---- Filter Bar ---- */}
            <div className="flex flex-wrap gap-3 mb-6 rounded-2xl p-4 items-center" style={{ background: '#13131a', border: '1px solid rgba(255,255,255,0.04)' }}>
              {/* Content type */}
              <div className="flex gap-1.5">
                {(['all', 'shorts', 'longs'] as ContentFilter[]).map(f => (
                  <button key={f} onClick={() => setContentFilter(f)} className="px-3 py-1.5 rounded-lg text-xs font-semibold transition-all"
                    style={{ background: contentFilter === f ? '#f97316' : '#1e1e2c', color: contentFilter === f ? '#fff' : '#666', border: '1px solid rgba(255,255,255,0.05)' }}>
                    {f === 'all' ? '📺 All' : f === 'shorts' ? '⚡ Shorts' : '🎬 Longs'}
                  </button>
                ))}
              </div>
              <div style={{ width: 1, height: 28, background: 'rgba(255,255,255,0.08)' }} />
              {/* Viral/special filters */}
              <div className="flex gap-1.5">
                {([
                  ['none', '🔎 All'],
                  ['viral48h', '⚡ Viral 48h'],
                  ['viral7d', '📅 Viral 7d'],
                  ['onehit', '🌟 1-Hit Wonder'],
                ] as [ViralFilter, string][]).map(([f, label]) => (
                  <button key={f} onClick={() => setViralFilter(f)} className="px-3 py-1.5 rounded-lg text-xs font-semibold transition-all"
                    style={{ background: viralFilter === f ? '#7c3aed' : '#1e1e2c', color: viralFilter === f ? '#fff' : '#666', border: '1px solid rgba(255,255,255,0.05)' }}>
                    {label}
                  </button>
                ))}
              </div>
              <div style={{ width: 1, height: 28, background: 'rgba(255,255,255,0.08)' }} />
              {/* Sort */}
              <div className="flex gap-1.5 items-center flex-wrap">
                <span className="text-xs" style={{ color: '#555' }}>Sort:</span>
                {([
                  ['subs', '👥 Subs'],
                  ['views', '👁 Views'],
                  ['multiplier', '⚡ Mult.'],
                  ['velocity', '📈 Velocity'],
                  ['growth', '🌱 48h Growth'],
                  ['age', '📅 Age'],
                ] as [SortMode, string][]).map(([s, label]) => {
                  const isActive = sortMode === s;
                  return (
                    <button key={s} onClick={() => handleSortClick(s)} className="px-2.5 py-1.5 rounded-lg text-xs font-semibold transition-all"
                      style={{ background: isActive ? '#2563eb' : '#1e1e2c', color: isActive ? '#fff' : '#666', border: isActive ? '1px solid #3b82f6' : '1px solid rgba(255,255,255,0.05)' }}>
                      {label}{isActive ? (sortDir === 'desc' ? ' ↓' : ' ↑') : ''}
                    </button>
                  );
                })}
              </div>
              <div style={{ width: 1, height: 28, background: 'rgba(255,255,255,0.08)' }} />
              {/* Numeric filters */}
              <div className="flex gap-2">
                <input type="number" value={minSubs} onChange={e => setMinSubs(e.target.value)} placeholder="Min Subs"
                  className="w-24 rounded-lg py-1.5 px-3 text-xs outline-none" style={{ background: '#1e1e2c', border: '1px solid rgba(255,255,255,0.05)', color: '#e8e8f0' }} />
                <input type="number" value={maxAge} onChange={e => setMaxAge(e.target.value)} placeholder="Max Age (mo)"
                  className="w-28 rounded-lg py-1.5 px-3 text-xs outline-none" style={{ background: '#1e1e2c', border: '1px solid rgba(255,255,255,0.05)', color: '#e8e8f0' }} />
              </div>
            </div>

            {/* ---- Opportunity Zone Banner ---- */}
            {opportunityZone && <OpportunityBanner oz={opportunityZone} />}

            {/* ---- AI Analyze + Save Niche Buttons ---- */}
            {searched && channels.length > 0 && !loading && (
              <div className="mb-4 flex gap-3 items-start flex-wrap">
                <div className="flex-1">
                  {!showNicheAI ? (
                    <button
                      onClick={async () => {
                        setShowNicheAI(true);
                        setNicheAILoading(true);
                        try {
                          const res = await axios.post('/api/analyze/niche', {
                            keyword: query,
                            channels: channels.slice(0, 15).map(c => ({
                              id: c.id,
                              title: c.title,
                              description: c.description,
                              country: '',
                              viewCount: c.viewCount,
                              subscriberCount: c.subscriberCount,
                            })),
                          });
                          setNicheAI(res.data);
                        } catch (err: any) {
                          setNicheAI({ error: err?.response?.data?.error || 'AI analysis failed. Check your GEMINI_API_KEY.' });
                        } finally {
                          setNicheAILoading(false);
                        }
                      }}
                      className="font-bold px-6 py-2.5 rounded-xl text-sm transition-all"
                      style={{ background: 'linear-gradient(135deg, #7c3aed, #4f46e5)', color: '#fff', boxShadow: '0 0 20px rgba(124,58,237,0.2)' }}
                    >
                      🤖 Analyze “{query}” Niche with AI
                    </button>
                  ) : nicheAILoading ? (
                    <div className="rounded-2xl p-6 mb-2 flex items-center gap-4" style={{ background: 'rgba(124,58,237,0.06)', border: '1px solid rgba(124,58,237,0.2)' }}>
                      <div className="w-8 h-8 rounded-full border-4 border-purple-500 border-t-transparent animate-spin flex-shrink-0" />
                      <p className="text-sm" style={{ color: '#888' }}>Running Gemini analysis on {query}...</p>
                    </div>
                  ) : nicheAI ? (
                    <NicheAIPanel ai={nicheAI} />
                  ) : null}
                </div>
                {/* 📌 Save Niche button */}
                <button
                  onClick={async () => {
                    if (nicheBookmarked) {
                      await axios.delete(`/api/niches/saved?keyword=${encodeURIComponent(query)}`).catch(() => { });
                      setNicheBookmarked(false);
                    } else {
                      await axios.post('/api/niches/saved', { keyword: query }).catch(() => { });
                      setNicheBookmarked(true);
                    }
                  }}
                  className="font-bold px-5 py-2.5 rounded-xl text-sm transition-all flex-shrink-0"
                  style={{
                    background: nicheBookmarked ? 'rgba(124,58,237,0.2)' : '#1a1a24',
                    color: nicheBookmarked ? '#a78bfa' : '#666',
                    border: `1px solid ${nicheBookmarked ? 'rgba(124,58,237,0.4)' : 'rgba(255,255,255,0.07)'}`,
                  }}
                >
                  {nicheBookmarked ? '📌 Niche Saved!' : '📌 Save Niche'}
                </button>
              </div>
            )}

            {/* ---- Feature Legend ---- */}
            {searched && channels.length > 0 && <FeatureLegend />}

            {/* ---- Results count ---- */}
            {searched && !loading && channels.length > 0 && (
              <p className="text-xs mb-4" style={{ color: '#555' }}>
                Showing <span style={{ color: '#f97316', fontWeight: 700 }}>{filtered.length}</span> of {channels.length} channels for &ldquo;{query}&rdquo;
              </p>
            )}

            {/* ---- Channel Grid ---- */}
            {loading ? (
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5">
                {[...Array(6)].map((_, i) => <div key={i} className="rounded-2xl animate-pulse h-80" style={{ background: '#16161f' }} />)}
              </div>
            ) : filtered.length > 0 ? (
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5">
                {filtered.map(ch => (
                  <ChannelCard key={ch.id} ch={ch} isWatched={watchedIds.has(ch.id)} onToggleWatch={toggleWatch} />
                ))}
              </div>
            ) : (
              searched ? (
                <div className="py-20 text-center rounded-2xl" style={{ background: '#16161f', border: '1px dashed rgba(255,255,255,0.07)' }}>
                  <span className="text-4xl mb-3 block">🔮</span>
                  <p style={{ color: '#555' }}>No channels match your current filters.</p>
                </div>
              ) : (
                <div className="py-20 text-center rounded-2xl" style={{ background: '#16161f', border: '1px dashed rgba(255,255,255,0.07)' }}>
                  <span className="text-4xl mb-3 block">🎯</span>
                  <p className="text-base" style={{ color: '#555' }}>Enter a niche keyword above to start discovering channels.</p>
                  <p className="text-xs mt-2" style={{ color: '#444' }}>Try: "study with me", "AI tools", "dark academia"</p>
                </div>
              )
            )}
          </>
        )}
      </main>
    </div>
  );
}
