// Variant D — Cockpit Stream
// Merge of B (3-column per-bot lanes) and C (depth: equity hero, filters,
// alerts, snapshot strip). Each column is now its own decision journal with
// reasoning, while the comparison context stays at the top.

const { useState: useStateD, useMemo: useMemoD } = React;

function VariantDCockpitStream() {
  const D = window.BOT_DATA;
  const [selected, setSelected] = useStateD(D.days[D.days.length - 1]);
  const [actionFilter, setActionFilter] = useStateD('all'); // all | trades | skips
  const bots = D.BOTS;

  const filterFn = (d) => {
    if (actionFilter === 'trades') return d.action !== 'SKIP';
    if (actionFilter === 'skips') return d.action === 'SKIP';
    return true;
  };

  const ranked = bots
    .map((b) => {
      const last = D.equityByBot[b.id][D.equityByBot[b.id].length - 1];
      return { bot: b, totalPct: (last.equity / 100000 - 1) * 100 };
    })
    .sort((a, b) => b.totalPct - a.totalPct);

  return (
    <div style={{
      width: 1600, height: 1080, background: '#0a0d12',
      color: '#d4d8df', fontFamily: 'Inter, system-ui, sans-serif',
      display: 'flex', flexDirection: 'column', overflow: 'hidden',
    }}>
      {/* slim header */}
      <header style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '0 24px', height: 56, borderBottom: '1px solid #1a1f29',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <div style={{ fontFamily: 'ui-monospace, monospace', fontSize: 20, letterSpacing: '0.18em', color: '#22c55e' }}>● TRADERBOT</div>
          <span style={{ color: '#5b6473', fontFamily: 'ui-monospace, monospace', fontSize: 15 }}>/</span>
          <span style={{ fontFamily: 'ui-monospace, monospace', fontSize: 20, letterSpacing: '0.10em', color: '#9aa3b2' }}>COCKPIT STREAM</span>
        </div>
        <div style={{ display: 'flex', gap: 14, fontFamily: 'ui-monospace, monospace', fontSize: 18, color: '#5b6473', letterSpacing: '0.06em' }}>
          {bots.map((b) => (
            <span key={b.id} style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
              <StatusDot status={b.status} />
              <span style={{ color: b.color }}>{b.name.toUpperCase()}</span>
              <span>{b.heartbeat}</span>
            </span>
          ))}
        </div>
      </header>

      {/* date ribbon */}
      <div style={{ padding: '12px 24px', borderBottom: '1px solid #1a1f29', background: '#0c1015' }}>
        <DateRibbon days={D.days} dailyPnLByBot={D.dailyPnLByBot} selected={selected} onSelect={setSelected} bots={bots} />
      </div>

      {/* equity hero — compact w/ leaderboard chips */}
      <div style={{
        display: 'grid', gridTemplateColumns: '1.55fr 1fr', gap: 16,
        padding: '14px 24px', borderBottom: '1px solid #1a1f29',
      }}>
        <div style={{ background: '#11151c', border: '1px solid #1a1f29', borderRadius: 6, padding: 12 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 4 }}>
            <div style={{ fontFamily: 'ui-monospace, monospace', fontSize: 18, color: '#9aa3b2', letterSpacing: '0.14em', fontWeight: 600 }}>
              EQUITY OVERLAY · 30D · % RETURN FROM $100K
            </div>
            <div style={{ fontFamily: 'ui-monospace, monospace', fontSize: 18, color: '#5b6473' }}>CLICK A DATE TO JUMP</div>
          </div>
          <EquityOverlay data={D.equityByBot} bots={bots} width={920} height={170} selectedDate={selected} onPickDate={setSelected} showAxis={false} showLegend={false} />
        </div>
        <div style={{ background: '#11151c', border: '1px solid #1a1f29', borderRadius: 6, padding: 12, display: 'flex', flexDirection: 'column' }}>
          <div style={{ fontFamily: 'ui-monospace, monospace', fontSize: 18, color: '#9aa3b2', letterSpacing: '0.14em', fontWeight: 600, marginBottom: 8 }}>
            LIVE STATUS
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6, flex: 1, justifyContent: 'space-between' }}>
            {bots.map((b) => (
              <div key={b.id} style={{
                display: 'grid', gridTemplateColumns: 'auto 1fr auto', gap: 10, alignItems: 'center',
                padding: '7px 10px', borderRadius: 4, background: '#0c1015', border: '1px solid #1a1f29',
              }}>
                <StatusDot status={b.status} />
                <div>
                  <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
                    <span style={{ fontFamily: 'ui-monospace, monospace', fontSize: 21, color: b.color, letterSpacing: '0.06em', fontWeight: 600 }}>{b.name.toUpperCase()}</span>
                    <span style={{ fontFamily: 'ui-monospace, monospace', fontSize: 17, color: '#5b6473' }}>{b.version}</span>
                  </div>
                  <div style={{ fontFamily: 'ui-monospace, monospace', fontSize: 17, color: '#5b6473', marginTop: 1 }}>
                    {b.status.toUpperCase()} · {b.heartbeat} · UP {b.uptime}
                  </div>
                </div>
                <button style={{
                  padding: '4px 9px', borderRadius: 3,
                  background: 'transparent', color: '#9aa3b2',
                  border: '1px solid #1a1f29', cursor: 'pointer',
                  fontFamily: 'ui-monospace, monospace', fontSize: 17, letterSpacing: '0.08em',
                }}>PAUSE</button>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* filter bar */}
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '10px 24px', borderBottom: '1px solid #1a1f29', background: '#0c1015',
      }}>
        <div style={{ display: 'flex', gap: 12, alignItems: 'baseline' }}>
          <div style={{ fontFamily: 'ui-monospace, monospace', fontSize: 18, color: '#5b6473', letterSpacing: '0.14em' }}>SESSION</div>
          <div style={{ fontFamily: 'Inter, system-ui, sans-serif', fontSize: 27, color: '#d4d8df', fontWeight: 500 }}>
            {fmtDateLong(selected)}
          </div>
        </div>
        <div style={{ display: 'flex', gap: 4, fontFamily: 'ui-monospace, monospace', fontSize: 14 }}>
          {[['all', 'ALL'], ['trades', 'TRADES'], ['skips', 'SKIPS']].map(([k, l]) => (
            <button key={k} onClick={() => setActionFilter(k)} style={{
              padding: '5px 12px', borderRadius: 3, cursor: 'pointer',
              background: actionFilter === k ? 'rgba(34,197,94,0.10)' : 'transparent',
              color: actionFilter === k ? '#22c55e' : '#9aa3b2',
              border: actionFilter === k ? '1px solid #22c55e55' : '1px solid #1a1f29',
              letterSpacing: '0.10em',
            }}>{l}</button>
          ))}
        </div>
      </div>

      {/* 3 columns */}
      <div style={{
        display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 0,
        flex: 1, overflow: 'hidden',
      }}>
        {bots.map((b, idx) => (
          <BotColumn
            key={b.id}
            bot={b}
            selected={selected}
            D={D}
            decisions={(D.decisionsByDay[selected] || []).filter((d) => d.bot === b.id).filter(filterFn)}
            isLast={idx === bots.length - 1}
          />
        ))}
      </div>
    </div>
  );
}

