// ===== Paper Spread Reporting Page =====
// Displays paper spread order history, summary stats, strategy breakdown,
// and exit reason analysis. Completely separate from BUY-only reporting.
// Enhanced with Sensibull-style payoff diagrams, risk metrics, and plain-English explanations.

// ── Payoff Diagram (HTML5 Canvas) ──
function SpreadPayoffDiagram({ order }) {
  const canvasRef = React.useRef(null);

  React.useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext('2d');
    const W = canvas.width = canvas.offsetWidth * 2;  // retina
    const H = canvas.height = 200 * 2;
    ctx.scale(2, 2);
    const w = W / 2, h = H / 2;
    ctx.clearRect(0, 0, w, h);

    const isCredit = order.strategy === 'CREDIT_SPREAD' || order.strategy === 'IRON_CONDOR' || order.strategy === 'IRON_BUTTERFLY';
    const isDebit = order.strategy === 'DEBIT_SPREAD';

    // Determine strike range
    const strikes = [order.sellStrike, order.hedgeStrike].sort((a, b) => a - b);
    const spread = strikes[1] - strikes[0];
    const margin = spread * 1.5;
    const xMin = strikes[0] - margin;
    const xMax = strikes[1] + margin;

    // Chart margins
    const ml = 55, mr = 15, mt = 20, mb = 35;
    const cw = w - ml - mr, ch = h - mt - mb;

    // P&L calculation at a given underlying price
    function getPnL(price) {
      if (isCredit) {
        if (order.sellOptionType === 'CE') {
          // Bear Call Spread: sell lower CE, buy higher CE
          const sellPayoff = Math.max(0, price - order.sellStrike);
          const hedgePayoff = Math.max(0, price - order.hedgeStrike);
          return (order.netPremium - (sellPayoff - hedgePayoff)) * order.sellQuantity;
        } else {
          // Bull Put Spread: sell higher PE, buy lower PE
          const sellPayoff = Math.max(0, order.sellStrike - price);
          const hedgePayoff = Math.max(0, order.hedgeStrike - price);
          return (order.netPremium - (sellPayoff - hedgePayoff)) * order.sellQuantity;
        }
      } else if (isDebit) {
        if (order.hedgeOptionType === 'CE') {
          // Bull Call Spread
          const buyPayoff = Math.max(0, price - order.hedgeStrike);
          const sellPayoff = Math.max(0, price - order.sellStrike);
          return ((buyPayoff - sellPayoff) - (order.hedgePremium - order.sellPremium)) * order.sellQuantity;
        } else {
          // Bear Put Spread
          const buyPayoff = Math.max(0, order.hedgeStrike - price);
          const sellPayoff = Math.max(0, order.sellStrike - price);
          return ((buyPayoff - sellPayoff) - (order.hedgePremium - order.sellPremium)) * order.sellQuantity;
        }
      }
      return 0;
    }

    // Sample P&L values
    const points = [];
    const steps = 200;
    let minPnL = Infinity, maxPnL = -Infinity;
    for (let i = 0; i <= steps; i++) {
      const price = xMin + (xMax - xMin) * (i / steps);
      const pnl = getPnL(price);
      points.push({ price, pnl });
      minPnL = Math.min(minPnL, pnl);
      maxPnL = Math.max(maxPnL, pnl);
    }

    // Y range with padding
    const yPad = Math.max(Math.abs(maxPnL - minPnL) * 0.15, 100);
    const yMin = minPnL - yPad;
    const yMax = maxPnL + yPad;

    function toX(price) { return ml + ((price - xMin) / (xMax - xMin)) * cw; }
    function toY(pnl) { return mt + (1 - (pnl - yMin) / (yMax - yMin)) * ch; }

    // Background
    ctx.fillStyle = '#fafbfc';
    ctx.fillRect(0, 0, w, h);

    // Grid
    ctx.strokeStyle = '#e8ecf0';
    ctx.lineWidth = 0.5;
    for (let i = 0; i <= 4; i++) {
      const y = mt + ch * i / 4;
      ctx.beginPath(); ctx.moveTo(ml, y); ctx.lineTo(w - mr, y); ctx.stroke();
    }

    // Zero line
    const zeroY = toY(0);
    if (zeroY >= mt && zeroY <= mt + ch) {
      ctx.strokeStyle = '#94a3b8';
      ctx.lineWidth = 1;
      ctx.setLineDash([4, 4]);
      ctx.beginPath(); ctx.moveTo(ml, zeroY); ctx.lineTo(w - mr, zeroY); ctx.stroke();
      ctx.setLineDash([]);
    }

    // Profit/loss zones (filled)
    ctx.beginPath();
    ctx.moveTo(toX(points[0].price), zeroY);
    for (const p of points) ctx.lineTo(toX(p.price), toY(p.pnl));
    ctx.lineTo(toX(points[points.length - 1].price), zeroY);
    ctx.closePath();
    const zoneGrad = ctx.createLinearGradient(0, mt, 0, mt + ch);
    zoneGrad.addColorStop(0, 'rgba(34,197,94,0.15)');
    zoneGrad.addColorStop(0.5, 'rgba(255,255,255,0.02)');
    zoneGrad.addColorStop(1, 'rgba(239,68,68,0.15)');
    ctx.fillStyle = zoneGrad;
    ctx.fill();

    // P&L line
    ctx.strokeStyle = '#4f46e5';
    ctx.lineWidth = 2;
    ctx.beginPath();
    for (let i = 0; i < points.length; i++) {
      const x = toX(points[i].price);
      const y = toY(points[i].pnl);
      i === 0 ? ctx.moveTo(x, y) : ctx.lineTo(x, y);
    }
    ctx.stroke();

    // Breakeven marker
    if (order.breakevenPrice != null) {
      const bx = toX(order.breakevenPrice);
      if (bx >= ml && bx <= w - mr) {
        ctx.strokeStyle = '#f59e0b';
        ctx.lineWidth = 1.5;
        ctx.setLineDash([3, 3]);
        ctx.beginPath(); ctx.moveTo(bx, mt); ctx.lineTo(bx, mt + ch); ctx.stroke();
        ctx.setLineDash([]);
        ctx.fillStyle = '#f59e0b';
        ctx.font = '600 10px Inter, system-ui, sans-serif';
        ctx.fillText('BE', bx - 7, mt + ch + 12);
      }
    }

    // Underlying entry price marker
    const ux = toX(order.underlyingPrice);
    if (ux >= ml && ux <= w - mr) {
      ctx.strokeStyle = '#6366f1';
      ctx.lineWidth = 1;
      ctx.setLineDash([2, 2]);
      ctx.beginPath(); ctx.moveTo(ux, mt); ctx.lineTo(ux, mt + ch); ctx.stroke();
      ctx.setLineDash([]);
      ctx.fillStyle = '#6366f1';
      ctx.font = '600 9px Inter, system-ui, sans-serif';
      ctx.fillText('Entry', ux - 12, mt - 5);
    }

    // Strike markers
    [order.sellStrike, order.hedgeStrike].forEach((strike, idx) => {
      const sx = toX(strike);
      if (sx >= ml && sx <= w - mr) {
        ctx.fillStyle = idx === 0 ? '#dc2626' : '#059669';
        ctx.beginPath();
        ctx.arc(sx, toY(0), 4, 0, Math.PI * 2);
        ctx.fill();
        ctx.font = '600 9px Inter, system-ui, sans-serif';
        ctx.fillText(idx === 0 ? 'S' : 'H', sx - 3, mt + ch + 12);
      }
    });

    // Y-axis labels
    ctx.fillStyle = '#64748b';
    ctx.font = '10px Inter, system-ui, sans-serif';
    ctx.textAlign = 'right';
    for (let i = 0; i <= 4; i++) {
      const val = yMax - (yMax - yMin) * i / 4;
      ctx.fillText(`₹${Math.round(val)}`, ml - 5, mt + ch * i / 4 + 4);
    }

    // X-axis labels
    ctx.textAlign = 'center';
    for (let i = 0; i <= 4; i++) {
      const val = xMin + (xMax - xMin) * i / 4;
      ctx.fillText(Math.round(val).toString(), ml + cw * i / 4, h - 5);
    }

    // Labels: Max Profit / Max Loss
    ctx.font = 'bold 10px Inter, system-ui, sans-serif';
    ctx.textAlign = 'left';
    const mpY = toY(maxPnL);
    if (mpY >= mt + 10 && mpY <= mt + ch - 10) {
      ctx.fillStyle = '#16a34a';
      ctx.fillText(`Max Profit: ₹${Math.round(maxPnL)}`, ml + 5, mpY - 5);
    }
    const mlY = toY(minPnL);
    if (mlY >= mt + 10 && mlY <= mt + ch - 10) {
      ctx.fillStyle = '#dc2626';
      ctx.fillText(`Max Loss: ₹${Math.round(minPnL)}`, ml + 5, mlY + 14);
    }
  }, [order]);

  return React.createElement('canvas', {
    ref: canvasRef,
    style: { width: '100%', height: '200px', borderRadius: '8px', border: '1px solid #e2e8f0' }
  });
}

