import { useState, useEffect } from 'react';
import { Badge } from '@/components/ui/Badge';
import { Button } from '@/components/ui/button';
import { cn } from '@/utils/cn';
import { X, Copy, Check } from 'lucide-react';

/**
 * Trade Plan Modal
 * Displays complete trade plan with entry, stop loss, targets, reasoning, etc.
 */
export function TradePlanModal({ row, isOpen, onClose }) {
  const [copied, setCopied] = useState(false);
  
  // Scroll to top when modal opens
  useEffect(() => {
    if (isOpen) {
      // Scroll to top smoothly
      window.scrollTo({ top: 0, behavior: 'smooth' });
    }
  }, [isOpen]);
  
  if (!isOpen || !row || !row.tradePlan) return null;

  const plan = row.tradePlan;
  const symbol = plan.symbol || row.symbol_norm || row.Symbol || 'UNKNOWN';
  const signal = plan.signal || 'WAIT';
  const confidence = plan.confidence || 0;
  
  // Use readiness from plan object (no hardcoded calculation)
  const displayPercentage = signal === 'WAIT' 
    ? (plan.readiness !== undefined ? plan.readiness : confidence)
    : confidence;

  // Calculate entry price for conditional stops/targets (even for WAIT signals)
  // For WAIT signals, use current price since there's no entry yet
  const getEntryPrice = () => {
    if (plan.entry?.primary) {
      const primaryPrice = parseFloat(plan.entry.primary);
      if (!isNaN(primaryPrice) && primaryPrice > 0) return primaryPrice;
    }
    // For WAIT signals or when no entry, use current price from row
    const currentPrice = parseFloat(row.u_close || row.spot_num || row.last_px || row.Price || 0) || 0;
    return currentPrice;
  };

  const entryPrice = getEntryPrice();
  const direction = row.direction || (signal === 'BUY' ? 'BULL' : signal === 'SELL' ? 'BEAR' : 'BULL');
  const isBullish = direction === 'BULL' || signal === 'BUY';

  // Calculate stop loss even if not in plan (for WAIT signals)
  const getStopLoss = () => {
    if (plan.stopLoss?.tight) {
      return {
        tight: parseFloat(plan.stopLoss.tight) || null,
        wide: parseFloat(plan.stopLoss.wide) || null,
        reasoning: plan.stopLoss.reasoning || ''
      };
    }
    
    if (!entryPrice || entryPrice === 0) return { tight: null, wide: null, reasoning: '' };
    
    // Validate OR values are reasonable (within 10% of current price)
    let orLow = parseFloat(row.or_low);
    let orHigh = parseFloat(row.or_high);
    
    if (orLow && Math.abs(orLow - entryPrice) / entryPrice > 0.10) {
      orLow = null; // Stale data, ignore it
    }
    if (orHigh && Math.abs(orHigh - entryPrice) / entryPrice > 0.10) {
      orHigh = null; // Stale data, ignore it
    }
    
    if (isBullish) {
      const tight = entryPrice * 0.985; // -1.5%
      const wide = orLow && orLow < entryPrice ? orLow : (entryPrice * 0.975); // OR low or -2.5%
      return {
        tight: tight,
        wide: wide,
        reasoning: 'Tight stop at -1.5% for quick exit. Wide stop below opening range low or -2.5%.'
      };
    } else {
      const tight = entryPrice * 1.015; // +1.5%
      const wide = orHigh && orHigh > entryPrice ? orHigh : (entryPrice * 1.025); // OR high or +2.5%
      return {
        tight: tight,
        wide: wide,
        reasoning: 'Tight stop at +1.5% for quick exit. Wide stop above opening range high or +2.5%.'
      };
    }
  };

  // Calculate targets even if not in plan
  const getTargets = () => {
    if (plan.targets?.t1?.price) {
      return plan.targets;
    }
    
    if (!entryPrice || entryPrice === 0) return { t1: {}, t2: {}, t3: {} };
    
    const strike = parseFloat(row.strike_num || row.Strike) || null;
    
    // Validate strike price is reasonable (within 20% of entry price)
    const isStrikeReasonable = strike && entryPrice > 0 && 
      Math.abs(strike - entryPrice) / entryPrice <= 0.20;
    
    if (isBullish) {
      const t1Price = entryPrice * 1.015; // +1.5%
      const t2Price = entryPrice * 1.025; // +2.5%
      // Only use strike if it's reasonable and above entry
      const t3Price = (isStrikeReasonable && strike > entryPrice) 
        ? strike 
        : (entryPrice * 1.04); // +4% default
      
      return {
        t1: { price: t1Price.toFixed(2), percentage: 50, gain: '+1.5%' },
        t2: { price: t2Price.toFixed(2), percentage: 30, gain: '+2.5%' },
        t3: { price: t3Price.toFixed(2), percentage: 20, gain: (isStrikeReasonable && strike > entryPrice) 
          ? ((t3Price - entryPrice) / entryPrice * 100).toFixed(1) + '%' 
          : '+4.0%' }
      };
    } else {
      const t1Price = entryPrice * 0.985; // -1.5%
      const t2Price = entryPrice * 0.975; // -2.5%
      // Only use strike if it's reasonable and below entry
      const t3Price = (isStrikeReasonable && strike < entryPrice) 
        ? strike 
        : (entryPrice * 0.96); // -4% default
      
      return {
        t1: { price: t1Price.toFixed(2), percentage: 50, gain: '-1.5%' },
        t2: { price: t2Price.toFixed(2), percentage: 30, gain: '-2.5%' },
        t3: { price: t3Price.toFixed(2), percentage: 20, gain: (isStrikeReasonable && strike < entryPrice) 
          ? ((entryPrice - t3Price) / entryPrice * 100).toFixed(1) + '%' 
          : '-4.0%' }
      };
    }
  };

  const stopLoss = getStopLoss();
  const targets = getTargets();
  
  // Calculate risk/reward ratio
  const calculateRiskReward = () => {
    if (!entryPrice || entryPrice === 0 || !stopLoss.tight) {
      return { risk: null, reward: null, ratio: null };
    }
    
    const stopPrice = stopLoss.tight;
    const targetPrice = targets.t1?.price ? parseFloat(targets.t1.price) : null;
    
    if (!targetPrice) return { risk: null, reward: null, ratio: null };
    
    const risk = isBullish 
      ? entryPrice - stopPrice 
      : stopPrice - entryPrice;
    const reward = isBullish
      ? targetPrice - entryPrice
      : entryPrice - targetPrice;
    
    const riskPct = (risk / entryPrice * 100).toFixed(2);
    const rewardPct = (reward / entryPrice * 100).toFixed(2);
    const ratio = risk > 0 ? (reward / risk).toFixed(2) : null;
    
    return {
      risk: risk.toFixed(2),
      reward: reward.toFixed(2),
      riskPct: riskPct,
      rewardPct: rewardPct,
      ratio: ratio ? parseFloat(ratio) : null,
      stopPrice: stopPrice,
      targetPrice: targetPrice
    };
  };

  const riskReward = calculateRiskReward();

  const copyToClipboard = () => {
    const planText = formatTradePlanForClipboard(plan);
    navigator.clipboard.writeText(planText).then(() => {
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    });
  };

  const getSignalColor = () => {
    if (signal === 'BUY') return 'text-green-400 bg-green-500/20 border-green-500/50';
    if (signal === 'SELL') return 'text-red-400 bg-red-500/20 border-red-500/50';
    return 'text-yellow-400 bg-yellow-500/20 border-yellow-500/50';
  };

  const getSignalEmoji = () => {
    if (signal === 'BUY') return '🚀';
    if (signal === 'SELL') return '🔴';
    return '⏸';
  };

  return (
    <div 
      className="fixed inset-0 bg-black/80 backdrop-blur-sm flex items-start justify-center p-4 overflow-y-auto"
      style={{ zIndex: 9999 }}
      onClick={(e) => {
        // Close on backdrop click
        if (e.target === e.currentTarget) {
          onClose();
        }
      }}
    >
      <div className="w-full max-w-6xl my-2 bg-slate-900 border border-slate-800 rounded-lg shadow-2xl overflow-hidden flex flex-col max-h-[calc(100vh-1rem)]">
        {/* Header */}
        <div className="flex items-center justify-between p-3 border-b border-slate-800 bg-slate-950/50 flex-shrink-0">
          <div className="flex items-center gap-3">
            <div>
              <h2 className="text-xl font-bold text-slate-100">Trade Plan: {symbol}</h2>
              <div className="flex items-center gap-2 mt-1">
                <Badge className={cn("text-xs font-semibold", getSignalColor())}>
                  {getSignalEmoji()} {signal} {displayPercentage}%
                  {signal === 'WAIT' && <span className="ml-1 text-xs opacity-75">ready</span>}
                </Badge>
                {plan.score && (
                  <Badge className="bg-blue-500/20 text-blue-400 border-blue-500/50 text-xs">
                    Score: {plan.score.toFixed(1)}
                  </Badge>
                )}
              </div>
            </div>
          </div>
          <div className="flex items-center gap-2">
            <Button
              variant="outline"
              size="sm"
              onClick={copyToClipboard}
              className="text-slate-300 border-slate-700 hover:bg-slate-800 h-8 px-3 text-xs"
            >
              {copied ? (
                <>
                  <Check className="w-3 h-3 mr-1" />
                  Copied!
                </>
              ) : (
                <>
                  <Copy className="w-3 h-3 mr-1" />
                  Copy
                </>
              )}
            </Button>
            <Button
              variant="ghost"
              size="sm"
              onClick={onClose}
              className="text-slate-400 hover:text-slate-200 h-8 w-8 p-0"
            >
              <X className="w-4 h-4" />
            </Button>
          </div>
        </div>

        {/* Content - Section-Based Layout */}
        <div className="flex-1 overflow-y-auto p-2">
          <div className="space-y-3 pb-4">
            {/* Entry + Time Grouped */}
            <div className="bg-slate-800/50 rounded-lg p-2 border border-slate-700/50">
              <div className="grid grid-cols-2 gap-3">
                {/* Entry Strategy */}
                <div>
                  <h3 className="text-sm font-semibold text-yellow-400 mb-1.5">⚡ Entry Strategy</h3>
                  {signal === 'WAIT' && plan.entry?.conditionalTriggers && plan.entry.conditionalTriggers.length > 0 ? (
                    <div className="space-y-1">
                      <p className="text-yellow-400 text-xs font-medium mb-1">
                        Entry activates IF:
                      </p>
                      {plan.entry.conditionalTriggers.map((trigger, idx) => (
                        <div 
                          key={idx}
                          className={cn(
                            "p-1.5 rounded text-sm mb-1",
                            trigger.priority === 'HIGH' 
                              ? "bg-yellow-900/20"
                              : "bg-slate-900/30"
                          )}
                        >
                          <div className="flex items-start gap-1.5">
                            <span className={cn(
                              "font-semibold text-sm",
                              trigger.priority === 'HIGH' ? "text-yellow-400" : "text-slate-400"
                            )}>
                              {idx + 1}.
                            </span>
                            <div className="flex-1 min-w-0">
                              <div className="text-slate-200 leading-snug text-sm">{trigger.condition}</div>
                              {trigger.price && (
                                <div className="text-slate-400 mt-0.5 text-xs">
                                  Price: <span className="text-yellow-300 font-mono">${trigger.price}</span>
                                </div>
                              )}
                            </div>
                            {trigger.priority === 'HIGH' && (
                              <Badge className="bg-yellow-500/20 text-yellow-400 text-xs font-medium flex-shrink-0 px-1.5 py-0">
                                HIGH
                              </Badge>
                            )}
                          </div>
                        </div>
                      ))}
                    </div>
                  ) : (
                    <div className="space-y-1.5">
                      {plan.entry?.primary && (
                        <div>
                          <div className="text-xs text-gray-400 mb-0.5">Primary</div>
                          <div className="text-lg font-bold text-yellow-300 font-mono">
                            ${plan.entry.primary}
                          </div>
                        </div>
                      )}
                      {plan.entry?.aggressive && (
                        <div>
                          <div className="text-xs text-gray-400 mb-0.5">Aggressive</div>
                          <div className="text-lg font-bold text-yellow-200 font-mono">
                            ${plan.entry.aggressive}
                          </div>
                        </div>
                      )}
                      {plan.entry?.reasoning && (
                        <p className="text-slate-300 text-xs mt-1 italic leading-relaxed">{plan.entry.reasoning}</p>
                      )}
                    </div>
                  )}
                </div>

                {/* Time & Risk */}
                {plan.timeHorizon && (
                  <div>
                    <h3 className="text-sm font-semibold text-slate-200 mb-1.5">⏰ Time & Risk</h3>
                    <div className="space-y-1">
                      {plan.timeHorizon.style === 'SCALP' ? (
                        <>
                          <div className="flex items-center justify-between">
                            <span className="text-xs text-gray-400">Enter by:</span>
                            <span className="text-sm font-semibold font-mono">10:00 AM ET</span>
                          </div>
                          <div className="flex items-center justify-between">
                            <span className="text-xs text-gray-400">Exit by:</span>
                            <span className="text-sm font-semibold font-mono">3:30 PM ET</span>
                          </div>
                        </>
                      ) : plan.timeHorizon.style === 'INTRADAY' ? (
                        <>
                          <div className="flex items-center justify-between">
                            <span className="text-xs text-gray-400">Enter by:</span>
                            <span className="text-sm font-semibold font-mono">11:00 AM ET</span>
                          </div>
                          <div className="flex items-center justify-between">
                            <span className="text-xs text-gray-400">Exit by:</span>
                            <span className="text-sm font-semibold font-mono">3:30 PM ET</span>
                          </div>
                        </>
                      ) : plan.timeHorizon.style === 'SWING' ? (
                        <>
                          <div className="flex items-center justify-between">
                            <span className="text-xs text-gray-400">Expected:</span>
                            <span className="text-sm">{plan.timeHorizon.expected}</span>
                          </div>
                          <div className="flex items-center justify-between">
                            <span className="text-xs text-gray-400">Max Hold:</span>
                            <span className="text-sm">{plan.timeHorizon.maxHold}</span>
                          </div>
                        </>
                      ) : (
                        <>
                          <div className="flex items-center justify-between">
                            <span className="text-xs text-gray-400">Enter by:</span>
                            <span className="text-sm font-semibold font-mono">11:00 AM ET</span>
                          </div>
                          <div className="flex items-center justify-between">
                            <span className="text-xs text-gray-400">Exit by:</span>
                            <span className="text-sm font-semibold font-mono">3:30 PM ET</span>
                          </div>
                        </>
                      )}
                      {plan.timeHorizon.style && (
                        <div className="flex items-center justify-between pt-1 border-t border-slate-700/50">
                          <span className="text-xs text-gray-400">Style:</span>
                          <Badge className="bg-blue-500/20 text-blue-400 text-xs px-1.5 py-0 font-medium">
                            {plan.timeHorizon.style}
                          </Badge>
                        </div>
                      )}
                    </div>
                  </div>
                )}
              </div>
            </div>

            {/* Stop + Targets Grouped */}
            <div className="bg-slate-800/50 rounded-lg p-2 border border-slate-700/50">
              <div className="grid grid-cols-2 gap-3">
                {/* Stop Loss */}
                <div>
                  <h3 className="text-sm font-semibold text-red-400 mb-1.5">
                    🛑 Stop Loss {signal === 'WAIT' && <span className="text-xs font-normal">(If Entered)</span>}
                  </h3>

                  
                  {stopLoss.tight ? (
                    <>
                      <div className="space-y-1 mb-1.5">
                        <div>
                          <div className="text-xs text-gray-400 mb-0.5">Tight Stop</div>
                          <div className="text-lg font-bold text-red-400 font-mono">
                            ${stopLoss.tight.toFixed(2)}
                          </div>
                          <div className="text-xs text-red-300">(-1.5%)</div>
                        </div>
                        
                        <div>
                          <div className="text-xs text-gray-400 mb-0.5">Wide Stop {row.or_low ? '(OR Low)' : ''}</div>
                          <div className="text-lg font-bold text-red-300 font-mono">
                            ${stopLoss.wide.toFixed(2)}
                          </div>
                        </div>
                      </div>
                      
                      <div className="mt-1.5 pt-1.5 border-t border-red-500/20">
                        <div className="font-medium text-red-400 mb-1 text-xs">Exit Immediately If:</div>
                        <ul className="space-y-0.5 text-xs text-gray-300">
                          {stopLoss.wide && (isBullish ? (row.or_low || stopLoss.wide < entryPrice * 0.98) : (row.or_high || stopLoss.wide > entryPrice * 1.02)) && (
                            <li className="flex items-start">
                              <span className="text-red-400 mr-1">•</span>
                              <span className="leading-tight">Price breaks {isBullish ? 'below' : 'above'} OR {isBullish ? 'low' : 'high'} (<span className="font-mono">${stopLoss.wide.toFixed(2)}</span>)</span>
                            </li>
                          )}
                          <li className="flex items-start">
                            <span className="text-red-400 mr-1">•</span>
                            <span className="leading-tight">Opposite flow (&gt;$500K)</span>
                          </li>
                          <li className="flex items-start">
                            <span className="text-red-400 mr-1">•</span>
                            <span className="leading-tight">No follow-through within 30 min</span>
                          </li>
                        </ul>
                      </div>
                    </>
                  ) : (
                    <div className="text-gray-400 text-xs">
                      No entry price available.
                    </div>
                  )}
                </div>

                {/* Profit Targets */}
                <div>
                  <h3 className="text-sm font-semibold text-green-400 mb-1.5">
                    🎯 Profit Targets {signal === 'WAIT' && <span className="text-xs font-normal">(If Entered)</span>}
                  </h3>
                  
                  {targets.t1?.price ? (
                    <>
                      <div className="space-y-1">
                        {targets.t1?.price && (
                          <div>
                            <div className="flex items-center justify-between mb-0.5">
                              <span className="text-xs text-gray-400">T1 (Quick)</span>
                              <Badge className="bg-green-500/20 text-green-400 text-xs font-medium px-1.5 py-0">
                                {targets.t1.percentage}%
                              </Badge>
                            </div>
                            <div className="text-lg font-bold text-green-300 font-mono">${targets.t1.price}</div>
                            <div className="text-sm text-green-400 font-medium">{targets.t1.gain}</div>
                          </div>
                        )}
                        {targets.t2?.price && (
                          <div>
                            <div className="flex items-center justify-between mb-0.5">
                              <span className="text-xs text-gray-400">T2 (Main)</span>
                              <Badge className="bg-green-500/20 text-green-400 text-xs font-medium px-1.5 py-0">
                                {targets.t2.percentage}%
                              </Badge>
                            </div>
                            <div className="text-lg font-bold text-green-300 font-mono">${targets.t2.price}</div>
                            <div className="text-sm text-green-400 font-medium">{targets.t2.gain}</div>
                          </div>
                        )}
                        {targets.t3?.price && (
                          <div>
                            <div className="flex items-center justify-between mb-0.5">
                              <span className="text-xs text-gray-400">T3 (Runner)</span>
                              <Badge className="bg-green-500/20 text-green-400 text-xs font-medium px-1.5 py-0">
                                {targets.t3.percentage}%
                              </Badge>
                            </div>
                            <div className="text-lg font-bold text-green-300 font-mono">${targets.t3.price}</div>
                            <div className="text-sm text-green-400 font-medium">{targets.t3.gain}</div>
                          </div>
                        )}
                      </div>
                      
                      <div className="mt-1.5 pt-1.5 border-t border-green-500/20">
                        <div className="text-xs text-gray-300 leading-relaxed">
                          💡 <span className="font-medium">Strategy:</span> Take {targets.t1.percentage}% at T1, scale rest at T2/T3.
                        </div>
                      </div>
                    </>
                  ) : (
                    <div className="text-gray-400 text-xs">
                      No entry price available.
                    </div>
                  )}
                </div>
              </div>
            </div>

            {/* Risk/Reward Analysis - Emphasized (Center Importance) */}
            <div className="bg-purple-900/20 rounded-lg p-2 border border-purple-500/50">
              <h3 className="text-sm font-semibold text-purple-400 mb-1.5">⚖️ Risk/Reward Analysis</h3>

              
              {riskReward.ratio !== null && riskReward.ratio !== undefined ? (
                <>
                  <div className="grid grid-cols-4 gap-2 mb-1.5">
                    <div className="text-center">
                      <div className="text-xs text-gray-400 mb-0.5">Entry</div>
                      <div className="text-base font-bold text-blue-400 font-mono">${entryPrice.toFixed(2)}</div>
                    </div>
                    <div className="text-center">
                      <div className="text-xs text-gray-400 mb-0.5">Risk</div>
                      <div className="text-base font-bold text-red-400 font-mono">
                        -${riskReward.risk}
                      </div>
                      <div className="text-xs text-red-300">({riskReward.riskPct}%)</div>
                    </div>
                    <div className="text-center">
                      <div className="text-xs text-gray-400 mb-0.5">Reward</div>
                      <div className="text-base font-bold text-green-400 font-mono">
                        +${riskReward.reward}
                      </div>
                      <div className="text-xs text-green-300">({riskReward.rewardPct}%)</div>
                    </div>
                    <div className="text-center">
                      <div className="text-xs text-gray-400 mb-0.5">R/R Ratio</div>
                      <div className="text-xl font-bold text-purple-400 font-mono">
                        {riskReward.ratio.toFixed(2)}:1
                      </div>
                    </div>
                  </div>
                  
                  <div className="text-center text-xs pt-1 border-t border-purple-500/20">
                    {riskReward.ratio >= 2.0 ? (
                      <div className="text-green-300">
                        ✅ Good risk/reward - worth taking
                      </div>
                    ) : riskReward.ratio >= 1.5 ? (
                      <div className="text-yellow-300">
                        ⚠️ Marginal R:R - high conviction only
                      </div>
                    ) : (
                      <div className="text-red-300">
                        ❌ Poor R:R - skip this trade
                      </div>
                    )}
                  </div>
                </>
              ) : (
                <div className="text-gray-400 text-xs text-center">
                  Risk/reward cannot be calculated.
                </div>
              )}
            </div>

            {/* Reasoning - Simplified 3 Clean Columns */}
            {plan.reasoning && (
              <div className="bg-slate-800/50 rounded-lg p-2 border border-slate-700/50">
                <h3 className="text-sm font-semibold text-slate-200 mb-1.5">💭 Reasoning</h3>
                <div className="grid grid-cols-3 gap-3">
                  {plan.reasoning.why && plan.reasoning.why.length > 0 && (
                    <div>
                      <h4 className="text-xs font-medium text-slate-300 mb-1">Why:</h4>
                      <ul className="space-y-0.5 text-slate-300 text-xs leading-relaxed">
                        {plan.reasoning.why.map((reason, idx) => (
                          <li key={idx} className="flex items-start">
                            <span className="text-blue-400 mr-1 mt-0.5">•</span>
                            <span>{reason}</span>
                          </li>
                        ))}
                      </ul>
                    </div>
                  )}
                  {plan.reasoning.catalysts && plan.reasoning.catalysts.length > 0 && (
                    <div>
                      <h4 className="text-xs font-medium text-slate-300 mb-1">Catalysts:</h4>
                      <ul className="space-y-0.5 text-slate-300 text-xs leading-relaxed">
                        {plan.reasoning.catalysts.map((catalyst, idx) => (
                          <li key={idx} className="flex items-start">
                            <span className="text-blue-400 mr-1 mt-0.5">•</span>
                            <span>{catalyst}</span>
                          </li>
                        ))}
                      </ul>
                    </div>
                  )}
                  {plan.reasoning.risks && plan.reasoning.risks.length > 0 && (
                    <div>
                      <h4 className="text-xs font-medium text-yellow-400 mb-1">Risks:</h4>
                      <ul className="space-y-0.5 text-yellow-300 text-xs leading-relaxed">
                        {plan.reasoning.risks.map((risk, idx) => (
                          <li key={idx} className="flex items-start">
                            <span className="text-yellow-400 mr-1 mt-0.5">•</span>
                            <span>{risk}</span>
                          </li>
                        ))}
                      </ul>
                    </div>
                  )}
                </div>
              </div>
            )}

            {/* Invalidation + Historical Edge Grouped (if available) */}
            {(plan.invalidation || (plan.historicalEdge && plan.historicalEdge.similarSetups > 0)) && (
              <div className="bg-slate-800/50 rounded-lg p-2 border border-slate-700/50">
                <div className="grid grid-cols-2 gap-3">
                  {/* Invalidation */}
                  {plan.invalidation && (
                    <div>
                      <h3 className="text-sm font-semibold text-slate-200 mb-1">❌ Invalidation</h3>
                      {plan.invalidation.priceLevel && (
                        <div className="mb-1">
                          <span className="text-xs text-gray-400">Price:</span>
                          <span className="text-red-400 font-mono font-bold text-base ml-1">
                            ${plan.invalidation.priceLevel}
                          </span>
                        </div>
                      )}
                      {plan.invalidation.conditions && plan.invalidation.conditions.length > 0 && (
                        <ul className="space-y-0.5 text-slate-300 text-xs leading-relaxed">
                          {plan.invalidation.conditions.map((condition, idx) => (
                            <li key={idx} className="flex items-start">
                              <span className="text-red-400 mr-1 mt-0.5">•</span>
                              <span>{condition}</span>
                            </li>
                          ))}
                        </ul>
                      )}
                    </div>
                  )}

                  {/* Historical Edge */}
                  {plan.historicalEdge && plan.historicalEdge.similarSetups > 0 && (
                    <div>
                      <h3 className="text-sm font-semibold text-slate-200 mb-1">📊 Historical Edge</h3>
                      <div className="grid grid-cols-2 gap-1.5 text-xs">
                        <div>
                          <span className="text-gray-400">Setups:</span>
                          <span className="text-slate-100 font-bold ml-1">{plan.historicalEdge.similarSetups}</span>
                        </div>
                        <div>
                          <span className="text-gray-400">Win Rate:</span>
                          <span className="text-slate-100 font-bold ml-1">
                            {plan.historicalEdge.winRate ? `${plan.historicalEdge.winRate}%` : 'N/A'}
                          </span>
                        </div>
                        <div>
                          <span className="text-gray-400">Avg Win:</span>
                          <span className="text-green-400 font-bold ml-1">
                            {plan.historicalEdge.avgWin ? `${plan.historicalEdge.avgWin}%` : 'N/A'}
                          </span>
                        </div>
                        <div>
                          <span className="text-gray-400">Avg Loss:</span>
                          <span className="text-red-400 font-bold ml-1">
                            {plan.historicalEdge.avgLoss ? `${plan.historicalEdge.avgLoss}%` : 'N/A'}
                          </span>
                        </div>
                      </div>
                    </div>
                  )}
                </div>
              </div>
            )}

          </div>
        </div>
      </div>
    </div>
  );
}

