/* dashboard.jsx — Avero Operator Console — MONITOR dashboard + tab panes
   Consumes the live feed (useLiveFeed) and shared algo state. */

const SIGNALS = [
  { sym: 'NVDA', action: 'buy', conf: 91, src: 'PPO·RF', ts: '14:32:07' },
  { sym: 'COIN', action: 'buy', conf: 78, src: 'CHART', ts: '14:31:50' },
  { sym: 'TSLA', action: 'sell', conf: 84, src: 'PPO·KNN', ts: '14:31:12' },
  { sym: 'SPY', action: 'hold', conf: 62, src: 'ENSEMBLE', ts: '14:30:44' },
  { sym: 'META', action: 'buy', conf: 73, src: 'PPO·LR', ts: '14:30:02' },
];

const LOG = [
  { ts: '14:32:07', lv: 'ok', cls: 'log-ok', msg: 'Filled NVDA ×120 @ 118.40' },
  { ts: '14:31:55', lv: 'info', cls: 'log-info', msg: 'Consensus 87% — 27/31 models agree BUY NVDA' },
  { ts: '14:31:12', lv: 'ok', cls: 'log-ok', msg: 'Opened SHORT TSLA ×60 @ 242.10' },
  { ts: '14:30:44', lv: 'warn', cls: 'log-warn', msg: 'Volatility spike VIX +8% — risk throttled to 0.6×' },
  { ts: '14:29:18', lv: 'info', cls: 'log-info', msg: 'Rebalance check — exposure 64% of floor' },
  { ts: '14:28:44', lv: 'err', cls: 'log-err', msg: 'Feed stale: tradier 3.2s — failover to finnhub' },
  { ts: '14:27:01', lv: 'ok', cls: 'log-ok', msg: 'BRAIN hybrid_reasoner conf=87.4%' },
  { ts: '14:26:30', lv: 'info', cls: 'log-info', msg: 'BOOT broker=public.com status=connected' },
];

/* per-algo vote for the current consensus (keyed by ALGO_DEFS id) */
const ALGO_VOTES = {
  ppo_knn: { action: 'BUY', conf: 91 }, ppo_rf: { action: 'BUY', conf: 88 },
  ppo_lr: { action: 'HOLD', conf: 54 }, chart: { action: 'BUY', conf: 79 },
  quantum: { action: 'BUY', conf: 83 }, sentiment: { action: 'SELL', conf: 61 },
  pine: { action: 'BUY', conf: 70 },
};

/* ── Positions table — live last price vs entry, live % change ─────────────── */
function PositionsTable({ positions, changed }) {
  return (
    <table className="pos-table">
      <thead><tr>
        <th>SYM</th><th>SIDE</th><th style={{ textAlign: 'right' }}>QTY</th>
        <th style={{ textAlign: 'right' }}>ENTRY</th><th style={{ textAlign: 'right' }}>LAST</th>
        <th style={{ textAlign: 'right' }}>CHG</th><th style={{ textAlign: 'right' }}>P&amp;L</th>
      </tr></thead>
      <tbody>
        {positions.map(p => {
          const up = p.pnl >= 0;
          const dir = changed[p.sym];
          return (
            <tr key={p.sym}>
              <td style={{ color: 'var(--text)', fontWeight: 700 }}>{p.sym}</td>
              <td><Badge kind={p.side === 'LONG' ? 'long' : 'short'}>{p.side}</Badge></td>
              <td style={{ textAlign: 'right' }}>{p.qty}</td>
              <td style={{ textAlign: 'right', color: 'var(--text-faint)' }}>${fmtNum(p.entry)}</td>
              <td style={{ textAlign: 'right' }} className={`px-cell ${dir === 'up' ? 'flash-up' : dir === 'down' ? 'flash-down' : ''}`}>${fmtNum(p.last)}</td>
              <td style={{ textAlign: 'right', color: up ? 'var(--green)' : 'var(--red)', fontWeight: 700 }}>{fmtPct(p.pnlPct)}</td>
              <td style={{ textAlign: 'right', color: up ? 'var(--green)' : 'var(--red)', fontWeight: 700 }}>{up ? '+' : '−'}${fmtNum(Math.abs(p.pnl), 0)}</td>
            </tr>
          );
        })}
      </tbody>
    </table>
  );
}