// ── Risk Metrics Component ──
function SpreadRiskMetrics({ order }) {
  const maxProfit = Math.abs(order.maxProfit);
  const maxLoss = Math.abs(order.maxLoss);
  const rrRatio = maxLoss > 0 ? (maxProfit / maxLoss).toFixed(2) : '∞';

  // Estimated probability of profit (simplified: credit/width ratio for credit spreads)
  const isCredit = order.netPremium > 0;
  let popEstimate = null;
  if (isCredit && order.spreadWidth > 0) {
    popEstimate = ((1 - Math.abs(order.netPremium) / order.spreadWidth) * 100).toFixed(0);
  } else if (!isCredit && order.spreadWidth > 0) {
    popEstimate = ((Math.abs(order.netPremium) / order.spreadWidth) * 100).toFixed(0);
  }

  const stratDescriptions = {
    CREDIT_SPREAD: {
      icon: '💰', name: 'Credit Spread', type: 'Directional Selling',
      desc: 'You sold an option and bought a cheaper one for protection. You profit if the market stays away from your sold strike. Time decay (theta) works in your favour.',
      risk: 'Limited risk, limited reward. Max profit = credit received. Max loss = spread width - credit.'
    },
    DEBIT_SPREAD: {
      icon: '🎯', name: 'Debit Spread', type: 'Directional Buying',
      desc: 'You bought an option and sold a further OTM one to reduce cost. You profit if the market moves towards your bought strike. You need directional movement.',
      risk: 'Limited risk, limited reward. Max profit = spread width - debit paid. Max loss = debit paid.'
    },
    IRON_CONDOR: {
      icon: '🦅', name: 'Iron Condor', type: 'Non-Directional (Range-Bound)',
      desc: 'Two credit spreads: one on the call side, one on the put side. You profit if the market stays within a range. Premium collected from BOTH sides. Like selling insurance on both ends.',
      risk: 'Limited risk on both sides. Max profit = total credit. Max loss = wing width - total credit (on the losing side).'
    },
    IRON_BUTTERFLY: {
      icon: '🦋', name: 'Iron Butterfly', type: 'Non-Directional (Pin to ATM)',
      desc: 'Sell ATM straddle (CE + PE at same strike) and buy OTM wings for protection. Highest premium collection but needs price to stay exactly at ATM. Like a tight Iron Condor.',
      risk: 'Limited risk. Max profit = total credit (only at ATM). Max loss = wing width - total credit.'
    }
  };

  const strat = stratDescriptions[order.strategy] || { icon: '📊', name: order.strategy, type: 'Spread', desc: '', risk: '' };

  const metricBox = (label, value, color) => React.createElement('div', {
    style: { textAlign: 'center', padding: '8px 4px' }
  },
    React.createElement('div', { style: { fontSize: '10px', color: '#94a3b8', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.5px', marginBottom: '4px' } }, label),
    React.createElement('div', { style: { fontSize: '18px', fontWeight: 800, color: color || 'var(--text-primary)' } }, value)
  );

  return React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: '12px' } },
    // Strategy Type Card
    React.createElement('div', { style: { background: 'linear-gradient(135deg, #eef2ff, #e0e7ff)', borderRadius: '10px', padding: '14px 16px', border: '1px solid #c7d2fe' } },
      React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '8px' } },
        React.createElement('span', { style: { fontSize: '24px' } }, strat.icon),
        React.createElement('div', null,
          React.createElement('div', { style: { fontWeight: 800, fontSize: '15px', color: '#312e81' } }, strat.name),
          React.createElement('div', { style: { fontSize: '11px', color: '#6366f1', fontWeight: 600 } }, strat.type)
        )
      ),
      React.createElement('div', { style: { fontSize: '12px', lineHeight: '1.6', color: '#4338ca', marginBottom: '6px' } }, strat.desc),
      React.createElement('div', { style: { fontSize: '11px', lineHeight: '1.5', color: '#6366f1', fontStyle: 'italic' } }, `⚠️ ${strat.risk}`)
    ),

    // Metrics Grid
    React.createElement('div', {
      style: { display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '4px', background: '#f8fafc', borderRadius: '10px', padding: '8px', border: '1px solid #e2e8f0' }
    },
      metricBox('R:R Ratio', `1:${rrRatio}`, '#4f46e5'),
      metricBox('PoP Est.', popEstimate ? `~${popEstimate}%` : 'N/A', '#0891b2'),
      metricBox('Max Profit', `₹${maxProfit.toFixed(0)}`, '#16a34a'),
      metricBox('Max Loss', `₹${maxLoss.toFixed(0)}`, '#dc2626')
    )
  );
}

