import { useEffect, useState, useMemo, useRef } from 'react';
import { useOptionsFlow } from '@/hooks/useOptionsFlow';
import { useStockPrices } from '@/hooks/useStockPrices';
import { DataTable } from '@/components/ui/data-table';
import { Badge } from '@/components/ui/Badge';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { BadgeCell } from '@/components/tables/BadgeCell';
import { SymbolTooltip } from '@/components/tables/SymbolTooltip';
import { ExpandedRowDetails } from '@/components/tables/ExpandedRowDetails';
import { ScoreBreakdownTooltip } from '@/components/tables/ScoreBreakdownTooltip';
import { TradeAnalysisModal } from '@/components/tables/TradeAnalysisModal';
import { TradePlanModal } from './TradePlanModal';
import { OptionsFlowCardList } from './OptionsFlowCardList';
import NoiseWarningModal from '@/components/modals/NoiseWarningModal';
import { OptionsFlowDetailPanel } from './OptionsFlowDetailPanel';
import { cn } from '@/utils/cn';
import { getApiUrl } from '@/config/api';

// Column visibility configuration
const COLUMN_GROUPS = {
  core: ['Symbol', 'badges', 'signalQuality', 'reversal', 'convergence', 'Rocket', 'Momentum', 'TradeSignal', 'TradePlan', 'NetPremium', 'Premium', 'SignalTier', 'Checklist'],
  institutional: ['confidence_score', 'signal_strength', 'relative_premium_score'], // Phase 2: Institutional Analytics columns
  option: ['CallPut', 'Strike', 'Spot', 'Moneyness', 'ExpirationDate'],
  volume: ['Volume', 'OI', 'Price', 'Side'],
  price: ['PctVsPriorClose', 'PctVsRthOpen', 'Pct5m', 'Pct15m', 'PriceReaction5m', 'VWAPDistance'],
  context: ['TapeAlign', 'NearAlert', 'CreatedDate', 'CreatedTime', 'LastFlow', 'FlowTrend']
};

const DEFAULT_VISIBLE_COLUMNS = [
  'Rank', 'Symbol', 'badges', 'signalQuality', 'reversal', 'convergence', 'Rocket', 'Momentum', 'TradeSignal', 'TradePlan', 'SignalTier', 'Checklist', 'NetPremium', 'FlowTrend', 
  'Premium', 'CallPut', 'Strike', 'TapeAlign', 'LastFlow', 'PctVsRthOpen', 'PriceReaction5m', 'CreatedTime'
];

