// Options chain table — BUY-only mechanics (Polymarket/Kalshi/HIP-4 share-based markets).
// Rows: ASK cells are primary tap targets to OPEN. BID cells are info-only unless user
// holds that side, in which case they become the CLOSE tap target. Click any row to expand
// inline mini depth ladder.
const { useState: useStateChain } = React;

function Chain({ sym, expiryKey, pro, onCellClick, holdings = {} }) {
  const VD = window.VD;
  const { Icon, ICONS } = window.VDIcons;
  const { DepthBar } = window.VDChart;
  const rows = VD.vdBuildChain(sym, expiryKey);
  const a = VD.VD_ASSETS.find(x => x.sym === sym);
  const [expanded, setExpanded] = useStateChain(null); // r.strike when expanded

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

  const headerCells = pro
    ? ['Strike','Δ','Vega','IV','IVR','YES Bid','YES Ask','NO Bid','NO Ask','Depth','Vol','OI']
    : ['Strike','YES Bid','YES Ask','NO Bid','NO Ask','Depth','Vol','OI'];

  const colTpl = pro
    ? '120px 56px 64px 64px 64px 1fr 1fr 1fr 1fr 80px 80px 80px'
    : '140px 1fr 1fr 1fr 1fr 100px 90px 90px';

  return (
    <div style={{ borderTop: '1px solid var(--line-subtle)' }}>
      <div className="cap" style={{
        display: 'grid', gridTemplateColumns: colTpl, gap: 12,
        padding: '12px 16px', background: 'var(--bg-elev)',
        borderBottom: '1px solid var(--line-subtle)',
        position: 'sticky', top: 0, zIndex: 2,
      }}>
        {headerCells.map((c, i) => <div key={i} style={{textAlign: i === 0 ? 'left' : i >= headerCells.length - 3 ? 'right' : 'center'}}>{c}</div>)}
      </div>

      {rows.map((r, idx) => {
        const yKey = `${sym}|YES|${r.strike}|${expiryKey}`;
        const nKey = `${sym}|NO|${r.strike}|${expiryKey}`;
        const yHold = holdings[yKey];
        const nHold = holdings[nKey];
        const isExp = expanded === r.strike;
        return (
          <React.Fragment key={r.strike}>
            <div onClick={() => setExpanded(isExp ? null : r.strike)} style={{
              display: 'grid', gridTemplateColumns: colTpl, gap: 12,
              padding: '8px 16px', alignItems: 'center',
              borderBottom: idx === rows.length - 1 && !isExp ? 'none' : '1px solid var(--line-subtle)',
              background: r.atm ? 'linear-gradient(90deg, rgba(151,252,228,0.04), transparent)' : 'transparent',
              position: 'relative', cursor: 'pointer',
            }}>
              {/* strike */}
              <div style={{display:'flex', alignItems:'center', gap:8}}>
                <span style={{
                  display: 'inline-block', width: 10, color: 'var(--text-4)', fontSize: 10,
                  transform: isExp ? 'rotate(90deg)' : 'rotate(0)', transition: 'transform 160ms',
                }}>▸</span>
                <span className="num" style={{fontSize: 14, fontWeight: 600, color: r.atm ? 'var(--mint)' : 'var(--text)'}}>
                  {r.strike >= 1000 ? r.strike.toLocaleString() : r.strike}
                </span>
                {r.atm && <span className="cap-sm" style={{color:'var(--mint)', fontSize: 9}}>ATM</span>}
              </div>

              {pro && (
                <>
                  <div className="num" style={{textAlign:'center', color:'var(--text-2)', fontSize:12}}>{r.delta.toFixed(2)}</div>
                  <div className="num" style={{textAlign:'center', color:'var(--text-2)', fontSize:12}}>{r.vega.toFixed(3)}</div>
                  <div className="num" style={{textAlign:'center', color:'var(--text-2)', fontSize:12}}>{r.iv.toFixed(1)}</div>
                  <div className="num" style={{textAlign:'center', color: r.ivRank > 70 ? 'var(--amber)' : 'var(--text-2)', fontSize:12}}>{r.ivRank}</div>
                </>
              )}

              {/* YES bid: muted unless user holds YES at this strike (then it's "Close"). */}
              <BidCell side="YES" price={r.yBid} size={r.yBidSize} hold={yHold} pro={pro} mid={(r.yBid + r.yAsk) / 2}
                onClickClose={(e) => { e.stopPropagation(); onCellClick({ sym, side: 'YES', action: 'Close', strike: r.strike, expiryKey, price: r.yBid, size: r.yBidSize, mid: (r.yBid+r.yAsk)/2, holding: yHold }); }} />
              {/* YES ask: primary BUY YES target */}
              <AskCell side="YES" price={r.yAsk} size={r.yAskSize} pro={pro} mid={(r.yBid + r.yAsk) / 2}
                onClick={(e) => { e.stopPropagation(); onCellClick({ sym, side: 'YES', action: 'Buy', strike: r.strike, expiryKey, price: r.yAsk, size: r.yAskSize, mid: (r.yBid+r.yAsk)/2, holding: yHold }); }} />
              {/* NO bid: muted unless user holds NO at this strike (then it's "Close"). */}
              <BidCell side="NO" price={r.nBid} size={r.nBidSize} hold={nHold} pro={pro} mid={(r.nBid + r.nAsk) / 2}
                onClickClose={(e) => { e.stopPropagation(); onCellClick({ sym, side: 'NO', action: 'Close', strike: r.strike, expiryKey, price: r.nBid, size: r.nBidSize, mid: (r.nBid+r.nAsk)/2, holding: nHold }); }} />
              {/* NO ask: primary BUY NO target */}
              <AskCell side="NO" price={r.nAsk} size={r.nAskSize} pro={pro} mid={(r.nBid + r.nAsk) / 2}
                onClick={(e) => { e.stopPropagation(); onCellClick({ sym, side: 'NO', action: 'Buy', strike: r.strike, expiryKey, price: r.nAsk, size: r.nAskSize, mid: (r.nBid+r.nAsk)/2, holding: nHold }); }} />

              <div style={{display:'flex', justifyContent:'center'}}><DepthBar value={r.depth} /></div>
              <div className="num" style={{textAlign:'right', color:'var(--text-2)', fontSize: 12}}>{fmtSize(r.vol)}</div>
              <div className="num" style={{textAlign:'right', color:'var(--text-2)', fontSize: 12}}>{fmtSize(r.oi)}</div>
            </div>

            {/* Inline expanded mini depth ladder */}
            {isExp && (
              <ExpandedRow row={r} sym={sym} expiryKey={expiryKey} onCellClick={onCellClick}
                last={idx === rows.length - 1} yHold={yHold} nHold={nHold} />
            )}
          </React.Fragment>
        );
      })}
    </div>
  );
}