function BotColumn({ bot, selected, D, decisions, isLast }) {
  const last = D.equityByBot[bot.id][D.equityByBot[bot.id].length - 1];
  const totalPct = (last.equity / 100000 - 1) * 100;
  const dayStat = D.dayStatsByBot[bot.id][selected];
  const last14 = D.dailyPnLByBot[bot.id].slice(-14).map((x) => x.pnlPct);
  const tradeCount = decisions.filter((d) => d.action !== 'SKIP').length;
  const skipCount = decisions.filter((d) => d.action === 'SKIP').length;

  return (
    <div style={{
      display: 'flex', flexDirection: 'column', minHeight: 0,
      borderRight: isLast ? 'none' : '1px solid #1a1f29',
    }}>
      {/* identity strip */}
      <div style={{
        padding: '12px 16px', borderBottom: '1px solid #1a1f29',
        background: `linear-gradient(180deg, ${bot.color}14 0%, transparent 100%)`,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <div style={{ width: 6, height: 26, background: bot.color, borderRadius: 1 }} />
            <div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                <span style={{ fontFamily: 'ui-monospace, monospace', fontSize: 27, color: bot.color, fontWeight: 600, letterSpacing: '0.04em' }}>{bot.name.toUpperCase()}</span>
                <StatusDot status={bot.status} />
                <span style={{ fontFamily: 'ui-monospace, monospace', fontSize: 17, color: '#5b6473', padding: '1px 5px', border: '1px solid #1a1f29', borderRadius: 3 }}>{bot.version}</span>
              </div>
              <div style={{ fontFamily: 'ui-monospace, monospace', fontSize: 17, color: '#9aa3b2', marginTop: 2 }}>{bot.strategy}</div>
            </div>
          </div>
          <Sparkline values={last14} color={bot.color} width={92} height={32} fill />
        </div>

        {/* stats grid */}
        <div style={{
          display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 1,
          background: '#1a1f29', border: '1px solid #1a1f29', borderRadius: 4, overflow: 'hidden',
        }}>
          {[
            ['DAY', `${dayStat.pnlPct >= 0 ? '+' : ''}${dayStat.pnlPct.toFixed(2)}%`, dayStat.pnlPct >= 0 ? '#22c55e' : '#ef4444'],
            ['30D', `${totalPct >= 0 ? '+' : ''}${totalPct.toFixed(1)}%`, totalPct >= 0 ? '#22c55e' : '#ef4444'],
            ['TRADES', String(dayStat.trades), '#d4d8df'],
            ['WR', `${(dayStat.winRate * 100).toFixed(0)}%`, '#d4d8df'],
          ].map(([l, v, c]) => (
            <div key={l} style={{ background: '#0c1015', padding: '6px 8px' }}>
              <div style={{ fontFamily: 'ui-monospace, monospace', fontSize: 16, color: '#5b6473', letterSpacing: '0.10em' }}>{l}</div>
              <div style={{ fontFamily: 'ui-monospace, monospace', fontSize: 22, color: c, fontWeight: 600, marginTop: 1 }}>{v}</div>
            </div>
          ))}
        </div>
      </div>

      {/* feed header */}
      <div style={{
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        padding: '8px 16px', borderBottom: '1px solid #1a1f29',
      }}>
        <div style={{ fontFamily: 'ui-monospace, monospace', fontSize: 17, color: '#9aa3b2', letterSpacing: '0.14em', fontWeight: 600 }}>
          DECISION JOURNAL
        </div>
        <div style={{ fontFamily: 'ui-monospace, monospace', fontSize: 17, color: '#5b6473' }}>
          {tradeCount}T · {skipCount}S
        </div>
      </div>

      {/* feed */}
      <div style={{ flex: 1, minHeight: 0, overflowY: 'auto', padding: '4px 12px' }}>
        <DecisionTimeline decisions={decisions} bots={[bot]} showBot={false} />
      </div>
    </div>
  );
}

window.VariantDCockpitStream = VariantDCockpitStream;