export default function OptionsFlowPanel() {
  const initialFilters = {
    minScore: 2.0,
    minPremium: 80000,
    session: 'ALL',
    startDate: new Date().toISOString().split('T')[0],
    endDate: new Date().toISOString().split('T')[0]
  };

  const [filters, setFilters] = useState(initialFilters);
  const [activeFilters, setActiveFilters] = useState(null); // Start with null to prevent initial fetch
  const [visibleColumns, setVisibleColumns] = useState(DEFAULT_VISIBLE_COLUMNS);
  const [showColumnSelector, setShowColumnSelector] = useState(false);
  const [showFilters, setShowFilters] = useState(true); // Always show filters
  const [selectedRow, setSelectedRow] = useState(null);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isTradePlanModalOpen, setIsTradePlanModalOpen] = useState(false);
  const [isDetailPanelOpen, setIsDetailPanelOpen] = useState(false);
  const [isNoiseWarningModalOpen, setIsNoiseWarningModalOpen] = useState(false);
  const [viewMode, setViewMode] = useState('cards'); // 'cards' or 'table'
  const [reversals, setReversals] = useState([]);
  const [convergences, setConvergences] = useState([]);
  const [filterNoise, setFilterNoise] = useState(true); // Filter retail noise by default
  const [cardViewSymbolFilter, setCardViewSymbolFilter] = useState(''); // Client-side symbol filter for card view only
  const columnSelectorRef = useRef(null);

  const { data, loading, error, filteredCount, refetch } = useOptionsFlow({
    autoRefresh: false, // Never auto-refresh, only fetch on Apply
    interval: 480000,
    filterNoise: filterNoise ? 'true' : 'false',
    ...(activeFilters || {}) // Only pass filters if they exist
  });

  // Calculate "best trade" score for ranking
  const calculateBestTradeScore = (row) => {
    const rocketScore = row.rocketScore || row.rocket_score || 0;
    const momentum = row.momentumScore || 0;
    const confidence = row.tradeSignal?.confidence || 0;
    const hasSignal = row.tradeSignal && row.tradeSignal.signal !== 'NEUTRAL' && row.tradeSignal.signal !== 'WAIT';
    const isGamma = row.isGammaSqueezeSetup;
    const trend = row.flowTrendRaw || row.flowTrend?.full;
    
    // Phase 1 enhancements
    const isTier1 = row.signal_tier === 'TIER_1';
    const checklistPassed = row.checklist_passed === true;
    const flowLedToMove = row.flow_led_to_move === true;
    const checklistScore = row.checklist_score || 0;
    
    // Institutional analytics (Phase 1)
    const confidenceScore = row.confidence_score || 0;
    const signalStrength = row.signal_strength || 0;
    const relativePremium = row.relative_premium_score || 0;
    
    let score = 0;
    score += rocketScore * 10; // 0-100 points
    score += momentum * 0.5; // 0-50 points
    score += confidence * 0.3; // 0-30 points
    if (hasSignal) score += 20;
    if (isGamma) score += 30;
    if (trend?.trend === 'SURGING') score += 15;
    
    // Phase 1 bonuses
    if (isTier1) score += 25; // Tier-1 signals get bonus
    if (checklistPassed) score += 20; // Checklist passed bonus
    if (flowLedToMove) score += 15; // Flow led to move bonus
    score += checklistScore * 2; // Checklist score bonus (0-10 points)
    
    // Institutional analytics bonuses (Phase 1)
    score += confidenceScore * 0.2; // 0-20 points (confidence_score is 0-100)
    score += signalStrength * 0.15; // 0-15 points (signal_strength is 0-100)
    score += relativePremium * 0.1; // 0-10 points (relative_premium_score is 0-100)
    
    return score;
  };

  // Extract unique symbols for stock price fetching
  const uniqueSymbols = useMemo(() => {
    if (!data) return [];
    return [...new Set(data.map(row => (row.symbol_norm || row.Symbol || '').toUpperCase()).filter(Boolean))];
  }, [data]);

  // Fetch reversals
  useEffect(() => {
    const fetchReversals = async () => {
      try {
        const response = await fetch(getApiUrl('/api/reversals/detect'));
        const data = await response.json();
        if (data.success) {
          setReversals(data.reversals || []);
        }
      } catch (error) {
        console.error('Reversal fetch error:', error);
      }
    };

    fetchReversals();
    const interval = setInterval(fetchReversals, 30000); // Check every 30s
    return () => clearInterval(interval);
  }, []);

  // Fetch convergences
  useEffect(() => {
    const fetchConvergences = async () => {
      try {
        const response = await fetch(getApiUrl('/api/convergence/detect?lookback=10'));
        const data = await response.json();
        if (data.success) {
          setConvergences(data.convergences || []);
        }
      } catch (error) {
        console.error('Convergence fetch error:', error);
      }
    };
    fetchConvergences();
    const interval = setInterval(fetchConvergences, 20000); // Check every 20s
    return () => clearInterval(interval);
  }, []);

  // Create a map of reversals by symbol for quick lookup
  const reversalsBySymbol = useMemo(() => {
    const map = {};
    reversals.forEach(rev => {
      map[rev.symbol] = rev;
    });
    return map;
  }, [reversals]);

  // Create a map of convergences by symbol for quick lookup
  const convergencesBySymbol = useMemo(() => {
    const map = {};
    convergences.forEach(conv => {
      const symbol = (conv.symbol || '').toUpperCase();
      if (symbol) {
        map[symbol] = conv;
      }
    });
    console.log('ConvergencesBySymbol map:', map); // Debug
    return map;
  }, [convergences]);

  // Fetch stock prices and volume asynchronously
  const { data: stockPricesData } = useStockPrices(uniqueSymbols);

  // Rank data by best trade score and merge stock price/volume data
  const filteredData = useMemo(() => {
    if (!data) return [];
    
    // Add best trade score and sort by it
    let filtered = data.map(row => {
      const symbolUpper = (row.symbol_norm || row.Symbol || '').toUpperCase();
      const stockPriceInfo = stockPricesData[symbolUpper];
      
      // Check for reversal
      const isReversal = reversalsBySymbol[symbolUpper] !== undefined;
      
      // Merge stock price and volume history data
      const mergedRow = {
      ...row,
      bestTradeScore: calculateBestTradeScore(row),
      isReversal,
      reversal: reversalsBySymbol[symbolUpper]
      };
      
      // Add stock price data if available
      if (stockPriceInfo) {
        if (stockPriceInfo.stockPrice) {
          mergedRow.stockPrice = stockPriceInfo.stockPrice;
        }
        if (stockPriceInfo.volumeHistory && stockPriceInfo.volumeHistory.length > 0) {
          mergedRow.volumeHistory = stockPriceInfo.volumeHistory;
        }
      }
      
      return mergedRow;
    });
    
    // Note: Phase 1 filters are now manual (button on each card)
    // Original filtering remains unchanged
    
    // Sort by flow trend priority first, then by best trade score
    const trendPriority = { 'SURGING': 4, 'STABLE': 3, 'FADING': 2, 'DEAD': 1 };
    filtered.sort((a, b) => {
      const trendA = a.flowTrendRaw?.trend || a.flowTrend?.full?.trend || 'STABLE';
      const trendB = b.flowTrendRaw?.trend || b.flowTrend?.full?.trend || 'STABLE';
      const priorityA = trendPriority[trendA] || 0;
      const priorityB = trendPriority[trendB] || 0;
      
      // First sort by trend priority (SURGING first)
      if (priorityB !== priorityA) {
        return priorityB - priorityA;
      }
      
      // Then sort by best trade score
      return b.bestTradeScore - a.bestTradeScore;
    });
    
    return filtered;
  }, [data, stockPricesData, activeFilters, reversalsBySymbol]);

  // Client-side symbol filter for card view only
  const cardViewFilteredData = useMemo(() => {
    if (viewMode !== 'cards' || !cardViewSymbolFilter.trim()) {
      return filteredData;
    }
    
    const filterSymbol = cardViewSymbolFilter.trim().toUpperCase();
    return filteredData.filter(row => {
      const symbolNorm = (row.symbol_norm || '').toUpperCase();
      const symbol = (row.Symbol || '').toUpperCase();
      const symbolDisplay = (row.symbolDisplay || '').toUpperCase();
      
      return symbolNorm.includes(filterSymbol) || 
             symbol.includes(filterSymbol) || 
             symbolDisplay.includes(filterSymbol);
    });
  }, [filteredData, viewMode, cardViewSymbolFilter]);

  // Get top 5 trades for summary
  // Filter: items repeated more than once, more than 2 rockets, highest premium
  const topTrades = useMemo(() => {
    if (!filteredData || filteredData.length === 0) return [];
    
    // Helper function to extract clean symbol
    const getCleanSymbol = (row) => {
      // Prioritize symbol_norm (clean, normalized)
      if (row.symbol_norm) {
        return row.symbol_norm.toUpperCase().trim();
      }
      // If Symbol is formatted like "(35) (35) HOOD · RTH ⚡ 🟢💎⭐💰⚡ 🔥", extract just the symbol
      if (row.Symbol) {
        const symbolStr = String(row.Symbol);
        // Try to extract symbol from formatted string (look for pattern like "HOOD ·" or just "HOOD")
        // The symbol is usually before the "·" separator
        const match = symbolStr.match(/([A-Z]{1,5})\s*·/);
        if (match && match[1]) {
          return match[1].toUpperCase().trim();
        }
        // If no separator, try to find a stock symbol (1-5 uppercase letters)
        const symbolMatch = symbolStr.match(/\b([A-Z]{1,5})\b/);
        if (symbolMatch && symbolMatch[1]) {
          return symbolMatch[1].toUpperCase().trim();
        }
        // Fallback: use the whole string if it's short and looks like a symbol
        const cleaned = symbolStr.replace(/[^A-Z]/g, '').toUpperCase();
        if (cleaned.length >= 1 && cleaned.length <= 5) {
          return cleaned;
        }
      }
      return '';
    };
    
    // Count symbol occurrences using clean symbols
    const symbolCounts = {};
    filteredData.forEach(row => {
      const symbol = getCleanSymbol(row);
      if (symbol) {
        symbolCounts[symbol] = (symbolCounts[symbol] || 0) + 1;
      }
    });
    
    // Helper function to count rockets
    const countRockets = (rocketStr) => {
      if (!rocketStr) return 0;
      // Count occurrences of 🚀 emoji
      return (rocketStr.match(/🚀/g) || []).length;
    };
    
    // Helper function to get premium as number
    const getPremiumNum = (row) => {
      // Try premium_num first (raw numeric value)
      if (row.premium_num !== undefined && row.premium_num !== null) {
        return parseFloat(row.premium_num) || 0;
      }
      // Try Premium field (might be formatted string like "500 K" or "1.2 M")
      if (row.Premium) {
        const premiumStr = String(row.Premium).trim();
        // Try to parse if it's a number string
        const num = parseFloat(premiumStr.replace(/[^0-9.-]/g, ''));
        if (!isNaN(num)) {
          // Check for K or M suffix
          if (premiumStr.toUpperCase().includes('M')) {
            return num * 1000000;
          } else if (premiumStr.toUpperCase().includes('K')) {
            return num * 1000;
          }
          return num;
        }
      }
      return 0;
    };
    
    // Filter: items that appear more than once AND have 2 or more rockets (>= 2, so 🚀🚀 or 🚀🚀🚀)
    const filtered = filteredData.filter(row => {
      const symbol = getCleanSymbol(row);
      // Check multiple rocket field variations
      const rocket = row.Rocket || row.rocketDisplay || row.rocket || row.rocket_with_mny || '';
      const rocketCount = countRockets(rocket);
      
      // Must appear more than once (duplicate)
      const isRepeated = symbolCounts[symbol] > 1;
      // Must have 2 or more rockets (count >= 2, so 🚀🚀 or 🚀🚀🚀)
      const has2OrMoreRockets = rocketCount >= 2;
      
      return isRepeated && has2OrMoreRockets;
    });
    
    // Sort by premium (highest first)
    filtered.sort((a, b) => {
      const premiumA = getPremiumNum(a);
      const premiumB = getPremiumNum(b);
      return premiumB - premiumA;
    });
    
    // Return top 5
    return filtered.slice(0, 5);
  }, [filteredData]);

  const handleRowClick = (row) => {
    setSelectedRow(row);
    
    // Show noise warning if signal quality is questionable or trash
    if (row.signalQuality === 'QUESTIONABLE' || row.signalQuality === 'TRASH') {
      setIsNoiseWarningModalOpen(true);
    }
    
    if (viewMode === 'cards') {
      setIsDetailPanelOpen(true);
    } else {
      setIsModalOpen(true);
    }
  };

  const handleApplyFilters = () => {
    setActiveFilters({ ...filters });
    // Trigger refetch when Apply is clicked
    refetch();
  };

  const handleResetFilters = () => {
    setFilters(initialFilters);
    setActiveFilters(null); // Reset to null to prevent auto-fetch
  };

  // Define all columns
  const allColumns = useMemo(() => [
    {
      accessorKey: 'Rank',
      header: '#',
      group: 'core',
      accessorFn: (row, index) => index + 1,
      cell: ({ row }) => {
        // Rank is already calculated in filteredData, use bestTradeScore position
        const rank = filteredData.findIndex(r => r === row.original) + 1;
        const isTop3 = rank <= 3;
        return (
          <div className="flex items-center gap-2">
            {isTop3 && <span className="text-lg">🏆</span>}
            <span className={cn(
              "font-bold text-sm",
              rank === 1 ? "text-yellow-400" :
              rank === 2 ? "text-slate-300" :
              rank === 3 ? "text-orange-400" :
              "text-slate-500"
            )}>
              #{rank}
            </span>
          </div>
        );
      }
    },
    {
      accessorKey: 'Symbol',
      header: 'Symbol',
      group: 'core',
      cell: ({ row }) => {
        const stockPrice = row.original.stockPrice;
        return (
          <SymbolTooltip row={row.original}>
            <div className="flex flex-col gap-0.5">
              <div className="font-mono text-sm whitespace-nowrap font-semibold cursor-help hover:text-blue-400 transition-colors">
                {row.original.Symbol || row.original.symbolDisplay}
              </div>
              {/* Stock Price from Yahoo Finance */}
              {stockPrice && stockPrice.currentPrice && (
                <div className="flex items-center gap-2">
                  <span className="font-mono text-xs font-semibold text-slate-300">
                    ${(typeof stockPrice.currentPrice === 'number' ? stockPrice.currentPrice : parseFloat(stockPrice.currentPrice) || 0).toFixed(2)}
                  </span>
                  {stockPrice.changePercent !== undefined && stockPrice.changePercent !== null && (
                    <span className={cn(
                      "text-xs font-medium",
                      (typeof stockPrice.changePercent === 'number' ? stockPrice.changePercent : parseFloat(stockPrice.changePercent) || 0) >= 0 
                        ? "text-green-400" 
                        : "text-red-400"
                    )}>
                      {(typeof stockPrice.changePercent === 'number' ? stockPrice.changePercent : parseFloat(stockPrice.changePercent) || 0) >= 0 ? '+' : ''}
                      {(typeof stockPrice.changePercent === 'number' ? stockPrice.changePercent : parseFloat(stockPrice.changePercent) || 0).toFixed(2)}%
                    </span>
                  )}
                </div>
              )}
            </div>
          </SymbolTooltip>
        );
      }
    },
    {
      accessorKey: 'badges',
      header: 'Badges',
      group: 'core',
      cell: ({ row }) => (
        <BadgeCell badges={row.original.badges} />
      )
    },
    {
      accessorKey: 'signalQuality',
      header: 'Quality',
      group: 'core',
      cell: ({ row }) => {
        const quality = row.original.signalQuality || 'ACCEPTABLE';
        const noiseScore = row.original.noiseScore || 0;
        
        const qualityConfig = {
          'CLEAN': { 
            badge: '✅ CLEAN', 
            color: 'bg-green-900 text-green-300',
            tooltip: `Noise score: ${noiseScore}/100 - Institutional-grade signal`
          },
          'ACCEPTABLE': { 
            badge: '🟡 OK', 
            color: 'bg-yellow-900 text-yellow-300',
            tooltip: `Noise score: ${noiseScore}/100 - Some retail activity detected`
          },
          'QUESTIONABLE': { 
            badge: '⚠️ IFFY', 
            color: 'bg-orange-900 text-orange-300',
            tooltip: `Noise score: ${noiseScore}/100 - Possible retail noise`
          },
          'TRASH': { 
            badge: '🚫 NOISE', 
            color: 'bg-red-900 text-red-300',
            tooltip: `Noise score: ${noiseScore}/100 - Retail garbage, ignore`
          }
        };
        
        const config = qualityConfig[quality] || qualityConfig['ACCEPTABLE'];
        
        return (
          <div 
            className={`px-2 py-1 rounded text-xs font-semibold ${config.color}`}
            title={config.tooltip}
          >
            {config.badge}
          </div>
        );
      }
    },
    {
      accessorKey: 'reversal',
      header: 'Status',
      group: 'core',
      cell: ({ row }) => {
        const symbol = (row.original.symbol_norm || row.original.Symbol || '').toUpperCase();
        const reversal = reversalsBySymbol[symbol];
        if (reversal) {
          return (
            <Badge variant="warning" className="animate-pulse">
              🔄 REVERSAL
            </Badge>
          );
        }
        return null;
      }
    },
    {
      accessorKey: 'convergence',
      header: 'Convergence',
      group: 'core',
      cell: ({ row }) => {
        const symbol = (row.original.symbol_norm || row.original.Symbol || '').toUpperCase();
        const convergence = convergencesBySymbol[symbol];
        if (convergence) {
          return (
            <Badge variant="destructive" className="animate-pulse">
              🔥 {convergence.signalCount} SIGNALS
            </Badge>
          );
        }
        return null;
      }
    },
    {
      accessorKey: 'Rocket',
      header: '🚀 Score',
      group: 'core',
      accessorFn: (row) => {
        // For sorting by conviction: score * confidence * flow trend multiplier
        const score = row.rocketScore || row.rocket_score || 0;
        const confidence = row.tradeSignal?.confidence || 50;
        const trend = row.flowTrendRaw || row.flowTrend?.full;
        let trendMultiplier = 1.0;
        if (trend) {
          if (trend.trend === 'SURGING') trendMultiplier = 1.5;
          else if (trend.trend === 'STABLE') trendMultiplier = 1.0;
          else if (trend.trend === 'FADING') trendMultiplier = 0.7;
          else if (trend.trend === 'DEAD') trendMultiplier = 0.3;
        }
        return score * (confidence / 100) * trendMultiplier;
      },
      cell: ({ row }) => {
        const rocket = row.original.Rocket || row.original.rocketDisplay || '';
        const scoreRaw = row.original.rocketScore || row.original.rocket_score || 0;
        const score = typeof scoreRaw === 'number' ? scoreRaw : parseFloat(scoreRaw) || 0;
        const maxScore = 10; // Assuming max score is 10
        const percentage = Math.min((score / maxScore) * 100, 100);
        
        return (
          <ScoreBreakdownTooltip row={row.original}>
            <div className="flex items-center gap-2 min-w-[120px] cursor-help">
              <span className="text-lg">{rocket}</span>
              <div className="flex-1 flex flex-col gap-1">
                {/* Visual gauge bar */}
                <div className="w-full h-2 bg-slate-800 rounded-full overflow-hidden">
                  <div 
                    className={cn(
                      "h-full transition-all",
                      score >= 5 ? "bg-green-500" :
                      score >= 3.5 ? "bg-yellow-500" :
                      score >= 2 ? "bg-orange-500" :
                      "bg-slate-600"
                    )}
                    style={{ width: `${percentage}%` }}
                  />
                </div>
                {/* Score number */}
                <Badge 
                  variant={
                    score >= 5 ? 'destructive' : 
                    score >= 3.5 ? 'warning' : 
                    'secondary'
                  }
                  className="text-xs w-fit"
                >
                  {score.toFixed(1)}/10
                </Badge>
              </div>
            </div>
          </ScoreBreakdownTooltip>
        );
      }
    },
    {
      accessorKey: 'Momentum',
      header: 'Momentum',
      group: 'core',
      accessorFn: (row) => row.momentumScore || 0,
      cell: ({ row }) => {
        const momentum = row.original.momentumScore || 0;
        const label = row.original.momentumLabel || 'MODERATE';
        const color = row.original.momentumColor || 'yellow';
        const icon = row.original.momentumIcon || '🟡';
        
        const colorClasses = {
          green: 'text-green-400 bg-green-500/20',
          yellow: 'text-yellow-400 bg-yellow-500/20',
          orange: 'text-orange-400 bg-orange-500/20',
          red: 'text-red-400 bg-red-500/20'
        };
        
        const barColorClasses = {
          green: 'bg-green-500',
          yellow: 'bg-yellow-500',
          orange: 'bg-orange-500',
          red: 'bg-red-500'
        };
        
        return (
          <div className="flex items-center gap-2 min-w-[120px]">
            <div className="flex-1 bg-slate-800 rounded-full h-2">
              <div 
                className={`${barColorClasses[color] || 'bg-yellow-500'} h-2 rounded-full transition-all`}
                style={{ width: `${momentum}%` }}
              />
            </div>
            <div className={`px-2 py-1 rounded text-xs font-medium ${colorClasses[color] || colorClasses.yellow}`}>
              <span className="mr-1">{icon}</span>
              {momentum}
            </div>
          </div>
        );
      }
    },
    {
      accessorKey: 'TradeSignal',
      header: 'Trade Signal',
      group: 'core',
      cell: ({ row }) => {
        const signal = row.original.tradeSignal;
        if (!signal || signal.signal === 'NEUTRAL' || signal.signal === 'WAIT') {
          return (
            <div className="flex flex-col gap-1">
              <Badge variant="outline" className="text-xs w-fit">
                {signal?.signal === 'WAIT' ? '⏸ WAIT' : '—'}
              </Badge>
              {signal?.confidence && (
                <span className="text-xs text-slate-500">{signal.confidence}%</span>
              )}
            </div>
          );
        }
        
        const isBuy = signal.signal === 'BUY';
        
        // Extract price values from entry/stop/target (handle both object and string formats)
        const extractPrice = (value) => {
          if (!value) return '—';
          if (typeof value === 'string') {
            const match = value.match(/\$?([\d.]+)/);
            return match ? `$${match[1]}` : value;
          }
          if (typeof value === 'object') {
            const primary = value.primary || value.aggressive || value.tight || value.wide || value.t1;
            if (typeof primary === 'string') {
              const match = primary.match(/\$?([\d.]+)/);
              return match ? `$${match[1]}` : primary;
            }
          }
          return '—';
        };
        
        const entryPrice = extractPrice(signal.entry);
        const stopPrice = extractPrice(signal.stop);
        const targetPrice = extractPrice(signal.target);
        
        return (
          <div className="flex flex-col gap-1 min-w-[140px]">
            <Badge 
              variant={isBuy ? 'success' : 'destructive'} 
              className="text-xs w-fit font-semibold"
            >
              {signal.type === 'GAMMA_SQUEEZE_SETUP' ? '⚡ GAMMA BUY' : 
               isBuy ? '🚀 BUY' : '🔴 SHORT'}
            </Badge>
            {signal.type === 'GAMMA_SQUEEZE_SETUP' && (
              <Badge className="bg-purple-500/20 text-purple-400 text-xs border-purple-500/50 mt-1">
                Gamma Squeeze Setup
              </Badge>
            )}
            <div className="text-xs space-y-0.5">
              <div className="text-slate-300">
                <span className="text-slate-500">Conf:</span> {signal.confidence || '—'}%
              </div>
              <div className="text-green-400">
                <span className="text-slate-500">Entry:</span> {entryPrice}
              </div>
              <div className="text-red-400">
                <span className="text-slate-500">Stop:</span> {stopPrice}
              </div>
              <div className="text-blue-400">
                <span className="text-slate-500">Target:</span> {targetPrice}
              </div>
            </div>
          </div>
        );
      }
    },
    {
      accessorKey: 'TradePlan',
      header: 'Trade Plan',
      group: 'core',
      cell: ({ row }) => {
        const tradePlan = row.original.tradePlan;
        const tradePlanDisplay = row.original.tradePlanDisplay;
        
        if (!tradePlan || !tradePlanDisplay) {
          return (
            <span className="text-slate-500 text-xs">—</span>
          );
        }
        
        const signal = tradePlan.signal || 'WAIT';
        const confidence = tradePlan.confidence || 0;
        
        const getSignalColor = () => {
          if (signal === 'BUY') return 'bg-green-500/20 text-green-400 border-green-500/50 hover:bg-green-500/30';
          if (signal === 'SELL') return 'bg-red-500/20 text-red-400 border-red-500/50 hover:bg-red-500/30';
          return 'bg-yellow-500/20 text-yellow-400 border-yellow-500/50 hover:bg-yellow-500/30';
        };
        
        return (
          <div className="flex flex-col gap-1">
            <button
              onClick={(e) => {
                e.stopPropagation();
                setSelectedRow(row.original);
                setIsTradePlanModalOpen(true);
              }}
              className={cn(
                "px-2 py-1 rounded text-xs font-semibold border transition-colors cursor-pointer text-left",
                getSignalColor()
              )}
              title={signal === 'WAIT' && tradePlan.reasoning?.why?.length > 0 
                ? tradePlan.reasoning.why.join('; ') 
                : tradePlanDisplay}
            >
              {tradePlanDisplay}
            </button>
            {/* Show first wait reason as subtitle */}
            {signal === 'WAIT' && tradePlan.reasoning?.why?.length > 0 && (
              <div className="text-xs text-yellow-300/70 italic px-2">
                {tradePlan.reasoning.why[0]}
              </div>
            )}
          </div>
        );
      }
    },
    {
      accessorKey: 'NetPremium',
      header: 'Net Premium',
      group: 'core',
      cell: ({ row }) => {
        const value = row.original.NetPremium || row.original.netPremiumDisplay;
        const netPremium = (row.original.bull_total || 0) - (row.original.bear_total || 0);
        const isBullish = netPremium > 0;
        const absNetPrem = Math.abs(netPremium);
        
        // Color coding: bullish=green, bearish=red, tiny=gray
        let colorClass = 'text-slate-400'; // default gray for tiny
        if (absNetPrem > 100000) {
          colorClass = isBullish ? 'text-green-400 font-bold' : 'text-red-400 font-bold';
        } else if (absNetPrem > 50000) {
          colorClass = isBullish ? 'text-green-300 font-semibold' : 'text-red-300 font-semibold';
        }
        
        return (
          <span className={colorClass}>
            {value || '—'}
          </span>
        );
      }
    },
    {
      accessorKey: 'FlowTrend',
      header: 'Flow Trend',
      group: 'core',
      cell: ({ row }) => {
        const trend = row.original.flowTrend || row.original.flowTrendRaw;
        if (!trend) return '—';
        
        const trendData = trend.full || trend;
        const trendValue = trendData.trend || 'STABLE';
        const minutesAgo = trendData.lastFlowMinutesAgo;
        
        // Get premium for temporal context
        const premium = row.original.premium_num || 0;
        const netPremiumCurrent = trendData.netPremiumCurrent || premium;
        
        const getTrendConfig = (trendValue, minutesAgo, premium) => {
          const baseConfig = {
            'SURGING': { 
              icon: '🔥', 
              text: 'SURGING', 
              color: 'text-red-400 font-bold'
            },
            'STABLE': { 
              icon: '🟡', 
              text: 'STABLE', 
              color: 'text-yellow-400'
            },
            'FADING': { 
              icon: '⚠️', 
              text: 'FADING', 
              color: 'text-orange-400'
            },
            'DEAD': { 
              icon: '💀', 
              text: 'DEAD', 
              color: 'text-gray-500'
            }
          };
          
          const config = baseConfig[trendValue] || baseConfig['STABLE'];
          
          // Add temporal explanation
          if (trendValue === 'DEAD') {
            if (minutesAgo !== null && minutesAgo >= 60) {
              const numPremium = typeof premium === 'number' ? premium : parseFloat(premium) || 0;
              const premiumText = numPremium >= 1000000 
                ? `$${(numPremium / 1000000).toFixed(1)}M premium`
                : `$${(numPremium / 1000).toFixed(0)}K premium`;
              config.tooltip = `Initial positioning detected (${premiumText}), but accumulation stopped. Last flow ${minutesAgo}min ago - no continuation detected.`;
              config.temporalExplanation = `Flow occurred earlier; no continuation in last ${minutesAgo}min`;
            } else {
              config.tooltip = `No recent flow detected`;
              config.temporalExplanation = 'No flow data available';
            }
          } else if (trendValue === 'FADING') {
            config.tooltip = `Institutions slowing down. Last flow ${minutesAgo !== null ? minutesAgo : 'N/A'}min ago - accumulation may be complete.`;
            config.temporalExplanation = minutesAgo !== null 
              ? `Flow detected ${minutesAgo}min ago; slowing accumulation`
              : 'Flow slowing';
          } else if (trendValue === 'SURGING') {
            config.tooltip = `Institutions actively buying. Last flow ${minutesAgo !== null ? minutesAgo : 'N/A'}min ago - accumulation continuing.`;
            config.temporalExplanation = minutesAgo !== null 
              ? `Active accumulation (last flow ${minutesAgo}min ago)`
              : 'Active accumulation';
          } else {
            config.tooltip = `Flow holding steady. Last flow ${minutesAgo !== null ? minutesAgo : 'N/A'}min ago.`;
            config.temporalExplanation = minutesAgo !== null 
              ? `Last flow ${minutesAgo}min ago`
              : 'Flow stable';
          }
          
          return config;
        };
        
        const trendConfig = getTrendConfig(trendValue, minutesAgo, netPremiumCurrent);
        
        return (
          <div 
            className={cn(
              "flex flex-col gap-1 p-2 rounded border-2",
              trendValue === 'DEAD' && "bg-slate-900/50 border-slate-700 opacity-60",
              trendValue === 'SURGING' && "bg-red-900/30 border-red-500/50 shadow-lg shadow-red-500/20",
              trendValue === 'FADING' && "bg-orange-900/30 border-orange-500/50",
              trendValue === 'STABLE' && "bg-yellow-900/20 border-yellow-500/30"
            )}
            title={trendConfig.tooltip}
          >
            <div className={cn(
              "flex items-center gap-2",
              trendValue === 'SURGING' && "animate-pulse"
            )}>
              <span className={cn(
                "text-xl font-bold",
                trendValue === 'SURGING' && "text-red-400",
                trendValue === 'DEAD' && "text-gray-500",
                trendValue === 'FADING' && "text-orange-400",
                trendValue === 'STABLE' && "text-yellow-400"
              )}>
                {trendConfig.icon}
              </span>
              <span className={cn(
                "font-bold text-sm uppercase tracking-wide",
                trendConfig.color
              )}>
                {trendConfig.text}
              </span>
            </div>
            {/* Show temporal explanation for DEAD/FADING */}
            {(trendValue === 'DEAD' || trendValue === 'FADING') && trendConfig.temporalExplanation && (
              <div className="text-xs text-slate-400 italic pl-7">
                {trendConfig.temporalExplanation}
              </div>
            )}
          </div>
        );
      }
    },
    {
      accessorKey: 'Premium',
      header: 'Premium',
      group: 'core',
      cell: ({ row }) => (
        <span className="font-mono text-slate-200">
          {row.original.Premium || row.original.premiumDisplay || '—'}
        </span>
      )
    },
    {
      accessorKey: 'Moneyness',
      header: 'Moneyness',
      group: 'option',
      cell: ({ row }) => {
        const moneyness = row.original.moneynessLabel || 'Unknown';
        const isGamma = row.original.isGammaSqueezeSetup;
        const moneynessContext = row.original.moneynessContext;
        
        // Color code based on moneyness
        let badgeVariant = 'outline';
        let badgeClass = 'text-xs';
        
        if (moneynessContext) {
          if (moneynessContext.category === 'DEEP_ITM' || moneynessContext.category === 'ITM') {
            badgeClass += ' bg-green-500/10 border-green-500/50 text-green-400';
          } else if (moneynessContext.category === 'DEEP_OTM' || moneynessContext.category === 'EXTREME_OTM') {
            badgeClass += ' bg-purple-500/10 border-purple-500/50 text-purple-400';
          } else if (moneynessContext.category === 'NEAR_ATM') {
            badgeClass += ' bg-blue-500/10 border-blue-500/50 text-blue-400';
          }
        }
        
        return (
          <div className="flex items-center gap-1">
            <Badge variant="outline" className={badgeClass}>
              {moneyness}
            </Badge>
            {isGamma && (
              <Badge className="bg-purple-500/20 text-purple-400 text-xs border-purple-500/50">
                ⚡ GAMMA
              </Badge>
            )}
          </div>
        );
      }
    },
    {
      accessorKey: 'CallPut',
      header: 'Type',
      group: 'option',
      cell: ({ row }) => {
        const type = row.original.CallPut;
        if (!type) return '—';
        return (
          <Badge variant={type === 'CALL' ? 'success' : 'destructive'} className="text-xs">
            {type}
          </Badge>
        );
      }
    },
    {
      accessorKey: 'Strike',
      header: 'Strike',
      group: 'option',
      cell: ({ row }) => (
        <span className="font-mono text-slate-200">
          {row.original.Strike ? `$${row.original.Strike}` : '—'}
        </span>
      )
    },
    {
      accessorKey: 'Spot',
      header: 'Spot',
      group: 'option',
      cell: ({ row }) => (
        <span className="font-mono text-slate-300">
          {row.original.Spot ? `$${row.original.Spot}` : '—'}
        </span>
      )
    },
    {
      accessorKey: 'ExpirationDate',
      header: 'Expiry',
      group: 'option',
      cell: ({ row }) => {
        const date = row.original.ExpirationDate;
        if (!date) return '—';
        return (
          <span className="text-xs text-slate-400">
            {new Date(date).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}
          </span>
        );
      }
    },
    {
      accessorKey: 'Volume',
      header: 'Volume',
      group: 'volume',
      cell: ({ row }) => (
        <span className="font-mono text-slate-200">
          {row.original.Volume ? Number(row.original.Volume).toLocaleString() : '—'}
        </span>
      )
    },
    {
      accessorKey: 'OI',
      header: 'OI',
      group: 'volume',
      cell: ({ row }) => (
        <span className="font-mono text-slate-200">
          {row.original.OI ? Number(row.original.OI).toLocaleString() : '—'}
        </span>
      )
    },
    {
      accessorKey: 'Price',
      header: 'Price',
      group: 'volume',
      cell: ({ row }) => (
        <span className="font-mono text-slate-200">
          {row.original.Price ? `$${row.original.Price}` : '—'}
        </span>
      )
    },
    {
      accessorKey: 'Side',
      header: 'Side',
      group: 'volume',
      cell: ({ row }) => {
        const side = row.original.Side;
        if (!side) return '—';
        return (
          <Badge variant="outline" className="text-xs">
            {side}
          </Badge>
        );
      }
    },
    {
      accessorKey: 'PctVsPriorClose',
      header: 'vs Prior',
      group: 'price',
      cell: ({ row }) => {
        const val = row.original.PctVsPriorClose;
        if (val === null || val === undefined) return '—';
        const numVal = typeof val === 'number' ? val : parseFloat(val);
        if (isNaN(numVal)) return '—';
        return (
          <span className={`font-medium ${numVal > 0 ? 'text-green-400' : 'text-red-400'}`}>
            {numVal > 0 ? '+' : ''}{numVal.toFixed(2)}%
          </span>
        );
      }
    },
    {
      accessorKey: 'PctVsRthOpen',
      header: 'vs RTH',
      group: 'price',
      cell: ({ row }) => {
        const val = row.original.PctVsRthOpen || row.original.pct_vs_rth_open;
        if (val === null || val === undefined) return '—';
        const numVal = typeof val === 'number' ? val : parseFloat(val);
        if (isNaN(numVal)) return '—';
        return (
          <span className={`font-medium ${numVal > 0 ? 'text-green-400' : 'text-red-400'}`}>
            {numVal > 0 ? '+' : ''}{numVal.toFixed(2)}%
          </span>
        );
      }
    },
    {
      accessorKey: 'Pct5m',
      header: '5m',
      group: 'price',
      cell: ({ row }) => {
        const val = row.original.Pct5m || row.original.pct_5m_momo;
        if (val === null || val === undefined) return '—';
        const numVal = typeof val === 'number' ? val : parseFloat(val);
        if (isNaN(numVal)) return '—';
        return (
          <span className={`text-xs ${numVal > 0 ? 'text-green-400' : 'text-red-400'}`}>
            {numVal > 0 ? '+' : ''}{numVal.toFixed(2)}%
          </span>
        );
      }
    },
    {
      accessorKey: 'Pct15m',
      header: '15m',
      group: 'price',
      cell: ({ row }) => {
        const val = row.original.Pct15m || row.original.pct_15m_momo;
        if (val === null || val === undefined) return '—';
        const numVal = typeof val === 'number' ? val : parseFloat(val);
        if (isNaN(numVal)) return '—';
        return (
          <span className={`text-xs ${numVal > 0 ? 'text-green-400' : 'text-red-400'}`}>
            {numVal > 0 ? '+' : ''}{numVal.toFixed(2)}%
          </span>
        );
      }
    },
    {
      accessorKey: 'TapeAlign',
      header: 'Tape',
      group: 'context',
      cell: ({ row }) => {
        const arrow = row.original.TapeAlign || row.original.tapeArrow;
        if (!arrow) return '—';
        return (
          <div className="text-center text-xl" title="Tape Alignment">
            {arrow}
          </div>
        );
      }
    },
    {
      accessorKey: 'LastFlow',
      header: 'Last Flow',
      group: 'context',
      cell: ({ row }) => {
        const trend = row.original.flowTrendRaw || row.original.flowTrend?.full;
        const decay = row.original.flowDecayRaw || row.original.flowDecay?.full;
        const minutesAgo = trend?.lastFlowMinutesAgo ?? decay?.lastFlowMinutesAgo;
        
        if (minutesAgo === null || minutesAgo === undefined) {
          const createdTime = row.original.CreatedTime || row.original.CreatedDate;
          if (createdTime) {
            const time = new Date(createdTime);
            const now = new Date();
            const diff = Math.floor((now - time) / (1000 * 60));
            return (
              <span className="text-xs text-slate-400 font-mono">
                {diff}min ago
              </span>
            );
          }
          return '—';
        }
        
        // Color code based on staleness
        let colorClass = 'text-green-400';
        if (minutesAgo >= 60) colorClass = 'text-slate-500';
        else if (minutesAgo >= 30) colorClass = 'text-yellow-400';
        
        return (
          <span className={`text-xs font-mono ${colorClass}`}>
            {minutesAgo}min ago
          </span>
        );
      }
    },
    {
      accessorKey: 'NearAlert',
      header: 'Catalyst',
      group: 'context',
      cell: ({ row }) => {
        const alert = row.original.NearAlert || row.original.near_alert_type;
        if (!alert) return '—';
        return (
          <Badge variant="outline" className="text-xs bg-yellow-500/10 border-yellow-500/50 text-yellow-400">
            {alert}
          </Badge>
        );
      }
    },
    {
      accessorKey: 'CreatedDate',
      header: 'Date',
      group: 'context',
      cell: ({ row }) => {
        const date = row.original.CreatedDate;
        if (!date) return '—';
        return (
          <span className="text-xs text-slate-400">
            {new Date(date).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}
          </span>
        );
      }
    },
    {
      accessorKey: 'CreatedTime',
      header: 'Time',
      group: 'context',
      cell: ({ row }) => (
        <span className="text-xs text-slate-400 font-mono">
          {row.original.CreatedTime || '—'}
        </span>
      )
    },
    // Phase 1: Signal Tier
    {
      accessorKey: 'SignalTier',
      header: 'Tier',
      group: 'core',
      cell: ({ row }) => {
        const tier = row.original.signal_tier;
        if (!tier) return '—';
        
        const tierConfig = {
          'TIER_1': { label: 'Tier-1', color: 'text-green-400 bg-green-500/20 border-green-500/50', icon: '🥇' },
          'TIER_2': { label: 'Tier-2', color: 'text-yellow-400 bg-yellow-500/20 border-yellow-500/50', icon: '🥈' },
          'IGNORE': { label: 'Ignore', color: 'text-slate-400 bg-slate-500/20 border-slate-500/50', icon: '🚫' }
        };
        
        const config = tierConfig[tier] || tierConfig['IGNORE'];
        
        return (
          <Badge variant="outline" className={`text-xs ${config.color}`}>
            <span className="mr-1">{config.icon}</span>
            {config.label}
          </Badge>
        );
      }
    },
    // Phase 1: Checklist
    {
      accessorKey: 'Checklist',
      header: 'Checklist',
      group: 'core',
      cell: ({ row }) => {
        const score = row.original.checklist_score;
        const passed = row.original.checklist_passed;
        const details = row.original.checklist_details;
        
        if (score === undefined || score === null) return '—';
        
        return (
          <div className="flex flex-col gap-1 min-w-[80px]">
            <Badge 
              variant={passed ? 'success' : 'secondary'}
              className={`text-xs w-fit ${passed ? 'bg-green-500/20 border-green-500/50 text-green-400' : 'bg-red-500/20 border-red-500/50 text-red-400'}`}
              title={details ? JSON.stringify(details, null, 2) : ''}
            >
              {score}/5 {passed ? '✅' : '❌'}
            </Badge>
            {details && (
              <div className="text-xs text-slate-500">
                {Object.values(details).filter(v => v).length}/5 passed
              </div>
            )}
          </div>
        );
      }
    },
    // Phase 2: Institutional Analytics Columns
    {
      accessorKey: 'confidence_score',
      header: 'Confidence',
      group: 'institutional',
      accessorFn: (row) => row.confidence_score || 0,
      cell: ({ row }) => {
        const scoreRaw = row.original.confidence_score;
        if (scoreRaw === null || scoreRaw === undefined) return '—';
        const score = typeof scoreRaw === 'number' ? scoreRaw : parseFloat(scoreRaw);
        if (isNaN(score)) return '—';
        
        const roundedScore = Math.round(score);
        const colorClass = score >= 70 ? 'text-green-400' :
                          score >= 50 ? 'text-yellow-400' :
                          'text-orange-400';
        
        return (
          <div className="flex items-center gap-2 min-w-[90px]">
            <div className="flex-1 bg-slate-800 rounded-full h-2">
              <div 
                className={cn(
                  "h-2 rounded-full transition-all",
                  score >= 70 ? "bg-green-500" :
                  score >= 50 ? "bg-yellow-500" :
                  "bg-orange-500"
                )}
                style={{ width: `${Math.min(100, score)}%` }}
              />
            </div>
            <Badge 
              variant={score >= 70 ? 'success' : score >= 50 ? 'warning' : 'secondary'}
              className={cn("text-xs w-12 justify-center", colorClass)}
            >
              {roundedScore}%
            </Badge>
          </div>
        );
      }
    },
    {
      accessorKey: 'signal_strength',
      header: 'Signal Strength',
      group: 'institutional',
      accessorFn: (row) => row.signal_strength || 0,
      cell: ({ row }) => {
        const strengthRaw = row.original.signal_strength;
        if (strengthRaw === null || strengthRaw === undefined) return '—';
        const strength = typeof strengthRaw === 'number' ? strengthRaw : parseFloat(strengthRaw);
        if (isNaN(strength)) return '—';
        
        const roundedStrength = Math.round(strength);
        const colorClass = strength >= 70 ? 'text-purple-400' :
                          strength >= 50 ? 'text-blue-400' :
                          'text-slate-400';
        
        return (
          <div className="flex items-center gap-2 min-w-[90px]">
            <div className="flex-1 bg-slate-800 rounded-full h-2">
              <div 
                className={cn(
                  "h-2 rounded-full transition-all",
                  strength >= 70 ? "bg-purple-500" :
                  strength >= 50 ? "bg-blue-500" :
                  "bg-slate-500"
                )}
                style={{ width: `${Math.min(100, strength)}%` }}
              />
            </div>
            <span className={cn("text-xs font-semibold w-8 text-right", colorClass)}>
              {roundedStrength}
            </span>
          </div>
        );
      }
    },
    {
      accessorKey: 'relative_premium_score',
      header: 'Rel. Premium',
      group: 'institutional',
      accessorFn: (row) => row.relative_premium_score || 0,
      cell: ({ row }) => {
        const scoreRaw = row.original.relative_premium_score;
        if (scoreRaw === null || scoreRaw === undefined) return '—';
        const score = typeof scoreRaw === 'number' ? scoreRaw : parseFloat(scoreRaw);
        if (isNaN(score)) return '—';
        
        const roundedScore = Math.round(score);
        const colorClass = score >= 70 ? 'text-green-400' :
                          score >= 50 ? 'text-yellow-400' :
                          'text-orange-400';
        
        return (
          <div className="flex items-center gap-2 min-w-[85px]">
            <div className="flex-1 bg-slate-800 rounded-full h-2">
              <div 
                className={cn(
                  "h-2 rounded-full transition-all",
                  score >= 70 ? "bg-green-500" :
                  score >= 50 ? "bg-yellow-500" :
                  "bg-orange-500"
                )}
                style={{ width: `${Math.min(100, score)}%` }}
              />
            </div>
            <span className={cn("text-xs font-semibold w-8 text-right", colorClass)}>
              {roundedScore}
            </span>
          </div>
        );
      }
    },
    // Phase 1: Price Reaction 5m
    {
      accessorKey: 'PriceReaction5m',
      header: '5m Reaction',
      group: 'price',
      cell: ({ row }) => {
        const reaction = row.original.price_reaction_5m_pct;
        const ledToMove = row.original.flow_led_to_move;
        
        if (reaction === null || reaction === undefined) return '—';
        const numReaction = typeof reaction === 'number' ? reaction : parseFloat(reaction);
        if (isNaN(numReaction)) return '—';
        
        return (
          <div className="flex flex-col gap-0.5">
            <span className={`text-xs font-medium ${numReaction > 0 ? 'text-green-400' : numReaction < 0 ? 'text-red-400' : 'text-slate-400'}`}>
              {numReaction > 0 ? '+' : ''}{numReaction.toFixed(2)}%
            </span>
            {ledToMove && (
              <span className="text-xs text-green-400" title="Flow led to price move">✓</span>
            )}
          </div>
        );
      }
    },
    // Phase 1: VWAP Distance
    {
      accessorKey: 'VWAPDistance',
      header: 'vs VWAP',
      group: 'price',
      cell: ({ row }) => {
        const vwapDist = row.original.price_vs_vwap_pct;
        const vwap = row.original.vwap_at_signal;
        
        if (vwapDist === null || vwapDist === undefined) {
          if (!vwap) return <span className="text-xs text-slate-500">No VWAP</span>;
          return '—';
        }
        const numVwapDist = typeof vwapDist === 'number' ? vwapDist : parseFloat(vwapDist);
        if (isNaN(numVwapDist)) return '—';
        
        // Color code: near VWAP = good, far from VWAP = caution
        const absDist = Math.abs(numVwapDist);
        let colorClass = 'text-slate-400';
        if (absDist <= 1) colorClass = 'text-green-400';
        else if (absDist <= 2) colorClass = 'text-yellow-400';
        else colorClass = 'text-red-400';
        
        const numVwap = typeof vwap === 'number' ? vwap : parseFloat(vwap);
        
        return (
          <div className="flex flex-col gap-0.5">
            <span className={`text-xs font-medium ${colorClass}`}>
              {numVwapDist > 0 ? '+' : ''}{numVwapDist.toFixed(2)}%
            </span>
            {vwap && !isNaN(numVwap) && (
              <span className="text-xs text-slate-500" title={`VWAP: $${numVwap.toFixed(2)}`}>
                V: ${numVwap.toFixed(2)}
              </span>
            )}
          </div>
        );
      }
    }
  ], []);

  // Filter columns based on visibility
  const columns = useMemo(() => 
    allColumns.filter(col => visibleColumns.includes(col.accessorKey)),
    [allColumns, visibleColumns]
  );

  const toggleColumn = (columnKey) => {
    setVisibleColumns(prev => 
      prev.includes(columnKey)
        ? prev.filter(k => k !== columnKey)
        : [...prev, columnKey]
    );
  };

  // Close column selector when clicking outside
  useEffect(() => {
    const handleClickOutside = (event) => {
      if (columnSelectorRef.current && !columnSelectorRef.current.contains(event.target)) {
        setShowColumnSelector(false);
      }
    };

    if (showColumnSelector) {
      document.addEventListener('mousedown', handleClickOutside);
      return () => document.removeEventListener('mousedown', handleClickOutside);
    }
  }, [showColumnSelector]);

  // Format date for display
  const getDisplayDate = () => {
    const startDate = activeFilters?.startDate || filters.startDate;
    const endDate = activeFilters?.endDate || filters.endDate;
    
    if (!startDate || !endDate) {
      return 'No date selected';
    }
    
    const start = new Date(startDate);
    const end = new Date(endDate);
    
    const startFormatted = start.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
    const endFormatted = end.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
    
    // If same date, show only once
    if (startFormatted === endFormatted) {
      return startFormatted;
    }
    
    return `${startFormatted} - ${endFormatted}`;
  };
  
  const displayDate = getDisplayDate();

  return (
    <div className="space-y-4">
      {/* Descriptive Disclaimer */}
      <div className="bg-yellow-950/20 border border-yellow-900/50 p-4 rounded-lg flex items-start gap-3 text-sm text-yellow-200/80 shadow-inner">
        <span className="text-xl leading-none">⚠️</span>
        <p>
          <strong>Descriptive Only.</strong> Options flow imbalance is shown strictly for market context and sentiment analysis. 
          The "Smart Money" thesis has not been validated out-of-sample as a predictive signal by our engine. Do not treat flow as a buy/sell signal.
        </p>
      </div>

      {/* Header with Date and Quick Actions */}
      <div className="flex items-center justify-between bg-slate-900/50 backdrop-blur-sm rounded-lg border border-slate-800/50 p-3">
        <div className="flex items-center gap-4">
          <div className="flex items-center gap-2">
            <span className="text-lg">📅</span>
            <span className="text-sm font-semibold text-slate-200">{displayDate}</span>
          </div>
          <div className="text-xs text-slate-400">
            <span className="text-slate-200 font-semibold">{filteredData?.length || 0}</span> of <span className="text-slate-300">{data?.length || 0}</span> results
            {activeFilters && (activeFilters.tier1Only || activeFilters.checklistPassed || activeFilters.flowLedToMove) && (
              <span className="ml-2 text-yellow-400">
                (Phase 1 filters active)
              </span>
            )}
          </div>
        </div>
        <div className="flex items-center gap-2">
          <Button
            onClick={() => setShowFilters(!showFilters)}
            variant="outline"
            size="sm"
            className="h-8 px-3 text-xs"
          >
            <span className="mr-1.5">{showFilters ? '▼' : '▶'}</span>
            Filters
          </Button>
          <Button 
            onClick={refetch} 
            variant="outline"
            size="sm"
            className="h-8 px-3 text-xs"
          >
            <span className="mr-1.5">🔄</span>
            Refresh
          </Button>
        </div>
      </div>

      {/* Top Trades Summary */}
      {!loading && !error && (
        <div className="bg-gradient-to-r from-blue-500/10 to-purple-500/10 border border-blue-500/30 rounded-lg p-4">
          <div className="flex items-center justify-between mb-3">
            <h3 className="text-sm font-semibold text-slate-200">🏆 TOP 5 TRADES FOR TODAY</h3>
            <span className="text-xs text-slate-400">
              {topTrades.length > 0 
                ? `Filtered: Repeated symbols with 2+ rockets, sorted by highest premium`
                : `No trades found matching criteria (repeated symbols with 2+ rockets)`}
            </span>
          </div>
          {topTrades.length > 0 ? (
            <div className="grid grid-cols-1 md:grid-cols-5 gap-3">
              {topTrades.map((row, idx) => {
              const signal = row.tradeSignal;
              // Use clean symbol extraction (same logic as filtering)
              const symbol = row.symbol_norm || (row.Symbol && row.Symbol.match(/([A-Z]{1,5})\s*·/)?.[1]) || row.Symbol || 'UNKNOWN';
              const score = row.bestTradeScore || 0;
              const hasSignal = signal && signal.signal !== 'NEUTRAL' && signal.signal !== 'WAIT';
              
              return (
                <button
                  key={idx}
                  onClick={() => handleRowClick(row)}
                  className="bg-slate-800/70 hover:bg-slate-800 border border-slate-700 rounded-lg p-3 text-left transition-all hover:border-blue-500/50 hover:shadow-lg"
                >
                  <div className="flex items-center justify-between mb-2">
                    <span className="text-lg font-bold text-slate-100">{symbol}</span>
                    <Badge variant="outline" className="text-xs">
                      #{idx + 1}
                    </Badge>
                  </div>
                  {hasSignal && (
                    <div className="mb-2">
                      <Badge 
                        variant={signal.signal === 'BUY' ? 'success' : 'destructive'}
                        className="text-xs"
                      >
                        {signal.signal === 'BUY' ? '🚀 BUY' : '🔴 SHORT'}
                      </Badge>
                    </div>
                  )}
                  <div className="space-y-1 text-xs">
                    <div className="flex justify-between">
                      <span className="text-slate-500">Score:</span>
                      <span className="text-slate-200 font-semibold">{Math.round(score)}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-slate-500">Confidence:</span>
                      <span className="text-slate-200">{signal?.confidence || '—'}%</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-slate-500">Momentum:</span>
                      <span className="text-slate-200">{row.momentumScore || 0}</span>
                    </div>
                  </div>
                </button>
              );
            })}
            </div>
          ) : (
            <div className="text-center py-8 text-slate-400 text-sm">
              <p>No trades found that meet the criteria:</p>
              <p className="mt-2 text-xs">• Symbol appears more than once in the data</p>
              <p className="text-xs">• Has 2 or more rockets (🚀🚀 or 🚀🚀🚀)</p>
              <p className="text-xs">• Sorted by highest premium</p>
            </div>
          )}
        </div>
      )}

      {/* Filters Section - Always Visible */}
      {showFilters && (
        <div className="bg-slate-900/50 backdrop-blur-sm rounded-lg border border-slate-800/50 p-3 shadow-lg space-y-3">
          {/* Numeric Filters - Compact Single Row */}
          <div className="flex items-center gap-3 flex-wrap">
            <div className="flex items-center gap-2">
              <label className="text-xs text-slate-400">Min Score:</label>
              <Input
                type="number"
                step="0.5"
                min="0"
                value={filters.minScore}
                onChange={(e) => setFilters({...filters, minScore: parseFloat(e.target.value) || 0})}
                className="w-16 h-7 text-xs"
                placeholder="2.0"
              />
            </div>
            <div className="flex items-center gap-2">
              <label className="text-xs text-slate-400">Min Premium:</label>
              <Input
                type="number"
                step="10000"
                min="0"
                value={filters.minPremium}
                onChange={(e) => setFilters({...filters, minPremium: parseInt(e.target.value) || 0})}
                className="w-20 h-7 text-xs"
                placeholder="80K"
              />
            </div>
            <div className="flex items-center gap-2">
              <label className="text-xs text-slate-400">Session:</label>
              <select
                value={filters.session}
                onChange={(e) => setFilters({...filters, session: e.target.value})}
                className="h-7 px-2 bg-slate-800 border border-slate-700 rounded text-xs text-slate-200 focus:outline-none focus:ring-1 focus:ring-slate-500"
              >
                <option value="ALL">All</option>
                <option value="RTH">RTH</option>
                <option value="PRE">Pre</option>
                <option value="POST">Post</option>
              </select>
            </div>
            {/* Noise Filter Toggle */}
            <div className="flex items-center gap-2 ml-2 pl-4 border-l border-slate-700">
              <label className="flex items-center gap-2 cursor-pointer">
                <input
                  type="checkbox"
                  checked={filterNoise}
                  onChange={(e) => setFilterNoise(e.target.checked)}
                  className="w-4 h-4 rounded border-slate-600 bg-slate-800 text-blue-600 focus:ring-2 focus:ring-blue-500"
                />
                <span className="text-xs text-slate-400">Hide Retail Noise</span>
              </label>
              {filterNoise && filteredCount > 0 && (
                <Badge variant="outline" className="text-xs">
                  {filteredCount} signals hidden
                </Badge>
              )}
            </div>
            {/* Phase 1 Data Status Indicator */}
            {data && data.length > 0 && (
              <div className="flex items-center gap-2 ml-2 pl-4 border-l border-slate-700">
                <div className="text-xs">
                  {data[0].signal_tier || data[0].checklist_passed !== undefined ? (
                    <span className="text-green-400">✓ Phase 1 data available - Click "Phase 1" button on cards to check eligibility</span>
                  ) : (
                    <span className="text-yellow-400" title="Phase 1 fields not found in data. Make sure Python service is running and returning Phase 1 fields.">
                      ⚠ No Phase 1 data
                    </span>
                  )}
                </div>
              </div>
            )}
            {/* Date Range - Always Visible */}
            <div className="flex items-center gap-2">
              <label className="text-xs text-slate-400">Start Date:</label>
                  <Input
                    type="date"
                    value={filters.startDate}
                    onChange={(e) => setFilters({...filters, startDate: e.target.value})}
                    className="w-28 h-7 text-xs"
                    max={new Date().toISOString().split('T')[0]}
                  />
            </div>
            <div className="flex items-center gap-2">
              <label className="text-xs text-slate-400">End Date:</label>
                  <Input
                    type="date"
                    value={filters.endDate}
                    onChange={(e) => setFilters({...filters, endDate: e.target.value})}
                    className="w-28 h-7 text-xs"
                    max={new Date().toISOString().split('T')[0]}
                    min={filters.startDate}
                  />
            </div>
            <div className="flex items-center gap-2 ml-auto">
              <Button 
                onClick={handleApplyFilters} 
                variant="outline"
                size="sm"
                className="h-7 px-3 text-xs bg-blue-600/20 border-blue-500/50 text-blue-400 hover:bg-blue-600/30"
              >
                Apply
              </Button>
              <Button 
                onClick={handleResetFilters} 
                variant="outline"
                size="sm"
                className="h-7 px-2 text-xs"
              >
                Reset
              </Button>
            </div>
          </div>
        </div>
      )}

      {/* View Mode Toggle & Column Selector */}
      <div className="flex items-center justify-end gap-2">
        {/* Symbol Filter for Card View */}
        {viewMode === 'cards' && (
          <div className="flex items-center gap-2">
            <label className="text-xs text-slate-400 whitespace-nowrap">Symbol:</label>
            <Input
              type="text"
              placeholder="Filter by symbol..."
              value={cardViewSymbolFilter}
              onChange={(e) => setCardViewSymbolFilter(e.target.value)}
              className="w-32 h-8 text-xs"
            />
            {cardViewSymbolFilter && (
              <Button
                onClick={() => setCardViewSymbolFilter('')}
                variant="ghost"
                size="sm"
                className="h-8 px-2 text-xs"
              >
                ✕
              </Button>
            )}
          </div>
        )}
        <div className="flex items-center gap-2 bg-slate-800/50 rounded-lg p-1">
          <button
            onClick={() => setViewMode('cards')}
            className={cn(
              "px-3 py-1 rounded text-xs font-medium transition-colors",
              viewMode === 'cards' 
                ? "bg-blue-600 text-white" 
                : "text-slate-400 hover:text-slate-200"
            )}
          >
            📋 Cards
          </button>
          <button
            onClick={() => setViewMode('table')}
            className={cn(
              "px-3 py-1 rounded text-xs font-medium transition-colors",
              viewMode === 'table' 
                ? "bg-blue-600 text-white" 
                : "text-slate-400 hover:text-slate-200"
            )}
          >
            📊 Table
          </button>
        </div>
        {viewMode === 'table' && (
          <div className="relative" ref={columnSelectorRef}>
            <Button
              onClick={() => setShowColumnSelector(!showColumnSelector)}
              variant="outline"
              size="sm"
              className="h-8 px-3 text-xs hover:bg-slate-800/50"
            >
              <span className="mr-1.5">👁️</span>
              Columns ({visibleColumns.length}/{allColumns.length})
            </Button>
          
            {showColumnSelector && (
              <div className="absolute top-full right-0 mt-2 bg-slate-900 border border-slate-800 rounded-lg shadow-xl p-4 z-50 min-w-[300px] max-h-96 overflow-y-auto">
                <div className="flex items-center justify-between mb-3">
                  <div className="text-xs font-semibold text-slate-300">Select Columns</div>
                  <button
                    onClick={() => setShowColumnSelector(false)}
                    className="text-slate-500 hover:text-slate-300 text-lg leading-none"
                  >
                    ×
                  </button>
                </div>
                <div className="space-y-3">
                  {Object.entries(COLUMN_GROUPS).map(([groupName, groupColumns]) => (
                    <div key={groupName}>
                      <div className="text-xs font-medium text-slate-400 mb-2 uppercase tracking-wider">
                        {groupName}
                      </div>
                      <div className="space-y-1.5">
                        {allColumns
                          .filter(col => groupColumns.includes(col.accessorKey))
                          .map(col => (
                            <label
                              key={col.accessorKey}
                              className="flex items-center gap-2 cursor-pointer hover:bg-slate-800/50 p-1.5 rounded text-sm text-slate-300 transition-colors"
                            >
                              <input
                                type="checkbox"
                                checked={visibleColumns.includes(col.accessorKey)}
                                onChange={() => toggleColumn(col.accessorKey)}
                                className="w-4 h-4 rounded border-slate-700 bg-slate-800 text-blue-600 focus:ring-2 focus:ring-blue-500"
                              />
                              <span>{col.header}</span>
                            </label>
                          ))}
                      </div>
                    </div>
                  ))}
                </div>
                <div className="flex gap-2 mt-4 pt-4 border-t border-slate-800">
                  <Button
                    onClick={() => setVisibleColumns(DEFAULT_VISIBLE_COLUMNS)}
                    variant="outline"
                    className="h-7 px-3 text-xs flex-1"
                  >
                    Reset
                  </Button>
                  <Button
                    onClick={() => setVisibleColumns(allColumns.map(c => c.accessorKey))}
                    variant="outline"
                    className="h-7 px-3 text-xs flex-1"
                  >
                    Show All
                  </Button>
                </div>
              </div>
            )}
          </div>
        )}
      </div>

      {/* List View */}
      {loading && (
        <div className="flex items-center justify-center py-16">
          <div className="flex flex-col items-center gap-3">
            <div className="w-8 h-8 border-4 border-blue-500 border-t-transparent rounded-full animate-spin"></div>
            <div className="text-slate-400 text-sm">Loading flow data...</div>
          </div>
        </div>
      )}
      
      {error && (
        <div className="bg-red-500/10 border border-red-500/50 rounded-lg p-4">
          <div className="flex items-center gap-2 text-red-400">
            <span>⚠️</span>
            <span className="font-medium">Error loading data</span>
          </div>
          <div className="text-sm text-red-300/80 mt-1">{error}</div>
        </div>
      )}
      
      {!loading && !error && data && data.length === 0 && (
        <div className="bg-slate-900/50 border border-slate-800 rounded-lg p-12 text-center">
          <div className="text-slate-400 text-lg mb-2">No data found</div>
          <div className="text-slate-500 text-sm">
            Try adjusting your filters or date range
          </div>
        </div>
      )}
      
      {!loading && !error && data && data.length > 0 && (
        <div className="relative">
          {viewMode === 'cards' ? (
            <div className="bg-slate-900/50 backdrop-blur-sm border border-slate-800/50 rounded-lg shadow-lg p-4">
              <OptionsFlowCardList
                data={cardViewFilteredData}
                onCardClick={handleRowClick}
                selectedRow={selectedRow}
                reversalsBySymbol={reversalsBySymbol}
                convergencesBySymbol={convergencesBySymbol}
              />
            </div>
          ) : (
            <div className="bg-slate-900/50 backdrop-blur-sm border border-slate-800/50 rounded-lg shadow-lg overflow-hidden">
              <DataTable
                columns={columns}
                data={filteredData}
                className=""
                defaultSort={{ column: 'bestTradeScore', direction: 'desc' }}
                renderExpandedRow={({ row }) => <ExpandedRowDetails row={row.original} />}
                onRowClick={handleRowClick}
                getRowClassName={(row, index) => {
                  // Highlight top 3 trades
                  const isTop3 = index < 3;
                  const baseClass = cn(
                    isTop3 && "bg-gradient-to-r from-blue-500/5 to-purple-500/5 border-l-4",
                    index === 0 && "border-l-yellow-500",
                    index === 1 && "border-l-slate-400",
                    index === 2 && "border-l-orange-500"
                  );
                  
                  // Get flow trend
                  const trend = row.flowTrendRaw || row.flowTrend?.full;
                  const trendValue = trend?.trend || 'STABLE';
                  const minutesAgo = trend?.lastFlowMinutesAgo;
                  
                  // Session-based color coding
                  const session = row.session_bucket || 'RTH';
                  
                  let sessionClass = '';
                  let opacityClass = '';
                  let flowTrendClass = '';
                  
                  // Flow trend-based styling (takes priority over session styling)
                  if (trendValue === 'DEAD') {
                    opacityClass = 'opacity-40';
                  } else if (trendValue === 'FADING') {
                    opacityClass = 'opacity-70';
                  } else if (trendValue === 'SURGING' && !isTop3) {
                    // Add red border for SURGING flows (unless it's already a top 3)
                    flowTrendClass = 'border-l-4 border-l-red-500';
                  }
                  
                  // Fallback: Stale flow (60+ min) - gray out (if not already handled by DEAD)
                  if (trendValue !== 'DEAD' && minutesAgo !== null && minutesAgo >= 60) {
                    opacityClass = 'opacity-50';
                  } else if (!isTop3 && !flowTrendClass) {
                    // Session-based border colors (only if not top 3 and not SURGING)
                    if (session === 'RTH') {
                      sessionClass = 'border-l-2 border-green-500/50';
                    } else if (session === 'PRE') {
                      sessionClass = 'border-l-2 border-yellow-500/50';
                    } else if (session === 'POST') {
                      sessionClass = 'border-l-2 border-blue-500/50';
                    }
                  }
                  
                  return cn(baseClass, sessionClass, opacityClass, flowTrendClass);
                }}
              />
            </div>
          )}
        </div>
      )}

      {/* Detail Panel (for card view) */}
      <OptionsFlowDetailPanel
        row={selectedRow}
        isOpen={isDetailPanelOpen}
        onClose={() => {
          setIsDetailPanelOpen(false);
          setSelectedRow(null);
        }}
      />

      {/* Trade Analysis Modal (for table view) */}
      <TradeAnalysisModal
        row={selectedRow}
        isOpen={isModalOpen}
        onClose={() => {
          setIsModalOpen(false);
          setSelectedRow(null);
        }}
      />
      
      <TradePlanModal
        row={selectedRow}
        isOpen={isTradePlanModalOpen}
        onClose={() => {
          setIsTradePlanModalOpen(false);
          setSelectedRow(null);
        }}
      />
      
      <NoiseWarningModal
        flow={selectedRow}
        isOpen={isNoiseWarningModalOpen}
        onClose={() => {
          setIsNoiseWarningModalOpen(false);
        }}
      />
    </div>
  );
}
