// terminal-order.jsx — Order ticket overlay.
// Tap "Trade" on a holding detail → slides up a full-screen order entry sheet
// with live verification preview. This is where the Council + compute_proof
// system becomes concrete to the trader: BEFORE confirming, they see exactly
// how many verifiers would sign + what the compute trail will look like.

function OrderTicketScreen({ sym, onClose, mode = 'live' }) {
  const tile = marketTileFor(sym);
  const holding = holdingFor(sym);
  const isShadow = mode === 'shadow';

  const [side, setSide]       = React.useState('BUY');
  const [orderType, setType]  = React.useState('MARKET');
  const [qty, setQty]         = React.useState('1');
  const [limit, setLimit]     = React.useState(tile.price.toFixed(2));
  const [tif, setTif]         = React.useState('DAY');

  const qtyNum = parseFloat(qty) || 0;
  const px = orderType === 'MARKET' ? tile.price : (parseFloat(limit) || tile.price);
  const value = +(qtyNum * px).toFixed(2);

  // Deterministic preview of how the Council would respond to THIS order.
  // Seed off sym + side + qty + price so the preview is reproducible.
  const previewSeed = (typeof seedFromHex === 'function')
    ? (typeof tmHash === 'function' ? tmHash(`prev:${sym}:${side}:${qty}:${px}`) : 1)
    : 1;
  const rng = (typeof tmRng === 'function') ? tmRng(previewSeed) : (() => 0.5);
  // High-confidence symbols clear more agreement. Big sizes drop it.
  const baseAgreement = tile.up ? 0.86 : 0.68;
  const sizePenalty = qtyNum > 100 ? 0.06 : qtyNum > 25 ? 0.02 : 0;
  const agreement = Math.max(0.40, Math.min(0.96, baseAgreement - sizePenalty + (rng() - 0.5) * 0.03));
  const yesVotes = Math.round(agreement * 25);
  const willClear = yesVotes >= 17;

  // Mock compute latency from the dispatcher
  const computeMs = 70 + Math.floor(rng() * 50);

  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflowY: 'auto', background: TM.surface }} className="tx-scroll">
      <TopBar title={`${isShadow ? 'Shadow · ' : ''}${side === 'BUY' ? 'Buy' : 'Sell'} ${sym}`}
        subtitle={isShadow ? 'Records the Council vote without placing the order' : tile.name}
        onBack={onClose}/>

      {isShadow && (
        <div style={{
          margin: '12px 16px 0', padding: '10px 14px',
          background: TM.violet + '1a', border: `1px solid ${TM.violet}55`, borderRadius: 8,
          display: 'flex', alignItems: 'flex-start', gap: 10,
        }}>
          <span style={{
            width: 22, height: 22, borderRadius: 4, flexShrink: 0,
            background: TM.violet + '33', color: TM.violet,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontFamily: GM, fontSize: 12, fontWeight: 700,
          }}>◐</span>
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: GM, fontSize: 10, color: TM.violet, fontWeight: 600, letterSpacing: 1.2 }}>
              SHADOW MODE · NO BROKER · NO FEES
            </div>
            <div style={{ marginTop: 4, fontFamily: GE, fontSize: 12.5, color: TM.text, lineHeight: 1.5, letterSpacing: -0.05 }}>
              The Council still votes. The receipt still anchors on Base. Your account is not touched. Use it to test conviction before committing real capital.
            </div>
          </div>
        </div>
      )}

      {/* Price + side toggle */}
      <div style={{ padding: '14px 16px 0' }}>
        <div style={{
          display: 'flex', alignItems: 'baseline', justifyContent: 'space-between',
          marginBottom: 12,
        }}>
          <div>
            <div style={{ fontFamily: GE, fontSize: 11, color: TM.muted }}>Last price</div>
            <div style={{ fontFamily: GM, fontSize: 28, fontWeight: 600, color: TM.text, letterSpacing: -0.6, marginTop: 2, lineHeight: 1 }}>
              ${tile.price.toLocaleString(undefined, { maximumFractionDigits: 2 })}
            </div>
          </div>
          <span style={{ fontFamily: GM, fontSize: 13, color: tile.up ? TM.green : TM.red }}>
            {tile.up ? '+' : ''}{tile.pct.toFixed(2)}% today
          </span>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
          {['BUY', 'SELL'].map(s => {
            const active = side === s;
            const c = s === 'BUY' ? TM.green : TM.orange;
            return (
              <button key={s} onClick={() => setSide(s)} style={{
                padding: '12px 0',
                background: active ? c : 'transparent',
                border: `1px solid ${active ? c : TM.border}`,
                borderRadius: 8,
                fontFamily: GE, fontSize: 14, fontWeight: 600,
                color: active ? TM.ink : TM.text, letterSpacing: -0.1,
              }}>{s === 'BUY' ? 'Buy' : 'Sell'}</button>
            );
          })}
        </div>
      </div>

      {/* Order type tabs */}
      <div style={{ padding: '16px 16px 0' }}>
        <div style={{
          display: 'flex', gap: 18, borderBottom: `1px solid ${TM.border}`,
        }}>
          {['MARKET', 'LIMIT', 'STOP'].map(t => {
            const active = orderType === t;
            return (
              <button key={t} onClick={() => setType(t)} style={{
                padding: '8px 0 10px',
                fontFamily: GE, fontSize: 13, fontWeight: active ? 600 : 400,
                color: active ? TM.text : TM.muted, letterSpacing: -0.1,
                borderBottom: active ? `2px solid ${TM.orange}` : '2px solid transparent',
              }}>{t}</button>
            );
          })}
        </div>
      </div>

      {/* Quantity + limit price + TIF */}
      <div style={{ padding: '16px', display: 'flex', flexDirection: 'column', gap: 12 }}>
        <NumberField label="Quantity" value={qty} onChange={setQty} suffix={sym === 'BTC' || sym === 'ETH' ? sym : 'sh'}/>
        {orderType !== 'MARKET' && (
          <NumberField label={orderType === 'LIMIT' ? 'Limit price' : 'Stop price'} value={limit} onChange={setLimit} prefix="$"/>
        )}
        <div>
          <div style={{ fontFamily: GE, fontSize: 11, color: TM.muted, letterSpacing: -0.05, marginBottom: 6 }}>Time in force</div>
          <Segmented value={tif} onChange={setTif} options={[
            { key: 'DAY', label: 'Day' },
            { key: 'GTC', label: 'GTC' },
            { key: 'IOC', label: 'IOC' },
          ]}/>
        </div>
      </div>

      {/* Order summary */}
      <div style={{
        margin: '0 16px', padding: '14px 16px',
        background: TM.surfaceHi, border: `1px solid ${TM.border}`, borderRadius: 10,
        display: 'flex', flexDirection: 'column', gap: 8,
      }}>
        {[
          ['Side',        side === 'BUY' ? 'Buy' : 'Sell',                   side === 'BUY' ? TM.green : TM.orange],
          ['Order type',  orderType.charAt(0) + orderType.slice(1).toLowerCase(), TM.text],
          ['Quantity',    `${qtyNum} ${sym === 'BTC' || sym === 'ETH' ? sym : 'shares'}`, TM.text],
          ['Price',       orderType === 'MARKET' ? `Market (~$${tile.price.toFixed(2)})` : `$${parseFloat(limit).toFixed(2)}`, TM.text],
          ['Value',       `$${value.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`, TM.text],
          ['Time in force', tif,                                              TM.text],
        ].map(([k, v, c], i) => (
          <div key={k} style={{
            display: 'flex', justifyContent: 'space-between',
            padding: i === 0 ? 0 : '8px 0 0',
            borderTop: i === 0 ? 'none' : `1px solid ${TM.border}`,
          }}>
            <span style={{ fontFamily: GE, fontSize: 12.5, color: TM.muted, letterSpacing: -0.05 }}>{k}</span>
            <span style={{ fontFamily: GM, fontSize: 12.5, color: c, letterSpacing: 0.1 }}>{v}</span>
          </div>
        ))}
      </div>

      {/* COUNCIL PREVIEW — TradeXchange-specific, this is the differentiator */}
      <div style={{
        margin: '16px 16px 0', padding: '14px 16px',
        background: willClear ? TM.cyanSoft : TM.redSoft,
        border: `1px solid ${willClear ? TM.cyan : TM.red}55`, borderRadius: 10,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <span style={{ fontFamily: GM, fontSize: 10, fontWeight: 600, color: willClear ? TM.cyan : TM.red, letterSpacing: 1.2 }}>
            {willClear ? 'COUNCIL PREVIEW · LIKELY CLEAR' : 'COUNCIL PREVIEW · LIKELY REFUSED'}
          </span>
          <span style={{ fontFamily: GM, fontSize: 11, color: TM.muted, letterSpacing: 0.4 }}>
            est. {computeMs + 187 + 64}ms
          </span>
        </div>

        <div style={{
          marginTop: 12, fontFamily: GM, fontSize: 22, fontWeight: 600, color: TM.text, letterSpacing: -0.4,
        }}>
          {yesVotes} / 25 verifiers
          <span style={{ fontFamily: GE, fontWeight: 400, fontSize: 13, color: TM.muted, marginLeft: 8 }}>
            ({Math.round(agreement * 100)}% agreement · need 17)
          </span>
        </div>

        {/* 25-cell mini bar with pass-bar marker */}
        <div style={{ marginTop: 10, position: 'relative' }}>
          <div style={{
            display: 'grid', gridTemplateColumns: 'repeat(25, 1fr)', gap: 2,
            background: 'rgba(244,244,240,0.04)', padding: 2,
          }}>
            {Array.from({ length: 25 }).map((_, i) => (
              <span key={i} style={{
                height: 14,
                background: i < yesVotes ? (willClear ? TM.green : TM.red) : 'rgba(244,244,240,0.10)',
              }}/>
            ))}
          </div>
          <span style={{
            position: 'absolute', left: `${(17 / 25) * 100}%`,
            top: -2, bottom: -2, width: 1,
            background: TM.orange, marginLeft: -0.5,
          }}/>
        </div>

        <div style={{
          marginTop: 12, display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10,
          fontFamily: GM, fontSize: 10.5, color: TM.muted, letterSpacing: 0.4,
        }}>
          <div>
            <div style={{ color: TM.cyan, fontSize: 9.5, fontWeight: 600, letterSpacing: 1 }}>COMPUTE</div>
            <div style={{ marginTop: 2, color: TM.text }}>cusv · {computeMs}ms</div>
          </div>
          <div>
            <div style={{ color: TM.cyan, fontSize: 9.5, fontWeight: 600, letterSpacing: 1 }}>RISK CHECK</div>
            <div style={{ marginTop: 2, color: TM.text }}>10 of 10 ready</div>
          </div>
          <div>
            <div style={{ color: TM.cyan, fontSize: 9.5, fontWeight: 600, letterSpacing: 1 }}>RECEIPT</div>
            <div style={{ marginTop: 2, color: TM.text }}>anchored on Base</div>
          </div>
        </div>

        <div style={{
          marginTop: 12, fontFamily: GE, fontSize: 11.5, color: TM.muted, lineHeight: 1.5, letterSpacing: -0.05,
        }}>
          This preview reruns the same verification the live Council will sign. Final agreement may shift ±2 votes as fresh market data lands.
        </div>
      </div>

      {/* Buying power / holdings strip */}
      <div style={{
        margin: '16px 16px 0', padding: '12px 16px',
        background: TM.surfaceHi, border: `1px solid ${TM.border}`, borderRadius: 10,
        display: 'flex', justifyContent: 'space-between',
      }}>
        <div>
          <div style={{ fontFamily: GE, fontSize: 11, color: TM.muted }}>Buying power</div>
          <div style={{ fontFamily: GM, fontSize: 14, color: TM.text, marginTop: 2 }}>$8,420.18</div>
        </div>
        <div style={{ textAlign: 'right' }}>
          <div style={{ fontFamily: GE, fontSize: 11, color: TM.muted }}>Holding</div>
          <div style={{ fontFamily: GM, fontSize: 14, color: TM.text, marginTop: 2 }}>
            {holding ? `${holding.shares} ${sym}` : '0'}
          </div>
        </div>
      </div>

      {/* Sticky confirm button */}
      <div style={{
        position: 'sticky', bottom: 0, padding: '14px 16px',
        background: TM.surface, borderTop: `1px solid ${TM.border}`, marginTop: 20,
      }}>
        <button onClick={onClose} style={{
          width: '100%', padding: '14px 0', borderRadius: 10,
          background: isShadow
            ? TM.violet
            : (willClear ? TM.orange : TM.surfaceHi),
          color: isShadow ? '#fff' : (willClear ? TM.ink : TM.text),
          border: isShadow
            ? 'none'
            : (willClear ? 'none' : `1px solid ${TM.border}`),
          fontFamily: GE, fontSize: 15, fontWeight: 600, letterSpacing: -0.2,
        }}>
          {isShadow
            ? `Save shadow ${side === 'BUY' ? 'buy' : 'sell'}`
            : (willClear ? `Place ${side === 'BUY' ? 'Buy' : 'Sell'} Order` : 'Place anyway — Council will refuse')}
        </button>
        <div style={{
          marginTop: 8, fontFamily: GM, fontSize: 10, color: TM.muted, letterSpacing: 0.6, textAlign: 'center',
        }}>
          {isShadow
            ? 'NO MONEY MOVES · COUNCIL STILL VOTES · RECEIPT STILL ANCHORED'
            : (willClear
              ? 'ORDER WILL ROUTE THROUGH 25 VERIFIERS · COMPUTE · RISK · BROKER'
              : 'COUNCIL REFUSAL IS LIKELY · NO FEES IF REFUSED')}
        </div>
      </div>
    </div>
  );
}

