// Risk check — the second pass before any order reaches the broker.
// Shows the routing decision from the risk engine across 10 named checks.

const QALGOS = [
  { id: 'liq',  name: 'Liquidity check',        tier: 'Live',     where: 'order-book depth · top 10 levels' },
  { id: 'vol',  name: 'Volatility check',        tier: 'Live',     where: '30-day realized + implied' },
  { id: 'sz',   name: 'Position size',           tier: 'Live',     where: '% of average daily volume' },
  { id: 'corr', name: 'Correlation check',       tier: 'Live',     where: 'vs your other positions' },
  { id: 'pat',  name: 'Pattern check',           tier: 'Live',     where: 'last 90 days of price action' },
  { id: 'evt',  name: 'Event proximity',         tier: 'Live',     where: 'earnings · Fed · catalysts' },
  { id: 'news', name: 'News-flow check',         tier: 'Live',     where: 'headline + sentiment scan' },
  { id: 'mkt',  name: 'Market regime',           tier: 'Live',     where: 'bull · bear · chop classifier' },
  { id: 'exp',  name: 'Exposure check',          tier: 'Live',     where: 'sector + beta concentration' },
  { id: 'ovr',  name: 'Override check',          tier: 'Override', where: 'rules you set on your account' },
];

const QSCENARIOS = [
  { sym: 'AAPL',  notional: 20542,   pick: 'sz',   verdict: 'clear',   latency: 87,  reason: 'within size limits · clean signal' },
  { sym: 'TSLA',  notional: 287100,  pick: 'sz',   verdict: 'caution', latency: 142, reason: 'oversized · 2.4% of average daily volume' },
  { sym: 'GME',   notional: 127500,  pick: 'pat',  verdict: 'risky',   latency: 109, reason: 'flagged · meme pattern + 23-hour vol spike' },
  { sym: 'NVDA',  notional: 11479,   pick: 'liq',  verdict: 'clear',   latency: 64,  reason: 'order-book deep · all 9 other checks passed' },
  { sym: 'SPY',   notional: 0,       pick: 'liq',  verdict: 'refused', latency: 38,  reason: 'stale quote · refused without re-quoting' },
];