/* ── AI consensus grid — reflects live algo toggles ────────────────────────── */
function ConsensusGrid({ algos }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 6 }}>
      {ALGO_DEFS.map(a => {
        const on = algos[a.id];
        const vote = ALGO_VOTES[a.id] || { action: 'HOLD', conf: 0 };
        const accent = !on ? 'var(--text-faint)' : vote.action === 'BUY' ? 'var(--green)' : vote.action === 'SELL' ? 'var(--red)' : 'var(--cyan)';
        return (
          <div key={a.id} style={{ border: '1px solid var(--border)', borderRadius: 6, padding: '6px 5px', textAlign: 'center', background: on ? 'rgba(0,245,255,0.03)' : 'transparent', opacity: on ? 1 : 0.4, transition: 'opacity .2s' }}>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 8, color: 'var(--text-faint)', letterSpacing: '.4px' }}>{a.model}</div>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, fontWeight: 800, color: accent, marginTop: 2 }}>{on ? vote.action : 'OFF'}</div>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 9, color: 'var(--text-dim)' }}>{on ? `${vote.conf}%` : '—'}</div>
          </div>
        );
      })}
    </div>
  );
}

function RiskGauges() {
  const rows = [['INTRADAY DD', 0.42, 1.5, 'var(--green)'], ['DAILY LOSS', 1.1, 5, 'var(--green)'], ['DRAWDOWN', 8.4, 25, 'var(--amber)']];
  return (
    <div>
      {rows.map(([label, v, max, color]) => (
        <div key={label} style={{ marginBottom: 9 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 9, fontFamily: 'var(--font-mono)', color: 'var(--text-faint)', marginBottom: 3 }}>
            <span>{label}</span><span style={{ color }}>{fmtPct(v)} / {fmtPct(max)}</span>
          </div>
          <div className="bar"><div className="fill" style={{ width: `${Math.min(v / max * 100, 100)}%`, background: `linear-gradient(90deg, ${color}, ${color}88)` }} /></div>
        </div>
      ))}
      <div style={{ marginTop: 12, padding: '7px 10px', borderRadius: 6, background: 'rgba(0,255,136,0.06)', border: '1px solid rgba(0,255,136,0.2)', fontSize: 9, fontFamily: 'var(--font-mono)', display: 'flex', justifyContent: 'space-between' }}>
        <span style={{ color: 'var(--green)', fontWeight: 700 }}>CIRCUIT BREAKERS</span>
        <span style={{ color: 'var(--green)' }}>● ALL CLOSED</span>
      </div>
    </div>
  );
}

function SignalFeed({ onBrief }) {
  const [filter, setFilter] = useState('ALL');
  const shown = filter === 'ALL' ? SIGNALS : SIGNALS.filter(s => s.action.toUpperCase() === filter);
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
      <div style={{ display: 'flex', gap: 4 }}>
        {['ALL', 'BUY', 'SELL'].map(f => (
          <button key={f} className="btn" data-active={filter === f} style={{ padding: '2px 9px', fontSize: 8 }} onClick={() => setFilter(f)}>{f}</button>
        ))}
      </div>
      {shown.map(s => (
        <div key={s.sym + s.ts} onClick={() => onBrief(s)} style={{ cursor: 'pointer', padding: '7px 10px', borderRadius: 6, border: '1px solid var(--border)', background: 'rgba(0,245,255,0.03)' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <span style={{ fontFamily: 'var(--font-mono)', fontWeight: 700, fontSize: 11, color: 'var(--text)' }}>{s.sym}</span>
            <Badge kind={s.action}>{s.action.toUpperCase()}</Badge>
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 9, color: 'var(--text-faint)', fontFamily: 'var(--font-mono)', marginTop: 3 }}>
            <span>Conf {s.conf}%</span><span>{s.src}</span><span>{s.ts}</span>
          </div>
        </div>
      ))}
    </div>
  );
}