// ============== Inline expanded row: mini depth ladder + last trades ==============
function ExpandedRow({ row, sym, expiryKey, onCellClick, last, yHold, nHold }) {
  // Synthesize a 5-level depth ladder from the row's quoted size (deterministic per strike)
  const seed = (row.strike * 7 + 13) | 0;
  const rand = (i) => {
    const x = Math.sin(seed + i * 47) * 10000;
    return x - Math.floor(x);
  };
  const yLadder = Array.from({ length: 5 }, (_, i) => ({
    bid: Math.max(1, row.yBid - i),
    bSize: Math.round(row.yBidSize * (0.7 + rand(i) * 0.6)),
    ask: Math.min(99, row.yAsk + i),
    aSize: Math.round(row.yAskSize * (0.6 + rand(i + 5) * 0.7)),
  }));
  const nLadder = Array.from({ length: 5 }, (_, i) => ({
    bid: Math.max(1, row.nBid - i),
    bSize: Math.round(row.nBidSize * (0.7 + rand(i + 11) * 0.6)),
    ask: Math.min(99, row.nAsk + i),
    aSize: Math.round(row.nAskSize * (0.6 + rand(i + 17) * 0.7)),
  }));
  const fmtSize = (n) => n >= 1000 ? (n/1000).toFixed(1) + 'K' : String(n);

  return (
    <div style={{
      padding: '14px 24px 18px',
      background: 'var(--bg-elev-2)',
      borderBottom: last ? 'none' : '1px solid var(--line-subtle)',
      display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 32,
    }}>
      {/* YES side mini ladder */}
      <MiniLadder side="YES" rows={yLadder} hold={yHold}
        onBuy={(price, size) => onCellClick({ sym, side: 'YES', action: 'Buy', strike: row.strike, expiryKey, price, size, mid: (row.yBid+row.yAsk)/2, holding: yHold })}
        onClose={(price, size) => onCellClick({ sym, side: 'YES', action: 'Close', strike: row.strike, expiryKey, price, size, mid: (row.yBid+row.yAsk)/2, holding: yHold })}
        fmtSize={fmtSize} />
      {/* NO side mini ladder */}
      <MiniLadder side="NO" rows={nLadder} hold={nHold}
        onBuy={(price, size) => onCellClick({ sym, side: 'NO', action: 'Buy', strike: row.strike, expiryKey, price, size, mid: (row.nBid+row.nAsk)/2, holding: nHold })}
        onClose={(price, size) => onCellClick({ sym, side: 'NO', action: 'Close', strike: row.strike, expiryKey, price, size, mid: (row.nBid+row.nAsk)/2, holding: nHold })}
        fmtSize={fmtSize} />
    </div>
  );
}

