import { useState, useEffect } from 'react';
import { createPortal } from 'react-dom';
import { Badge } from '@/components/ui/Badge';
import { Button } from '@/components/ui/button';
import { X, Loader2, RefreshCw } from 'lucide-react';
import { cn } from '@/utils/cn';

/**
 * Phase 1 Eligibility Modal
 * Shows Phase 1 analysis for a specific signal
 * Fetches Phase 1 data on-demand when modal opens
 * Uses localStorage caching to reduce API calls and improve performance
 */

// Cache configuration
const CACHE_PREFIX = 'phase1_cache_';
const CACHE_EXPIRY_MS = 60 * 60 * 1000; // 1 hour
const CACHE_KEY_MAX_LENGTH = 200; // Limit cache key length

/**
 * Generate cache key from signal data
 */
function getCacheKey(symbol, flowTsUtc) {
  const key = `${symbol}_${flowTsUtc}`;
  // Truncate if too long (localStorage has size limits)
  return key.length > CACHE_KEY_MAX_LENGTH 
    ? key.substring(0, CACHE_KEY_MAX_LENGTH) 
    : key;
}

/**
 * Get cached Phase 1 data
 */
function getCachedData(symbol, flowTsUtc) {
  try {
    const cacheKey = `${CACHE_PREFIX}${getCacheKey(symbol, flowTsUtc)}`;
    const cached = localStorage.getItem(cacheKey);
    if (!cached) return null;
    
    const { data, timestamp } = JSON.parse(cached);
    const age = Date.now() - timestamp;
    
    // Check if cache is expired
    if (age > CACHE_EXPIRY_MS) {
      localStorage.removeItem(cacheKey);
      return null;
    }
    
    return { data, age, cached: true };
  } catch (e) {
    console.warn('Error reading Phase 1 cache:', e);
    return null;
  }
}

/**
 * Store Phase 1 data in cache
 */
function setCachedData(symbol, flowTsUtc, data) {
  try {
    const cacheKey = `${CACHE_PREFIX}${getCacheKey(symbol, flowTsUtc)}`;
    const cacheValue = {
      data,
      timestamp: Date.now()
    };
    localStorage.setItem(cacheKey, JSON.stringify(cacheValue));
  } catch (e) {
    console.warn('Error storing Phase 1 cache:', e);
    // If storage is full, try to clear old entries
    if (e.name === 'QuotaExceededError') {
      clearOldCacheEntries();
    }
  }
}

/**
 * Clear old cache entries to free up space
 */
function clearOldCacheEntries() {
  try {
    const keys = Object.keys(localStorage);
    const phase1Keys = keys.filter(k => k.startsWith(CACHE_PREFIX));
    
    // Sort by timestamp (oldest first) and remove oldest 50%
    const entries = phase1Keys.map(key => {
      try {
        const cached = localStorage.getItem(key);
        if (cached) {
          const { timestamp } = JSON.parse(cached);
          return { key, timestamp };
        }
      } catch (e) {
        // Invalid entry, remove it
        localStorage.removeItem(key);
      }
      return null;
    }).filter(Boolean).sort((a, b) => a.timestamp - b.timestamp);
    
    // Remove oldest 50% of entries
    const toRemove = Math.floor(entries.length / 2);
    entries.slice(0, toRemove).forEach(({ key }) => {
      localStorage.removeItem(key);
    });
    
    console.log(`Cleared ${toRemove} old Phase 1 cache entries`);
  } catch (e) {
    console.error('Error clearing old cache entries:', e);
  }
}

