"use client";

import React, { useState, useEffect, useCallback, useRef } from 'react';
import { marketService } from '@/services/marketService';
import { RefreshCw, Zap, PlayCircle, Clock } from 'lucide-react';
import PageBreadcrumb from "@/components/common/PageBreadCrumb";
import ComponentCard from "@/components/common/ComponentCard";
import Badge from "@/components/ui/badge/Badge";
import Button from "@/components/ui/button/Button";
import { Table, TableHeader, TableBody, TableRow, TableCell } from "@/components/ui/table";
import { useSocket } from '@/hooks/useSocket';

// Cumulative Normal Distribution Function N(x) using high-accuracy numerical approximation
function normalCDF(x: number): number {
  const t = 1 / (1 + 0.2316419 * Math.abs(x));
  const d = 0.39894228;
  const p = d * Math.exp(-0.5 * x * x);
  const val = 1 - p * ((((1.330274429 * t - 1.821255978) * t + 1.781477937) * t - 0.356563782) * t + 0.31938153) * t;
  return x >= 0 ? val : 1 - val;
}

function calculateProbabilityOfItm(spot: number, strike: number, type: 'CE' | 'PE', sigma: number, T: number, r: number = 0.065): number {
  if (T <= 0 || sigma <= 0) {
    if (type === 'CE') return spot >= strike ? 100 : 0;
    return spot <= strike ? 100 : 0;
  }
  const d2 = (Math.log(spot / strike) + (r - 0.5 * sigma * sigma) * T) / (sigma * Math.sqrt(T));
  const probCall = normalCDF(d2);
  const probabilityOfItm = type === 'CE' ? probCall : 1 - probCall;
  return parseFloat((probabilityOfItm * 100).toFixed(2));
}

// Gamma Calculation
function calculateGamma(spot: number, strike: number, sigma: number, T: number, r: number = 0.065): number {
  if (T <= 0 || sigma <= 0 || spot <= 0) return 0;
  const d1 = (Math.log(spot / strike) + (r + 0.5 * sigma * sigma) * T) / (sigma * Math.sqrt(T));
  const nPrimeD1 = Math.exp(-0.5 * d1 * d1) / Math.sqrt(2 * Math.PI);
  return nPrimeD1 / (spot * sigma * Math.sqrt(T));
}

function getStrikeInterval(sym: string): number {
  const s = sym.toUpperCase();
  if (s.includes('BANK')) return 100;
  if (s.includes('MIDCP') || s.includes('SELECT')) return 25;
  return 50;
}

function parseContract(contractStr: string) {
  if (!contractStr) return { strikePrice: null, type: null };
  const clean = contractStr.toUpperCase().replace(/\s+/g, '');
  const isCE = clean.includes('CE') || clean.includes('CALL');
  const isPE = clean.includes('PE') || clean.includes('PUT');

  // Attempt to match digits immediately preceding CE, PE, CALL, or PUT
  const optMatch = clean.match(/(\d+)(?:CE|PE|CALL|PUT)/);
  let strikePrice: number | null = null;

  if (optMatch) {
    strikePrice = parseInt(optMatch[1]);
  } else {
    const match = clean.match(/\d{4,5}/) || clean.match(/\d+/);
    strikePrice = match ? parseInt(match[0]) : null;
  }

  return {
    strikePrice,
    type: isCE ? 'CE' : (isPE ? 'PE' : null) as 'CE' | 'PE' | null
  };
}


