// Trade ticket — BUY-only mechanics (Polymarket / Kalshi / HIP-4 share-based markets).
//
// Opening: action is always BUY; user picks YES or NO side. No sell-to-open.
// Closing: if ctx.holding is set and ctx.action === 'Close', shows realize-P&L card.
// Pro mode: full order book ladder + recent trades + cumulative depth chart.
const { useState: useStateTk, useMemo: useMemoTk, useEffect: useEffectTk } = React;

function TradeTicket({ ctx, onClose, onPlace, holdings = {}, pro = false }) {
  // ctx: { sym, side, action, strike, expiryKey, price, size, mid, holding }
  const VD = window.VD;
  const { Icon, ICONS, AssetGlyph } = window.VDIcons;

  // Local side state — user can flip YES/NO when opening (action is always Buy).
  const startSide = ctx.holding ? ctx.holding.side || ctx.side : ctx.side;
  const [side, setSide] = useStateTk(startSide || 'YES');
  const isYes = side === 'YES';
  const accent = isYes ? 'var(--mint)' : 'var(--coral)';
  const accentDim = isYes ? 'var(--mint-dim)' : 'var(--coral-dim)';
  const accentBg = isYes ? 'var(--mint-bg10)' : 'var(--coral-bg10)';

  const expiry = VD.VD_EXPIRIES.find(e => e.key === ctx.expiryKey) || { label: 'Today', sub: '0DTE' };
  const isClose = ctx.holding && ctx.action === 'Close';

  // Resolve current best price for the chosen side from the chain row
  const chainRows = VD.vdBuildChain(ctx.sym, ctx.expiryKey);
  const row = chainRows.find(r => r.strike === ctx.strike) || chainRows[0];
  const bestAsk = isYes ? row.yAsk : row.nAsk;
  const bestBid = isYes ? row.yBid : row.nBid;
  const askSize = isYes ? row.yAskSize : row.nAskSize;

  const [orderType, setOrderType] = useStateTk('market');
  const [qty, setQty] = useStateTk(ctx.holding ? Math.min(ctx.holding.qty, 10) : 10);
  const [limitPrice, setLimitPrice] = useStateTk(isClose ? bestBid : bestAsk);
  const [placing, setPlacing] = useStateTk(false);
  const [success, setSuccess] = useStateTk(false);

  // When opening, price = ask. When closing, price = bid (sell to close).
  const referencePrice = isClose ? bestBid : bestAsk;
  const effPrice = orderType === 'market' ? referencePrice : limitPrice;

  // Re-sync limit price if user flips YES/NO
  useEffectTk(() => { setLimitPrice(referencePrice); }, [side, isClose]);

  const cost = (effPrice / 100) * qty;
  const maxGain = qty - cost;
  const maxLoss = cost;
  const breakeven = `${effPrice}¢`;

  const fmtUsd = (v) => '$' + v.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
  const cap = ctx.holding ? ctx.holding.qty : 1000000;

  // P&L if closing now
  const realizedPnl = ctx.holding ? ((effPrice - ctx.holding.avg) / 100) * qty : 0;

  const place = () => {
    setPlacing(true);
    setTimeout(() => { setSuccess(true); setTimeout(() => { onPlace({ ...ctx, side, qty, price: effPrice, orderType, action: isClose ? 'Close' : 'Buy' }); }, 800); }, 380);
  };

  const fmtStrike = (k) => k >= 1000 ? k.toLocaleString() : k;
  const ctaLabel = isClose
    ? `Close ${qty} ${side} · realize ${realizedPnl >= 0 ? '+' : '−'}${fmtUsd(Math.abs(realizedPnl))}`
    : `Buy ${qty} ${side} · ${fmtUsd(cost)}`;

  return (
    <div className="vd-backdrop" onClick={onClose}>
      <div className="vd-card-rise" onClick={(e) => e.stopPropagation()} style={{
        width: pro ? 720 : 420,
        maxHeight: '90vh', overflowY: 'auto',
        background: 'var(--bg-elev)',
        border: '1px solid var(--line)',
        borderRadius: 'var(--r-xl)',
        overflow: 'hidden',
        boxShadow: '0 0 0 1px rgba(151,252,228,0.06)',
        display: pro ? 'grid' : 'block',
        gridTemplateColumns: pro ? '1fr 320px' : '1fr',
      }}>
        {/* LEFT: order entry */}
        <div style={{ display: 'flex', flexDirection: 'column' }}>
          {/* Header */}
          <div style={{ padding: '14px 18px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', borderBottom: '1px solid var(--line-subtle)' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <AssetGlyph sym={ctx.sym} size={26} />
              <div>
                <div style={{ fontWeight: 600, fontSize: 14 }}>{ctx.sym}<span style={{ color: 'var(--text-3)', fontWeight: 400 }}> · {expiry.label}</span></div>
                <div className="num" style={{ color: 'var(--text-3)', fontSize: 11 }}>{fmtStrike(ctx.strike)} strike</div>
              </div>
            </div>
            <button className="btn-ghost btn" style={{ width: 32, height: 32, padding: 0 }} onClick={onClose}>{ICONS.close}</button>
          </div>

          {/* YES/NO side selector — only shown when opening (no holding to close) */}
          {!isClose && (
            <div style={{ padding: '14px 18px 0' }}>
              <div className="cap-sm" style={{ marginBottom: 8 }}>Pick a side</div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
                {['YES', 'NO'].map(s => {
                  const isActive = side === s;
                  const sAccent = s === 'YES' ? 'var(--mint)' : 'var(--coral)';
                  const sBg = s === 'YES' ? 'var(--mint-bg10)' : 'var(--coral-bg10)';
                  const sAsk = s === 'YES' ? row.yAsk : row.nAsk;
                  return (
                    <button key={s} onClick={() => setSide(s)} style={{
                      padding: '12px 14px', borderRadius: 8,
                      background: isActive ? sBg : 'var(--bg-elev-2)',
                      border: `1px solid ${isActive ? sAccent : 'var(--line-subtle)'}`,
                      color: isActive ? sAccent : 'var(--text-2)',
                      cursor: 'pointer', textAlign: 'left',
                      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                      transition: 'all 120ms var(--ease)',
                    }}>
                      <div>
                        <div style={{ fontSize: 13, fontWeight: 700 }}>BUY {s}</div>
                        <div style={{ fontSize: 10, color: 'var(--text-3)', marginTop: 2 }}>
                          {s === 'YES' ? `${ctx.sym} > ${fmtStrike(ctx.strike)}` : `${ctx.sym} < ${fmtStrike(ctx.strike)}`}
                        </div>
                      </div>
                      <div className="num" style={{ fontSize: 16, fontWeight: 700, color: isActive ? sAccent : 'var(--text-2)' }}>{sAsk}¢</div>
                    </button>
                  );
                })}
              </div>
            </div>
          )}

          {/* Action chip + price hero (close mode only — open mode covered by side selector) */}
          {isClose && (
            <div style={{ padding: '20px 18px 8px', textAlign: 'center' }}>
              <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, padding: '4px 12px', borderRadius: 999, background: accentBg, border: `1px solid color-mix(in oklab, ${isYes ? '#97FCE4':'#ED7088'} 35%, transparent)`, color: accent, fontSize: 11, fontWeight: 700, letterSpacing: '0.06em', textTransform: 'uppercase' }}>
                Close {side}
              </div>
              <div style={{ marginTop: 14 }}>
                <span className="num dlg" style={{ color: accent, fontSize: 56 }}>{effPrice}¢</span>
              </div>
              <div className="num" style={{ color: 'var(--text-3)', fontSize: 12, marginTop: 4 }}>
                Sell to close · best bid · {askSize.toLocaleString()} contracts
              </div>
            </div>
          )}

          {/* Holding banner (always show if holding) */}
          {ctx.holding && (
            <div style={{ margin: '12px 18px 0', padding: '10px 12px', borderRadius: 8, background: 'var(--bg-elev-2)', border: '1px solid var(--line-subtle)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <div>
                <div className="cap-sm" style={{ color: 'var(--text-3)', marginBottom: 2 }}>You hold</div>
                <div className="num" style={{ fontSize: 13, color: 'var(--text)' }}>{ctx.holding.qty} {side} @ {ctx.holding.avg}¢ avg</div>
              </div>
              <div style={{ textAlign: 'right' }}>
                <div className="cap-sm" style={{ color: 'var(--text-3)', marginBottom: 2 }}>{isClose ? 'Realize' : 'Mark P&L'}</div>
                <div className="num" style={{ fontSize: 13, color: realizedPnl >= 0 ? 'var(--mint)' : 'var(--coral)' }}>{realizedPnl >= 0 ? '+' : ''}{fmtUsd(realizedPnl)}</div>
              </div>
            </div>
          )}

          {/* Order type toggle */}
          <div style={{ padding: '14px 18px 0' }}>
            <div style={{ display: 'flex', background: 'var(--bg-elev-2)', borderRadius: 8, padding: 3, border: '1px solid var(--line-subtle)' }}>
              {['market','limit'].map(t => (
                <button key={t} onClick={() => setOrderType(t)} style={{
                  flex: 1, height: 30, borderRadius: 6, fontSize: 12, fontWeight: 600,
                  background: orderType === t ? 'var(--bg-elev-3)' : 'transparent',
                  color: orderType === t ? 'var(--text)' : 'var(--text-3)',
                  textTransform: 'capitalize',
                  transition: 'all 120ms var(--ease)',
                }}>{t}</button>
              ))}
            </div>
          </div>

          {/* Limit price input */}
          {orderType === 'limit' && (
            <div style={{ padding: '12px 18px 0' }}>
              <div className="cap-sm" style={{ marginBottom: 6 }}>Limit price</div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <button className="btn" style={{ width: 36, height: 36 }} onClick={() => setLimitPrice(Math.max(1, limitPrice - 1))}>{ICONS.arrowDn}</button>
                <div style={{ flex: 1, height: 36, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'var(--bg-elev-2)', borderRadius: 6, border: '1px solid var(--line)' }}>
                  <span className="num" style={{ fontSize: 16, fontWeight: 600 }}>{limitPrice}¢</span>
                </div>
                <button className="btn" style={{ width: 36, height: 36 }} onClick={() => setLimitPrice(Math.min(99, limitPrice + 1))}>{ICONS.arrowUp}</button>
              </div>
            </div>
          )}

          {/* Quantity stepper */}
          <div style={{ padding: '14px 18px 0' }}>
            <div className="cap-sm" style={{ marginBottom: 6, display: 'flex', justifyContent: 'space-between' }}>
              <span>Quantity</span>
              {ctx.holding && <span style={{ color: 'var(--text-3)' }}>max {cap}</span>}
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <button className="btn" style={{ width: 36, height: 36 }} onClick={() => setQty(Math.max(1, qty - 1))}>{ICONS.arrowDn}</button>
              <div style={{ flex: 1, height: 36, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'var(--bg-elev-2)', borderRadius: 6, border: '1px solid var(--line)' }}>
                <span className="num" style={{ fontSize: 16, fontWeight: 600 }}>{qty}</span>
              </div>
              <button className="btn" style={{ width: 36, height: 36 }} onClick={() => setQty(Math.min(cap, qty + 1))}>{ICONS.arrowUp}</button>
            </div>
            <div style={{ display: 'flex', gap: 6, marginTop: 8 }}>
              {[1, 5, 10, 25, 100].map(n => (
                <button key={n} onClick={() => setQty(Math.min(cap, n))} className="chip" style={{ flex: 1, height: 28, justifyContent: 'center' }}>{n}</button>
              ))}
            </div>
          </div>

          {/* Preview rows */}
          <div style={{ padding: '16px 18px 0' }}>
            <div style={{ background: 'var(--bg-elev-2)', borderRadius: 8, padding: '12px 14px', border: '1px solid var(--line-subtle)', display: 'grid', gap: 8 }}>
              {isClose ? (
                <>
                  <Row k="Sell at"     v={`${effPrice}¢ × ${qty}`} />
                  <Row k="Avg cost"    v={`${ctx.holding.avg}¢ × ${qty}`} />
                  <Row k="Realized P&L" v={`${realizedPnl >= 0 ? '+' : '−'}${fmtUsd(Math.abs(realizedPnl))}`} c={realizedPnl >= 0 ? 'var(--mint)' : 'var(--coral)'} />
                </>
              ) : (
                <>
                  <Row k="Cost"        v={fmtUsd(cost)} />
                  <Row k="Max gain"    v={`+${fmtUsd(maxGain)}`} c="var(--mint)" />
                  <Row k="Max loss"    v={`−${fmtUsd(maxLoss)}`} c="var(--coral)" />
                  <Row k="Breakeven"   v={breakeven} />
                </>
              )}
            </div>
          </div>

          {/* CTA */}
          <div style={{ padding: '14px 18px 18px' }}>
            <button onClick={place} disabled={placing} className="btn btn-primary btn-xl btn-full" style={{
              background: success ? 'var(--mint)' : (placing ? 'var(--mint-dim)' : (isClose ? 'var(--text)' : accent)),
              color: isClose && !success && !placing ? 'var(--bg)' : undefined,
            }}>
              {success ? <><span style={{display:'inline-flex'}}>{ICONS.check}</span> {isClose ? 'Closed' : 'Order placed'}</>
               : placing ? 'Placing…'
               : ctaLabel}
            </button>
          </div>

          {/* Resolution copy */}
          <div style={{ padding: '0 18px 16px', color: 'var(--text-3)', fontSize: 11, lineHeight: 1.5 }}>
            Resolves YES if {VD.VD_ASSETS.find(a => a.sym === ctx.sym).name} closes above{' '}
            <span className="num" style={{color:'var(--text-2)'}}>{fmtStrike(ctx.strike)}</span> on {expiry.label} per Pyth aggregate. 4-hour dispute window before final settlement.
          </div>
        </div>

        {/* RIGHT: order book ladder + recent trades (Pro only) */}
        {pro && <OrderBookPanel sym={ctx.sym} side={side} row={row} strike={ctx.strike} />}
      </div>
    </div>
  );
}

// ============== Order book panel ==============
function OrderBookPanel({ sym, side, row, strike }) {
  const isYes = side === 'YES';
  const accent = isYes ? 'var(--mint)' : 'var(--coral)';
  const bestBid = isYes ? row.yBid : row.nBid;
  const bestAsk = isYes ? row.yAsk : row.nAsk;
  const bidSize = isYes ? row.yBidSize : row.nBidSize;
  const askSize = isYes ? row.yAskSize : row.nAskSize;

  // Synthesize 8-level ladder + recent trades, deterministic per strike + side
  const seed = (strike * 11 + (isYes ? 7 : 23)) | 0;
  const rand = (i) => {
    const x = Math.sin(seed + i * 53) * 10000;
    return x - Math.floor(x);
  };
  const N = 8;
  const asks = Array.from({ length: N }, (_, i) => ({
    price: Math.min(99, bestAsk + i),
    size: Math.round(askSize * (0.6 + rand(i) * 0.9)),
  }));
  const bids = Array.from({ length: N }, (_, i) => ({
    price: Math.max(1, bestBid - i),
    size: Math.round(bidSize * (0.6 + rand(i + 50) * 0.9)),
  }));

  // Cumulative depth for the depth chart
  let cumA = 0, cumB = 0;
  const asksCum = asks.map(a => { cumA += a.size; return { ...a, cum: cumA }; });
  const bidsCum = bids.map(b => { cumB += b.size; return { ...b, cum: cumB }; });
  const maxCum = Math.max(cumA, cumB);

  // Recent trades — deterministic
  const trades = Array.from({ length: 8 }, (_, i) => {
    const r = rand(i + 100);
    const isBuy = r > 0.42;
    return {
      price: isBuy ? bestAsk - Math.floor(rand(i + 200) * 2) : bestBid + Math.floor(rand(i + 300) * 2),
      size: Math.max(1, Math.round(rand(i + 400) * 80)),
      isBuy,
      ago: i === 0 ? 'now' : `${Math.round(rand(i + 500) * 50 + i * 8)}s`,
    };
  });

  const fmtSize = (n) => n >= 1000 ? (n/1000).toFixed(1) + 'K' : String(n);

  return (
    <div style={{
      borderLeft: '1px solid var(--line-subtle)',
      background: 'var(--bg-elev-2)',
      display: 'flex', flexDirection: 'column',
    }}>
      {/* Header */}
      <div style={{ padding: '14px 16px', borderBottom: '1px solid var(--line-subtle)' }}>
        <div style={{
          fontSize: 10, fontWeight: 700, color: accent,
          fontFamily: 'JetBrains Mono, monospace', textTransform: 'uppercase', letterSpacing: '0.12em',
        }}>{side} order book</div>
        <div style={{ fontSize: 10, color: 'var(--text-3)', fontFamily: 'JetBrains Mono, monospace', marginTop: 2 }}>
          spread {bestAsk - bestBid}¢ · mid {((bestAsk + bestBid) / 2).toFixed(1)}¢
        </div>
      </div>

      {/* Ladder */}
      <div style={{ padding: '8px 12px', flex: 1 }}>
        <div style={{
          display: 'grid', gridTemplateColumns: '1fr 60px 60px',
          fontSize: 9, color: 'var(--text-3)', fontFamily: 'JetBrains Mono, monospace',
          textTransform: 'uppercase', letterSpacing: '0.08em',
          padding: '0 6px 4px', borderBottom: '1px solid var(--line-subtle)',
        }}>
          <span></span><span style={{ textAlign: 'right' }}>Size</span><span style={{ textAlign: 'right' }}>Cum</span>
        </div>

        {/* Asks (top) — reversed so best ask is closest to spread line */}
        {[...asksCum].reverse().map((a, i) => (
          <LadderRow key={'a' + i} price={a.price} size={a.size} cum={a.cum}
            color="var(--coral)" maxCum={maxCum} isAsk />
        ))}
        <div style={{
          padding: '8px 6px', display: 'flex', justifyContent: 'space-between', alignItems: 'center',
          borderTop: '1px dashed var(--line)', borderBottom: '1px dashed var(--line)',
          background: 'var(--bg-elev)',
          fontFamily: 'JetBrains Mono, monospace', fontSize: 11,
        }}>
          <span style={{ color: 'var(--text-3)', fontSize: 9, textTransform: 'uppercase', letterSpacing: '0.08em' }}>spread</span>
          <span style={{ color: accent, fontWeight: 700 }}>{((bestAsk + bestBid) / 2).toFixed(1)}¢</span>
        </div>
        {/* Bids (bottom) */}
        {bidsCum.map((b, i) => (
          <LadderRow key={'b' + i} price={b.price} size={b.size} cum={b.cum}
            color="var(--mint)" maxCum={maxCum} />
        ))}
      </div>

      {/* Recent trades */}
      <div style={{ borderTop: '1px solid var(--line-subtle)', padding: '12px 16px' }}>
        <div className="cap-sm" style={{ marginBottom: 8, fontSize: 9 }}>Recent fills</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
          {trades.map((t, i) => (
            <div key={i} style={{
              display: 'grid', gridTemplateColumns: '50px 1fr 50px',
              fontFamily: 'JetBrains Mono, monospace', fontSize: 11, alignItems: 'center',
            }}>
              <span style={{ color: t.isBuy ? 'var(--mint)' : 'var(--coral)', fontWeight: 600 }}>
                {t.price}¢
              </span>
              <span style={{ color: 'var(--text-3)' }}>{fmtSize(t.size)} × {t.isBuy ? 'BUY' : 'SELL'}</span>
              <span style={{ color: 'var(--text-4)', textAlign: 'right', fontSize: 10 }}>{t.ago}</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function LadderRow({ price, size, cum, color, maxCum, isAsk }) {
  const fmtSize = (n) => n >= 1000 ? (n/1000).toFixed(1) + 'K' : String(n);
  const depthPct = (cum / maxCum) * 100;
  const bg = isAsk ? 'rgba(255,107,107,0.08)' : 'rgba(151,252,228,0.08)';
  return (
    <div style={{
      display: 'grid', gridTemplateColumns: '1fr 60px 60px',
      padding: '5px 6px', position: 'relative',
      fontFamily: 'JetBrains Mono, monospace', fontSize: 12,
      cursor: 'pointer',
    }}>
      {/* Cumulative depth bar */}
      <div style={{
        position: 'absolute', top: 0, bottom: 0, right: 0,
        width: depthPct + '%', background: bg, pointerEvents: 'none',
      }} />
      <span style={{ color, fontWeight: 600, position: 'relative' }}>{price}¢</span>
      <span style={{ color: 'var(--text-2)', textAlign: 'right', position: 'relative' }}>{fmtSize(size)}</span>
      <span style={{ color: 'var(--text-4)', textAlign: 'right', position: 'relative' }}>{fmtSize(cum)}</span>
    </div>
  );
}

function Row({ k, v, c }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
      <span style={{ color: 'var(--text-3)', fontSize: 12 }}>{k}</span>
      <span className="num" style={{ color: c || 'var(--text)', fontSize: 13, fontWeight: 600 }}>{v}</span>
    </div>
  );
}

window.VDTicket = { TradeTicket };