// ── Inline number field with stepper buttons ─────────────────
function NumberField({ label, value, onChange, prefix, suffix }) {
  const decrement = () => {
    const n = parseFloat(value) || 0;
    onChange(String(Math.max(0, +(n - 1).toFixed(4))));
  };
  const increment = () => {
    const n = parseFloat(value) || 0;
    onChange(String(+(n + 1).toFixed(4)));
  };
  return (
    <div>
      <div style={{ fontFamily: GE, fontSize: 11, color: TM.muted, letterSpacing: -0.05, marginBottom: 6 }}>{label}</div>
      <div style={{
        display: 'flex', alignItems: 'stretch',
        background: TM.surfaceHi, border: `1px solid ${TM.border}`, borderRadius: 8,
        overflow: 'hidden',
      }}>
        <button onClick={decrement} style={{
          width: 44, color: TM.muted, fontFamily: GE, fontSize: 22,
          borderRight: `1px solid ${TM.border}`,
        }}>−</button>
        <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 4, padding: '8px 12px' }}>
          {prefix && <span style={{ fontFamily: GM, fontSize: 14, color: TM.muted }}>{prefix}</span>}
          <input value={value} onChange={(e) => onChange(e.target.value)} style={{
            width: '100%', textAlign: 'center', border: 'none', outline: 'none',
            background: 'transparent', fontFamily: GM, fontSize: 18, fontWeight: 600,
            color: TM.text, letterSpacing: -0.2,
          }}/>
          {suffix && <span style={{ fontFamily: GM, fontSize: 12, color: TM.muted }}>{suffix}</span>}
        </div>
        <button onClick={increment} style={{
          width: 44, color: TM.muted, fontFamily: GE, fontSize: 22,
          borderLeft: `1px solid ${TM.border}`,
        }}>+</button>
      </div>
    </div>
  );
}

Object.assign(window, { OrderTicketScreen, NumberField });
