// ===== Manual Paper Trading — One-Click Buy at Live ATM Price =====

function ManualTradePage() {
  const toast = useToast();
  const [orders, setOrders] = React.useState([]);
  const [summary, setSummary] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [days, setDays] = React.useState(7);
  const [placing, setPlacing] = React.useState(null); // 'CE' or 'PE' while placing
  const [mode, setMode] = React.useState('NIFTY');

  // Live ATM snapshot
  const [snapshots, setSnapshots] = React.useState([]);
  const [snapLoading, setSnapLoading] = React.useState(true);

  // Close order
  const [closeLoading, setCloseLoading] = React.useState(null); // orderId while closing

  // Refs for keyboard shortcut access to latest state
  const placingRef = React.useRef(null);
  const closingIdRef = React.useRef(null);
  React.useEffect(() => { placingRef.current = placing; }, [placing]);
  React.useEffect(() => { closingIdRef.current = closeLoading; }, [closeLoading]);

  // Keyboard shortcuts: C = Buy CE, P = Buy PE
  React.useEffect(() => {
    function onKey(e) {
      if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA' || e.target.isContentEditable) return;
      if (e.ctrlKey || e.altKey || e.metaKey) return;
      if (placingRef.current || closingIdRef.current) return;
      const k = e.key.toLowerCase();
      if (k === 'c') { e.preventDefault(); quickBuy('CE'); }
      if (k === 'p') { e.preventDefault(); quickBuy('PE'); }
    }
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [mode]);

  React.useEffect(() => { loadOrders(); }, [days]);

  // Auto-refresh orders + ATM snapshot
  React.useEffect(() => {
    loadSnapshot();
    const iv = setInterval(() => { loadOrders(); loadSnapshot(); }, 5000);
    return () => clearInterval(iv);
  }, [days]);

  async function loadOrders() {
    try {
      const data = await API.get(`/api/user-paper-orders?days=${days}`);
      setOrders(data.orders || []);
      setSummary(data.summary || null);
    } catch (e) {
      // silent
    } finally {
      setLoading(false);
    }
  }

  async function loadSnapshot() {
    try {
      const data = await API.get('/api/user-paper-orders/atm-snapshot');
      setSnapshots(data.snapshots || []);
    } catch (e) {
      // silent
    } finally {
      setSnapLoading(false);
    }
  }

  async function quickBuy(optionType) {
    setPlacing(optionType);
    try {
      const res = await API.post('/api/user-paper-orders/quick-buy', {
        optionType,
        mode,
        quantity: 1
      });
      toast(res.message || 'Order placed!', 'success');
      loadOrders();
      loadSnapshot();
    } catch (e) {
      toast(e.message || 'Failed to place order', 'error');
    } finally {
      setPlacing(null);
    }
  }

  async function closeOrder(order) {
    // Find matching ATM snapshot for this order's option type
    var snap = snapshots.find(s => s.mode === order.mode && s.optionType === order.optionType);
    var exitPrice = snap ? snap.ltp : null;
    if (!exitPrice || exitPrice <= 0) {
      toast('No live LTP available to close. Market may be closed.', 'error');
      return;
    }
    setCloseLoading(order.orderId);
    try {
      const res = await API.post(`/api/user-paper-orders/${order.orderId}/close`, {
        exitPrice: exitPrice
      });
      toast(res.message || 'Order closed', 'success');
      loadOrders();
    } catch (e) {
      toast(e.message || 'Failed to close', 'error');
    } finally {
      setCloseLoading(null);
    }
  }

  function pnlColor(val) {
    if (val == null) return '';
    return val > 0 ? 'var(--green)' : val < 0 ? 'var(--red)' : '';
  }

  function statusBadge(status, exitReason) {
    if (status === 'OPEN') return React.createElement('span', { className: 'badge badge-info' }, '● OPEN');
    const label = exitReason || 'CLOSED';
    const cls = label === 'TARGET_HIT' || label === 'TRAILING_SL' ? 'badge-success'
              : label === 'STOP_LOSS' ? 'badge-danger'
              : 'badge-secondary';
    return React.createElement('span', { className: `badge ${cls}` }, label);
  }

  // Get snapshot for current mode
  var ceSnap = snapshots.find(s => s.mode === mode && s.optionType === 'CE');
  var peSnap = snapshots.find(s => s.mode === mode && s.optionType === 'PE');
  var spotPrice = ceSnap ? ceSnap.underlyingLtp : (peSnap ? peSnap.underlyingLtp : null);

  return React.createElement('div', { className: 'page-content' },
    React.createElement('h2', null, '📝 Manual Paper Trading'),
    React.createElement('p', { className: 'text-muted', style: { marginBottom: '1.5rem' } },
      'One-click paper orders at live ATM price. System auto-monitors SL (7%), target (15%), trailing SL (10%), and EOD close.'),

    // ── Mode selector ──
    React.createElement('div', { style: { display: 'flex', gap: '0.5rem', marginBottom: '1rem', alignItems: 'center' } },
      React.createElement('span', { className: 'text-muted', style: { marginRight: '0.5rem' } }, 'Index:'),
      ['NIFTY', 'SENSEX'].map(m =>
        React.createElement('button', {
          key: m, className: `btn ${mode === m ? 'btn-primary' : 'btn-outline'}`,
          onClick: () => setMode(m)
        }, m)),
      spotPrice && React.createElement('span', {
        style: { marginLeft: 'auto', fontSize: '1.1rem', fontWeight: 600 }
      }, `${mode} Spot: ₹${spotPrice.toLocaleString('en-IN')}`)
    ),

    // ── One-Click Buy Panel ──
    React.createElement('div', { className: 'card', style: { marginBottom: '1.5rem' } },
      React.createElement('div', { className: 'card-header' },
        React.createElement('h3', { style: { margin: 0 } }, 'Quick Buy — ATM Options')),
      React.createElement('div', { className: 'card-body' },
        snapLoading ? React.createElement('div', { className: 'text-muted' }, 'Loading live prices...') :
        (!ceSnap && !peSnap) ? React.createElement('div', { className: 'text-muted' },
          `No live ATM data for ${mode}. Worker may not be running or market is closed.`) :
        React.createElement('div', { style: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '1rem' } },
          // CE Card
          React.createElement('div', {
            style: {
              border: '2px solid var(--green, #28a745)', borderRadius: '8px', padding: '1.25rem',
              textAlign: 'center', background: 'rgba(40, 167, 69, 0.05)'
            }
          },
            React.createElement('div', { style: { fontSize: '0.85rem', color: 'var(--text-muted)', marginBottom: '0.25rem' } }, 'CALL (CE)'),
            ceSnap ? React.createElement(React.Fragment, null,
              React.createElement('div', { style: { fontSize: '0.8rem', color: 'var(--text-muted)' } },
                `Strike: ${ceSnap.strikePrice}`),
              React.createElement('div', { style: { fontSize: '1.8rem', fontWeight: 700, margin: '0.5rem 0', color: 'var(--green, #28a745)' } },
                `₹${ceSnap.ltp.toFixed(2)}`),
              React.createElement('div', { style: { fontSize: '0.75rem', color: 'var(--text-muted)', marginBottom: '0.75rem' } },
                ceSnap.isStale ? '⚠️ Stale data' : `Updated: ${ceSnap.updatedAtIst}`),
              React.createElement('button', {
                className: 'btn btn-success',
                style: { width: '100%', fontSize: '1.1rem', padding: '0.75rem' },
                onClick: () => quickBuy('CE'),
                disabled: placing || ceSnap.isStale
              }, placing === 'CE' ? 'Placing...' : `BUY CE @ ₹${ceSnap.ltp.toFixed(2)}`)
            ) : React.createElement('div', { className: 'text-muted' }, 'No data')
          ),
          // PE Card
          React.createElement('div', {
            style: {
              border: '2px solid var(--red, #dc3545)', borderRadius: '8px', padding: '1.25rem',
              textAlign: 'center', background: 'rgba(220, 53, 69, 0.05)'
            }
          },
            React.createElement('div', { style: { fontSize: '0.85rem', color: 'var(--text-muted)', marginBottom: '0.25rem' } }, 'PUT (PE)'),
            peSnap ? React.createElement(React.Fragment, null,
              React.createElement('div', { style: { fontSize: '0.8rem', color: 'var(--text-muted)' } },
                `Strike: ${peSnap.strikePrice}`),
              React.createElement('div', { style: { fontSize: '1.8rem', fontWeight: 700, margin: '0.5rem 0', color: 'var(--red, #dc3545)' } },
                `₹${peSnap.ltp.toFixed(2)}`),
              React.createElement('div', { style: { fontSize: '0.75rem', color: 'var(--text-muted)', marginBottom: '0.75rem' } },
                peSnap.isStale ? '⚠️ Stale data' : `Updated: ${peSnap.updatedAtIst}`),
              React.createElement('button', {
                className: 'btn btn-danger',
                style: { width: '100%', fontSize: '1.1rem', padding: '0.75rem' },
                onClick: () => quickBuy('PE'),
                disabled: placing || peSnap.isStale
              }, placing === 'PE' ? 'Placing...' : `BUY PE @ ₹${peSnap.ltp.toFixed(2)}`)
            ) : React.createElement('div', { className: 'text-muted' }, 'No data')
          )
        ),
        // Defaults info
        React.createElement('div', { className: 'text-muted small', style: { marginTop: '0.75rem', textAlign: 'center' } },
          'Defaults: SL 7% · Target 15% · Trailing SL 10% · Max 5 open orders · Auto-close at 15:20 IST'),
        React.createElement('div', { className: 'text-muted small', style: { marginTop: '0.4rem', textAlign: 'center', opacity: 0.7 } },
          '⌨️ Keyboard: press ', React.createElement('kbd', { style: { background: 'var(--border, #e5e7eb)', padding: '2px 6px', borderRadius: '4px', fontSize: '0.8rem', fontWeight: 600 } }, 'C'),
          ' to Buy CE · ', React.createElement('kbd', { style: { background: 'var(--border, #e5e7eb)', padding: '2px 6px', borderRadius: '4px', fontSize: '0.8rem', fontWeight: 600 } }, 'P'),
          ' to Buy PE')
      )
    ),

    // ── Summary ──
    summary && React.createElement('div', { style: { display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(120px, 1fr))', gap: '0.75rem', marginBottom: '1rem' } },
      React.createElement('div', { className: 'card card-body text-center' },
        React.createElement('div', { className: 'text-muted small' }, 'Open'),
        React.createElement('div', { className: 'h4' }, summary.openOrders)),
      React.createElement('div', { className: 'card card-body text-center' },
        React.createElement('div', { className: 'text-muted small' }, 'Closed'),
        React.createElement('div', { className: 'h4' }, summary.closedOrders)),
      React.createElement('div', { className: 'card card-body text-center' },
        React.createElement('div', { className: 'text-muted small' }, 'Total P&L'),
        React.createElement('div', { className: 'h4', style: { color: pnlColor(summary.totalPnL) } },
          `₹${summary.totalPnL?.toFixed(2) || '0'}`)),
      React.createElement('div', { className: 'card card-body text-center' },
        React.createElement('div', { className: 'text-muted small' }, 'Win Rate'),
        React.createElement('div', { className: 'h4' }, `${summary.winRate || 0}%`))),

    // ── Days filter ──
    React.createElement('div', { style: { display: 'flex', gap: '0.5rem', marginBottom: '1rem' } },
      [1, 3, 7, 14, 30].map(d =>
        React.createElement('button', {
          key: d, className: `btn btn-sm ${days === d ? 'btn-primary' : 'btn-outline'}`,
          onClick: () => setDays(d)
        }, d === 1 ? 'Today' : `${d}d`))),

    // ── Orders ──
    loading ? React.createElement('div', null, 'Loading...') :
    orders.length === 0 ? React.createElement('div', { className: 'text-muted' }, 'No orders yet. Click Buy CE or Buy PE above to place your first paper trade!') :
    React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: '0.75rem' } },
      orders.map(o => {
        const isCe = o.optionType === 'CE';
        const isOpen = o.status === 'OPEN';
        const accentColor = isCe ? 'var(--green, #16a34a)' : 'var(--red, #dc2626)';
        const pnlVal = o.pnL;
        const pnlStr = pnlVal != null ? `₹${pnlVal.toFixed(2)}` : '—';
        const pnlClr = pnlVal > 0 ? 'var(--green, #16a34a)' : pnlVal < 0 ? 'var(--red, #dc2626)' : 'var(--text-muted)';

        return React.createElement('div', {
          key: o.orderId,
          className: 'card',
          style: { borderLeft: `4px solid ${accentColor}`, padding: 0, overflow: 'hidden' }
        },
          // Top row: symbol + status + time
          React.createElement('div', {
            style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '12px 16px 8px', flexWrap: 'wrap', gap: '8px' }
          },
            React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: '8px' } },
              React.createElement('span', {
                style: { fontWeight: 700, fontSize: '0.95rem', color: accentColor }
              }, isCe ? '▲ CE' : '▼ PE'),
              React.createElement('span', {
                style: { fontWeight: 600, fontSize: '0.9rem' }
              }, o.mode),
              React.createElement('span', {
                style: { fontSize: '0.8rem', color: 'var(--text-muted)', fontFamily: 'monospace', wordBreak: 'break-all' }
              }, o.symbol)
            ),
            React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: '8px' } },
              statusBadge(o.status, o.exitReason),
              React.createElement('span', {
                style: { fontSize: '0.75rem', color: 'var(--text-muted)' }
              }, formatTime(o.createdAtIst))
            )
          ),

          // Price grid
          React.createElement('div', {
            style: {
              display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(90px, 1fr))',
              gap: '1px', background: 'var(--border, #e5e7eb)', borderTop: '1px solid var(--border, #e5e7eb)'
            }
          },
            // Entry
            React.createElement('div', { style: { background: 'var(--surface, #fff)', padding: '10px 14px', textAlign: 'center' } },
              React.createElement('div', { style: { fontSize: '0.7rem', color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.5px', marginBottom: '2px' } }, 'Entry'),
              React.createElement('div', { style: { fontWeight: 600, fontSize: '0.9rem' } }, `₹${o.entryPrice}`)
            ),
            // SL
            React.createElement('div', { style: { background: 'var(--surface, #fff)', padding: '10px 14px', textAlign: 'center' } },
              React.createElement('div', { style: { fontSize: '0.7rem', color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.5px', marginBottom: '2px' } }, 'SL'),
              React.createElement('div', { style: { fontWeight: 600, fontSize: '0.9rem', color: 'var(--red, #dc2626)' } }, o.stopLossPrice ? `₹${o.stopLossPrice}` : '—')
            ),
            // Target
            React.createElement('div', { style: { background: 'var(--surface, #fff)', padding: '10px 14px', textAlign: 'center' } },
              React.createElement('div', { style: { fontSize: '0.7rem', color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.5px', marginBottom: '2px' } }, 'Target'),
              React.createElement('div', { style: { fontWeight: 600, fontSize: '0.9rem', color: 'var(--green, #16a34a)' } }, o.targetPrice ? `₹${o.targetPrice}` : '—')
            ),
            // HWM
            React.createElement('div', { style: { background: 'var(--surface, #fff)', padding: '10px 14px', textAlign: 'center' } },
              React.createElement('div', { style: { fontSize: '0.7rem', color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.5px', marginBottom: '2px' } }, 'HWM'),
              React.createElement('div', { style: { fontWeight: 600, fontSize: '0.9rem' } }, o.highWaterMark ? `₹${o.highWaterMark}` : '—')
            ),
            // Exit
            React.createElement('div', { style: { background: 'var(--surface, #fff)', padding: '10px 14px', textAlign: 'center' } },
              React.createElement('div', { style: { fontSize: '0.7rem', color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.5px', marginBottom: '2px' } }, 'Exit'),
              React.createElement('div', { style: { fontWeight: 600, fontSize: '0.9rem' } }, o.exitPrice ? `₹${o.exitPrice}` : '—')
            ),
            // P&L
            React.createElement('div', { style: { background: 'var(--surface, #fff)', padding: '10px 14px', textAlign: 'center' } },
              React.createElement('div', { style: { fontSize: '0.7rem', color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.5px', marginBottom: '2px' } }, 'P&L'),
              React.createElement('div', { style: { fontWeight: 700, fontSize: '0.95rem', color: pnlClr } }, pnlStr)
            )
          ),

          // Action bar (only for open orders)
          isOpen && React.createElement('div', {
            style: { padding: '8px 16px', borderTop: '1px solid var(--border, #e5e7eb)', display: 'flex', alignItems: 'center', gap: '8px', justifyContent: 'flex-end' }
          },
            React.createElement('button', {
              className: 'btn btn-sm btn-outline',
              onClick: () => closeOrder(o),
              disabled: closeLoading === o.orderId
            }, closeLoading === o.orderId ? 'Closing...' : `✕ Close @ ₹${((snapshots.find(s => s.mode === o.mode && s.optionType === o.optionType) || {}).ltp || 0).toFixed(2)}`)
          )
        );
      })
    )
  );

  function formatTime(ist) {
    if (!ist) return '';
    try {
      var d = new Date(ist);
      return d.toLocaleTimeString('en-IN', { hour: '2-digit', minute: '2-digit', hour12: false })
        + ' ' + d.toLocaleDateString('en-IN', { day: '2-digit', month: 'short' });
    } catch { return ist; }
  }
}