// ── Visual Strike Placement Bar ──
function StrikePlacementBar({ order }) {
  const allStrikes = [order.sellStrike, order.hedgeStrike, order.underlyingPrice];
  if (order.breakevenPrice != null) allStrikes.push(order.breakevenPrice);
  const min = Math.min(...allStrikes);
  const max = Math.max(...allStrikes);
  const range = max - min || 1;
  const pad = range * 0.2;
  const xMin = min - pad;
  const xMax = max + pad;
  const totalRange = xMax - xMin;

  function pct(val) { return ((val - xMin) / totalRange * 100).toFixed(1) + '%'; }

  const marker = (val, label, color, top) => React.createElement('div', {
    style: {
      position: 'absolute', left: pct(val), transform: 'translateX(-50%)',
      [top ? 'top' : 'bottom']: top ? '-22px' : '-22px',
      fontSize: '10px', fontWeight: 700, color: color, whiteSpace: 'nowrap', textAlign: 'center'
    }
  },
    React.createElement('div', null, label),
    React.createElement('div', {
      style: { width: '2px', height: '30px', background: color, margin: '0 auto',
               position: 'absolute', left: '50%', transform: 'translateX(-50%)',
               [top ? 'bottom' : 'top']: '-30px'
             }
    })
  );

  return React.createElement('div', {
    style: { position: 'relative', height: '60px', margin: '30px 0 30px', padding: '0 20px' }
  },
    // Track bar
    React.createElement('div', {
      style: { position: 'absolute', top: '28px', left: '20px', right: '20px', height: '4px', background: '#e2e8f0', borderRadius: '2px' }
    }),
    // Sell zone (profit zone for credit, loss zone for debit)
    React.createElement('div', {
      style: {
        position: 'absolute', top: '24px', height: '12px', borderRadius: '6px',
        left: `calc(20px + ${pct(Math.min(order.sellStrike, order.hedgeStrike))})`,
        width: `calc(${((Math.abs(order.sellStrike - order.hedgeStrike) / totalRange) * 100).toFixed(1)}%)`,
        background: order.netPremium > 0 ? 'rgba(239,68,68,0.2)' : 'rgba(34,197,94,0.2)',
        border: `1px solid ${order.netPremium > 0 ? '#fca5a5' : '#86efac'}`
      }
    }),
    // Markers
    marker(order.sellStrike, `Sell ${order.sellStrike}`, '#dc2626', true),
    marker(order.hedgeStrike, `Hedge ${order.hedgeStrike}`, '#059669', false),
    marker(order.underlyingPrice, `Spot ${order.underlyingPrice.toFixed(0)}`, '#6366f1', true),
    order.breakevenPrice != null && marker(order.breakevenPrice, `BE ${order.breakevenPrice.toFixed(0)}`, '#f59e0b', false)
  );
}

