// ============================================================
// System log feed — timeline of agent runs
// ============================================================

function SysLogFeed({ syslog }) {
  const [showAll, setShowAll] = useState(false);
  const entries = syslog?.entries || [];
  // newest first
  const sorted = [...entries].sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
  const visible = showAll ? sorted : sorted.slice(0, 6);

  return (
    <div className="card accent-purple">
      <CardCommand command="./tail_system_log.sh" flag="--all" live={true} />
      <div className="card-head">
        <div className="card-head-row">
          <span className="section-label">AGENT_ACTIVITY</span>
          <span className="badge neutral">{entries.length} runs</span>
        </div>
        {entries.length > 6 && (
          <button className="expand-btn" onClick={() => setShowAll(!showAll)}>
            {showAll ? `▴ show 6` : `▾ show all ${entries.length}`}
          </button>
        )}
      </div>

      <div className="log-list">
        {visible.map((e, i) => {
          const agentKey = BTC.LOG_AGENT_MAP[e.agent] || e.agent;
          const isErr = e.status?.includes('fail') || (e.errors && e.errors.length > 0);
          const isMismatch = e.status?.includes('mismatch');
          return (
            <div key={i} className={`log-entry ${agentKey}`}>
              <div className="log-dot"></div>
              <div className="log-body">
                <div className="log-head">
                  <span className="log-agent" style={{ textTransform: 'capitalize' }}>{e.agent.replace('_', ' ')}</span>
                  <span className="log-run">{(e.run_type || '').replace(/_/g, ' ')}</span>
                  {isErr && <span className="badge under" style={{ fontSize: 9 }}>error</span>}
                  {isMismatch && <span className="badge warn" style={{ fontSize: 9 }}>mismatch</span>}
                  {!isErr && !isMismatch && e.status === 'success' && <span className="badge active" style={{ fontSize: 9 }}>ok</span>}
                  <span className="log-time">{BTC.formatTimeUTC(e.timestamp)} · {BTC.formatDay(e.timestamp)} · {BTC.relTime(e.timestamp)}</span>
                </div>
                <div className="log-msg">{BTC.truncate(e.notes || '', 280)}</div>
                <div className="log-action-row">
                  {e.btc_price_at_run != null && <span><strong>BTC</strong> {BTC.fmtUSD(e.btc_price_at_run)}</span>}
                  {e.vs_hodl_btc_pct != null && (
                    <span><strong>vs hodl</strong> {BTC.fmtPctSigned(e.vs_hodl_btc_pct, 3)}</span>
                  )}
                  {e.signals_executed != null && (
                    <span><strong>signals</strong> {e.signals_executed} exec / {e.signals_rejected || 0} rej</span>
                  )}
                  {e.bybit_orders_placed != null && (
                    <span><strong>orders</strong> {e.bybit_orders_placed}</span>
                  )}
                </div>
              </div>
            </div>
          );
        })}
        {visible.length === 0 && (
          <div className="empty-state">
            <div className="empty-state-body">No agent runs logged yet.</div>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { SysLogFeed });