export function Phase1EligibilityModal({ row, isOpen, onClose }) {
  const [phase1Data, setPhase1Data] = useState(null);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState(null);
  const [isCached, setIsCached] = useState(false);
  const [forceRefresh, setForceRefresh] = useState(false);

  // Fetch Phase 1 data when modal opens
  useEffect(() => {
    if (isOpen && row) {
      fetchPhase1Data(forceRefresh);
    } else {
      // Reset when modal closes
      setPhase1Data(null);
      setError(null);
      setIsCached(false);
      setForceRefresh(false);
    }
  }, [isOpen, row, forceRefresh]);

  const fetchPhase1Data = async (bypassCache = false) => {
    if (!row) return;
    
    // Prepare request data
    // Format timestamps properly
    let flowTsUtc = row.flow_ts_utc || row.CreatedDate;
    if (flowTsUtc && typeof flowTsUtc === 'string') {
      // Ensure it's in ISO format
      try {
        const date = new Date(flowTsUtc);
        if (!isNaN(date.getTime())) {
          flowTsUtc = date.toISOString();
        }
      } catch (e) {
        console.warn('Error formatting flow_ts_utc:', e);
      }
    } else if (flowTsUtc instanceof Date) {
      flowTsUtc = flowTsUtc.toISOString();
    }
    
    let flowDateCst = row.flow_date_cst || row.CreatedDate;
    if (flowDateCst && typeof flowDateCst === 'string') {
      // Extract just the date part (YYYY-MM-DD)
      flowDateCst = flowDateCst.split('T')[0].split(' ')[0];
    } else if (flowDateCst instanceof Date) {
      flowDateCst = flowDateCst.toISOString().split('T')[0];
    }
      
      const symbol = row.symbol_norm || row.Symbol;
      
      // Check cache first (unless bypassing)
      if (!bypassCache) {
        const cached = getCachedData(symbol, flowTsUtc);
        if (cached) {
          console.log(`✅ Using cached Phase 1 data for ${symbol} (age: ${Math.round(cached.age / 1000)}s)`);
          setPhase1Data(cached.data);
          setIsCached(true);
          setError(null);
          return; // Return early, no API call needed
        }
      }
      
      // No cache hit, fetch from API
      setIsLoading(true);
      setError(null);
      setIsCached(false);
      
      try {
        const requestData = {
          symbol,
          flow_ts_utc: flowTsUtc,
          flow_date_cst: flowDateCst,
          row_data: {
            // Include all necessary fields for Phase 1 calculation
            badge_round: row.badge_round || (row.badgesRaw && row.badgesRaw.round),
            badge_more: row.badge_more || (row.badgesRaw && row.badgesRaw.more),
            premium_num: row.premium_num || row.Premium,
            direction: row.direction,
            bull_total: row.bull_total,
            bear_total: row.bear_total,
            prem_cb_itm: row.prem_cb_itm,
            prem_ps_itm: row.prem_ps_itm,
            prem_cs_itm: row.prem_cs_itm,
            prem_pb_itm: row.prem_pb_itm,
            vol_num: row.vol_num || row.Volume,
            oi_num: row.oi_num || row.OI,
            index_aligned: row.index_aligned,
            ...row  // Include all other fields
          }
        };

        // Create AbortController with longer timeout for Phase 1 calculations
        const controller = new AbortController();
        const timeoutId = setTimeout(() => controller.abort(), 150000); // 150 seconds (2.5 minutes)
        
        const response = await fetch('/api/options/phase1/calculate', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(requestData),
          signal: controller.signal
        });
        
        clearTimeout(timeoutId);

        if (!response.ok) {
          const errorData = await response.json().catch(() => ({ error: response.statusText }));
          throw new Error(errorData.error || `Failed to calculate Phase 1: ${response.statusText}`);
        }

        const result = await response.json();
        
        if (result.success && result.data) {
          // Always store in cache (even after refresh, so next time it's available)
          // If this was a refresh, we already cleared the old cache entry
          setCachedData(symbol, flowTsUtc, result.data);
          setPhase1Data(result.data);
          setIsCached(false); // Fresh data, not cached
          if (bypassCache) {
            console.log(`✅ Phase 1 data recalculated with latest data for ${symbol}`);
          } else {
            console.log(`✅ Phase 1 data fetched for ${symbol}`);
          }
        } else {
          throw new Error(result.error || 'Failed to calculate Phase 1 data');
        }
      } catch (err) {
        console.error('Error fetching Phase 1 data:', err);
        setError(err.message || 'Failed to calculate Phase 1 metrics');
      } finally {
        setIsLoading(false);
      }
  };

  const handleRefresh = () => {
    // Clear cache for this symbol/timestamp to force fresh calculation
    if (row) {
      const symbol = row.symbol_norm || row.Symbol;
      let flowTsUtc = row.flow_ts_utc || row.CreatedDate;
      if (flowTsUtc && typeof flowTsUtc === 'string') {
        try {
          const date = new Date(flowTsUtc);
          if (!isNaN(date.getTime())) {
            flowTsUtc = date.toISOString();
          }
        } catch (e) {
          console.warn('Error formatting flow_ts_utc for cache clear:', e);
        }
      } else if (flowTsUtc instanceof Date) {
        flowTsUtc = flowTsUtc.toISOString();
      }
      
      try {
        const cacheKey = `${CACHE_PREFIX}${getCacheKey(symbol, flowTsUtc)}`;
        localStorage.removeItem(cacheKey);
        console.log(`🗑️  Cleared cache for ${symbol} to force fresh calculation`);
      } catch (e) {
        console.warn('Error clearing cache:', e);
      }
    }
    
    // Set loading state and trigger refresh
    setIsLoading(true);
    setError(null);
    setForceRefresh(true);
    // The useEffect will trigger fetchPhase1Data with bypassCache=true
  };

  if (!isOpen || !row) {
    return null;
  }

  // Use fetched Phase 1 data if available, otherwise fall back to row data
  const data = phase1Data || row;
  
  // Extract Phase 1 data
  const hasPhase1Fields = 'signal_tier' in data || 'checklist_score' in data || 'price_reaction_5m_pct' in data;
  
  const signalTier = data.signal_tier;
  const isTradeable = data.is_tradeable;
  const checklistScore = data.checklist_score;
  const checklistPassed = data.checklist_passed;
  const checklistDetails = data.checklist_details || {};
  const priceReaction5m = data.price_reaction_5m_pct;
  const priceReaction15m = data.price_reaction_15m_pct;
  const flowLedToMove = data.flow_led_to_move;
  const vwapAtSignal = data.vwap_at_signal;
  const priceVsVwap = data.price_vs_vwap_pct;
  const highBreak5m = data.high_break_5m;
  const lowBreak5m = data.low_break_5m;
  
  // Determine if fields were calculated (exist but may be null) vs not calculated (don't exist)
  const signalTierCalculated = 'signal_tier' in data;
  const checklistCalculated = 'checklist_score' in data;
  const priceReactionCalculated = 'price_reaction_5m_pct' in data;
  const vwapCalculated = 'vwap_at_signal' in data;

  // Determine overall eligibility
  const isEligible = signalTier === 'TIER_1' && checklistPassed === true && flowLedToMove === true;
  const hasPartialEligibility = (signalTier === 'TIER_1' || checklistPassed === true || flowLedToMove === true);

  // Handle click outside to close
  const handleBackdropClick = (e) => {
    if (e.target === e.currentTarget) {
      onClose();
    }
  };

  // Prevent body scroll when modal is open
  useEffect(() => {
    if (isOpen) {
      document.body.style.overflow = 'hidden';
    } else {
      document.body.style.overflow = 'unset';
    }
    return () => {
      document.body.style.overflow = 'unset';
    };
  }, [isOpen]);

  const modalContent = (
    <div 
      className="fixed inset-0 bg-black/50 backdrop-blur-sm z-[9999] flex items-center justify-center p-4"
      onClick={handleBackdropClick}
      style={{ zIndex: 9999 }}
    >
      <div 
        className="bg-slate-900 border border-slate-700 rounded-lg shadow-xl max-w-2xl w-full max-h-[90vh] overflow-y-auto"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div className="sticky top-0 bg-slate-900 border-b border-slate-700 p-4 flex items-center justify-between">
          <div className="flex-1">
            <div className="flex items-center gap-2">
              <h2 className="text-xl font-bold text-slate-100">Phase 1 Eligibility Check</h2>
              {isCached && (
                <Badge variant="outline" className="text-xs bg-blue-500/10 text-blue-400 border-blue-500/50">
                  Cached
                </Badge>
              )}
            </div>
            <p className="text-sm text-slate-400 mt-1">
              {row.symbol_norm || row.Symbol} • {row.CreatedDate ? new Date(row.CreatedDate).toLocaleDateString() : 'N/A'}
            </p>
          </div>
          <div className="flex items-center gap-2">
            <Button
              variant="ghost"
              size="sm"
              onClick={handleRefresh}
              disabled={isLoading}
              className="h-8 w-8 p-0 text-slate-400 hover:text-slate-100"
              title="Refresh Phase 1 data"
            >
              <RefreshCw className={cn("h-4 w-4", isLoading && "animate-spin")} />
            </Button>
            <Button
              variant="ghost"
              size="sm"
              onClick={onClose}
              className="h-8 w-8 p-0"
            >
              <X className="h-4 w-4" />
            </Button>
          </div>
        </div>

        {/* Content */}
        <div className="p-6 space-y-6">
          {/* Loading State */}
          {isLoading && (
            <div className="flex items-center justify-center py-12">
              <div className="flex flex-col items-center gap-3">
                <Loader2 className="w-8 h-8 animate-spin text-blue-400" />
                <p className="text-sm text-slate-400">Calculating Phase 1 metrics...</p>
                <p className="text-xs text-slate-500">Fetching real-time data from Yahoo Finance</p>
              </div>
            </div>
          )}

          {/* Error State */}
          {error && !isLoading && (
            <div className="bg-red-500/10 border border-red-500/50 rounded-lg p-4">
              <div className="flex items-start gap-3">
                <span className="text-2xl">❌</span>
                <div>
                  <h4 className="text-sm font-semibold text-red-400 mb-1">Error Calculating Phase 1</h4>
                  <p className="text-xs text-red-300/80">{error}</p>
                </div>
              </div>
            </div>
          )}

          {/* Warning if Phase 1 fields don't exist */}
          {!isLoading && !error && !hasPhase1Fields && (
            <div className="bg-yellow-500/10 border border-yellow-500/50 rounded-lg p-4">
              <div className="flex items-start gap-3">
                <span className="text-2xl">⚠️</span>
                <div>
                  <h4 className="text-sm font-semibold text-yellow-400 mb-1">Phase 1 Data Not Available</h4>
                  <p className="text-xs text-yellow-300/80">
                    This data came from SQL fallback (not Python service). Phase 1 features require the Python service to be running.
                    <br />
                    <span className="mt-1 block">To enable Phase 1 analysis, ensure the Python service is running at <code className="bg-slate-800 px-1 rounded">http://localhost:8010</code></span>
                  </p>
                </div>
              </div>
            </div>
          )}

          {/* Phase 1 Content - Only show if not loading and no error */}
          {!isLoading && !error && (
            <>
              {/* Overall Status */}
          <div className={cn(
            "p-4 rounded-lg border-2",
            isEligible 
              ? "bg-green-500/10 border-green-500/50" 
              : hasPartialEligibility
              ? "bg-yellow-500/10 border-yellow-500/50"
              : "bg-red-500/10 border-red-500/50"
          )}>
            <div className="flex items-center gap-3">
              <span className="text-3xl">
                {isEligible ? '✅' : hasPartialEligibility ? '⚠️' : '❌'}
              </span>
              <div>
                <h3 className="text-lg font-bold text-slate-100">
                  {isEligible ? 'Fully Eligible' : hasPartialEligibility ? 'Partially Eligible' : 'Not Eligible'}
                </h3>
                <p className="text-sm text-slate-400">
                  {isEligible 
                    ? 'This signal meets all Phase 1 criteria - ready to trade!'
                    : hasPartialEligibility
                    ? 'This signal meets some Phase 1 criteria - review details below'
                    : hasPhase1Fields
                    ? 'This signal does not meet Phase 1 criteria'
                    : 'Phase 1 analysis not available - Python service required'}
                </p>
              </div>
            </div>
          </div>

          {/* 1. Signal Tier */}
          <div className="space-y-2">
            <h4 className="text-sm font-semibold text-slate-300 uppercase tracking-wide">1. Signal Tier</h4>
            <div className="bg-slate-800/50 rounded-lg p-4">
              {!signalTierCalculated ? (
                <div className="space-y-2">
                  <span className="text-sm text-slate-500">Not calculated</span>
                  <p className="text-xs text-slate-600">Python service may not be running or data came from SQL fallback</p>
                </div>
              ) : signalTier ? (
                <div className="flex items-center gap-3">
                  <Badge 
                    variant="outline"
                    className={cn(
                      "text-sm px-3 py-1",
                      signalTier === 'TIER_1' ? "bg-green-500/20 border-green-500/50 text-green-400" :
                      signalTier === 'TIER_2' ? "bg-yellow-500/20 border-yellow-500/50 text-yellow-400" :
                      "bg-slate-500/20 border-slate-500/50 text-slate-400"
                    )}
                  >
                    {signalTier === 'TIER_1' ? '🥇 Tier-1' : signalTier === 'TIER_2' ? '🥈 Tier-2' : '🚫 Ignore'}
                  </Badge>
                  <span className="text-sm text-slate-300">
                    {signalTier === 'TIER_1' 
                      ? 'Tradeable alone - highest quality signal'
                      : signalTier === 'TIER_2'
                      ? 'Needs confirmation - wait 10-30 minutes'
                      : 'Do not trade - likely hedge or low quality'}
                  </span>
                </div>
              ) : (
                <span className="text-sm text-slate-500">Calculated but no tier assigned (likely missing required badges)</span>
              )}
            </div>
          </div>

          {/* 2. Trade Checklist */}
          <div className="space-y-2">
            <h4 className="text-sm font-semibold text-slate-300 uppercase tracking-wide">2. Trade Checklist</h4>
            <div className="bg-slate-800/50 rounded-lg p-4 space-y-3">
              {!checklistCalculated ? (
                <div className="space-y-2">
                  <span className="text-sm text-slate-500">Not calculated</span>
                  <p className="text-xs text-slate-600">Python service may not be running or data came from SQL fallback</p>
                </div>
              ) : checklistScore !== undefined && checklistScore !== null ? (
                <>
                  <div className="flex items-center gap-3">
                    <Badge 
                      variant={checklistPassed ? 'success' : 'secondary'}
                      className={cn(
                        "text-sm px-3 py-1",
                        checklistPassed ? "bg-green-500/20 border-green-500/50 text-green-400" : "bg-red-500/20 border-red-500/50 text-red-400"
                      )}
                    >
                      {checklistScore}/5 {checklistPassed ? '✅ Passed' : '❌ Failed'}
                    </Badge>
                    <span className="text-sm text-slate-300">
                      {checklistPassed ? 'Meets minimum requirements (4/5)' : 'Does not meet minimum requirements'}
                    </span>
                  </div>
                  
                  {/* Checklist Details */}
                  <div className="space-y-2 pt-2 border-t border-slate-700">
                    <div className="text-xs font-semibold text-slate-400 mb-2">Checklist Items:</div>
                    {Object.entries(checklistDetails).map(([key, value]) => (
                      <div key={key} className="flex items-center justify-between text-sm">
                        <span className="text-slate-400 capitalize">
                          {key.replace(/_/g, ' ')}:
                        </span>
                        <Badge 
                          variant="outline"
                          className={cn(
                            "text-xs",
                            value ? "bg-green-500/20 border-green-500/50 text-green-400" : "bg-red-500/20 border-red-500/50 text-red-400"
                          )}
                        >
                          {value ? '✅' : '❌'}
                        </Badge>
                      </div>
                    ))}
                  </div>
                </>
              ) : (
                <span className="text-sm text-slate-500">Calculated but score unavailable</span>
              )}
            </div>
          </div>

          {/* 3. Price Reaction */}
          <div className="space-y-2">
            <h4 className="text-sm font-semibold text-slate-300 uppercase tracking-wide">3. Price Reaction</h4>
            <div className="bg-slate-800/50 rounded-lg p-4 space-y-3">
              {!priceReactionCalculated ? (
                <div className="space-y-2">
                  <span className="text-sm text-slate-500">Not calculated</span>
                  <p className="text-xs text-slate-600">Python service may not be running or data came from SQL fallback</p>
                </div>
              ) : priceReaction5m !== undefined && priceReaction5m !== null ? (
                <>
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <div className="text-xs text-slate-400 mb-1">5 Minutes After:</div>
                      <div className={cn(
                        "text-lg font-bold",
                        priceReaction5m > 0 ? "text-green-400" : priceReaction5m < 0 ? "text-red-400" : "text-slate-400"
                      )}>
                        {priceReaction5m > 0 ? '+' : ''}{priceReaction5m != null ? priceReaction5m.toFixed(2) : '0.00'}%
                      </div>
                    </div>
                    {priceReaction15m !== undefined && priceReaction15m !== null && (
                      <div>
                        <div className="text-xs text-slate-400 mb-1">15 Minutes After:</div>
                        <div className={cn(
                          "text-lg font-bold",
                          priceReaction15m > 0 ? "text-green-400" : priceReaction15m < 0 ? "text-red-400" : "text-slate-400"
                        )}>
                          {priceReaction15m > 0 ? '+' : ''}{priceReaction15m != null ? priceReaction15m.toFixed(2) : '0.00'}%
                        </div>
                      </div>
                    )}
                  </div>
                  
                  <div className="flex items-center gap-3 pt-2 border-t border-slate-700">
                    <Badge 
                      variant="outline"
                      className={cn(
                        "text-sm px-3 py-1",
                        flowLedToMove ? "bg-green-500/20 border-green-500/50 text-green-400" : "bg-red-500/20 border-red-500/50 text-red-400"
                      )}
                    >
                      {flowLedToMove ? '✅ Flow Led to Move' : '❌ Flow Did Not Move Price'}
                    </Badge>
                    <span className="text-xs text-slate-400">
                      {flowLedToMove 
                        ? 'Price moved >0.5% - Real positioning'
                        : 'Price moved <0.5% - Likely hedge/roll'}
                    </span>
                  </div>

                  {(highBreak5m || lowBreak5m) && (
                    <div className="pt-2 border-t border-slate-700">
                      <div className="text-xs text-slate-400 mb-1">Price Breaks:</div>
                      <div className="flex gap-2">
                        {highBreak5m && (
                          <Badge className="bg-green-500/20 text-green-400 text-xs">
                            ✅ High Break
                          </Badge>
                        )}
                        {lowBreak5m && (
                          <Badge className="bg-red-500/20 text-red-400 text-xs">
                            ⚠️ Low Break
                          </Badge>
                        )}
                      </div>
                    </div>
                  )}
                </>
              ) : (
                <span className="text-sm text-slate-500">Calculated but no price reaction data available (may be historical data, future date, or price data unavailable)</span>
              )}
            </div>
          </div>

          {/* 4. VWAP Analysis */}
          <div className="space-y-2">
            <h4 className="text-sm font-semibold text-slate-300 uppercase tracking-wide">4. VWAP Analysis</h4>
            <div className="bg-slate-800/50 rounded-lg p-4 space-y-3">
              {!vwapCalculated ? (
                <div className="space-y-2">
                  <span className="text-sm text-slate-500">Not calculated</span>
                  <p className="text-xs text-slate-600">Python service may not be running or data came from SQL fallback</p>
                </div>
              ) : vwapAtSignal !== undefined && vwapAtSignal !== null ? (
                <>
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <div className="text-xs text-slate-400 mb-1">VWAP at Signal:</div>
                      <div className="text-lg font-bold text-slate-100">
                        ${vwapAtSignal != null ? vwapAtSignal.toFixed(2) : 'N/A'}
                      </div>
                    </div>
                    {priceVsVwap !== undefined && priceVsVwap !== null && typeof priceVsVwap === 'number' && !isNaN(priceVsVwap) && (
                      <div>
                        <div className="text-xs text-slate-400 mb-1">Distance from VWAP:</div>
                        <div className={cn(
                          "text-lg font-bold",
                          Math.abs(priceVsVwap) <= 1 ? "text-green-400" :
                          Math.abs(priceVsVwap) <= 2 ? "text-yellow-400" :
                          "text-red-400"
                        )}>
                          {priceVsVwap > 0 ? '+' : ''}{priceVsVwap.toFixed(2)}%
                        </div>
                      </div>
                    )}
                  </div>
                  
                  {priceVsVwap !== undefined && priceVsVwap !== null && typeof priceVsVwap === 'number' && !isNaN(priceVsVwap) && (
                    <div className="pt-2 border-t border-slate-700">
                      <div className="text-xs text-slate-400">
                        {Math.abs(priceVsVwap) <= 1 
                          ? '✅ Price near VWAP - Good entry opportunity'
                          : Math.abs(priceVsVwap) <= 2
                          ? '⚠️ Price moderately extended - Consider waiting for pullback'
                          : '❌ Price far from VWAP - Wait for pullback before entry'}
                      </div>
                    </div>
                  )}
                </>
              ) : (
                <span className="text-sm text-slate-500">Calculated but VWAP unavailable (VWAP only available during RTH hours, or price data unavailable)</span>
              )}
            </div>
          </div>

              {/* Summary */}
              <div className="bg-slate-800/50 rounded-lg p-4 border border-slate-700">
                <h4 className="text-sm font-semibold text-slate-300 uppercase tracking-wide mb-3">Summary</h4>
                <div className="space-y-2 text-sm">
                  <div className="flex justify-between">
                    <span className="text-slate-400">Signal Tier:</span>
                    <span className={cn(
                      "font-semibold",
                      signalTier === 'TIER_1' ? "text-green-400" : signalTier === 'TIER_2' ? "text-yellow-400" : "text-slate-400"
                    )}>
                      {signalTier || 'N/A'}
                    </span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-slate-400">Checklist:</span>
                    <span className={cn(
                      "font-semibold",
                      checklistPassed ? "text-green-400" : "text-red-400"
                    )}>
                      {checklistScore !== undefined ? `${checklistScore}/5` : 'N/A'} {checklistPassed ? '✅' : '❌'}
                    </span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-slate-400">Price Reaction:</span>
                    <span className={cn(
                      "font-semibold",
                      flowLedToMove ? "text-green-400" : "text-red-400"
                    )}>
                      {flowLedToMove ? '✅ Moved' : priceReaction5m !== undefined ? '❌ No Move' : 'N/A'}
                    </span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-slate-400">VWAP Distance:</span>
                    <span className={cn(
                      "font-semibold",
                      priceVsVwap != null && typeof priceVsVwap === 'number' && !isNaN(priceVsVwap) && Math.abs(priceVsVwap) <= 1 ? "text-green-400" :
                      priceVsVwap != null && typeof priceVsVwap === 'number' && !isNaN(priceVsVwap) && Math.abs(priceVsVwap) <= 2 ? "text-yellow-400" :
                      "text-slate-400"
                    )}>
                      {priceVsVwap != null && typeof priceVsVwap === 'number' && !isNaN(priceVsVwap) ? `${priceVsVwap > 0 ? '+' : ''}${priceVsVwap.toFixed(2)}%` : 'N/A'}
                    </span>
                  </div>
                </div>
              </div>
            </>
          )}
        </div>

        {/* Footer */}
        <div className="sticky bottom-0 bg-slate-900 border-t border-slate-700 p-4 flex justify-end">
          <Button onClick={onClose} variant="outline">
            Close
          </Button>
        </div>
      </div>
    </div>
  );

  // Use portal to render modal at root level
  if (typeof window !== 'undefined') {
    return createPortal(modalContent, document.body);
  }
  
  return null;
}