/* ── MONITOR dashboard ─────────────────────────────────────────────────────── */
function MonitorDashboard({ kpi, live, algos, onBrief }) {
  const totalPnL = live.positions.reduce((s, p) => s + p.pnl, 0);
  const exposure = live.positions.reduce((s, p) => s + p.last * p.qty, 0);
  return (
    <div className="dash">
      <div className="dash-kpis">
        <MetricCard label="Equity" value={`$${fmtNum(live.equity[live.equity.length - 1].equity, 0)}`} sub="▲ live feed" subColor="var(--green)" accent="cyan" />
        <MetricCard label="Open P&L" value={`${totalPnL >= 0 ? '+' : '−'}$${fmtNum(Math.abs(totalPnL), 0)}`} sub={`${live.positions.length} positions`} subColor={totalPnL >= 0 ? 'var(--green)' : 'var(--red)'} accent={totalPnL >= 0 ? 'green' : 'red'} />
        <MetricCard label="Win Rate" value="68.2%" sub="last 50 trades" accent="cyan" />
        <MetricCard label="Confidence" value={`${kpi.confidence.toFixed(1)}%`} sub={`${kpi.activeAlgos} models`} accent="violet" />
        <MetricCard label="Exposure" value={`$${fmtNum(exposure / 1000, 0)}k`} sub="of floor" accent="amber" />
        <MetricCard label="Sharpe" value="2.41" sub="30-day" accent="cyan" />
      </div>

      <div className="card dash-equity">
        <div className="card-head"><div className="card-title"><span className="index">01</span> EQUITY CURVE</div><div className="card-actions"><LiveDot flash={live.flash} label={`STREAM · ${live.tickCount}`} /></div></div>
        <div style={{ flex: 1, minHeight: 0 }}><LiveEquityChart data={live.equity} /></div>
      </div>

      <div className="card dash-positions">
        <div className="card-head"><div className="card-title"><span className="index">02</span> OPEN POSITIONS <span style={{ color: 'var(--text-faint)' }}>· {live.positions.length}/8</span></div><div className="card-actions"><LiveDot flash={live.flash} label="MARK" /></div></div>
        <PositionsTable positions={live.positions} changed={live.changed} />
      </div>

      <div className="card glow dash-ai">
        <div className="card-head"><div className="card-title"><span className="index">03</span> AI CONSENSUS</div><div className="card-actions">NVDA</div></div>
        <GradientRing value={kpi.confidence} size={128}>
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: 26, fontWeight: 900, color: 'var(--text)' }}>{kpi.confidence.toFixed(0)}<span style={{ fontSize: 13 }}>%</span></div>
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: 8, color: 'var(--text-faint)', letterSpacing: '1px' }}>CONFIDENCE</div>
        </GradientRing>
        <div style={{ marginTop: 10 }}><ConsensusGrid algos={algos} /></div>
      </div>

      <div className="card dash-risk">
        <div className="card-head"><div className="card-title"><span className="index">04</span> RISK</div></div>
        <RiskGauges />
      </div>

      <div className="card dash-signals">
        <div className="card-head"><div className="card-title"><span className="index">05</span> SIGNAL FEED</div><div className="card-actions"><LiveDot flash={live.flash} label="LIVE" /></div></div>
        <SignalFeed onBrief={onBrief} />
      </div>

      <div className="card dash-log">
        <div className="card-head"><div className="card-title"><span className="index">06</span> ACTIVITY LOG <span style={{ color: 'var(--text-faint)' }}>· {LOG.length}</span></div></div>
        <div style={{ fontFamily: 'var(--font-mono)', maxHeight: 150, overflow: 'auto' }}>
          {LOG.map((l, i) => (
            <div key={i} className="log-line"><span className="log-ts">{l.ts}</span><span className={l.cls}>{l.lv.toUpperCase()}</span><span style={{ color: 'var(--text-dim)' }}>{l.msg}</span></div>
          ))}
        </div>
      </div>
    </div>
  );
}

/* ── Bots Library — live bot monitoring cards ─────────────────────────────── */
const BOT_DEFS = [
  { name: 'Momentum Alpha', strategy: 'PPO·RF · momentum', sym: 'NVDA', pnl: 842, status: 'running' },
  { name: 'Mean Reverter', strategy: 'PPO·KNN · reversion', sym: 'TSLA', pnl: -311, status: 'running' },
  { name: 'Quantum Confluence', strategy: 'QUANT · 8-factor', sym: 'AAPL', pnl: 118, status: 'paused' },
  { name: 'Crypto Swing', strategy: 'CHART · breakout', sym: 'COIN', pnl: 506, status: 'running' },
  { name: 'Index Hedge', strategy: 'ENSEMBLE · hedge', sym: 'SPY', pnl: -64, status: 'error' },
];
function BotsView({ onBrief }) {
  const [bots, setBots] = useState(() => BOT_DEFS.map(b => ({ ...b, ts: Date.now() - (Math.random() * 90000 | 0) })));
  useEffect(() => {
    const id = setInterval(() => setBots(bs => bs.map(b => b.status === 'running'
      ? { ...b, pnl: b.pnl + (Math.random() - 0.46) * 90, ts: Date.now() } : b)), 1400);
    return () => clearInterval(id);
  }, []);
  const toggle = (i) => setBots(bs => bs.map((b, j) => j === i ? { ...b, status: b.status === 'running' ? 'paused' : 'running' } : b));
  const ago = (ts) => { const s = Math.max(0, (Date.now() - ts) / 1000 | 0); return s < 60 ? s + 's ago' : (s / 60 | 0) + 'm ago'; };
  const statusCls = { running: 'live', paused: 'idle', error: 'error' };
  const statusTxt = { running: '● RUNNING', paused: '◷ PAUSED', error: '✕ ERROR' };
  return (
    <div className="bots-grid">
      {bots.map((b, i) => {
        const up = b.pnl >= 0;
        return (
          <div key={b.name} className={`card bot-card ${b.status === 'error' ? 'bot-err' : ''}`}>
            <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between' }}>
              <div>
                <div style={{ fontFamily: 'var(--font-display)', fontSize: 15, fontWeight: 700, color: 'var(--text)' }}>{b.name}</div>
                <div style={{ fontFamily: 'var(--font-mono)', fontSize: 9, color: 'var(--text-faint)', letterSpacing: '.5px', marginTop: 2 }}>{b.strategy}</div>
              </div>
              <span className={`bot-status-pill ${statusCls[b.status]}`}>{statusTxt[b.status]}</span>
            </div>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 14, margin: '12px 0' }}>
              <div><div style={{ fontFamily: 'var(--font-mono)', fontSize: 8, color: 'var(--text-faint)', letterSpacing: '.8px' }}>P&amp;L</div><div style={{ fontFamily: 'var(--font-mono)', fontSize: 20, fontWeight: 800, color: up ? 'var(--green)' : 'var(--red)' }}>{up ? '+' : '−'}${fmtNum(Math.abs(b.pnl), 0)}</div></div>
              <div><div style={{ fontFamily: 'var(--font-mono)', fontSize: 8, color: 'var(--text-faint)', letterSpacing: '.8px' }}>CURRENT TRADE</div><div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, fontWeight: 700, color: 'var(--text)' }}>{b.sym} <span style={{ color: 'var(--text-faint)', fontSize: 10 }}>· {up ? 'LONG' : 'SHORT'}</span></div></div>
              <div style={{ marginLeft: 'auto', textAlign: 'right' }}><div style={{ fontFamily: 'var(--font-mono)', fontSize: 8, color: 'var(--text-faint)', letterSpacing: '.8px' }}>LAST</div><div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--text-dim)' }}>{ago(b.ts)}</div></div>
            </div>
            <div style={{ display: 'flex', gap: 6 }}>
              <button className="btn" style={{ padding: '4px 10px', fontSize: 9 }} onClick={() => toggle(i)}>{b.status === 'running' ? '⏸ PAUSE' : '▶ RESUME'}</button>
              <button className="btn" style={{ padding: '4px 10px', fontSize: 9 }}>✎ EDIT</button>
              <button className="btn" style={{ padding: '4px 10px', fontSize: 9 }} onClick={() => onBrief({ sym: b.sym, action: up ? 'buy' : 'sell', conf: 80, src: b.strategy, ts: ago(b.ts) })}>▸ DETAILS</button>
            </div>
          </div>
        );
      })}
    </div>
  );
}