function MiniLadder({ side, rows, hold, onBuy, onClose, fmtSize }) {
  const isYes = side === 'YES';
  const accent = isYes ? 'var(--mint)' : 'var(--coral)';
  const accentDim = isYes ? 'var(--mint-dim)' : 'var(--coral-dim)';
  const total = rows.reduce((s, r) => s + r.aSize + r.bSize, 0);

  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 8 }}>
        <div style={{
          fontSize: 10, color: accent, fontWeight: 700,
          fontFamily: 'JetBrains Mono, monospace', letterSpacing: '0.12em', textTransform: 'uppercase',
        }}>{side} order book</div>
        <div style={{ fontSize: 10, color: 'var(--text-3)', fontFamily: 'JetBrains Mono, monospace' }}>
          depth · {fmtSize(total)} contracts
        </div>
      </div>
      <div style={{
        display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 1,
        background: 'var(--line-subtle)', border: '1px solid var(--line-subtle)',
      }}>
        {/* BID column header */}
        <div style={{ padding: '4px 8px', background: 'var(--bg)', fontSize: 9, color: 'var(--text-3)', fontFamily: 'JetBrains Mono, monospace', textTransform: 'uppercase', letterSpacing: '0.08em', display: 'flex', justifyContent: 'space-between' }}>
          <span>Bid · close</span><span>Size</span>
        </div>
        {/* ASK column header */}
        <div style={{ padding: '4px 8px', background: 'var(--bg)', fontSize: 9, color: 'var(--text-3)', fontFamily: 'JetBrains Mono, monospace', textTransform: 'uppercase', letterSpacing: '0.08em', display: 'flex', justifyContent: 'space-between' }}>
          <span>Size</span><span>Ask · buy</span>
        </div>
        {rows.map((r, i) => (
          <React.Fragment key={i}>
            {/* Bid cell — muted unless user holds */}
            <button
              disabled={!hold}
              onClick={() => hold && onClose(r.bid, r.bSize)}
              style={{
                display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                padding: '6px 8px', background: 'var(--bg-elev)',
                border: 'none', cursor: hold ? 'pointer' : 'default',
                fontFamily: 'JetBrains Mono, monospace', fontSize: 12,
                opacity: hold ? 1 : 0.45,
                transition: 'background 100ms',
              }}
              onMouseEnter={e => { if (hold) e.currentTarget.style.background = 'var(--bg-elev-3)'; }}
              onMouseLeave={e => { if (hold) e.currentTarget.style.background = 'var(--bg-elev)'; }}
            >
              <span style={{ color: hold ? accent : 'var(--text-3)', fontWeight: 600 }}>{r.bid}¢</span>
              <span style={{ color: 'var(--text-3)' }}>{fmtSize(r.bSize)}</span>
            </button>
            {/* Ask cell — clickable BUY */}
            <button
              onClick={() => onBuy(r.ask, r.aSize)}
              style={{
                display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                padding: '6px 8px', background: 'var(--bg-elev)',
                border: 'none', cursor: 'pointer',
                fontFamily: 'JetBrains Mono, monospace', fontSize: 12,
                transition: 'background 100ms',
              }}
              onMouseEnter={e => { e.currentTarget.style.background = isYes ? 'var(--mint-bg10)' : 'var(--coral-bg10)'; }}
              onMouseLeave={e => { e.currentTarget.style.background = 'var(--bg-elev)'; }}
            >
              <span style={{ color: 'var(--text-3)' }}>{fmtSize(r.aSize)}</span>
              <span style={{ color: accent, fontWeight: 600 }}>{r.ask}¢</span>
            </button>
          </React.Fragment>
        ))}
      </div>
      {hold && (
        <div style={{ marginTop: 6, fontSize: 10, color: 'var(--text-3)', fontFamily: 'JetBrains Mono, monospace' }}>
          You hold <span style={{ color: accent, fontWeight: 600 }}>{hold.qty} {side}</span> @ {hold.avg}¢ avg — bids are click-to-close.
        </div>
      )}
    </div>
  );
}

