import { Badge } from '@/components/ui/Badge';
import { Button } from '@/components/ui/button';
import { cn } from '@/utils/cn';
import { ChevronRight, CheckCircle2, Clock, FileText } from 'lucide-react';
import { useState } from 'react';
import { Phase1EligibilityModal } from '@/components/tables/Phase1EligibilityModal';
import { TradePlanModal } from './TradePlanModal';

/**
 * Compact card-based list view for options flow
 * Clicking a card expands details to the right
 */
export function OptionsFlowCardList({ data, onCardClick, selectedRow, reversalsBySymbol = {}, convergencesBySymbol = {} }) {
  const [phase1ModalRow, setPhase1ModalRow] = useState(null);
  const [isPhase1ModalOpen, setIsPhase1ModalOpen] = useState(false);
  const [tradePlanModalRow, setTradePlanModalRow] = useState(null);
  const [isTradePlanModalOpen, setIsTradePlanModalOpen] = useState(false);

  const handlePhase1Check = (e, row) => {
    e.stopPropagation(); // Prevent card click
    console.log('Phase 1 button clicked for row:', row.symbol_norm || row.Symbol);
    setPhase1ModalRow(row);
    setIsPhase1ModalOpen(true);
    console.log('Modal state set to open');
  };

  const handleTradePlanClick = (e, row) => {
    e.stopPropagation(); // Prevent card click
    console.log('Trade Plan button clicked for row:', row.symbol_norm || row.Symbol);
    setTradePlanModalRow(row);
    setIsTradePlanModalOpen(true);
  };

  if (!data || data.length === 0) {
    return (
      <div className="p-8 text-center text-slate-400">
        No data available
      </div>
    );
  }

  return (
    <>
    <div className="space-y-2">
      {data.map((row, index) => {
        const symbolNorm = row.symbol_norm || row.Symbol || 'UNKNOWN';
        const symbol = row.Symbol || row.symbol_norm || 'UNKNOWN';
        const symbolDisplay = row.symbolDisplay || (row.Symbol && row.Symbol !== symbolNorm ? row.Symbol : null);
        const badges = row.badges || row.badgesRaw || {};
        const callPut = row.CallPut || row.cp_norm || '';
        const strike = parseFloat(row.Strike || row.strike_num || 0) || 0;
        const spot = parseFloat(row.Spot || row.u_close || row.spot_num || 0) || 0;
        const side = row.Side || '—';
        const volume = row.Volume || row.vol_num || 0;
        const oi = row.OI || row.oi_num || 0;
        const optionPrice = parseFloat(row.Price || 0) || 0;
        const premium = parseFloat(row.premium_num || 0) || 0;
        const score = row.rocketScore || row.rocket_score || 0;
        const rocketDisplay = row.Rocket || row.rocket || '';
        const momentum = row.momentumScore || 0;
        const signal = row.tradeSignal;
        const isSelected = selectedRow && (selectedRow.Symbol === row.Symbol || selectedRow.symbol_norm === row.symbol_norm);
        const volumeHistory = row.volumeHistory || [];
        
        // Date fields
        const createdDate = row.CreatedDate;
        const createdTime = row.CreatedTime;
        const expirationDate = row.ExpirationDate;
        
        // Calculate ITM/OTM
        const moneynessLabel = row.moneynessLabel || row.moneyness || '';
        const moneynessContext = row.moneynessContext;
        const getMoneynessDisplay = () => {
          if (moneynessContext && moneynessContext.category) {
            const category = moneynessContext.category;
            if (category === 'DEEP_ITM' || category === 'ITM') return 'ITM';
            if (category === 'DEEP_OTM' || category === 'EXTREME_OTM' || category === 'OTM') return 'OTM';
            if (category === 'NEAR_ATM') return 'ATM';
          }
          // Fallback calculation
          if (strike > 0 && spot > 0) {
            if (callPut === 'CALL') {
              return strike <= spot ? 'ITM' : 'OTM';
            } else if (callPut === 'PUT') {
              return strike >= spot ? 'ITM' : 'OTM';
            }
          }
          return moneynessLabel || 'N/A';
        };
        const moneynessDisplay = getMoneynessDisplay();
        
        // Format premium
        const premiumDisplay = premium >= 1000000
          ? `$${(premium / 1000000).toFixed(2)}M` 
          : premium >= 1000
          ? `$${(premium / 1000).toFixed(0)}K`
          : `$${premium.toFixed(0)}`;
        
        // Format dates
        const formatCreatedDate = (date) => {
          if (!date) return 'N/A';
          try {
            return new Date(date).toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
          } catch {
            return date;
          }
        };
        
        const formatExpirationDate = (date) => {
          if (!date) return 'N/A';
          try {
            // Handle both ISO format and M/D/YYYY format
            if (typeof date === 'string' && date.includes('/')) {
              return date; // Already in M/D/YYYY format
            }
            return new Date(date).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
          } catch {
            return date;
          }
        };

        // Calculate relative time for created date
        const getRelativeTime = (date) => {
          if (!date) return null;
          try {
            const created = new Date(date);
            const now = new Date();
            const diffTime = now - created;
            const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));
            
            if (diffDays === 0) {
              return 'Today';
            } else if (diffDays === 1) {
              return '1 day old';
            } else {
              return `${diffDays} days old`;
            }
          } catch {
            return null;
          }
        };
        
        const relativeTime = getRelativeTime(createdDate);

        // Check if Phase 1 data exists
        const hasPhase1Data = row.signal_tier !== undefined || row.checklist_passed !== undefined || row.flow_led_to_move !== undefined;

        // Get flow trend data
        const trend = row.flowTrend || row.flowTrendRaw;
        const trendData = trend ? (trend.full || trend) : null;
        const trendValue = trendData?.trend || 'STABLE';
        const minutesAgo = trendData?.lastFlowMinutesAgo;

        // Flow trend configuration with temporal context
        const getFlowTrendConfig = (trendValue, minutesAgo, netPremiumCurrent) => {
          const baseConfig = {
            'SURGING': { 
              icon: '🔥', 
              text: 'SURGING', 
              color: 'text-red-400 font-bold',
              borderClass: 'border-l-4 border-l-red-500'
            },
            'STABLE': { 
              icon: '🟡', 
              text: 'STABLE', 
              color: 'text-yellow-400',
              borderClass: ''
            },
            'FADING': { 
              icon: '⚠️', 
              text: 'FADING', 
              color: 'text-orange-400',
              borderClass: ''
            },
            'DEAD': { 
              icon: '💀', 
              text: 'DEAD', 
              color: 'text-gray-500',
              borderClass: ''
            }
          };
          
          const config = baseConfig[trendValue] || baseConfig['STABLE'];
          
          // Add temporal explanation based on trend
          if (trendValue === 'DEAD') {
            if (minutesAgo !== null && minutesAgo >= 60) {
              const premiumText = netPremiumCurrent >= 1000000 
                ? `$${(netPremiumCurrent / 1000000).toFixed(1)}M premium`
                : `$${(netPremiumCurrent / 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 flowTrendConfig = getFlowTrendConfig(trendValue, minutesAgo, row.premium_num || 0);
        
        // Check for reversal and convergence
        const symbolUpper = (row.symbol_norm || row.Symbol || '').toUpperCase().trim();
        const reversal = reversalsBySymbol[symbolUpper];
        const convergence = convergencesBySymbol[symbolUpper];
        
        // Debug: log convergence detection
        if (convergence) {
          console.log(`🔥 Convergence detected for ${symbolUpper}:`, convergence);
        }

        return (
          <div
            key={`${symbolNorm}-${index}`}
            onClick={() => onCardClick(row)}
            className={cn(
              "bg-slate-800 hover:bg-slate-700 border border-slate-600 rounded-lg p-2 cursor-pointer transition-all relative",
              "hover:border-blue-500/50 hover:shadow-lg",
              isSelected && "border-blue-500 bg-blue-500/10",
              flowTrendConfig.borderClass,
              // Removed opacity dimming - keep all cards bright for better visibility
              reversal && "border-yellow-500 border-2 bg-yellow-900/10",
              convergence && "border-purple-500 border-2 bg-purple-900/30 shadow-purple-500/20"
            )}
          >
            <div className="grid grid-cols-3 gap-3">
              {/* Left Column */}
              <div className="space-y-1.5">
                {/* Symbol with symbolDisplay */}
                <div className="flex flex-col">
                  
                  <div className="flex items-center gap-2 flex-wrap">
                  <div className="font-mono text-3xl font-bold text-slate-100">
                    {symbolNorm}
                    
                  </div>
                  <Badge 
                    className={cn(
                      "text-base px-2.5 py-1 font-bold",
                      callPut === 'CALL' 
                        ? "bg-blue-500/20 text-blue-400 border-blue-500/50" 
                        : "bg-red-500/20 text-red-400 border-red-500/50"
                    )}
                  >
                    {callPut}
                  </Badge>

                  <Badge 
                    variant="outline"
                    className={cn(
                      "text-base px-2.5 py-1 font-bold",
                      moneynessDisplay === 'ITM' || moneynessDisplay === 'Deep ITM'
                        ? "bg-green-500/20 border-green-500/50 text-green-400"
                        : moneynessDisplay === 'OTM' || moneynessDisplay === 'Deep OTM' || moneynessDisplay === 'Extreme OTM'
                        ? "bg-purple-500/20 border-purple-500/50 text-purple-400"
                        : "bg-blue-500/20 border-blue-500/50 text-blue-400"
                    )}
                  >
                    {moneynessDisplay}
                  </Badge>
                  {side !== '—' && (
                    <Badge className="bg-slate-700/50 border-slate-600 text-slate-200">
                      <span className="text-sm text-slate-400">Side:</span>
                      <span className="text-xl font-bold text-slate-100 ml-1">{side}</span>
                    </Badge>
                  )}
                </div>
                  {symbolDisplay && (
                    <div className="font-mono text-sm text-slate-400 mt-0.5">
                      {symbolDisplay}
                    </div>
                  )}
                  {/* Stock Price from Yahoo Finance */}
                  {row.stockPrice && row.stockPrice.currentPrice && (
                    <div className="flex items-center gap-2 mt-1">
                      <span className="font-mono text-base font-semibold text-slate-200">
                        ${(typeof row.stockPrice.currentPrice === 'number' ? row.stockPrice.currentPrice : parseFloat(row.stockPrice.currentPrice) || 0).toFixed(2)}
                      </span>
                      {row.stockPrice.changePercent !== undefined && row.stockPrice.changePercent !== null && (
                        <span className={cn(
                          "text-sm font-semibold",
                          (typeof row.stockPrice.changePercent === 'number' ? row.stockPrice.changePercent : parseFloat(row.stockPrice.changePercent) || 0) >= 0 
                            ? "text-green-400" 
                            : "text-red-400"
                        )}>
                          {(typeof row.stockPrice.changePercent === 'number' ? row.stockPrice.changePercent : parseFloat(row.stockPrice.changePercent) || 0) >= 0 ? '+' : ''}
                          {(typeof row.stockPrice.changePercent === 'number' ? row.stockPrice.changePercent : parseFloat(row.stockPrice.changePercent) || 0).toFixed(2)}%
                        </span>
                      )}
                      {row.stockPrice.change !== undefined && row.stockPrice.change !== null && (
                        <span className={cn(
                          "text-sm",
                          (typeof row.stockPrice.change === 'number' ? row.stockPrice.change : parseFloat(row.stockPrice.change) || 0) >= 0 
                            ? "text-green-400" 
                            : "text-red-400"
                        )}>
                          ({(typeof row.stockPrice.change === 'number' ? row.stockPrice.change : parseFloat(row.stockPrice.change) || 0) >= 0 ? '+' : ''}
                          {(typeof row.stockPrice.change === 'number' ? row.stockPrice.change : parseFloat(row.stockPrice.change) || 0).toFixed(2)})
                        </span>
                      )}
                    </div>
                  )}
                </div>

                {/* Badges */}
                <div className="flex items-center gap-1 flex-wrap">
                  {badges.round && (
                    <span className="text-xl" title="Round lot">{badges.round}</span>
                  )}
                  {badges.more && (
                    <span className="text-lg" title="Additional badges">{badges.more}</span>
                  )}
                  {badges.flash && (
                    <span className="text-lg" title="Flash">{badges.flash}</span>
                  )}
                  {reversal && (
                    <Badge variant="warning" className="animate-pulse text-sm font-bold">
                      🔄 REVERSAL
                    </Badge>
                  )}
                  {convergence && (
                    <Badge 
                      variant="destructive" 
                      className="animate-pulse text-base font-bold px-2.5 py-1 bg-gradient-to-r from-purple-600/90 to-pink-600/90 border-2 border-purple-400 text-white shadow-lg"
                    >
                      🔥 {convergence.signalCount} SIGNALS
                    </Badge>
                  )}
                </div>

                {/* Strike, Spot, Option Price - Grouped */}
                <div className="grid grid-cols-3 gap-2 text-sm">
                  {strike > 0 && (
                    <div className="flex flex-col">
                      <span className="text-slate-500 text-xs">Strike</span>
                      <span className="text-slate-200 font-mono font-bold text-base">${strike.toFixed(2)}</span>
                    </div>
                  )}
                  {spot > 0 && (
                    <div className="flex flex-col">
                      <span className="text-slate-500 text-xs">Spot</span>
                      <span className="text-slate-200 font-mono font-bold text-base">${spot.toFixed(2)}</span>
                    </div>
                  )}
                  {optionPrice > 0 && (
                    <div className="flex flex-col">
                      <span className="text-slate-500 text-xs">Option</span>
                      <span className="text-slate-200 font-mono font-bold text-base">${optionPrice.toFixed(3)}</span>
                    </div>
                  )}
                </div>

                {/* Volume and Score */}
                <div className="space-y-1 text-sm">
                  {volume > 0 && (
                    <div className="flex items-center gap-1.5">
                      <span className="text-slate-500">Volume:</span>
                      <span className="text-slate-200 font-mono font-semibold">{volume.toLocaleString()} contracts</span>
                    </div>
                  )}
                  {oi > 0 && (
                    <div className="flex items-center gap-1.5">
                      <span className="text-slate-500">OI:</span>
                      <span className="text-slate-200 font-mono font-semibold">{oi.toLocaleString()}</span>
                    </div>
                  )}
                </div>
              </div>

              {/* Middle Column */}
              <div className="space-y-1.5">
                {/* Premium */}
                <div className="flex items-center gap-2 flex-wrap">
                  {premium > 0 && (
                    <div className="flex items-center gap-1.5">
                      <span className="text-sm text-slate-500">Premium:</span>
                      <span className="text-lg font-bold text-slate-100">{premiumDisplay}</span>
                    </div>
                  )}
                </div>

                {/* Flow Trend - VISUALLY DOMINANT */}
                {trendData && (
                  <div className={cn(
                    "flex flex-col gap-0.5 text-sm p-1.5 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"
                  )}>
                    <div className="flex items-center gap-2" title={flowTrendConfig.tooltip}>
                      <span className={cn(
                        "text-xl font-bold",
                        trendValue === 'SURGING' && "text-red-400 animate-pulse",
                        trendValue === 'DEAD' && "text-gray-500",
                        trendValue === 'FADING' && "text-orange-400",
                        trendValue === 'STABLE' && "text-yellow-400"
                      )}>
                        {flowTrendConfig.icon}
                      </span>
                      <span className={cn(
                        "font-bold text-base uppercase tracking-wide",
                        flowTrendConfig.color
                      )}>
                        {flowTrendConfig.text}
                      </span>
                    </div>
                    {/* Show temporal explanation for DEAD/FADING */}
                    {(trendValue === 'DEAD' || trendValue === 'FADING') && flowTrendConfig.temporalExplanation && (
                      <div className="text-sm text-slate-400 italic pl-8">
                        {flowTrendConfig.temporalExplanation}
                      </div>
                    )}
                  </div>
                )}

                {/* Momentum */}
                {momentum > 0 && (
                  <div className="flex items-center gap-1.5 text-sm">
                    <span className="text-slate-500">Momentum:</span>
                    <div className={cn(
                      "text-sm font-bold px-2 py-0.5 rounded",
                      momentum >= 70 ? "text-green-400 bg-green-400/10" :
                      momentum >= 50 ? "text-yellow-400 bg-yellow-400/10" :
                      "text-orange-400 bg-orange-400/10"
                    )}>
                      {momentum}
                    </div>
                  </div>
                )}

                {/* Phase 1: Institutional Analytics */}
                {(row.confidence_score !== null && row.confidence_score !== undefined) ||
                 (row.signal_strength !== null && row.signal_strength !== undefined) ||
                 (row.relative_premium_score !== null && row.relative_premium_score !== undefined) ? (
                  <div className="flex flex-col gap-1 text-xs pt-1 border-t border-slate-700/50">
                    <div className="text-slate-500 font-semibold uppercase tracking-wide text-[10px]">🏛️ Institutional</div>
                    <div className="grid grid-cols-3 gap-1.5">
                      {row.confidence_score !== null && row.confidence_score !== undefined && (
                        <div className="flex flex-col gap-0.5">
                          <span className="text-[10px] text-slate-500">Confidence</span>
                          <div className="flex items-center gap-1">
                            <div className="flex-1 bg-slate-800 rounded-full h-1">
                              <div 
                                className={cn(
                                  "h-1 rounded-full",
                                  (typeof row.confidence_score === 'number' ? row.confidence_score : parseFloat(row.confidence_score) || 0) >= 70 ? "bg-green-500" :
                                  (typeof row.confidence_score === 'number' ? row.confidence_score : parseFloat(row.confidence_score) || 0) >= 50 ? "bg-yellow-500" :
                                  "bg-orange-500"
                                )}
                                style={{ width: `${Math.min(100, typeof row.confidence_score === 'number' ? row.confidence_score : parseFloat(row.confidence_score) || 0)}%` }}
                              />
                            </div>
                            <span className={cn(
                              "text-[10px] font-bold w-8 text-right",
                              (typeof row.confidence_score === 'number' ? row.confidence_score : parseFloat(row.confidence_score) || 0) >= 70 ? 'text-green-400' :
                              (typeof row.confidence_score === 'number' ? row.confidence_score : parseFloat(row.confidence_score) || 0) >= 50 ? 'text-yellow-400' :
                              'text-orange-400'
                            )}>
                              {Math.round(typeof row.confidence_score === 'number' ? row.confidence_score : parseFloat(row.confidence_score) || 0)}%
                            </span>
                          </div>
                        </div>
                      )}
                      {row.signal_strength !== null && row.signal_strength !== undefined && (
                        <div className="flex flex-col gap-0.5">
                          <span className="text-[10px] text-slate-500">Strength</span>
                          <div className="flex items-center gap-1">
                            <div className="flex-1 bg-slate-800 rounded-full h-1">
                              <div 
                                className={cn(
                                  "h-1 rounded-full",
                                  (typeof row.signal_strength === 'number' ? row.signal_strength : parseFloat(row.signal_strength) || 0) >= 70 ? "bg-purple-500" :
                                  (typeof row.signal_strength === 'number' ? row.signal_strength : parseFloat(row.signal_strength) || 0) >= 50 ? "bg-blue-500" :
                                  "bg-slate-500"
                                )}
                                style={{ width: `${Math.min(100, typeof row.signal_strength === 'number' ? row.signal_strength : parseFloat(row.signal_strength) || 0)}%` }}
                              />
                            </div>
                            <span className={cn(
                              "text-[10px] font-bold w-6 text-right",
                              (typeof row.signal_strength === 'number' ? row.signal_strength : parseFloat(row.signal_strength) || 0) >= 70 ? 'text-purple-400' :
                              (typeof row.signal_strength === 'number' ? row.signal_strength : parseFloat(row.signal_strength) || 0) >= 50 ? 'text-blue-400' :
                              'text-slate-400'
                            )}>
                              {Math.round(typeof row.signal_strength === 'number' ? row.signal_strength : parseFloat(row.signal_strength) || 0)}
                            </span>
                          </div>
                        </div>
                      )}
                      {row.relative_premium_score !== null && row.relative_premium_score !== undefined && (
                        <div className="flex flex-col gap-0.5">
                          <span className="text-[10px] text-slate-500">Rel. Prem</span>
                          <div className="flex items-center gap-1">
                            <div className="flex-1 bg-slate-800 rounded-full h-1">
                              <div 
                                className={cn(
                                  "h-1 rounded-full",
                                  (typeof row.relative_premium_score === 'number' ? row.relative_premium_score : parseFloat(row.relative_premium_score) || 0) >= 70 ? "bg-green-500" :
                                  (typeof row.relative_premium_score === 'number' ? row.relative_premium_score : parseFloat(row.relative_premium_score) || 0) >= 50 ? "bg-yellow-500" :
                                  "bg-orange-500"
                                )}
                                style={{ width: `${Math.min(100, typeof row.relative_premium_score === 'number' ? row.relative_premium_score : parseFloat(row.relative_premium_score) || 0)}%` }}
                              />
                            </div>
                            <span className={cn(
                              "text-[10px] font-bold w-6 text-right",
                              (typeof row.relative_premium_score === 'number' ? row.relative_premium_score : parseFloat(row.relative_premium_score) || 0) >= 70 ? 'text-green-400' :
                              (typeof row.relative_premium_score === 'number' ? row.relative_premium_score : parseFloat(row.relative_premium_score) || 0) >= 50 ? 'text-yellow-400' :
                              'text-orange-400'
                            )}>
                              {Math.round(typeof row.relative_premium_score === 'number' ? row.relative_premium_score : parseFloat(row.relative_premium_score) || 0)}
                            </span>
                          </div>
                        </div>
                      )}
                    </div>
                  </div>
                ) : null}

                {/* Phase 3: Dealer & Regime Analytics */}
                {(row.dealer_hedge_pressure_score !== null && row.dealer_hedge_pressure_score !== undefined) ||
                 row.market_regime || row.volatility_intent ? (
                  <div className="flex flex-col gap-1 text-xs pt-1 border-t border-slate-700/50">
                    <div className="text-slate-500 font-semibold uppercase tracking-wide text-[10px]">🎯 Dealer & Regime</div>
                    <div className="flex flex-wrap gap-1.5">
                      {row.dealer_hedge_pressure_score !== null && row.dealer_hedge_pressure_score !== undefined && (
                        <div className="flex items-center gap-1">
                          <span className="text-[10px] text-slate-500">Pressure:</span>
                          <span className={cn(
                            "text-[10px] font-bold",
                            (typeof row.dealer_hedge_pressure_score === 'number' ? row.dealer_hedge_pressure_score : parseFloat(row.dealer_hedge_pressure_score) || 0) >= 70 ? "text-red-400" :
                            (typeof row.dealer_hedge_pressure_score === 'number' ? row.dealer_hedge_pressure_score : parseFloat(row.dealer_hedge_pressure_score) || 0) >= 50 ? "text-orange-400" :
                            "text-yellow-400"
                          )}>
                            {Math.round(typeof row.dealer_hedge_pressure_score === 'number' ? row.dealer_hedge_pressure_score : parseFloat(row.dealer_hedge_pressure_score) || 0)}
                          </span>
                        </div>
                      )}
                      {row.market_regime && (
                        <Badge 
                          variant="outline"
                          className={cn(
                            "text-[10px] px-1.5 py-0",
                            row.market_regime === 'TREND' ? "bg-green-500/20 border-green-500/50 text-green-400" :
                            row.market_regime === 'RANGE' ? "bg-yellow-500/20 border-yellow-500/50 text-yellow-400" :
                            "bg-red-500/20 border-red-500/50 text-red-400"
                          )}
                        >
                          {row.market_regime === 'TREND' ? '📈' : row.market_regime === 'RANGE' ? '↔️' : '⚡'} {row.market_regime}
                        </Badge>
                      )}
                      {row.volatility_intent && (
                        <Badge 
                          variant="outline"
                          className={cn(
                            "text-[10px] px-1.5 py-0",
                            row.volatility_intent === 'LONG_VOL' ? "bg-green-500/20 border-green-500/50 text-green-400" :
                            row.volatility_intent === 'SHORT_VOL' ? "bg-red-500/20 border-red-500/50 text-red-400" :
                            row.volatility_intent === 'DIRECTIONAL' ? "bg-blue-500/20 border-blue-500/50 text-blue-400" :
                            "bg-orange-500/20 border-orange-500/50 text-orange-400"
                          )}
                        >
                          {row.volatility_intent === 'LONG_VOL' ? '📊' : row.volatility_intent === 'SHORT_VOL' ? '📉' : row.volatility_intent === 'DIRECTIONAL' ? '➡️' : '🔄'} {row.volatility_intent.replace('_', '/')}
                        </Badge>
                      )}
                    </div>
                  </div>
                ) : null}

                {/* Time-Sequenced Metrics */}
                {(row.flow_acceleration !== null && row.flow_acceleration !== undefined) ||
                 (row.time_between_hits !== null && row.time_between_hits !== undefined) ||
                 (row.follow_on_ratio !== null && row.follow_on_ratio !== undefined) ||
                 row.strike_laddering_detected ? (
                  <div className="flex flex-col gap-1 text-xs pt-1 border-t border-slate-700/50">
                    <div className="text-slate-500 font-semibold uppercase tracking-wide text-[10px]">⏱️ Time-Sequenced</div>
                    <div className="grid grid-cols-2 gap-1 text-[10px]">
                      {row.flow_acceleration !== null && row.flow_acceleration !== undefined && (
                        <div className="flex items-center gap-1">
                          <span className="text-slate-500">Accel:</span>
                          <span className={cn(
                            "font-bold",
                            (typeof row.flow_acceleration === 'number' ? row.flow_acceleration : parseFloat(row.flow_acceleration) || 0) > 0 ? "text-green-400" : "text-red-400"
                          )}>
                            {(typeof row.flow_acceleration === 'number' ? row.flow_acceleration : parseFloat(row.flow_acceleration) || 0) >= 1e6 
                              ? `${((typeof row.flow_acceleration === 'number' ? row.flow_acceleration : parseFloat(row.flow_acceleration) || 0) / 1e6).toFixed(1)}M/min`
                              : `${((typeof row.flow_acceleration === 'number' ? row.flow_acceleration : parseFloat(row.flow_acceleration) || 0) / 1e3).toFixed(0)}K/min`}
                          </span>
                        </div>
                      )}
                      {row.time_between_hits !== null && row.time_between_hits !== undefined && (
                        <div className="flex items-center gap-1">
                          <span className="text-slate-500">Gap:</span>
                          <span className="text-slate-300 font-semibold">
                            {(typeof row.time_between_hits === 'number' ? row.time_between_hits : parseFloat(row.time_between_hits) || 0).toFixed(1)}m
                          </span>
                        </div>
                      )}
                      {row.follow_on_ratio !== null && row.follow_on_ratio !== undefined && (
                        <div className="flex items-center gap-1">
                          <span className="text-slate-500">Follow:</span>
                          <span className={cn(
                            "font-bold",
                            (typeof row.follow_on_ratio === 'number' ? row.follow_on_ratio : parseFloat(row.follow_on_ratio) || 0) >= 0.7 ? "text-green-400" :
                            (typeof row.follow_on_ratio === 'number' ? row.follow_on_ratio : parseFloat(row.follow_on_ratio) || 0) >= 0.4 ? "text-yellow-400" :
                            "text-red-400"
                          )}>
                            {((typeof row.follow_on_ratio === 'number' ? row.follow_on_ratio : parseFloat(row.follow_on_ratio) || 0) * 100).toFixed(0)}%
                          </span>
                        </div>
                      )}
                      {row.strike_laddering_detected !== null && row.strike_laddering_detected !== undefined && row.strike_laddering_detected && (
                        <div className="flex items-center gap-1">
                          <span className="text-slate-500">Ladder:</span>
                          <span className="text-green-400 font-bold">✅</span>
                        </div>
                      )}
                    </div>
                  </div>
                ) : null}

                {/* Signal */}
                {signal && signal.signal !== 'NEUTRAL' && signal.signal !== 'WAIT' && (
                  <div className="flex items-center gap-1.5 text-sm">
                    <span className="text-slate-500">Signal:</span>
                    <Badge 
                      variant={signal.signal === 'BUY' ? 'success' : 'destructive'}
                      className="text-sm px-2 py-0.5"
                    >
                      {signal.signal === 'BUY' ? '🚀' : '🔴'}
                    </Badge>
                  </div>
                )}

                {/* Trade Plan Display */}
                {row.tradePlan && row.tradePlanDisplay && (
                  <div className="flex flex-col gap-1 text-sm">
                    <div className="flex items-center gap-1.5">
                      <span className="text-slate-500">Trade Plan:</span>
                      <Badge 
                        className={cn(
                          "text-sm px-2 py-0.5 font-semibold cursor-pointer",
                          row.tradePlan.signal === 'BUY' 
                            ? "bg-green-500/20 text-green-400 border-green-500/50 hover:bg-green-500/30"
                            : row.tradePlan.signal === 'SELL'
                            ? "bg-red-500/20 text-red-400 border-red-500/50 hover:bg-red-500/30"
                            : "bg-yellow-500/20 text-yellow-400 border-yellow-500/50 hover:bg-yellow-500/30"
                        )}
                        onClick={(e) => {
                          e.stopPropagation();
                          handleTradePlanClick(e, row);
                        }}
                        title={row.tradePlan.signal === 'WAIT' && row.tradePlan.reasoning?.why?.length > 0 
                          ? row.tradePlan.reasoning.why.join('; ') 
                          : row.tradePlanDisplay}
                      >
                        {row.tradePlanDisplay}
                      </Badge>
                    </div>
                    {/* Show first wait reason as tooltip/subtitle */}
                    {row.tradePlan.signal === 'WAIT' && row.tradePlan.reasoning?.why?.length > 0 && (
                      <div className="text-sm text-yellow-300/70 pl-1 italic">
                        {row.tradePlan.reasoning.why[0]}
                      </div>
                    )}
                  </div>
                )}
              </div>
              {/* Right Column */}
              <div className="space-y-1.5">
                {/* Rockets at top */}
                {rocketDisplay && (
                  <div className="flex justify-end">
                    <span className="text-2xl">{rocketDisplay}</span>
                  </div>
                )}
                
                {/* Dates - More Prominent */}
                <div className="space-y-1.5">
                  {createdDate && (
                    <div className="flex flex-col gap-0.5">
                      <div className="flex items-center gap-2 flex-wrap">
                        <span className="text-sm font-semibold text-slate-400 uppercase tracking-wide">Created:</span>
                        <span className="text-base font-bold text-slate-100">
                          {formatCreatedDate(createdDate)}
                        </span>
                        {createdTime && (
                          <span className="text-sm font-mono text-slate-300">
                            {createdTime}
                          </span>
                        )}
                      </div>
                      {relativeTime && (
                        <div className={cn(
                          "text-sm font-semibold",
                          relativeTime === 'Today' ? "text-green-400" :
                          relativeTime === '1 day old' ? "text-yellow-400" :
                          "text-orange-400"
                        )}>
                          {relativeTime}
                        </div>
                      )}
                    </div>
                  )}
                  {expirationDate && (
                    <div className="flex flex-col gap-0.5">
                      <div className="flex items-center gap-2 flex-wrap">
                        <span className="text-sm font-semibold text-slate-400 uppercase tracking-wide">Expires:</span>
                        <Badge 
                          variant="outline"
                          className={cn(
                            "text-base px-2.5 py-1 font-bold",
                            "bg-slate-800/50 border-slate-600 text-slate-100"
                          )}
                        >
                          {formatExpirationDate(expirationDate)}
                        </Badge>
                      </div>
                    </div>
                  )}
                </div>

                {/* Phase 1 Check Button, Trade Plan Button, and Wait Button */}
                <div className="flex justify-end gap-1.5 pt-1 relative z-10 flex-wrap">
                  {/* Wait Button - Show when signal is WAIT or no signal */}
                  {(signal?.signal === 'WAIT' || !signal || signal.signal === 'NEUTRAL') && (
                    <Button
                      onClick={(e) => {
                        e.preventDefault();
                        e.stopPropagation();
                        console.log('Wait button clicked for row:', row.symbol_norm || row.Symbol);
                        // Could open a modal or show wait reasoning
                      }}
                      variant="outline"
                      size="sm"
                      className={cn(
                        "h-8 px-2.5 text-sm relative z-10",
                        "bg-yellow-500/20 border-yellow-500/50 text-yellow-400 hover:bg-yellow-500/30"
                      )}
                      title="Wait for confirmation - Signal not clear or price not confirming flow"
                      type="button"
                    >
                      <Clock className="w-3.5 h-3.5 mr-1" />
                      Wait
                    </Button>
                  )}
                  
                  {/* Trade Plan Button - Always show, but disabled if no trade plan */}
                  <Button
                    onClick={(e) => {
                      e.preventDefault();
                      e.stopPropagation();
                      if (row.tradePlan) {
                        handleTradePlanClick(e, row);
                      }
                    }}
                    variant="outline"
                    size="sm"
                    disabled={!row.tradePlan}
                    className={cn(
                      "h-8 px-2.5 text-sm relative z-10",
                      row.tradePlan 
                        ? (row.tradePlan.signal === 'BUY'
                          ? "bg-green-500/20 border-green-500/50 text-green-400 hover:bg-green-500/30"
                          : row.tradePlan.signal === 'SELL'
                          ? "bg-red-500/20 border-red-500/50 text-red-400 hover:bg-red-500/30"
                          : "bg-yellow-500/20 border-yellow-500/50 text-yellow-400 hover:bg-yellow-500/30")
                        : "bg-slate-700/50 border-slate-600 text-slate-400 hover:bg-slate-700 opacity-50 cursor-not-allowed"
                    )}
                    title={row.tradePlan 
                      ? "View complete trade plan with entry, stop, targets, and reasoning"
                      : "Trade plan not available (rocket score < 2 or generation failed)"}
                    type="button"
                  >
                    <FileText className="w-3.5 h-3.5 mr-1" />
                    Trade Plan
                  </Button>
                  
                  {/* Phase 1 Check Button */}
                  <Button
                    onClick={(e) => {
                      e.preventDefault();
                      e.stopPropagation();
                      handlePhase1Check(e, row);
                    }}
                    variant="outline"
                    size="sm"
                    className={cn(
                      "h-8 px-2.5 text-sm relative z-10",
                      hasPhase1Data 
                        ? "bg-blue-500/20 border-blue-500/50 text-blue-400 hover:bg-blue-500/30"
                        : "bg-slate-700/50 border-slate-600 text-slate-400 hover:bg-slate-700"
                    )}
                    title={hasPhase1Data ? "Check Phase 1 Eligibility" : "Phase 1 data not available"}
                    type="button"
                  >
                    <CheckCircle2 className="w-3.5 h-3.5 mr-1" />
                    Phase 1
                  </Button>
                </div>
              </div>
            </div>
          </div>
        );
      })}
    </div>

      {/* Phase 1 Eligibility Modal */}
      {isPhase1ModalOpen && phase1ModalRow && (
        <Phase1EligibilityModal
          row={phase1ModalRow}
          isOpen={isPhase1ModalOpen}
          onClose={() => {
            setIsPhase1ModalOpen(false);
            setPhase1ModalRow(null);
          }}
        />
      )}

      {/* Trade Plan Modal */}
      {isTradePlanModalOpen && tradePlanModalRow && (
        <TradePlanModal
          row={tradePlanModalRow}
          isOpen={isTradePlanModalOpen}
          onClose={() => {
            setIsTradePlanModalOpen(false);
            setTradePlanModalRow(null);
          }}
        />
      )}
    </>
  );
}