function SupportPane() {
  const links = [['Documentation', 'Full API reference & strategy guides'], ['Getting Started', 'Deploy your first bot in 3 steps'], ['Status Page', 'Live system & feed uptime'], ['Contact Support', 'mathew@averotrading.net']];
  return (
    <div className="dash" style={{ display: 'grid', gridTemplateColumns: 'repeat(2,1fr)', gridTemplateAreas: 'none', gap: 12 }}>
      {links.map(([t, d]) => (
        <div className="card" key={t} style={{ minHeight: 90 }}>
          <div className="card-head"><div className="card-title">{t}</div></div>
          <div className="type-body-dim" style={{ fontFamily: 'var(--font-mono)', fontSize: 11 }}>{d}</div>
        </div>
      ))}
    </div>
  );
}

/* ── Placeholder panes for other tabs ──────────────────────────────────────── */
function PlaceholderPane({ id }) {
  const copy = {
    charts: ['CHARTS', 'TradingView-grade candlesticks, anti-repaint overlays, and pattern detection live here.'],
    screeners: ['9 MARKET SCREENERS', 'Stocks · ETFs · Crypto · Bonds · Options · DEX/CEX — one hub, twelve free data sources.'],
    ai: ['AI COMMAND CENTER', '31-model ensemble voting, signal fusion, and explainable-AI decision traces.'],
    trading: ['LIVE TRADING', 'Order ticket, position sizing, and broker routing — paper or live.'],
    risk: ['RISK DASHBOARD', 'VaR, drawdown ladders, and self-aware circuit breakers monitoring themselves.'],
    system: ['SYSTEM HEALTH', 'Model health, feed latency, and uptime telemetry for the autonomous engine.'],
  }[id] || ['PANEL', ''];
  return (
    <div className="dash" style={{ display: 'block' }}>
      <div className="card glow" style={{ minHeight: 360, alignItems: 'center', justifyContent: 'center', textAlign: 'center' }}>
        <div style={{ fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 700, color: 'var(--cyan)', letterSpacing: '2px', textTransform: 'uppercase' }}>{copy[0]}</div>
        <div className="type-body-dim" style={{ maxWidth: 460, marginTop: 12 }}>{copy[1]}</div>
        <div style={{ marginTop: 18, fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--text-faint)', letterSpacing: '1px' }}>SELECT <span style={{ color: 'var(--cyan)' }}>MONITOR</span> FOR THE LIVE DASHBOARD →</div>
      </div>
    </div>
  );
}

Object.assign(window, { MonitorDashboard, PlaceholderPane, ALGO_VOTES, BotsView, SupportPane });