// Robust HTML Sanitizer to prevent XSS vulnerabilities
function sanitizeHTML(html: string): string {
  if (!html) return '';
  let clean = html;

  // 1. Remove <script> tags and contents
  clean = clean.replace(/<script[^>]*>([\s\S]*?)<\/script>/gi, '');

  // 2. Remove all interactive/unsafe tags
  clean = clean.replace(/<(object|embed|iframe|form|input|button|link|meta|style)[^>]*>([\s\S]*?)<\/\1>/gi, '');
  clean = clean.replace(/<(object|embed|iframe|form|input|button|link|meta|style)[^>]*>/gi, '');

  // 3. Remove inline events with single/double quotes
  clean = clean.replace(/\s+on\w+\s*=\s*(["'])(.*?)\1/gi, '');

  // 4. Remove unquoted inline events
  clean = clean.replace(/\s+on\w+\s*=\s*([^\s>]+)/gi, '');

  // 5. Remove javascript: or vbscript: inside href/src
  clean = clean.replace(/\s+(href|src)\s*=\s*(["'])\s*(javascript|vbscript):.*?\2/gi, '');
  clean = clean.replace(/\s+(href|src)\s*=\s*(javascript|vbscript):[^\s>]+/gi, '');

  return clean;
}

export default function NSEOptionsPage() {
  const [symbol, setSymbol] = useState('NIFTY');
  const [data, setData] = useState<any>(null);
  const [expiries, setExpiries] = useState<string[]>([]);
  const [selectedExpiry, setSelectedExpiry] = useState('');
  const [loading, setLoading] = useState(true);
  const [lastUpdated, setLastUpdated] = useState('');
  const [stats, setStats] = useState<any>({});
  const [aiAnalysis, setAiAnalysis] = useState('');
  const [vipSignal, setVipSignal] = useState<any>(null);
  const [historySignals, setHistorySignals] = useState<any[]>([]);
  const [paperTrades, setPaperTrades] = useState<any[]>([]);
  const [signalEvolution, setSignalEvolution] = useState<any[]>([]);
  const [quantLevels, setQuantLevels] = useState<any>(null);
  const [chainData, setChainData] = useState<any[]>([]);
  const [optionTraps, setOptionTraps] = useState<{ calls: any[], puts: any[] }>({ calls: [], puts: [] });
  const hasAutoAnalyzed = useRef(false);
  const audioRef = useRef<HTMLAudioElement | null>(null);
  const fetchGenRef = useRef(0); // Race condition guard
  // Refs for stable access in runAIAnalysis (avoids stale closures)
  const statsRef = useRef(stats);
  const dataRef = useRef(data);
  const symbolRef = useRef(symbol);
  const paperTradesRef = useRef(paperTrades);
  const signalEvolutionRef = useRef(signalEvolution);
  const vipSignalRef = useRef(vipSignal);
  const quantLevelsRef = useRef(quantLevels);
  statsRef.current = stats;
  dataRef.current = data;
  symbolRef.current = symbol;
  paperTradesRef.current = paperTrades;
  signalEvolutionRef.current = signalEvolution;
  vipSignalRef.current = vipSignal;
  quantLevelsRef.current = quantLevels;

  // Initialize Audio
  useEffect(() => {
    audioRef.current = new Audio('https://assets.mixkit.co/active_storage/sfx/2869/2869-preview.mp3');
  }, []);

  const calculateStats = useCallback((rawData: any, expiry: string, currentSymbol: string) => {
    if (!rawData || !rawData.records) return;
    let spot = rawData.records.underlyingValue || 0;

    // Fallback for spot price from filtered data if records is empty
    if (spot === 0 && rawData.filtered?.underlyingValue) {
      spot = rawData.filtered.underlyingValue;
    }

    if (spot === 0) {
      console.warn(`[${currentSymbol}] Spot price is 0, skipping stats calculation`);
      return;
    }

    const recordsData = rawData.records.data || [];

    // Expiry Filtering — supports both V3 key formats, falls back to all data
    const filteredData = recordsData.filter((d: any) => {
      const rowExpiry = d.expiryDate || d.expiryDates;
      return String(rowExpiry).toLowerCase() === String(expiry).toLowerCase();
    }).sort((a: any, b: any) => a.strikePrice - b.strikePrice);

    const workingData = filteredData.length > 0 ? filteredData : recordsData;
    if (workingData.length === 0) {
      console.warn(`No data found for expiry: ${expiry}`);
      return;
    }

    // ═══ DAYS TO EXPIRY ═══
    let daysToExpiry = 7.0;
    if (expiry) {
      try {
        const currentDate = new Date();
        const expiryDate = new Date(expiry);
        currentDate.setHours(0, 0, 0, 0);
        expiryDate.setHours(0, 0, 0, 0);
        const diffTime = Math.max(0, expiryDate.getTime() - currentDate.getTime());
        daysToExpiry = diffTime / (1000 * 60 * 60 * 24);
        if (daysToExpiry === 0) daysToExpiry = 0.25;
      } catch (err) { }
    }
    const T = daysToExpiry / 365;

    // ═══ ATM STRIKE & IMPLIED VOLATILITY ═══
    const strikeInterval = getStrikeInterval(currentSymbol);
    const atmStrike = Math.round(spot / strikeInterval) * strikeInterval;
    const atmRow = workingData.find((r: any) => r.strikePrice === atmStrike);
    const ceIv = atmRow?.CE?.impliedVolatility || 0;
    const peIv = atmRow?.PE?.impliedVolatility || 0;
    let atmIvVal = (ceIv + peIv) / 2;
    if (atmIvVal === 0) atmIvVal = ceIv || peIv || (currentSymbol.toUpperCase().includes('BANK') ? 16.0 : 13.0);
    const sigma = atmIvVal / 100;

    // ═══ COMPREHENSIVE MARKET MICROSTRUCTURE SCAN ═══
    let totalCeOi = 0, totalPeOi = 0;
    let ceOiDelta = 0, peOiDelta = 0;
    let ceTotalVol = 0, peTotalVol = 0;
    let totalGex = 0;
    let maxCeOiVal = 0, maxPeOiVal = 0;
    let resistanceStrike = atmStrike + strikeInterval * 2;
    let supportStrike = atmStrike - strikeInterval * 2;
    let ceBidQty = 0, ceAskQty = 0, peBidQty = 0, peAskQty = 0;
    const contractSize = currentSymbol === 'BANKNIFTY' ? 15 : (currentSymbol === 'MIDCPNIFTY' ? 75 : 25);

    workingData.forEach((row: any) => {
      const strike = row.strikePrice;
      const gamma = calculateGamma(spot, strike, sigma, T);
      const gexMultiplier = contractSize * spot * spot * 0.01;

      if (row.CE) {
        totalCeOi += row.CE.openInterest || 0;
        ceOiDelta += row.CE.changeinOpenInterest || 0;
        ceTotalVol += row.CE.totalTradedVolume || 0;
        ceBidQty += row.CE.buyQty1 || 0;
        ceAskQty += row.CE.sellQty1 || 0;
        totalGex += gamma * (row.CE.openInterest || 0) * gexMultiplier;
        if ((row.CE.openInterest || 0) > maxCeOiVal) {
          maxCeOiVal = row.CE.openInterest;
          resistanceStrike = strike;
        }
      }
      if (row.PE) {
        totalPeOi += row.PE.openInterest || 0;
        peOiDelta += row.PE.changeinOpenInterest || 0;
        peTotalVol += row.PE.totalTradedVolume || 0;
        peBidQty += row.PE.buyQty1 || 0;
        peAskQty += row.PE.sellQty1 || 0;
        totalGex -= gamma * (row.PE.openInterest || 0) * gexMultiplier;
        if ((row.PE.openInterest || 0) > maxPeOiVal) {
          maxPeOiVal = row.PE.openInterest;
          supportStrike = strike;
        }
      }
    });

    const ceImbalance = ceAskQty > 0 ? ceBidQty / ceAskQty : 1;
    const peImbalance = peAskQty > 0 ? peBidQty / peAskQty : 1;
    const orderBookDelta = ceImbalance > peImbalance ? 'CE ACCUMULATION (Bullish)' : 'PE ACCUMULATION (Bearish)';

    // ═══ MAX PAIN CALCULATION ═══
    let maxPain = atmStrike;
    let minPain = Infinity;
    const allStrikes = workingData.map((r: any) => r.strikePrice);
    allStrikes.forEach((candidatePrice: number) => {
      let totalPayout = 0;
      workingData.forEach((row: any) => {
        const s = row.strikePrice;
        if (candidatePrice > s) totalPayout += (candidatePrice - s) * (row.CE?.openInterest || 0);
        if (candidatePrice < s) totalPayout += (s - candidatePrice) * (row.PE?.openInterest || 0);
      });
      if (totalPayout < minPain) { minPain = totalPayout; maxPain = candidatePrice; }
    });

    // ═══ REAL PCR (Total OI) + Flow PCR (OI Change) ═══
    const pcrTotal = totalCeOi > 0 ? parseFloat((totalPeOi / totalCeOi).toFixed(2)) : 1.0;
    const pcrDelta = ceOiDelta !== 0 ? parseFloat((peOiDelta / ceOiDelta).toFixed(2)) : 0;

    // ═══ MULTI-FACTOR INSTITUTIONAL COMPOSITE SCORE (0-100) ═══
    const pcrFactor = Math.min(100, Math.max(0, (pcrTotal - 0.5) * 100));
    const oiFlowDenom = Math.abs(peOiDelta) + Math.abs(ceOiDelta) + 1;
    const flowFactor = Math.min(100, Math.max(0, 50 + ((peOiDelta - ceOiDelta) / oiFlowDenom) * 50));
    const volFactor = Math.min(100, Math.max(0, (peTotalVol / (ceTotalVol || 1)) * 50));
    const gexFactor = totalGex > 0 ? 60 : 40;
    const ics = Math.round(pcrFactor * 0.30 + flowFactor * 0.30 + volFactor * 0.20 + gexFactor * 0.20);

    // ═══ IV REGIME — Relative Bands ═══
    const ivBands: Record<string, [number, number]> = { 'BANKNIFTY': [12, 20], 'NIFTY': [10, 18] };
    const [ivLow, ivHigh] = ivBands[currentSymbol] || [10, 18];
    const regime = atmIvVal < ivLow ? 'COMPRESSION' : (atmIvVal > ivHigh ? 'EXPANSION' : 'NORMAL');

    // ═══ DIRECTIONAL BIAS ═══
    const isBullish = ics > 55;
    const isBearish = ics < 45;

    // deltaLabel aligned with ICS direction to avoid contradictory UI signals
    const oiBias = peOiDelta > ceOiDelta ? 'BULLISH' : 'BEARISH';
    const deltaLabel = oiBias === 'BULLISH' ? "📈 PUT BUILDUP (Bullish Support)" : "📉 CALL BUILDUP (Bearish Ceiling)";

    setStats({
      spot, pcr: pcrTotal.toFixed(2), pcrDelta,
      smi: ics.toString(),
      totalGex,
      gexLabel: totalGex > 0 ? "PIN SUPPORT (Dealers Long γ)" : "VOLATILE (Dealers Short γ)",
      deltaLabel,
      vsaLabel: ceTotalVol > peTotalVol ? "High CE Volume" : "High PE Volume",
      smiStatus: ics > 65 ? "STRONG BULLISH FLOW" : ics < 35 ? "STRONG BEARISH FLOW" : "NEUTRAL / RANGE-BOUND",
      ceTotalVol, peTotalVol,
      regime, iv: atmIvVal.toFixed(1),
      maxPain, support: supportStrike, resistance: resistanceStrike,
      daysToExpiry: daysToExpiry.toFixed(1),
      orderBookDelta
    });

    // ═══ MULTI-SIGMA QUANT TARGETS — LOCKED UNTIL DIRECTION CHANGES ═══
    const dailyT = 1 / 365;
    const impliedMove = spot * sigma * Math.sqrt(dailyT);
    const probItm = calculateProbabilityOfItm(spot, atmStrike, isBullish ? 'CE' : 'PE', sigma, T);
    const confidence = Math.max(50, Math.min(98, probItm + (ics - 50) * 0.15));
    const dir = isBullish ? 1 : -1;
    const newType = isBullish ? 'BULLISH' : (isBearish ? 'BEARISH' : 'NEUTRAL');

    // Only update quant levels if direction changed or first calculation
    const prevType = quantLevelsRef.current?.type;
    if (!quantLevelsRef.current || prevType !== newType) {
      setQuantLevels({
        type: newType,
        entry: spot,
        t1: parseFloat((spot + dir * impliedMove * 0.5).toFixed(2)),
        t2: parseFloat((spot + dir * impliedMove * 1.0).toFixed(2)),
        t3: parseFloat((spot + dir * impliedMove * 1.5).toFixed(2)),
        sl: parseFloat((spot - dir * impliedMove * 0.40).toFixed(2)),
        probability: confidence,
        impliedMove: parseFloat(impliedMove.toFixed(2)),
      });
    } else {
      // Direction same — only update probability (it tracks live sentiment)
      setQuantLevels((prev: any) => prev ? { ...prev, probability: confidence } : prev);
    }

    // ═══ OPTION TRAP DETECTION ═══
    const atmIndex = workingData.findIndex((d: any) => d.strikePrice >= atmStrike);
    if (atmIndex !== -1) {
      // Trapped Callers: Sold CE (OI increased) but Spot > Strike (ITM for CE)
      // Filter for massive OI additions relative to the chain
      const trappedCallers = workingData.slice(0, atmIndex)
        .filter((d: any) => (d.CE?.changeinOpenInterest || 0) > 0)
        .sort((a: any, b: any) => b.CE.changeinOpenInterest - a.CE.changeinOpenInterest)
        .slice(0, 2);

      // Trapped Putters: Sold PE (OI increased) but Spot < Strike (ITM for PE)
      const trappedPutters = workingData.slice(atmIndex)
        .filter((d: any) => (d.PE?.changeinOpenInterest || 0) > 0)
        .sort((a: any, b: any) => b.PE.changeinOpenInterest - a.PE.changeinOpenInterest)
        .slice(0, 2);

      setOptionTraps({ calls: trappedCallers, puts: trappedPutters });

      // Option Chain Matrix data (24 strikes around ATM)
      const chainSlice = workingData.slice(Math.max(0, atmIndex - 12), Math.min(workingData.length, atmIndex + 12));
      setChainData(chainSlice);
    }

  }, []);

  const fetchData = useCallback(async (currentSymbol: string, expiry?: string) => {
    const gen = ++fetchGenRef.current; // Race condition guard
    setLoading(true);
    try {
      const res = await marketService.getOptionChain(currentSymbol, expiry);
      if (gen !== fetchGenRef.current) return; // Stale response, discard
      if (res && res.records) {
        setData(res);
        let activeExpiry = expiry;
        if (res.records.expiryDates) {
          setExpiries(res.records.expiryDates);
          if (!expiry && res.records.expiryDates.length > 0) {
            activeExpiry = res.records.expiryDates[0];
            setSelectedExpiry(activeExpiry || '');
          }
        }
        setLastUpdated(new Date().toLocaleTimeString());
        calculateStats(res, activeExpiry || res.records.expiryDates[0], currentSymbol);
      }
    } catch (error) {
      console.error("Error fetching option chain:", error);
    } finally {
      if (gen === fetchGenRef.current) setLoading(false);
    }
  }, [calculateStats]);

  const fetchHistory = useCallback(async (currentSymbol: string) => {
    try {
      const [sigRes, tradeRes] = await Promise.allSettled([
        marketService.getSignalHistory(currentSymbol),
        marketService.getTrades(currentSymbol)
      ]);

      // Only apply if symbol hasn't changed during fetch
      if (symbolRef.current !== currentSymbol) return;

      if (sigRes.status === 'fulfilled' && sigRes.value.status === 'success') {
        setHistorySignals(sigRes.value.data);
        const evo = sigRes.value.data.map((s: any) => ({
          symbol: s.symbol,
          time: new Date(s.timestamp).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }),
          type: s.signal_type,
          confidence: s.confidence || 'N/A',
          spot: s.spot_price,
          pcr: s.pcr,
          smi: s.smi,
          text: s.analysis_text?.substring(0, 150) + (s.analysis_text?.length > 150 ? '...' : '')
        }));
        setSignalEvolution(evo);
      }

      if (tradeRes.status === 'fulfilled' && tradeRes.value.status === 'success') {
        setPaperTrades(tradeRes.value.data);
      }
    } catch (error) {
      console.error("Error fetching history:", error);
    }
  }, []);

  const onSocketData = useCallback((payload: any) => {
    if (payload.type === 'OPTION_CHAIN' && payload.data) {
      const res = payload.data;
      const firstRow = res.records?.data?.[0];
      const resUnderlying = firstRow?.CE?.underlying || firstRow?.PE?.underlying || '';
      const mappedSymbol = resUnderlying === 'NIFTY BANK' ? 'BANKNIFTY' : (resUnderlying === 'NIFTY 50' ? 'NIFTY' : resUnderlying);

      // Race condition guard: discard data if it is for a different symbol than active state
      if (mappedSymbol && mappedSymbol !== symbol) {
        console.warn(`[onSocketData] Discarded option chain socket data for ${mappedSymbol} because current active symbol is ${symbol}`);
        return;
      }

      setData(res);
      setLastUpdated(new Date().toLocaleTimeString());

      let activeExpiry = selectedExpiry;
      const expiryDates = res.records?.expiryDates || [];
      if (!activeExpiry || !expiryDates.includes(activeExpiry)) {
        activeExpiry = expiryDates[0] || '';
      }
      calculateStats(res, activeExpiry, symbol);
    }
  }, [calculateStats, selectedExpiry, symbol]);

  useSocket(`market_data_${symbol}`, onSocketData);

  const parseAIResponse = (text: string) => {
    if (!text) return '';
    let html = text;

    html = html.replace(/<think>[\s\S]*?<\/think>/g, '');

    // Ultra-Premium HUD Headers (Light/Dark Aware)
    html = html.replace(/^# (.*$)/gm, '<div class="relative overflow-hidden p-4 sm:p-6 rounded-2xl bg-gradient-to-br from-brand-50 to-white dark:from-[#0f172a] dark:to-[#1e293b] border border-brand-200 dark:border-brand-500/30 mb-10 shadow-sm dark:shadow-[0_0_30px_rgba(70,95,255,0.15)]"><div class="absolute -right-10 -top-10 w-48 h-48 bg-brand-500/10 dark:bg-brand-500/20 blur-3xl rounded-full"></div><div class="flex flex-col sm:flex-row items-start sm:items-center gap-4 sm:gap-5 relative z-10"><div class="p-3 sm:p-4 bg-white dark:bg-brand-500/20 rounded-2xl border border-brand-100 dark:border-brand-500/40 shadow-sm dark:shadow-[0_0_15px_rgba(70,95,255,0.5)]"><svg class="w-6 h-6 sm:w-8 sm:h-8 text-brand-500 dark:text-brand-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M13 10V3L4 14h7v7l9-11h-7z"></path></svg></div><div><h1 class="text-2xl sm:text-3xl font-black text-gray-900 dark:text-white tracking-tighter uppercase dark:text-transparent dark:bg-clip-text dark:bg-gradient-to-r dark:from-white dark:to-gray-400 dark:drop-shadow-lg">$1</h1><p class="text-[9px] sm:text-[10px] font-black text-brand-600 dark:text-brand-400 uppercase tracking-[0.4em] mt-1.5 flex items-center gap-2"><span class="w-1.5 h-1.5 bg-brand-500 rounded-full animate-pulse"></span> ALGOSYNC PROTOCOL ENGAGED</p></div></div></div>');

    html = html.replace(/^## (.*$)/gm, '<div class="flex items-center gap-4 mt-12 mb-6"><div class="h-px bg-gradient-to-r from-brand-500/0 via-brand-500/30 dark:via-brand-500/50 to-brand-500/0 flex-1"></div><h2 class="text-lg font-black text-gray-900 dark:text-white uppercase tracking-[0.2em] px-4 py-1.5 rounded-lg bg-brand-50 dark:bg-brand-500/10 border border-brand-200 dark:border-brand-500/20 shadow-sm dark:shadow-[0_0_15px_rgba(70,95,255,0.1)]">$1</h2><div class="h-px bg-gradient-to-r from-brand-500/0 via-brand-500/30 dark:via-brand-500/50 to-brand-500/0 flex-1"></div></div>');

    html = html.replace(/^### (.*$)/gm, '<h3 class="text-sm font-bold text-gray-600 dark:text-gray-400 mt-8 mb-4 uppercase tracking-[0.2em] flex items-center gap-2"><span class="w-4 h-px bg-brand-500/50"></span>$1</h3>');

    html = html.replace(/\*\*(.*?)\*\*/g, '<strong class="font-bold text-gray-900 dark:text-white bg-brand-50 dark:bg-brand-500/10 px-2 py-0.5 rounded border border-brand-200 dark:border-brand-500/20 dark:shadow-[0_0_10px_rgba(70,95,255,0.1)]">$1</strong>');

    html = html.replace(/^\-\s+(.*$)/gm, '<div class="flex items-start gap-4 mb-4 p-4 rounded-xl bg-gray-50 dark:bg-[#0f172a]/50 border border-gray-100 dark:border-white/5 hover:border-brand-300 dark:hover:border-brand-500/30 transition-all hover:bg-white dark:hover:bg-[#0f172a] hover:shadow-sm dark:hover:shadow-[0_0_20px_rgba(70,95,255,0.05)] group"><div class="mt-1.5 w-2 h-2 bg-gray-300 dark:bg-gray-600 rounded-sm transform rotate-45 group-hover:bg-brand-500 transition-colors dark:shadow-[0_0_10px_rgba(70,95,255,0)] dark:group-hover:shadow-[0_0_10px_rgba(70,95,255,0.8)] flex-shrink-0"></div><p class="text-gray-700 dark:text-gray-300 leading-relaxed text-[15px]">$1</p></div>');

    html = html.replace(/Direction:\s*(🟢\s*LONG|🔴\s*SHORT|⚪\s*AVOID)/gi, (match, p1) => {
      const isLong = p1.includes('LONG');
      const isShort = p1.includes('SHORT');
      const colorClass = isLong ? 'bg-success-50 dark:bg-success-500/10 text-success-600 dark:text-success-400 border-success-200 dark:border-success-500/30 dark:shadow-[0_0_20px_rgba(18,183,106,0.2)]' : isShort ? 'bg-error-50 dark:bg-error-500/10 text-error-600 dark:text-error-400 border-error-200 dark:border-error-500/30 dark:shadow-[0_0_20px_rgba(240,68,56,0.2)]' : 'bg-gray-100 dark:bg-gray-500/10 text-gray-600 dark:text-gray-400 border-gray-300 dark:border-gray-500/30';
      const glowDot = isLong ? 'bg-success-500 dark:bg-success-400' : isShort ? 'bg-error-500 dark:bg-error-400' : 'bg-gray-500 dark:bg-gray-400';
      return `<div class="inline-flex items-center gap-3 px-6 py-3 rounded-xl border ${colorClass} font-black text-[13px] tracking-[0.2em] uppercase mb-6 backdrop-blur-sm"><span class="relative flex h-2.5 w-2.5"><span class="animate-ping absolute inline-flex h-full w-full rounded-full ${glowDot} opacity-75"></span><span class="relative inline-flex rounded-full h-2.5 w-2.5 ${glowDot}"></span></span>DIRECTION: ${isLong ? 'LONG' : isShort ? 'SHORT' : 'AVOID'}</div>`;
    });

    html = html.replace(/Verdict:\s*(✅\s*YES|❌\s*NO)/gi, (match, p1) => {
      const isYes = p1.includes('YES');
      const boxColor = isYes ? 'from-success-50 to-white dark:from-success-500/20 dark:to-[#0a0a0b] border-success-200 dark:border-success-500/40 dark:shadow-[0_0_30px_rgba(18,183,106,0.15)]' : 'from-error-50 to-white dark:from-error-500/20 dark:to-[#0a0a0b] border-error-200 dark:border-error-500/40 dark:shadow-[0_0_30px_rgba(240,68,56,0.15)]';
      const textColor = isYes ? 'text-success-600 dark:text-success-400' : 'text-error-600 dark:text-error-400';
      return `<div class="mt-2 mb-8 py-5 px-4 sm:px-8 rounded-2xl bg-gradient-to-b ${boxColor} flex flex-col items-center justify-center text-center border overflow-hidden relative"><div class="absolute inset-0 bg-[url('https://www.transparenttextures.com/patterns/carbon-fibre.png')] opacity-[0.03] dark:opacity-[0.03]"></div><span class="text-[9px] sm:text-[10px] font-black uppercase tracking-[0.4em] opacity-60 mb-1.5 relative z-10 text-gray-800 dark:text-white">System Verdict</span><span class="text-2xl sm:text-3xl font-black tracking-tight ${textColor} relative z-10 drop-shadow-sm dark:drop-shadow-lg">${isYes ? 'EXECUTION APPROVED' : 'EXECUTION DENIED'}</span></div>`;
    });

    if (html.includes('|')) {
      const lines = html.split('\n');
      let newLines = [];
      let inTable = false;
      let tableHtml = '';

      for (let i = 0; i < lines.length; i++) {
        const line = lines[i].trim();
        if (line.startsWith('|') && line.endsWith('|')) {
          if (!inTable) {
            inTable = true;
            tableHtml = '<div class="my-8 rounded-2xl border border-gray-200 dark:border-white/10 bg-white dark:bg-[#0f172a]/80 dark:backdrop-blur-md overflow-x-auto shadow-sm dark:shadow-[0_0_30px_rgba(0,0,0,0.5)]"><div class="min-w-[500px]">';
          }
          if (line.includes('---')) continue;

          const cells = line.split('|').filter((_, idx, arr) => idx > 0 && idx < arr.length - 1).map(c => c.trim());
          const colCount = Math.min(cells.length, 4);
          const gridStyle = `grid-template-columns: repeat(${colCount}, minmax(0, 1fr))`;

          if (!tableHtml.includes('bg-brand-50')) {
            tableHtml += `<div class="grid bg-brand-50 dark:bg-brand-500/10 border-b border-brand-200 dark:border-brand-500/30 p-5 gap-4" style="${gridStyle}">`;
            cells.forEach(cell => {
              tableHtml += `<div class="text-xs font-black text-brand-600 dark:text-brand-400 uppercase tracking-[0.2em] dark:drop-shadow-[0_0_5px_rgba(70,95,255,0.8)] text-left">${cell}</div>`;
            });
            tableHtml += '</div>';
          } else {
            tableHtml += `<div class="grid p-5 border-b border-gray-100 dark:border-white/[0.05] hover:bg-gray-50 dark:hover:bg-brand-500/5 transition-colors items-center gap-4 group" style="${gridStyle}">`;
            cells.forEach((cell, idx) => {
              let formattedCell = cell;
              if (cell.toUpperCase().includes('BULL') || cell.toUpperCase().includes('LONG') || cell.toUpperCase() === 'YES') {
                formattedCell = `<span class="inline-flex px-3 py-1 rounded bg-success-50 dark:bg-success-500/10 text-success-600 dark:text-success-400 font-black text-[11px] uppercase tracking-widest border border-success-200 dark:border-success-500/20 dark:shadow-[0_0_10px_rgba(18,183,106,0.2)]">${cell}</span>`;
              } else if (cell.toUpperCase().includes('BEAR') || cell.toUpperCase().includes('SHORT') || cell.toUpperCase() === 'NO') {
                formattedCell = `<span class="inline-flex px-3 py-1 rounded bg-error-50 dark:bg-error-500/10 text-error-600 dark:text-error-400 font-black text-[11px] uppercase tracking-widest border border-error-200 dark:border-error-500/20 dark:shadow-[0_0_10px_rgba(240,68,56,0.2)]">${cell}</span>`;
              } else if (idx === 0) {
                formattedCell = `<span class="text-gray-700 dark:text-gray-300 font-bold group-hover:text-gray-900 dark:group-hover:text-white transition-colors flex items-center gap-2"><span class="w-1.5 h-1.5 bg-gray-300 dark:bg-white/20 rounded-full group-hover:bg-brand-500 transition-colors"></span>${cell}</span>`;
              } else {
                formattedCell = `<span class="text-gray-900 dark:text-white font-mono font-bold text-lg">${cell}</span>`;
              }
              tableHtml += `<div class="text-left">${formattedCell}</div>`;
            });
            tableHtml += '</div>';
          }
        } else {
          if (inTable) {
            tableHtml += '</div></div>';
            newLines.push(tableHtml);
            inTable = false;
            tableHtml = '';
          }
          newLines.push(line);
        }
      }
      if (inTable) {
        tableHtml += '</div></div>';
        newLines.push(tableHtml);
      }
      html = newLines.join('\n');
    }

    html = html.split('\n').map(line => {
      const trimmed = line.trim();
      if (!trimmed || trimmed.startsWith('<div') || trimmed.startsWith('<h') || trimmed.startsWith('<hr')) return line;
      return `<p class="text-gray-600 dark:text-gray-400 leading-relaxed mb-5 text-[15px] dark:opacity-90">${line}</p>`;
    }).join('');

    return sanitizeHTML(html);
  };

  const handleCloseTrade = useCallback(async (trade: any) => {
    const currentSymbol = symbolRef.current;
    const currentStats = statsRef.current;
    if (trade.symbol !== currentSymbol) {
      alert(`Switch to ${trade.symbol} first to close this trade with correct spot price.`);
      return;
    }

    // Use current index spot price as exit (all targets are index-based)
    const exitPrice = currentStats.spot || 0;

    if (exitPrice <= 0) {
      alert("Error: Could not retrieve current spot price. Please refresh and try again.");
      return;
    }

    try {
      await marketService.closeTrade(trade.id, exitPrice);
      fetchHistory(currentSymbol);
      alert(`Trade Closed Successfully @ ₹${exitPrice} (Index Spot)!`);
    } catch (e) { console.error(e); }
  }, [fetchHistory]);

  const executeTrade = useCallback(async () => {
    if (!vipSignalRef.current) return;
    const currentSymbol = symbolRef.current;
    const sig = vipSignalRef.current;
    try {
      await marketService.executeTrade({
        symbol: currentSymbol,
        type: sig.action,
        contract: sig.contract,
        entry_price: sig.entry,
        t1: sig.t1,
        t2: sig.t2,
        sl: sig.sl
      });
      fetchHistory(currentSymbol);
      alert("Trade Executed!");
    } catch (e) { console.error(e); }
  }, [fetchHistory]);

  const runAIAnalysis = useCallback(async () => {
    // Read from refs for fresh values (no stale closures)
    const currentSymbol = symbolRef.current;
    const currentStats = statsRef.current;
    const currentData = dataRef.current;
    const currentTrades = paperTradesRef.current;
    const currentEvolution = signalEvolutionRef.current;
    const currentVipSignal = vipSignalRef.current;
    const currentQuant = quantLevelsRef.current;

    console.log(`[${currentSymbol}] Starting Managed AI Analysis...`);
    setAiAnalysis("Analyzing market structure & managing active trades...");
    if (!currentData || !currentData.records) return;

    const spot = currentStats.spot || 0;
    if (spot === 0) { setAiAnalysis('Waiting for spot price...'); return; }
    const API_URL = process.env.NEXT_PUBLIC_API_URL || "http://127.0.0.1:5050/api";

    const activeTrade = currentTrades.find((t: any) => t.status === 'OPEN');
    const recentSentiment = currentEvolution.slice(0, 5).map((s: any) => `${s.time}:${s.type}`).join(" -> ");

    let tradeContext = activeTrade
      ? `[ACTIVE TRADE]: Currently ${activeTrade.type} on ${activeTrade.contract} from ${activeTrade.entry_price}. Current P&L is ${((spot - activeTrade.entry_price) * (activeTrade.type.includes('BUY') ? 1 : -1)).toFixed(2)} pts.`
      : "[ACTIVE TRADE]: None.";

    let candleHistory = "Fetching...";
    try {
      const chartRes = await fetch(`${API_URL}/market/nse/chart?symbol=${currentSymbol}&_=${Date.now()}`, { credentials: 'include' });
      if (chartRes.ok) {
        const chartJson = await chartRes.json();
        let graphPoints = chartJson.grapthData || chartJson.data?.grapthData || [];
        candleHistory = graphPoints.length > 0 ? graphPoints.slice(-20).map((p: any) => p[1].toFixed(2)).join(",") : "Chart Offline";
      } else { candleHistory = "Chart Offline"; }
    } catch (e) { candleHistory = "Chart Offline"; }

    const marketDataString = `SYM:${currentSymbol} | SPOT:${spot} | PCR_OI:${currentStats.pcr} | PCR_FLOW:${currentStats.pcrDelta || 0} | ICS:${currentStats.smi} | GEX:${currentStats.gexLabel} | OI_FLOW:${currentStats.deltaLabel} | VOL_CE:${currentStats.ceTotalVol} | VOL_PE:${currentStats.peTotalVol} | MAX_PAIN:${currentStats.maxPain || 0} | OI_SUPPORT:${currentStats.support || 0} | OI_RESISTANCE:${currentStats.resistance || 0} | IV:${currentStats.iv}% | DTE:${currentStats.daysToExpiry || 0} | REGIME:${currentStats.regime || 'N/A'} | HIST_SENTIMENT: ${recentSentiment} | CANDLES(20p): ${candleHistory}`;

    const quantTargetsString = currentQuant ? `\n[ALGO REFERENCE DATA]: Algo Bias: ${currentQuant.type}, Algo Entry: ${currentQuant.entry}, Algo T1: ${currentQuant.t1}, Algo SL: ${currentQuant.sl}\n(WARNING: These are just statistical baselines. Do NOT blindly copy them. The final decision, logic, and exact price levels MUST be determined completely by YOU based on Smart Money Concepts.)` : '';

    // Previous signal context for AI hysteresis (prevents flip-flopping)
    let prevSignalContext = '';
    if (currentVipSignal && currentVipSignal.action) {
      prevSignalContext = `\n[PREVIOUS SIGNAL]: Action: ${currentVipSignal.action}, Type: ${currentVipSignal.type}, Entry: ${currentVipSignal.entry}, T1: ${currentVipSignal.t1}, T2: ${currentVipSignal.t2}, SL: ${currentVipSignal.sl}, Contract: ${currentVipSignal.contract}`;
      prevSignalContext += `\nIMPORTANT: Do NOT change direction unless there is a SIGNIFICANT structural break (PCR shift > 0.3, ICS swing > 15 pts, or trend reversal on 5m/15m). If data is similar to previous cycle, output ACTION: HOLD with same TYPE as previous signal.`;
    }

    const systemPrompt = `ACT AS AN INSTITUTIONAL QUANT TRADING STRATEGIST (V8.1 - MASTERMIND).\\nYOUR GOAL: Provide independent, high-conviction analysis based on structural order flow and SMC.\\nCONTEXT: ${tradeContext}\\nLAST SENTIMENT HISTORY: ${recentSentiment}${quantTargetsString}${prevSignalContext}\\nSTABILITY RULES:\\n1. You are the sole AI Mastermind. We have provided you with ALL statistical algo data, BUT THE FINAL DECISION IS YOURS. You MUST generate your OWN unique entry, target, and stop loss levels based on Fair Value Gaps (FVG), Liquidity Pools (BSL/SSL), and VWAP.\\n2. If the current market data has not meaningfully changed structurally from the last signal, MAINTAIN THE PREVIOUS VIEW (ACTION: HOLD) to prevent noise.\\n3. Only change from BULLISH/BEARISH to NEUTRAL (or vice-versa) if there is a significant structural break.\\nOUTPUT FORMAT:
    Structure your reasoning EXACTLY like this (use markdown tables):
    # 🏦 CR LEGEND SIGNAL
    Direction: 🟢 LONG or 🔴 SHORT or ⚪ AVOID
    Verdict: ✅ YES or ❌ NO
    
    ## 📊 KEY QUANT METRICS
    | Metric | Value | Institutional Bias |
    |:---|:---|:---|
    | PCR Ratio | [val] | [bias] |
    | Comp. Score (ICS) | [val] | [bias] |
    | Gamma Exp. | [val] | [bias] |
    | Option Vol | [val] | [bias] |
    
    ## 🎯 EXECUTION TARGETS (ALL PRICES ARE INDEX SPOT LEVELS)
    | Level | Index Price | Action |
    |:---|:---|:---|
    | Entry | [current index spot] | Enter Position |
    | Stop Loss | [index level below/above entry] | Risk Invalidation |
    | T1 | [index level] | Conservative Target |
    | T2 | [index level] | Extended Target |
    
    ## 🧠 STRATEGIC REASONING
    - Point 1
    - Point 2
    
    [[SET_SIGNAL: ACTION|TYPE|ENTRY|T1|T2|SL|CONFIDENCE%]]
    
    TAG RULES:
    - ACTION: MUST be one of (LONG, SHORT, AVOID, HOLD, EXIT)
    - TYPE: MUST be one of (BULLISH, BEARISH, NEUTRAL). Do NOT use terms like "LIMIT" or "MARKET".`;

    try {
      const response = await fetch(`${API_URL}/ai/chat/nse`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ message: `Market Data: ${marketDataString}`, system_prompt: systemPrompt, symbol: currentSymbol }),
        credentials: 'include'
      });
      if (!response.ok) throw new Error("AI Server Error");
      if (!response.body) return;
      const reader = response.body.getReader();
      const decoder = new TextDecoder();
      let fullContent = "";
      while (true) {
        const { done, value } = await reader.read();
        if (done) break;
        // Abort if symbol changed mid-stream
        if (symbolRef.current !== currentSymbol) { reader.cancel(); return; }
        const chunk = decoder.decode(value);
        const lines = chunk.split('\n');
        for (const line of lines) {
          if (line.startsWith('data: ')) {
            try {
              const json = JSON.parse(line.substring(6));
              if (json.text) {
                fullContent += json.text;
                // Sanitize HTML to prevent XSS and pass through Premium HUD Parser
                const rawMarkdown = fullContent.replace(/\[\[SET_SIGNAL:.*?\]\]/gi, "").replace(/```html/g, "").replace(/```/g, "").replace(/<script[^>]*>.*?<\/script>/gi, '').replace(/on\w+="[^"]*"/gi, '');
                setAiAnalysis(parseAIResponse(rawMarkdown));
              }
            } catch (e) { }
          }
        }
      }

      const match = fullContent.match(/\[\[SET_SIGNAL:\s*(.*?)\|(.*?)\|(.*?)\|(.*?)\|(.*?)\|(.*?)\|(.*?)\]\]/);
      if (match && spot > 0) {
        const [_, action, type, entry, t1, t2, sl, confidence] = match.map(m => m.trim().toUpperCase());
        const parsedEntry = parseFloat(entry) || 0;

        // Index Price Sanity Guard: entry should be within ±10% of current spot
        const isNeutralAction = ['AVOID', 'HOLD', 'EXIT'].includes(action);
        if (!isNeutralAction && parsedEntry > 0 && Math.abs(parsedEntry - spot) > spot * 0.10) {
          console.warn(`[NSE UI] Vetoed signal: Index entry ${parsedEntry} is too far from spot ${spot}. Likely an AI hallucination.`);
          setVipSignal({
            action: 'HOLD',
            type: 'NEUTRAL',
            contract: 'SYSTEM STANCE: HOLD (VETOED HALLUCINATION)',
            entry: 0,
            t1: 0,
            t2: 0,
            sl: 0,
            confidence: '95%'
          });
          setLastUpdated(new Date().toLocaleTimeString());
          return;
        }

        const isBearish = type.includes('BEAR') || type.includes('SHORT');
        const isBullish = type.includes('BULL') || type.includes('LONG');

        // FOR RETAIL: ALWAYS FORCE OPTION BUYING (NEVER SELL OPTIONS).
        // If they are bearish, they BUY PE. If bullish, they BUY CE.
        let inferredAction = 'BUY';
        if (['AVOID', 'HOLD', 'EXIT'].includes(action)) {
          inferredAction = action;
        }

        let contractOptionType = 'CE';
        if (isBullish) {
          contractOptionType = 'CE'; // Bullish -> Buy CE
        } else if (isBearish) {
          contractOptionType = 'PE'; // Bearish -> Buy PE
        } else {
          contractOptionType = 'CE';
        }

        const strikeInterval = getStrikeInterval(currentSymbol);
        const atmStrike = Math.round(spot / strikeInterval) * strikeInterval;

        setVipSignal({
          action: inferredAction,
          type,
          contract: ['AVOID', 'HOLD'].includes(inferredAction) || parsedEntry === 0
            ? `SYSTEM STANCE: ${inferredAction}`
            : `${inferredAction} ${currentSymbol} ${atmStrike} ${contractOptionType}`,
          entry: parsedEntry,
          t1: parseFloat(t1) || 0,
          t2: parseFloat(t2) || 0,
          sl: parseFloat(sl) || 0,
          confidence
        });

        const normalizedAction = ['LONG', 'SHORT', 'BUY', 'SELL'].includes(inferredAction) ? 'NEW' : inferredAction;

        if (['NEW', 'REVERSE', 'HOLD', 'AVOID', 'EXIT'].includes(normalizedAction)) {
          audioRef.current?.play().catch(() => { });
          setTimeout(() => fetchHistory(currentSymbol), 1500);
        }
        setLastUpdated(new Date().toLocaleTimeString());
      } else {
        console.warn("AI skipped Signal Tag. Attempting DB-sync fallback...");
        setTimeout(async () => {
          try {
            const res = await marketService.getLatestSignal(currentSymbol);
            if (res.status === 'success' && res.data) {
              const s = res.data;
              const parsedEntry = parseFloat(s.entry) || 0;
              const dbSpot = parseFloat(s.spot_price) || spot;

              // Index Price Sanity Guard: entry should be within ±10% of spot
              if (parsedEntry > 0 && dbSpot > 0 && Math.abs(parsedEntry - dbSpot) > dbSpot * 0.10) {
                console.warn(`[NSE UI Fallback] Vetoed DB signal: index entry ${parsedEntry} is too far from spot ${dbSpot}.`);
                setVipSignal({
                  action: 'HOLD',
                  type: 'NEUTRAL',
                  entry: 0,
                  t1: 0,
                  t2: 0,
                  sl: 0,
                  contract: 'SYSTEM STANCE: HOLD (VETOED HALLUCINATION)',
                  confidence: '95%'
                });
                setLastUpdated(new Date().toLocaleTimeString());
                return;
              }

              const isBearish = s.signal_type.toUpperCase().includes('BEAR') || s.signal_type.toUpperCase().includes('SHORT');
              const isBullish = s.signal_type.toUpperCase().includes('BULL') || s.signal_type.toUpperCase().includes('LONG');

              let inferredAction = 'HOLD';
              if (parsedEntry > 0) {
                inferredAction = 'BUY'; // FORCE BUY
              }

              let contractOptionType = 'CE';
              if (isBullish) {
                contractOptionType = 'CE';
              } else if (isBearish) {
                contractOptionType = 'PE';
              }

              const strikeInterval = getStrikeInterval(currentSymbol);
              const atmStrike = Math.round(dbSpot / strikeInterval) * strikeInterval;

              setVipSignal({
                action: inferredAction,
                type: s.signal_type,
                entry: parsedEntry,
                t1: parseFloat(s.t1) || 0,
                t2: parseFloat(s.t2) || 0,
                sl: parseFloat(s.sl) || 0,
                contract: inferredAction === 'HOLD'
                  ? `SYSTEM STANCE: HOLD`
                  : `${inferredAction} ${currentSymbol} ${atmStrike} ${contractOptionType}`,
                confidence: s.confidence || 'HIGH'
              });
              setLastUpdated(new Date().toLocaleTimeString());
              fetchHistory(currentSymbol);
            }
          } catch (e) {
            console.error("DB Fallback failed:", e);
          }
        }, 2000);
      }
    } catch (error) { console.error("AI Analysis Error:", error); }
  }, [fetchHistory]);

  useEffect(() => {
    fetchData(symbol);
    fetchHistory(symbol);
    const aiInterval = setInterval(() => runAIAnalysis(), 300000);
    return () => clearInterval(aiInterval);
  }, [symbol, fetchData, fetchHistory, runAIAnalysis]);

  useEffect(() => {
    if (data) {
      setLastUpdated(new Date().toLocaleTimeString());
    }
  }, [data]);

  useEffect(() => {
    if (stats.spot && stats.spot > 0 && data && !hasAutoAnalyzed.current) {
      console.log(`[${symbol}] Auto-triggering AI Analysis for spot @${stats.spot}`);
      hasAutoAnalyzed.current = true;
      runAIAnalysis();
    }
  }, [stats.spot, data, symbol, runAIAnalysis]);

  const handleSymbolChange = (newSymbol: string) => {
    if (newSymbol === symbol) return;

    // Clear stale data BEFORE setting new symbol to prevent cross-contamination
    setData(null);
    setStats({});
    setQuantLevels(null);
    setPaperTrades([]);
    setHistorySignals([]);
    setSignalEvolution([]);
    setVipSignal(null);
    setAiAnalysis('');
    hasAutoAnalyzed.current = false;
    setSelectedExpiry('');
    setSymbol(newSymbol);

    // Pre-load signal from DB for instant UI fill
    marketService.getLatestSignal(newSymbol).then(res => {
      if (symbolRef.current !== newSymbol) return; // Stale
      if (res.status === 'success' && res.data) {
        const s = res.data;
        const parsedEntry = parseFloat(s.entry) || 0;
        const dbSpot = parseFloat(s.spot_price) || 0;

        // Index Price Sanity Guard: entry should be within ±10% of spot
        if (parsedEntry > 0 && dbSpot > 0 && Math.abs(parsedEntry - dbSpot) > dbSpot * 0.10) {
          console.warn(`[NSE UI Preload] Vetoed DB preload signal: index entry ${parsedEntry} is too far from spot ${dbSpot}.`);
          setVipSignal({
            action: 'HOLD',
            type: 'NEUTRAL',
            entry: 0,
            t1: 0,
            t2: 0,
            sl: 0,
            contract: 'SYSTEM STANCE: HOLD (VETOED HALLUCINATION)',
            confidence: '95%'
          });
          setAiAnalysis(s.analysis_text || '');
          return;
        }

        const isBearish = s.signal_type.toUpperCase().includes('BEAR') || s.signal_type.toUpperCase().includes('SHORT');
        const isBullish = s.signal_type.toUpperCase().includes('BULL') || s.signal_type.toUpperCase().includes('LONG');

        let inferredAction = 'HOLD';
        if (parsedEntry > 0) {
          inferredAction = 'BUY'; // FORCE BUY
        }

        let contractOptionType = 'CE';
        if (isBullish) {
          contractOptionType = 'CE';
        } else if (isBearish) {
          contractOptionType = 'PE';
        }
        const strikeInterval = getStrikeInterval(newSymbol);
        const atmStrike = dbSpot > 0 ? Math.round(dbSpot / strikeInterval) * strikeInterval : 0;

        setVipSignal({
          action: inferredAction,
          type: s.signal_type,
          entry: parsedEntry,
          t1: parseFloat(s.t1) || 0,
          t2: parseFloat(s.t2) || 0,
          sl: parseFloat(s.sl) || 0,
          contract: inferredAction === 'HOLD' || atmStrike === 0
            ? `SYSTEM STANCE: HOLD`
            : `${inferredAction} ${newSymbol} ${atmStrike} ${contractOptionType}`,
          confidence: s.confidence || 'HIGH'
        });
        setAiAnalysis(s.analysis_text || '');
      } else {
        setVipSignal(null);
        setAiAnalysis('');
      }
    }).catch(() => { });
  };

  const formatNum = (num: number) => num ? num.toLocaleString('en-IN') : '0';
  const getHeatmapColor = (val: number) => {
    if (!val) return '';
    const opacity = Math.min(0.2, Math.abs(val) / 100000);
    return val > 0 ? `rgba(34, 197, 94, ${opacity})` : `rgba(239, 68, 68, ${opacity})`;
  };

  return (
    <div className="space-y-6">
      <PageBreadcrumb pageTitle="NSE Institutional Terminal" />
      <ComponentCard
        title="Market Synchronization"
        desc=""
      >
        <div className="flex flex-wrap items-center justify-between gap-4 mb-4 pb-4 border-b border-gray-100 dark:border-gray-800">
          <div className="flex items-center gap-2">
            <div className="flex items-center gap-1.5 px-3 py-1 bg-success-500/10 rounded-full">
              <div className="w-1.5 h-1.5 bg-success-500 rounded-full animate-pulse"></div>
              <span className="text-[10px] font-bold text-success-600 uppercase tracking-tight">Live Connection</span>
            </div>
            <span className="text-[11px] text-gray-500 font-medium">Updated: {lastUpdated || '--:--:--'}</span>
            <span className="text-[11px] text-gray-400">|</span>
            <span className="text-[11px] text-gray-500 font-medium">AI Analysis: 5m</span>
          </div>
          <div className="flex items-center gap-2">
            {stats.regime && (
              <Badge color={stats.regime === 'COMPRESSION' ? 'warning' : stats.regime === 'EXPANSION' ? 'error' : 'success'} variant="light" size="sm">
                VOL REGIME: {stats.regime} (IV: {stats.iv}%)
              </Badge>
            )}
            <Badge color="info" variant="light" size="sm">AUTO-SYNC ON</Badge>
          </div>
        </div>
        <div className="flex flex-col sm:flex-row flex-wrap items-start sm:items-center justify-between gap-4">
          <div className="flex bg-gray-100 dark:bg-gray-800 p-1 rounded-xl w-full sm:w-auto overflow-x-auto custom-scrollbar pb-1 sm:pb-1">
            {['NIFTY', 'BANKNIFTY'].map(s => (
              <button key={s} onClick={() => handleSymbolChange(s)} className={`px-4 sm:px-6 py-2 rounded-lg text-sm font-semibold transition-all whitespace-nowrap ${symbol === s ? 'bg-white dark:bg-gray-700 text-brand-500 shadow-sm' : 'text-gray-500 hover:text-gray-700 dark:hover:text-gray-300'}`}>{s}</button>
            ))}
          </div>
          <div className="flex flex-wrap items-center gap-2 sm:gap-3 w-full sm:w-auto">
            <select value={selectedExpiry} onChange={(e) => { setSelectedExpiry(e.target.value); fetchData(symbol, e.target.value); }} className="flex-1 sm:flex-none bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg px-4 py-2 text-sm font-medium outline-none">
              {expiries.map(exp => <option key={exp} value={exp}>{exp}</option>)}
            </select>
            <Button onClick={() => fetchData(symbol, selectedExpiry)} variant="outline" size="sm" className="flex-1 sm:flex-none justify-center" startIcon={<RefreshCw size={16} className={loading ? 'animate-spin' : ''} />}>Refresh</Button>
            <Button onClick={runAIAnalysis} variant="primary" size="sm" className="w-full sm:w-auto justify-center" startIcon={<Zap size={16} />}>AI Analyze</Button>
          </div>
        </div>
      </ComponentCard>

      <div className="grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-4 gap-4">
        <StatCard label="Live Spot" value={formatNum(stats.spot)} sub="NSE Feed" color="text-brand-500" />
        <StatCard label="PCR (Total OI)" value={stats.pcr || '0.00'} sub={stats.pcr ? (parseFloat(stats.pcr) > 1.0 ? 'Bullish ↑ (Put Support)' : (parseFloat(stats.pcr) < 0.7 ? 'Bearish ↓ (Call Resistance)' : 'Neutral')) : 'Loading...'} color={stats.pcr ? (parseFloat(stats.pcr) > 1.0 ? 'text-success-500' : (parseFloat(stats.pcr) < 0.7 ? 'text-error-500' : 'text-gray-400')) : 'text-gray-400'} />
        <StatCard label="ICS (Composite)" value={stats.smi || '0'} sub={stats.smiStatus} color="text-brand-500" />
        <StatCard label="Max Pain" value={formatNum(stats.maxPain)} sub={stats.spot && stats.maxPain ? (stats.spot > stats.maxPain ? `Spot +${(stats.spot - stats.maxPain).toFixed(0)} above` : `Spot ${(stats.spot - stats.maxPain).toFixed(0)} below`) : ''} color="text-warning-500" />
      </div>
      <div className="grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-4 gap-4">
        <StatCard label="OI Support" value={formatNum(stats.support)} sub="Max PE OI Strike" color="text-success-500" />
        <StatCard label="OI Resistance" value={formatNum(stats.resistance)} sub="Max CE OI Strike" color="text-error-500" />
        <StatCard label="Order Flow Delta" value={stats.orderBookDelta ? stats.orderBookDelta.split(' ')[0] : '--'} sub={stats.orderBookDelta || 'Loading...'} color={stats.orderBookDelta?.includes('Bullish') ? 'text-success-500' : 'text-error-500'} />
        <StatCard label="Days to Expiry" value={stats.daysToExpiry || '--'} sub={`IV: ${stats.iv || '--'}% | ${stats.regime || ''}`} color="text-brand-500" />
      </div>

      {/* Dual Engine Section */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <ComponentCard title="Institutional Mastermind">
          {vipSignal ? (
            <div className="space-y-4">
              <div className="flex items-center justify-between">
                <Badge
                  color={
                    ['AVOID', 'HOLD'].includes(vipSignal.action) || vipSignal.type.includes('NEUTRAL')
                      ? 'info'
                      : (vipSignal.type.includes('BUY') || vipSignal.type.includes('BULL') ? 'success' : 'error')
                  }
                  variant="solid"
                >
                  {vipSignal.type}
                </Badge>
                <span className="text-[10px] font-bold text-gray-400 uppercase tracking-widest">Mastermind v8.1</span>
              </div>
              <h3 className="text-2xl font-black text-gray-800 dark:text-white">{vipSignal.contract}</h3>
              {['AVOID', 'HOLD'].includes(vipSignal.action) || vipSignal.entry === 0 ? (
                <div className="py-6 px-4 rounded-xl bg-gray-50 dark:bg-white/5 border border-gray-100 dark:border-gray-800 text-center">
                  <p className="text-xs font-bold text-gray-500 uppercase tracking-wider">No Active Trade Execution Recommended</p>
                  <p className="text-[10px] text-gray-400 mt-1">The system is currently standing by and monitoring market structural shifts.</p>
                </div>
              ) : (
                <>
                  <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
                    <TradeInfo label="Entry" val={formatNum(vipSignal.entry)} color="" />
                    <TradeInfo label="Stop Loss" val={formatNum(vipSignal.sl)} color="text-error-500" />
                    <TradeInfo label="Target 1" val={formatNum(vipSignal.t1)} color="text-success-500" />
                    <TradeInfo label="Target 2" val={formatNum(vipSignal.t2)} color="text-success-500" />
                  </div>
                  <Button onClick={executeTrade} className="w-full mt-2" variant="primary" startIcon={<PlayCircle size={16} />}>Execute Live Trade</Button>
                </>
              )}
            </div>
          ) : <div className="py-12 text-center text-gray-400 italic">Scanning orderflow...</div>}
        </ComponentCard>

        <ComponentCard title="Quant Engine (σ Volatility Model)">
          {quantLevels ? (
            <div className="space-y-4">
              <div className="flex items-center justify-between">
                <Badge color={quantLevels.type === 'BULLISH' ? 'success' : quantLevels.type === 'BEARISH' ? 'error' : 'info'} variant="light">{quantLevels.type}</Badge>
                <div className="flex items-center gap-2">
                  <span className="text-[10px] font-bold text-gray-400 uppercase">Confidence</span>
                  <Badge color="primary" variant="solid" size="sm">{quantLevels.probability.toFixed(0)}%</Badge>
                </div>
              </div>
              <h3 className="text-2xl font-black text-gray-800 dark:text-white">Multi-Sigma Algo v2</h3>
              <p className="text-[10px] text-gray-400 font-bold">Daily Implied Move: ±{formatNum(quantLevels.impliedMove || 0)} pts (1σ)</p>
              <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
                <TradeInfo label="Entry (Spot)" val={formatNum(quantLevels.entry)} color="" />
                <TradeInfo label="SL (0.4σ)" val={formatNum(quantLevels.sl)} color="text-error-400" />
                <TradeInfo label="T1 (0.5σ)" val={formatNum(quantLevels.t1)} color="text-success-400" />
                <TradeInfo label="T2 (1.0σ)" val={formatNum(quantLevels.t2)} color="text-success-500" />
                <TradeInfo label="T3 (1.5σ)" val={formatNum(quantLevels.t3 || 0)} color="text-success-600" />
              </div>
              <div className="mt-4 pt-4 border-t border-gray-100 dark:border-gray-800 flex justify-between items-center">
                <span className="text-[10px] text-gray-400 uppercase font-bold tracking-tighter">Black-Scholes Intraday σ Model</span>
                <Badge color="info" size="sm">REAL-TIME</Badge>
              </div>
            </div>
          ) : <div className="py-12 text-center text-gray-400 italic">Calculating...</div>}
        </ComponentCard>
      </div>

      {/* Institutional Traps UI */}
      {optionTraps.calls.length > 0 || optionTraps.puts.length > 0 ? (
        <ComponentCard title="Institutional Trap Zones">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="space-y-2">
              <h4 className="text-xs font-bold text-gray-500 uppercase">Trapped Call Writers (Short Squeeze Risk)</h4>
              {optionTraps.calls.map((t: any) => (
                <div key={t.strikePrice} className="p-3 bg-error-500/10 border border-error-500/20 rounded-lg flex justify-between items-center">
                  <div>
                    <span className="text-error-500 font-bold">{t.strikePrice} CE</span>
                    <p className="text-[10px] text-gray-400">Added {formatNum(t.CE.changeinOpenInterest)} OI while ITM</p>
                  </div>
                  <Badge color="error" variant="light">BEAR TRAP</Badge>
                </div>
              ))}
              {optionTraps.calls.length === 0 && <div className="text-gray-500 text-sm italic">No trapped call writers.</div>}
            </div>
            <div className="space-y-2">
              <h4 className="text-xs font-bold text-gray-500 uppercase">Trapped Put Writers (Long Liquidation Risk)</h4>
              {optionTraps.puts.map((t: any) => (
                <div key={t.strikePrice} className="p-3 bg-success-500/10 border border-success-500/20 rounded-lg flex justify-between items-center">
                  <div>
                    <span className="text-success-500 font-bold">{t.strikePrice} PE</span>
                    <p className="text-[10px] text-gray-400">Added {formatNum(t.PE.changeinOpenInterest)} OI while ITM</p>
                  </div>
                  <Badge color="success" variant="light">BULL TRAP</Badge>
                </div>
              ))}
              {optionTraps.puts.length === 0 && <div className="text-gray-500 text-sm italic">No trapped put writers.</div>}
            </div>
          </div>
        </ComponentCard>
      ) : null}

      {/* Live Option Chain Matrix */}
      {chainData.length > 0 && (
        <ComponentCard title="Live Option Chain Matrix">
          <div className="overflow-x-auto text-[11px]">
            <table className="w-full text-right border-collapse whitespace-nowrap">
              <thead>
                <tr className="border-b border-gray-100 dark:border-gray-800 text-gray-500">
                  <th className="py-2 px-2 text-left font-normal">CE OI</th>
                  <th className="py-2 px-2 font-normal">CE ΔOI</th>
                  <th className="py-2 px-2 font-normal">CE Vol</th>
                  <th className="py-2 px-2 font-normal">CE LTP</th>
                  <th className="py-2 px-4 text-center font-bold text-gray-800 dark:text-gray-200 bg-gray-50 dark:bg-gray-800/50 rounded-t-lg">STRIKE</th>
                  <th className="py-2 px-2 font-normal">PE LTP</th>
                  <th className="py-2 px-2 font-normal">PE Vol</th>
                  <th className="py-2 px-2 font-normal">PE ΔOI</th>
                  <th className="py-2 px-2 text-right font-normal">PE OI</th>
                </tr>
              </thead>
              <tbody>
                {chainData.map((row: any) => {
                  const strike = row.strikePrice;
                  const isCallItm = strike < stats.spot;
                  const isPutItm = strike > stats.spot;
                  const isAtm = Math.abs(strike - stats.spot) <= getStrikeInterval(symbol) / 2;

                  return (
                    <tr key={strike} className={`border-b border-gray-50 dark:border-gray-800/50 hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors ${isAtm ? 'bg-brand-500/10 dark:bg-brand-500/20' : ''}`}>
                      <td className={`py-1.5 px-2 text-left ${isCallItm ? 'bg-warning-500/10 dark:bg-warning-500/20 font-medium' : 'text-gray-500'}`}>{formatNum(row.CE?.openInterest)}</td>
                      <td className={`py-1.5 px-2 ${isCallItm ? 'bg-warning-500/10 dark:bg-warning-500/20 font-medium' : 'text-gray-500'}`}>{formatNum(row.CE?.changeinOpenInterest)}</td>
                      <td className={`py-1.5 px-2 ${isCallItm ? 'bg-warning-500/10 dark:bg-warning-500/20 font-medium' : 'text-gray-500'}`}>{formatNum(row.CE?.totalTradedVolume)}</td>
                      <td className={`py-1.5 px-2 font-bold ${row.CE?.change > 0 ? 'text-success-500' : 'text-error-500'} ${isCallItm ? 'bg-warning-500/10 dark:bg-warning-500/20' : ''}`}>{row.CE?.lastPrice?.toFixed(1) || '--'}</td>

                      <td className="py-1.5 px-4 text-center font-bold text-brand-500 bg-gray-50 dark:bg-gray-800/50 border-x border-gray-100 dark:border-gray-800/50">{strike}</td>

                      <td className={`py-1.5 px-2 font-bold ${row.PE?.change > 0 ? 'text-success-500' : 'text-error-500'} ${isPutItm ? 'bg-warning-500/10 dark:bg-warning-500/20' : ''}`}>{row.PE?.lastPrice?.toFixed(1) || '--'}</td>
                      <td className={`py-1.5 px-2 ${isPutItm ? 'bg-warning-500/10 dark:bg-warning-500/20 font-medium' : 'text-gray-500'}`}>{formatNum(row.PE?.totalTradedVolume)}</td>
                      <td className={`py-1.5 px-2 ${isPutItm ? 'bg-warning-500/10 dark:bg-warning-500/20 font-medium' : 'text-gray-500'}`}>{formatNum(row.PE?.changeinOpenInterest)}</td>
                      <td className={`py-1.5 px-2 text-right ${isPutItm ? 'bg-warning-500/10 dark:bg-warning-500/20 font-medium' : 'text-gray-500'}`}>{formatNum(row.PE?.openInterest)}</td>
                    </tr>
                  )
                })}
              </tbody>
            </table>
          </div>
        </ComponentCard>
      )}

      {/* Analysis Section */}
      <ComponentCard title="AI Mastermind Analysis (Managed Mode)">
        <div className="ai-detailed-response max-h-[500px] overflow-y-auto custom-scrollbar">
          <div dangerouslySetInnerHTML={{ __html: aiAnalysis || '<div class="py-12 text-center text-gray-400 italic">Waiting for next analysis cycle... Click AI Analyze to force refresh.</div>' }} />
        </div>
      </ComponentCard>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <div className="lg:col-span-2 space-y-6">
          <ComponentCard title="Signal Evolution Timeline">
            <div className="max-h-[500px] overflow-y-auto pr-2 custom-scrollbar">
              <div className="space-y-4">
                {signalEvolution.map((evo, i) => (
                  <div key={i} className="flex gap-4 items-start relative pb-4 border-l-2 border-gray-100 dark:border-gray-800 ml-2 pl-6">
                    <div className={`absolute -left-[9px] w-4 h-4 rounded-full border-2 border-white dark:border-gray-900 ${evo.type.includes('BUY') || evo.type.includes('BULL') ? 'bg-success-500' : 'bg-error-500'}`}></div>
                    <div className="flex-1">
                      <div className="flex justify-between items-start mb-1.5">
                        <div className="flex flex-col">
                          <div className="flex items-center gap-2">
                            <Badge color="info" variant="light" size="sm" className="px-1.5 py-0 text-[8px] font-bold">{evo.symbol || symbol}</Badge>
                            <span className="text-xs font-black uppercase text-gray-800 dark:text-white">{evo.type} @ {formatNum(evo.spot)}</span>
                          </div>
                          <div className="flex items-center gap-2 mt-1">
                            <span className="text-[9px] bg-gray-50 dark:bg-gray-800 px-1.5 py-0.5 rounded font-bold text-gray-500">PCR: {evo.pcr}</span>
                            <span className="text-[9px] bg-gray-50 dark:bg-gray-800 px-1.5 py-0.5 rounded font-bold text-gray-500">SMI: {evo.smi}</span>
                            <Badge color={evo.confidence === 'HIGH' ? 'success' : 'info'} size="sm" variant="outline" className="text-[8px] py-0">{evo.confidence}</Badge>
                          </div>
                        </div>
                        <span className="text-[10px] text-gray-400 font-black tracking-tighter">{evo.time}</span>
                      </div>
                      <p className="text-[10px] text-gray-500 leading-relaxed bg-gray-50/50 dark:bg-white/5 p-2 rounded-lg border border-gray-100/50 dark:border-gray-800/50 line-clamp-3 italic">{evo.text}</p>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </ComponentCard>
          <ComponentCard title="OI Heatmap Option Chain">
            <div className="overflow-x-auto -mx-6 custom-scrollbar">
              <Table className="text-right">
                <TableHeader className="bg-gray-50 dark:bg-white/[0.02]"><TableRow className="text-[10px] text-gray-400"><TableCell className="p-2">OI</TableCell><TableCell className="p-2">OI CHG</TableCell><TableCell className="p-2">LTP</TableCell><TableCell className="p-2 text-center bg-gray-100 dark:bg-white/5 font-bold text-gray-800 dark:text-white">STRIKE</TableCell><TableCell className="p-2 text-left">LTP</TableCell><TableCell className="p-2 text-left">OI CHG</TableCell><TableCell className="p-2 text-left">OI</TableCell></TableRow></TableHeader>
                <TableBody>
                  {(() => {
                    const filtered = (data?.records?.data || []).filter((d: any) => d.expiryDate === selectedExpiry || d.expiryDates === selectedExpiry).sort((a: any, b: any) => a.strikePrice - b.strikePrice);
                    const atmIdx = filtered.findIndex((d: any) => d.strikePrice >= stats.spot);
                    return filtered.slice(Math.max(0, atmIdx - 8), Math.min(filtered.length, atmIdx + 8)).map((row: any) => (
                      <TableRow key={row.strikePrice} className="border-b border-gray-100 dark:border-gray-800">
                        <TableCell className="p-2 text-xs">{formatNum(row.CE?.openInterest)}</TableCell>
                        <TableCell className="p-0 text-xs font-bold"><span className="block p-2" style={{ backgroundColor: getHeatmapColor(row.CE?.changeinOpenInterest) }}>{formatNum(row.CE?.changeinOpenInterest)}</span></TableCell>
                        <TableCell className="p-2 text-xs font-bold">{formatNum(row.CE?.lastPrice)}</TableCell>
                        <TableCell className="p-2 text-xs text-center font-black text-brand-500">{row.strikePrice}</TableCell>
                        <TableCell className="p-2 text-xs font-bold text-left">{formatNum(row.PE?.lastPrice)}</TableCell>
                        <TableCell className="p-0 text-xs font-bold text-left"><span className="block p-2" style={{ backgroundColor: getHeatmapColor(row.PE?.changeinOpenInterest) }}>{formatNum(row.PE?.changeinOpenInterest)}</span></TableCell>
                        <TableCell className="p-2 text-xs text-left">{formatNum(row.PE?.openInterest)}</TableCell>
                      </TableRow>
                    ));
                  })()}
                </TableBody>
              </Table>
            </div>
          </ComponentCard>
        </div>
        <div className="lg:col-span-1">
          <ComponentCard title="Active Live Trades">
            <div className="max-h-[600px] overflow-y-auto pr-2 custom-scrollbar">
              <div className="space-y-3">
                {paperTrades.filter(t => t.status === 'OPEN').map((trade, i) => {
                  if (!stats.spot) return null;

                  // P&L based on index spot movement (all entry/targets are index prices)
                  const pnlPoints = (stats.spot - trade.entry_price) * (trade.type.includes('BUY') ? 1 : -1);

                  const lotSizes: Record<string, number> = {
                    'NIFTY': 25,
                    'BANKNIFTY': 15,
                    'FINNIFTY': 25,
                    'MIDCPNIFTY': 75
                  };
                  const lotSize = lotSizes[trade.symbol] || 25;
                  const cashPnl = pnlPoints * lotSize;
                  const isProfit = pnlPoints >= 0;
                  return (
                    <div key={i} className={`p-4 rounded-2xl border ${isProfit ? 'bg-success-500/5 border-success-500/20' : 'bg-error-500/5 border-error-500/20 shadow-sm'}`}>
                      <div className="flex justify-between items-center mb-3">
                        <div>
                          <div className="flex items-center gap-2">
                            <Badge color="info" variant="light" size="sm">{trade.symbol}</Badge>
                            <span className="text-xs font-black text-gray-800 dark:text-white block">{trade.contract}</span>
                          </div>
                          <span className="text-[9px] text-gray-400 font-bold uppercase tracking-tighter">1 Lot ({lotSize} Qty)</span>
                        </div>
                        <Badge color={isProfit ? 'success' : 'error'} variant="solid" size="sm">{isProfit ? '▲' : '▼'} {Math.abs((pnlPoints / (trade.entry_price || 1)) * 100).toFixed(2)}%</Badge>
                      </div>
                      <div className="flex items-end justify-between">
                        <div className="space-y-1">
                          <p className="text-[10px] text-gray-500 font-medium">Points: <span className={isProfit ? 'text-success-500' : 'text-error-500'}>{pnlPoints.toFixed(1)}</span></p>
                          <p className="text-[10px] text-gray-500 font-medium">Entry: <span className="text-gray-700 dark:text-gray-300">@{formatNum(trade.entry_price)}</span></p>
                          <button onClick={() => handleCloseTrade(trade)} className="text-[9px] font-bold text-brand-500 hover:text-brand-600 uppercase tracking-tighter mt-1 block">Exit Position ✕</button>
                        </div>
                        <div className="text-right">
                          <p className="text-[10px] text-gray-400 font-bold uppercase mb-0.5">Estimated P&L</p>
                          <p className={`text-xl font-black ${isProfit ? 'text-success-500' : 'text-error-500'}`}>{isProfit ? '₹' : '-₹'}{Math.abs(cashPnl).toLocaleString('en-IN', { minimumFractionDigits: 2 })}</p>
                        </div>
                      </div>
                    </div>
                  );
                })}
                {paperTrades.filter(t => t.status === 'OPEN').length === 0 && <div className="py-8 text-center text-gray-400 text-sm italic border-2 border-dashed border-gray-100 dark:border-gray-800 rounded-2xl">No active trades. Execute a signal to start tracking.</div>}
              </div>
            </div>
          </ComponentCard>
        </div>
      </div>
    </div>
  );
}

function StatCard({ label, value, sub, color }: any) {
  return (
    <div className="bg-white dark:bg-gray-900 p-6 rounded-2xl border border-gray-100 dark:border-gray-800 shadow-theme-xs">
      <p className="text-[10px] font-bold text-gray-400 uppercase tracking-widest mb-1">{label}</p>
      <p className={`text-2xl font-bold ${color}`}>{value}</p>
      <p className="text-[10px] text-gray-500 mt-2 font-medium">{sub}</p>
    </div>
  );
}

function TradeInfo({ label, val, color }: any) {
  return (
    <div className="p-3 bg-gray-50 dark:bg-white/5 rounded-xl border border-gray-100 dark:border-gray-800">
      <p className="text-[10px] text-gray-500 uppercase font-bold">{label}</p>
      <p className={`text-lg font-bold ${color}`}>@{val}</p>
    </div>
  );
}