// ============== Cell components ==============
// Bid cell — info-only by default. If user holds this side at this strike, becomes a Close tap target.
function BidCell({ side, price, size, hold, pro, mid, onClickClose }) {
  const isYes = side === 'YES';
  const color = isYes ? 'var(--mint)' : 'var(--coral)';
  const dim = isYes ? 'var(--mint-dim)' : 'var(--coral-dim)';
  const bgHover = isYes ? 'var(--mint-bg10)' : 'var(--coral-bg10)';
  const fmtSize = (n) => n >= 1000 ? (n/1000).toFixed(1) + 'K' : String(n);

  if (!hold) {
    // Muted info display — not interactive
    return (
      <div style={{
        display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
        padding: '6px 8px', opacity: 0.42,
      }}>
        <span className="num" style={{ color: 'var(--text-3)', fontSize: 13 }}>
          {pro ? `${mid.toFixed(1)}¢` : `${price}¢`}
        </span>
        <span className="num" style={{ color: 'var(--text-4)', fontSize: 10.5, marginTop: 2 }}>
          {fmtSize(size)}
        </span>
      </div>
    );
  }

  // User holds this side — bid becomes the Close action
  return (
    <button onClick={onClickClose} style={{
      display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
      padding: '6px 8px', borderRadius: 6,
      border: `1px dashed ${dim}`, background: 'transparent',
      transition: 'background 120ms var(--ease), border-color 120ms var(--ease)',
      position: 'relative', cursor: 'pointer',
    }}
      onMouseEnter={(e) => { e.currentTarget.style.background = bgHover; e.currentTarget.style.borderColor = color; }}
      onMouseLeave={(e) => { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.borderColor = dim; }}
    >
      <span className="num" style={{ color, fontWeight: 600, fontSize: 14 }}>{price}¢</span>
      <span className="num" style={{ color: 'var(--text-3)', fontSize: 10.5, marginTop: 2 }}>
        close · {fmtSize(size)}
      </span>
      <span style={{ position: 'absolute', top: 3, right: 3, width: 5, height: 5, borderRadius: 999, background: color }} />
    </button>
  );
}

// Ask cell — primary BUY action.
function AskCell({ side, price, size, pro, mid, onClick }) {
  const isYes = side === 'YES';
  const color = isYes ? 'var(--mint)' : 'var(--coral)';
  const bgHover = isYes ? 'var(--mint-bg10)' : 'var(--coral-bg10)';
  const fmtSize = (n) => n >= 1000 ? (n/1000).toFixed(1) + 'K' : String(n);
  return (
    <button onClick={onClick} style={{
      display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
      padding: '6px 8px', borderRadius: 6,
      border: '1px solid transparent', background: 'transparent',
      transition: 'background 120ms var(--ease), border-color 120ms var(--ease)',
      position: 'relative', cursor: 'pointer',
    }}
      onMouseEnter={(e) => { e.currentTarget.style.background = bgHover; e.currentTarget.style.borderColor = `color-mix(in oklab, ${isYes ? '#97FCE4' : '#ED7088'} 35%, transparent)`; }}
      onMouseLeave={(e) => { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.borderColor = 'transparent'; }}
    >
      <span className="num" style={{ color, fontWeight: 600, fontSize: 14 }}>
        {pro ? `${mid.toFixed(1)}¢` : `${price}¢`}
      </span>
      <span className="num" style={{ color: 'var(--text-3)', fontSize: 10.5, marginTop: 2 }}>
        buy · {fmtSize(size)}
      </span>
    </button>
  );
}

window.VDChain = { Chain };