/**
 * Format trade plan as text for clipboard
 */
function formatTradePlanForClipboard(plan) {
  const lines = [];
  
  lines.push(`TRADE PLAN: ${plan.symbol}`);
  lines.push(`Signal: ${plan.signal} | Confidence: ${plan.confidence}%`);
  lines.push('');
  
  lines.push('ENTRY STRATEGY:');
  if (plan.entry?.primary) lines.push(`  Primary: $` + plan.entry.primary);
  if (plan.entry?.aggressive) lines.push(`  Aggressive: $` + plan.entry.aggressive);
  if (plan.entry?.reasoning) lines.push(`  ${plan.entry.reasoning}`);
  lines.push('');
  
  lines.push('STOP LOSS:');
  if (plan.stopLoss?.tight) lines.push(`  Tight: $` + plan.stopLoss.tight);
  if (plan.stopLoss?.wide) lines.push(`  Wide: $` + plan.stopLoss.wide);
  if (plan.stopLoss?.reasoning) lines.push(`  ${plan.stopLoss.reasoning}`);
  lines.push('');
  
  lines.push('PROFIT TARGETS:');
  if (plan.targets?.t1?.price) {
    lines.push(`  T1: $` + plan.targets.t1.price + ` (${plan.targets.t1.gain}) - Take ${plan.targets.t1.percentage}%`);
  }
  if (plan.targets?.t2?.price) {
    lines.push(`  T2: $` + plan.targets.t2.price + ` (${plan.targets.t2.gain}) - Take ${plan.targets.t2.percentage}%`);
  }
  if (plan.targets?.t3?.price) {
    lines.push(`  T3: $` + plan.targets.t3.price + ` (${plan.targets.t3.gain}) - Runner ${plan.targets.t3.percentage}%`);
  }
  lines.push('');
  
  if (plan.timeHorizon) {
    lines.push('TIME HORIZON:');
    lines.push(`  Expected: ${plan.timeHorizon.expected}`);
    lines.push(`  Max Hold: ${plan.timeHorizon.maxHold}`);
    lines.push(`  Style: ${plan.timeHorizon.style}`);
    lines.push('');
  }
  
  if (plan.riskReward?.ratio) {
    lines.push('RISK/REWARD:');
    lines.push(`  Risk: ${plan.riskReward.risk} | Reward: ${plan.riskReward.reward} | Ratio: ${plan.riskReward.ratio}`);
    lines.push('');
  }
  
  if (plan.reasoning) {
    lines.push('REASONING:');
    if (plan.reasoning.why?.length > 0) {
      lines.push('  Why:');
      plan.reasoning.why.forEach(reason => lines.push(`    - ${reason}`));
    }
    if (plan.reasoning.catalysts?.length > 0) {
      lines.push('  Catalysts:');
      plan.reasoning.catalysts.forEach(catalyst => lines.push(`    - ${catalyst}`));
    }
    if (plan.reasoning.risks?.length > 0) {
      lines.push('  Risks:');
      plan.reasoning.risks.forEach(risk => lines.push(`    - ${risk}`));
    }
    lines.push('');
  }
  
  if (plan.invalidation) {
    lines.push('INVALIDATION CONDITIONS:');
    if (plan.invalidation.priceLevel) {
      lines.push(`  Price Level: $` + plan.invalidation.priceLevel);
    }
    if (plan.invalidation.conditions?.length > 0) {
      plan.invalidation.conditions.forEach(condition => lines.push(`  - ${condition}`));
    }
  }
  
  return lines.join('\n');
}