function SpreadReportingPage() {
  const toast = useToast();
  const [mode, setMode] = React.useState('');
  const [strategy, setStrategy] = React.useState('');
  const [days, setDays] = React.useState(3);
  const [useCustomRange, setUseCustomRange] = React.useState(false);
  const [fromDate, setFromDate] = React.useState('');
  const [toDate, setToDate] = React.useState('');
  const [orders, setOrders] = React.useState([]);
  const [summary, setSummary] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [expandedOrderId, setExpandedOrderId] = React.useState(new Set());

  React.useEffect(() => {
    if (useCustomRange && (!fromDate || !toDate)) return;
    loadData();
  }, [mode, strategy, days, useCustomRange, fromDate, toDate]);

  async function loadData() {
    setLoading(true);
    try {
      const params = [];
      if (useCustomRange && fromDate && toDate) {
        params.push(`from=${fromDate}`, `to=${toDate}`);
      } else {
        params.push(`days=${days}`);
      }
      if (mode) params.push(`mode=${mode}`);
      if (strategy) params.push(`strategy=${strategy}`);
      const qs = params.join('&');
      const result = await API.get(`/api/paper-spread-orders?${qs}`);
      setOrders(result.orders || []);
      setSummary(result.summary || null);
    } catch (err) { toast(err.message, 'error'); }
    finally { setLoading(false); }
  }

  return React.createElement('div', { className: 'page-content' },
    React.createElement('div', { className: 'page-header' },
      React.createElement('h1', { className: 'page-title' }, '\uD83D\uDCCA Spread Reporting'),
      React.createElement('p', { className: 'page-subtitle' }, 'Paper spread order history, P&L analysis, strategy & exit breakdowns')
    ),

    // Filters
    React.createElement('div', { className: 'filters-bar' },
      // Mode
      React.createElement('div', { className: 'flex gap-2' },
        React.createElement('button', { className: `filter-chip ${mode === '' ? 'active' : ''}`, onClick: () => setMode('') }, 'All'),
        React.createElement('button', { className: `filter-chip ${mode === 'NIFTY' ? 'active' : ''}`, onClick: () => setMode('NIFTY') }, 'NIFTY'),
        React.createElement('button', { className: `filter-chip ${mode === 'SENSEX' ? 'active' : ''}`, onClick: () => setMode('SENSEX') }, 'SENSEX')
      ),
      React.createElement('span', { className: 'text-muted' }, '|'),
      // Strategy
      React.createElement('div', { className: 'flex gap-2' },
        React.createElement('button', { className: `filter-chip ${strategy === '' ? 'active' : ''}`, onClick: () => setStrategy('') }, 'All Strategies'),
        React.createElement('button', { className: `filter-chip ${strategy === 'CREDIT_SPREAD' ? 'active' : ''}`, onClick: () => setStrategy('CREDIT_SPREAD') }, 'Credit'),
        React.createElement('button', { className: `filter-chip ${strategy === 'DEBIT_SPREAD' ? 'active' : ''}`, onClick: () => setStrategy('DEBIT_SPREAD') }, 'Debit'),
        React.createElement('button', { className: `filter-chip ${strategy === 'IRON_CONDOR' ? 'active' : ''}`, onClick: () => setStrategy('IRON_CONDOR') }, 'Iron Condor'),
        React.createElement('button', { className: `filter-chip ${strategy === 'IRON_BUTTERFLY' ? 'active' : ''}`, onClick: () => setStrategy('IRON_BUTTERFLY') }, 'Iron Butterfly')
      ),
      React.createElement('span', { className: 'text-muted' }, '|'),
      // Date
      React.createElement('div', { className: 'flex gap-2 items-center flex-wrap' },
        React.createElement('button', {
          className: `filter-chip ${!useCustomRange && days === 1 ? 'active' : ''}`,
          onClick: () => { setUseCustomRange(false); setDays(1); }
        }, 'Today'),
        React.createElement('button', {
          className: `filter-chip ${!useCustomRange && days === 3 ? 'active' : ''}`,
          onClick: () => { setUseCustomRange(false); setDays(3); }
        }, '3 Days'),
        React.createElement('button', {
          className: `filter-chip ${!useCustomRange && days === 7 ? 'active' : ''}`,
          onClick: () => { setUseCustomRange(false); setDays(7); }
        }, '7 Days'),
        React.createElement('button', {
          className: `filter-chip ${useCustomRange ? 'active' : ''}`,
          onClick: () => {
            if (!useCustomRange) {
              const now = new Date();
              const ist = new Date(now.getTime() + (now.getTimezoneOffset() * 60000) + (5.5 * 60 * 60 * 1000));
              const todayStr = ist.toISOString().split('T')[0];
              if (!fromDate) setFromDate(todayStr);
              if (!toDate) setToDate(todayStr);
            }
            setUseCustomRange(!useCustomRange);
          }
        }, '\uD83D\uDCC5 Date Range'),
        useCustomRange && React.createElement('input', {
          type: 'date', className: 'form-input',
          style: { width: '140px', padding: '4px 8px', fontSize: '13px' },
          value: fromDate, onChange: (e) => setFromDate(e.target.value)
        }),
        useCustomRange && React.createElement('span', { className: 'text-muted text-sm' }, 'to'),
        useCustomRange && React.createElement('input', {
          type: 'date', className: 'form-input',
          style: { width: '140px', padding: '4px 8px', fontSize: '13px' },
          value: toDate, onChange: (e) => setToDate(e.target.value)
        })
      ),
      React.createElement('button', { className: 'btn btn-outline btn-sm', onClick: loadData }, '\u21BB')
    ),

    loading ? React.createElement(Loading, { text: 'Loading spread orders\u2026' }) : React.createElement(React.Fragment, null,

      // Summary Stats
      summary && React.createElement('div', { className: 'stats-grid' },
        React.createElement(StatCard, { label: 'Total Spreads', value: summary.totalOrders }),
        React.createElement(StatCard, { label: 'Open', value: summary.openOrders }),
        React.createElement(StatCard, { label: 'Win / Loss', value: `${summary.winners} / ${summary.losers}`,
          sub: `Win rate: ${(summary.winRate * 100).toFixed(0)}%` }),
        React.createElement(StatCard, { label: 'Total P&L', value: formatCurrency(summary.totalPnL),
          type: summary.totalPnL >= 0 ? 'positive' : 'negative' }),
        React.createElement(StatCard, { label: 'Avg P&L', value: formatCurrency(summary.averagePnL),
          type: summary.averagePnL >= 0 ? 'positive' : 'negative' }),
        summary.bestPnL !== 0 && React.createElement(StatCard, { label: 'Best', value: formatCurrency(summary.bestPnL), type: 'positive' }),
        summary.worstPnL !== 0 && React.createElement(StatCard, { label: 'Worst', value: formatCurrency(summary.worstPnL), type: 'negative' })
      ),

      // Strategy Breakdown
      summary && summary.byStrategy && Object.keys(summary.byStrategy).length > 0 && React.createElement('div', { className: 'card mb-4' },
        React.createElement('div', { className: 'card-header' },
          React.createElement('span', null, '\uD83C\uDFAF Strategy Breakdown'),
          React.createElement('span', { className: 'text-sm text-muted' }, `${Object.keys(summary.byStrategy).length} strateg${Object.keys(summary.byStrategy).length !== 1 ? 'ies' : 'y'}`)
        ),
        React.createElement('div', { className: 'card-body' },
          React.createElement('div', { style: { display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(240px, 1fr))', gap: '12px' } },
            Object.entries(summary.byStrategy).map(([stratName, strat]) => {
              const isProfit = strat.totalPnL >= 0;
              const labels = { CREDIT_SPREAD: 'Credit Spread', DEBIT_SPREAD: 'Debit Spread', IRON_CONDOR: 'Iron Condor', IRON_BUTTERFLY: 'Iron Butterfly' };
              return React.createElement('div', {
                key: stratName,
                style: {
                  padding: '16px', borderRadius: '10px',
                  background: isProfit
                    ? 'linear-gradient(135deg, #f0fdf4, #dcfce7)'
                    : 'linear-gradient(135deg, #fef2f2, #fee2e2)',
                  border: `1px solid ${isProfit ? '#bbf7d0' : '#fecaca'}`,
                }
              },
                React.createElement('div', { style: { fontWeight: 700, fontSize: '14px', marginBottom: '8px' } }, labels[stratName] || stratName),
                React.createElement('div', { style: { display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '4px', fontSize: '12px' } },
                  React.createElement('div', null,
                    React.createElement('div', { style: { color: 'var(--text-secondary)' } }, 'Count'),
                    React.createElement('div', { style: { fontWeight: 600 } }, strat.count)
                  ),
                  React.createElement('div', null,
                    React.createElement('div', { style: { color: 'var(--text-secondary)' } }, 'Win Rate'),
                    React.createElement('div', { style: { fontWeight: 600 } }, `${(strat.winRate * 100).toFixed(0)}%`)
                  ),
                  React.createElement('div', null,
                    React.createElement('div', { style: { color: 'var(--text-secondary)' } }, 'P&L'),
                    React.createElement('div', { style: { fontWeight: 700, color: isProfit ? '#16a34a' : '#dc2626' } }, formatCurrency(strat.totalPnL))
                  )
                ),
                React.createElement('div', { style: { marginTop: '6px', fontSize: '11px', color: 'var(--text-secondary)' } },
                  `${strat.winners}W / ${strat.losers}L`
                )
              );
            })
          )
        )
      ),

      // Exit Reason Breakdown
      summary && summary.byExitReason && Object.keys(summary.byExitReason).length > 0 && React.createElement('div', { className: 'card mb-4' },
        React.createElement('div', { className: 'card-header' },
          React.createElement('span', null, '\uD83D\uDEAA Exit Reason Breakdown'),
          React.createElement('span', { className: 'text-sm text-muted' }, 'How spreads were closed')
        ),
        React.createElement('div', { className: 'card-body' },
          React.createElement('div', { style: { display: 'flex', gap: '12px', flexWrap: 'wrap' } },
            Object.entries(summary.byExitReason).map(([reason, count]) => {
              const icons = {
                THETA_TARGET: '\uD83C\uDFAF', SL_HIT: '\uD83D\uDED1',
                UNDERLYING_BREACH: '\u26A0\uFE0F', EOD_CLOSE: '\uD83C\uDF05',
                EXPIRY_CLOSE: '\u23F0', MANUAL: '\u270B',
                PROFIT_TARGET: '\uD83D\uDCB0'
              };
              const labels = {
                THETA_TARGET: 'Theta Target', SL_HIT: 'Stop Loss',
                UNDERLYING_BREACH: 'Breach', EOD_CLOSE: 'EOD Close',
                EXPIRY_CLOSE: 'Expiry Close', MANUAL: 'Manual',
                PROFIT_TARGET: 'Profit Target'
              };
              return React.createElement('div', {
                key: reason,
                style: {
                  padding: '12px 20px', borderRadius: '10px',
                  background: '#f8fafc', border: '1px solid #e2e8f0',
                  textAlign: 'center', minWidth: '100px',
                }
              },
                React.createElement('div', { style: { fontSize: '20px', marginBottom: '4px' } }, icons[reason] || '\u2753'),
                React.createElement('div', { style: { fontSize: '11px', fontWeight: 600, color: 'var(--text-secondary)', textTransform: 'uppercase', letterSpacing: '0.5px' } }, labels[reason] || reason),
                React.createElement('div', { style: { fontSize: '22px', fontWeight: 800, marginTop: '4px' } }, count)
              );
            })
          )
        )
      ),

      // Order History Table
      React.createElement('div', { className: 'card' },
        React.createElement('div', { className: 'card-header' },
          React.createElement('span', null, '\uD83D\uDCCB Spread Order History'),
          React.createElement('span', { className: 'text-sm text-muted' }, `${orders.length} spread${orders.length !== 1 ? 's' : ''}`)
        ),
        orders.length === 0
          ? React.createElement('div', { className: 'card-body' }, React.createElement(EmptyState, { title: 'No spread orders found', text: 'Adjust filters or date range.' }))
          : React.createElement('div', { className: 'card-body-flush table-responsive' },
              React.createElement('table', { className: 'data-table' },
                React.createElement('thead', null,
                  React.createElement('tr', null,
                    React.createElement('th', null, 'Time'),
                    React.createElement('th', null, 'Strategy'),
                    React.createElement('th', null, 'Mode'),
                    React.createElement('th', null, 'Direction'),
                    React.createElement('th', null, 'Sell Leg'),
                    React.createElement('th', null, 'Hedge Leg'),
                    React.createElement('th', null, 'Net Prem'),
                    React.createElement('th', null, 'Width'),
                    React.createElement('th', null, 'P&L'),
                    React.createElement('th', null, 'P&L %'),
                    React.createElement('th', null, 'Status'),
                    React.createElement('th', null, 'Exit Reason')
                  )
                ),
                React.createElement('tbody', null,
                  orders.map((o, i) => {
                    const pnl = o.pnL;
                    const pnlPct = o.pnLPercent;
                    const pnlClass = pnl > 0 ? 'pnl-positive' : pnl < 0 ? 'pnl-negative' : 'pnl-zero';
                    const isExpanded = expandedOrderId.has(o.orderId);
                    const stratLabels = { CREDIT_SPREAD: 'Credit', DEBIT_SPREAD: 'Debit', IRON_CONDOR: 'IC', IRON_BUTTERFLY: 'IB' };
                    const isGrouped = o.strategy === 'IRON_CONDOR' || o.strategy === 'IRON_BUTTERFLY';
                    const groupColor = isGrouped && o.spreadGroupId
                      ? `hsl(${Math.abs(o.spreadGroupId.charCodeAt(0) * 37) % 360}, 60%, 90%)`
                      : undefined;
                    const badgeType = o.strategy === 'CREDIT_SPREAD' ? 'info'
                      : o.strategy === 'IRON_CONDOR' ? 'success'
                      : o.strategy === 'IRON_BUTTERFLY' ? 'warning'
                      : 'neutral';
                    return React.createElement(React.Fragment, { key: o.orderId || i },
                      React.createElement('tr', {
                        style: { cursor: 'pointer', background: isExpanded ? 'var(--bg-secondary, #f8f9fa)' : undefined, borderLeft: isGrouped ? `3px solid ${groupColor}` : undefined },
                        onClick: () => setExpandedOrderId(prev => { const next = new Set(prev); if (next.has(o.orderId)) next.delete(o.orderId); else next.add(o.orderId); return next; }),
                        title: 'Click to expand details'
                      },
                        React.createElement('td', { className: 'text-xs font-mono', style: { whiteSpace: 'nowrap' } },
                          React.createElement('span', { style: { marginRight: '6px', fontSize: '10px', opacity: 0.5 } }, isExpanded ? '\u25BC' : '\u25B6'),
                          formatDate(o.createdAtIst)
                        ),
                        React.createElement('td', null, React.createElement(Badge, { type: badgeType }, stratLabels[o.strategy] || o.strategy)),
                        React.createElement('td', null, React.createElement(Badge, { type: 'neutral' }, o.mode)),
                        React.createElement('td', { className: 'text-xs' }, o.direction),
                        React.createElement('td', { className: 'font-mono text-xs' },
                          `${o.sellOptionType} ${o.sellStrike} @ \u20B9${o.sellPremium.toFixed(2)}`
                        ),
                        React.createElement('td', { className: 'font-mono text-xs' },
                          `${o.hedgeOptionType} ${o.hedgeStrike} @ \u20B9${o.hedgePremium.toFixed(2)}`
                        ),
                        React.createElement('td', { className: 'font-mono' }, `\u20B9${o.netPremium.toFixed(2)}`),
                        React.createElement('td', { className: 'font-mono' }, `${o.spreadWidth}`),
                        React.createElement('td', { className: pnlClass, style: { whiteSpace: 'nowrap' } }, pnl != null ? formatCurrency(pnl) : '\u2014'),
                        React.createElement('td', { className: pnlClass, style: { whiteSpace: 'nowrap' } }, pnlPct != null ? `${(pnlPct * 100).toFixed(1)}%` : '\u2014'),
                        React.createElement('td', null, React.createElement(Badge, {
                          type: o.status === 'OPEN' ? 'info' : 'neutral'
                        }, o.status)),
                        React.createElement('td', { className: 'text-sm' }, o.exitReason || '\u2014')
                      ),
                      // Expanded detail row — Sensibull-style
                      isExpanded && React.createElement('tr', null,
                        React.createElement('td', { colSpan: 12, style: { padding: '0', border: 'none' } },
                          React.createElement('div', { style: { padding: '16px 20px', background: 'var(--bg-secondary, #f8f9fa)' } },

                            // Top row: Payoff Diagram + Risk Metrics side by side
                            React.createElement('div', { style: { display: 'grid', gridTemplateColumns: '2fr 1fr', gap: '16px', marginBottom: '16px' } },
                              // Payoff Diagram
                              React.createElement('div', null,
                                React.createElement('div', { style: { fontWeight: 700, fontSize: '13px', marginBottom: '8px', color: 'var(--text-secondary)' } }, '📈 Payoff at Expiry'),
                                React.createElement(SpreadPayoffDiagram, { order: o })
                              ),
                              // Risk Metrics + Strategy Explanation
                              React.createElement(SpreadRiskMetrics, { order: o })
                            ),

                            // Strike Placement Bar
                            React.createElement('div', { style: { background: '#fff', borderRadius: '10px', padding: '12px 16px', border: '1px solid #e2e8f0', marginBottom: '16px' } },
                              React.createElement('div', { style: { fontWeight: 700, fontSize: '13px', marginBottom: '4px', color: 'var(--text-secondary)' } }, '📍 Strike Placement'),
                              React.createElement(StrikePlacementBar, { order: o })
                            ),

                            // Detailed legs + economics grid
                            React.createElement('div', { style: { display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(200px, 1fr))', gap: '12px', fontSize: '12px' } },
                              React.createElement('div', { style: { background: '#fff', borderRadius: '8px', padding: '12px', border: '1px solid #fecaca' } },
                                React.createElement('div', { style: { color: '#dc2626', fontWeight: 700, marginBottom: '6px', fontSize: '13px' } }, '🔴 Sell Leg (Short)'),
                                React.createElement('div', null, `Symbol: ${o.sellSymbol}`),
                                React.createElement('div', null, `Strike: ${o.sellStrike} ${o.sellOptionType}`),
                                React.createElement('div', null, `Entry: ₹${o.sellPremium.toFixed(2)}`),
                                o.sellExitPremium != null && React.createElement('div', null, `Exit: ₹${o.sellExitPremium.toFixed(2)}`),
                                React.createElement('div', null, `Qty: ${o.sellQuantity}`)
                              ),
                              React.createElement('div', { style: { background: '#fff', borderRadius: '8px', padding: '12px', border: '1px solid #bbf7d0' } },
                                React.createElement('div', { style: { color: '#059669', fontWeight: 700, marginBottom: '6px', fontSize: '13px' } }, '🟢 Hedge Leg (Long)'),
                                React.createElement('div', null, `Symbol: ${o.hedgeSymbol}`),
                                React.createElement('div', null, `Strike: ${o.hedgeStrike} ${o.hedgeOptionType}`),
                                React.createElement('div', null, `Entry: ₹${o.hedgePremium.toFixed(2)}`),
                                o.hedgeExitPremium != null && React.createElement('div', null, `Exit: ₹${o.hedgeExitPremium.toFixed(2)}`),
                                React.createElement('div', null, `Qty: ${o.hedgeQuantity}`)
                              ),
                              React.createElement('div', { style: { background: '#fff', borderRadius: '8px', padding: '12px', border: '1px solid #e2e8f0' } },
                                React.createElement('div', { style: { color: 'var(--text-secondary)', fontWeight: 700, marginBottom: '6px', fontSize: '13px' } }, '💵 Economics'),
                                React.createElement('div', null, `Net Premium: ₹${o.netPremium.toFixed(2)}`),
                                React.createElement('div', { style: { color: '#16a34a', fontWeight: 600 } }, `Max Profit: ₹${o.maxProfit.toFixed(2)}`),
                                React.createElement('div', { style: { color: '#dc2626', fontWeight: 600 } }, `Max Loss: ₹${o.maxLoss.toFixed(2)}`),
                                o.breakevenPrice != null && React.createElement('div', null, `Breakeven: ${o.breakevenPrice}`),
                                React.createElement('div', null, `Spread Width: ${o.spreadWidth} pts`)
                              ),
                              React.createElement('div', { style: { background: '#fff', borderRadius: '8px', padding: '12px', border: '1px solid #e2e8f0' } },
                                React.createElement('div', { style: { color: 'var(--text-secondary)', fontWeight: 700, marginBottom: '6px', fontSize: '13px' } }, '📊 Market Context'),
                                React.createElement('div', null, `Underlying: ₹${o.underlyingPrice.toFixed(2)}`),
                                o.ivRank != null && React.createElement('div', null, `IV Rank: ${o.ivRank.toFixed(1)}`),
                                o.buyConfidence != null && React.createElement('div', null, `BUY Conf: ${(o.buyConfidence * 100).toFixed(1)}%`),
                                React.createElement('div', null, `Sideways: ${o.isSideways ? '✅ Yes' : '❌ No'}`),
                                o.exitedAtIst && React.createElement('div', null, `Exited: ${formatDate(o.exitedAtIst)}`)
                              )
                            ),

                            // Exit Notes
                            o.exitNotes && React.createElement('div', { style: { marginTop: '12px', background: '#fff', borderRadius: '8px', padding: '12px 16px', border: '1px solid #fed7aa' } },
                              React.createElement('div', { style: { color: '#c2410c', fontWeight: 700, marginBottom: '4px', fontSize: '13px' } }, '🚪 Exit Notes'),
                              React.createElement('div', { style: { fontStyle: 'italic', fontSize: '12px', lineHeight: '1.5' } }, o.exitNotes)
                            ),

                            // Entry Rationale — Why this strategy?
                            o.entryRationale && React.createElement('div', { style: { marginTop: '12px', background: 'linear-gradient(135deg, #eef2ff, #e0e7ff)', borderRadius: '10px', padding: '14px 16px', border: '1px solid #c7d2fe' } },
                              React.createElement('div', { style: { color: '#4338ca', fontWeight: 800, marginBottom: '6px', fontSize: '14px' } }, '💡 Why this strategy was chosen'),
                              React.createElement('div', { style: { fontSize: '12px', lineHeight: '1.6', color: '#312e81' } }, o.entryRationale)
                            )
                          )
                        )
                      )
                    );
                  })
                )
              )
            )
      )
    )
  );
}