function QuantumDemo() {
  const [idx, setIdx] = React.useState(0);
  const [pinned, setPinned] = React.useState(false);
  const [phase, setPhase] = React.useState('routing'); // routing → executing → verdict
  const s = QSCENARIOS[idx];
  const algo = QALGOS.find(a => a.id === s.pick);
  const verdictKind = ({ clear: 'allow', caution: 'caution', risky: 'caution', refused: 'refuse' })[s.verdict];

  React.useEffect(() => {
    setPhase('routing');
    const t1 = setTimeout(() => setPhase('executing'), 600);
    const t2 = setTimeout(() => setPhase('verdict'), 600 + s.latency + 200);
    const t3 = !pinned ? setTimeout(() => setIdx((idx + 1) % QSCENARIOS.length), 600 + s.latency + 3500) : null;
    return () => { clearTimeout(t1); clearTimeout(t2); if (t3) clearTimeout(t3); };
  }, [idx, pinned]);

  const qStyles = {
    wrap: { display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: 0,
      border: `1px solid ${T.inkBorder}`, background: T.ink, color: T.textInv },
    left: { padding: 26, borderRight: `1px solid ${T.inkBorder}`, position: 'relative' },
    right: { padding: 26, background: 'rgba(244,244,240,0.02)' },
    algoRow: (active) => ({
      display: 'grid', gridTemplateColumns: '60px 1fr auto', gap: 14,
      padding: '10px 12px', alignItems: 'center',
      background: active ? T.allowSoft : 'transparent',
      borderLeft: `2px solid ${active ? T.allow : 'transparent'}`,
      transition: 'all .2s ease',
    }),
  };

  return (
    <div style={qStyles.wrap}>
      <CornerMark where="tl" color={T.inkBorder}/>
      <CornerMark where="tr" color={T.inkBorder}/>
      <CornerMark where="bl" color={T.inkBorder}/>
      <CornerMark where="br" color={T.inkBorder}/>

      <div style={qStyles.left}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 22 }}>
          <Bracket color={T.allow}>RISK CHECK · LIVE</Bracket>
          <Mono color={T.muteInv}>10 CHECKS · PER ORDER</Mono>
        </div>

        <div style={{ marginBottom: 18, padding: '12px 14px', background: 'rgba(244,244,240,0.04)' }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 14 }}>
              <span style={{ fontFamily: GMONO, fontSize: 22, color: T.textInv, fontWeight: 500, letterSpacing: 0.4 }}>{s.sym}</span>
              <Mono color={T.muteInv}>
                ORDER · {s.notional > 0 ? '$' + s.notional.toLocaleString() : '— stale quote'}
              </Mono>
            </div>
            <Mono color={phase === 'routing' ? T.caution : T.muteInv}>
              {phase === 'routing' ? 'CHECKING…' : phase === 'executing' ? 'RUNNING…' : 'COMPLETE'}
            </Mono>
          </div>
        </div>

        <Mono color={T.allow} weight={500}>CHECKS RUN</Mono>
        <div style={{ marginTop: 12, display: 'flex', flexDirection: 'column' }}>
          {QALGOS.map(a => {
            const active = phase !== 'routing' && a.id === s.pick;
            return (
              <div key={a.id} style={qStyles.algoRow(active)}>
                <Mono color={active ? T.allow : T.muteInv} weight={500}>{a.id}</Mono>
                <div>
                  <div style={{
                    fontFamily: GEIST, fontSize: 13, color: active ? T.textInv : 'rgba(244,244,240,0.7)',
                    letterSpacing: -0.1,
                  }}>{a.name}</div>
                  <Mono color={T.muteInv} size={9}>{a.where}</Mono>
                </div>
                <Mono color={a.tier === 'Override' ? T.caution : T.muteInv}>
                  {a.tier}
                </Mono>
              </div>
            );
          })}
        </div>
      </div>

      <div style={qStyles.right}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 22 }}>
          <Bracket color={T.allow}>VERDICT</Bracket>
          <Mono color={T.muteInv}>RECEIPT ATTACHED</Mono>
        </div>

        <div style={{ marginBottom: 24 }}>
          <Decision kind={verdictKind} size="lg"/>
          <p style={{
            marginTop: 14, fontFamily: GMONO, fontSize: 12,
            color: T.muteInv, letterSpacing: 0.2, lineHeight: 1.5,
          }}>{s.reason}</p>
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 14, paddingTop: 18, borderTop: `1px solid ${T.inkBorder}` }}>
          <QStat k="VERDICT" v={s.verdict} color={
            s.verdict === 'clear' ? T.allow :
            s.verdict === 'refused' ? T.refuse :
            T.caution
          }/>
          <QStat k="FLAGGED BY" v={algo.id + ' · ' + algo.name}/>
          <QStat k="RESPONSE" v={s.latency + ' ms'}/>
          <QStat k="NEXT STEP" v={
            s.verdict === 'clear'   ? 'Sent to your broker' :
            s.verdict === 'caution' ? 'Sent · caution flagged on receipt' :
            s.verdict === 'risky'   ? 'Blocked · receipt explains why' :
                                       'Refused · order never reaches the broker'
          }/>
        </div>

        <div style={{
          marginTop: 22, padding: '12px 14px',
          background: 'rgba(244,244,240,0.04)',
          borderLeft: `2px solid ${T.allow}`,
        }}>
          <Mono color={T.muteInv}>ALWAYS-ON · NON-NEGOTIABLE</Mono>
          <p style={{
            marginTop: 6, fontSize: 12.5, color: 'rgba(244,244,240,0.75)',
            letterSpacing: -0.05, lineHeight: 1.5, fontFamily: GEIST,
          }}>
            The risk check runs on every order, regardless of size. It is bundled in your session — no per-call billing, no per-trade fees on your side.
          </p>
        </div>

        {/* scenario tabs */}
        <div style={{
          marginTop: 22, paddingTop: 14, borderTop: `1px solid ${T.inkBorder}`,
          display: 'flex',
        }}>
          {QSCENARIOS.map((x, i) => (
            <button key={x.sym} onClick={() => { setPinned(true); setIdx(i); }} style={{
              flex: 1, background: 'transparent', border: 'none', cursor: 'pointer',
              padding: '8px 4px 0', textAlign: 'left',
              borderTop: i === idx ? `2px solid ${T.allow}` : '2px solid transparent',
              marginTop: -15,
            }}>
              <Mono color={i === idx ? T.textInv : T.muteInv}>{x.sym}</Mono>
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}

function QStat({ k, v, color }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '90px 1fr', gap: 16, alignItems: 'baseline' }}>
      <Mono color={T.muteInv}>{k}</Mono>
      <span style={{
        fontFamily: GMONO, fontSize: 13, color: color || T.textInv, letterSpacing: 0.2,
      }}>{v}</span>
    </div>
  );
}

Object.assign(window, { QuantumDemo, QALGOS, QSCENARIOS });
