  // ── Status cockpit + history feed ──────────────────────────────
  // Polls /api/status every 5s and updates the right column. The full
  // dashboard exposes a richer SSE /api/status-stream; we use plain
  // polling for round 1 to keep the slim self-contained. Round-2 should
  // switch to SSE so the "minions working" tile reacts in real time.

  var STATUS_POLL_MS = 5000;
  var pollTimer = null;
  var refreshTimer = null;

  function scheduleStatusRefresh(delay) {
    if (refreshTimer) clearTimeout(refreshTimer);
    refreshTimer = setTimeout(function() {
      refreshTimer = null;
      pollStatusOnce();
    }, delay || 0);
  }

  // Apply lit-state and value/detail text to a tile.
  function updateTile(key, value, detail, lit) {
    var tile = document.querySelector('.cockpit-tile[data-tile="' + key + '"]');
    if (!tile) return;
    var valEl = tile.querySelector('.cockpit-value');
    var detEl = tile.querySelector('.cockpit-detail');
    if (valEl) {
      valEl.textContent = (value === null || value === undefined) ? '—' : String(value);
      valEl.classList.toggle('dim', !lit);
    }
    if (detEl) detEl.textContent = detail || '';
    tile.classList.remove('lit-blue', 'lit-green', 'lit-amber', 'lit-red');
    if (lit) tile.classList.add('lit-' + lit);
  }

  // Latest /api/status snapshot — read by the cockpit-tile detail modals.
  var lastStatusData = null;

  function applyStatus(data) {
    if (!data) return;
    lastStatusData = data;
    // ── Engine tile ────────────────────────────────────────────
    var engine = data.engine || {};
    // /api/status exposes `state` ('running'|'paused'|'stopping'|'stopped')
    // and `started_at`. Trust `state` only — codeVersion/started_at are static
    // fields that persist when the engine is paused/stopped, so they'd mislabel
    // a down engine as running. Absent state (shouldn't happen) reads as down.
    var engineState = engine.state || '';
    var startedAt = engine.started_at;
    var engineRunning = !!engineState && engineState !== 'stopped';
    if (!engineState) engineState = 'stopped';
    var engineLit = engineState === 'running' ? 'green' : (engineState === 'paused' ? 'amber' : 'red');
    updateTile(
      'engine',
      engineRunning ? engineState : 'down',
      startedAt ? 'up since ' + relTime(startedAt) : '—',
      engineLit
    );

    // ── Dispatches ─────────────────────────────────────────────
    // The per-minion "working" view moved to the Team cards (renderMembers);
    // this section only drives the system tiles now.
    var dispatch = data.dispatch || {};
    var active = Array.isArray(dispatch.active) ? dispatch.active : [];
    var pending = Array.isArray(dispatch.pending) ? dispatch.pending : [];
    var completed = Array.isArray(dispatch.completed) ? dispatch.completed : [];
    updateTile(
      'dispatches',
      active.length,
      active.length ? 'in flight' : 'none in flight',
      active.length ? 'blue' : null
    );
    updateTile(
      'queued',
      pending.length,
      pending.length ? 'waiting to spawn' : 'queue empty',
      pending.length ? 'amber' : null
    );

    // ── PR tile (status snapshot from cached pull-requests) ─────
    var prs = Array.isArray(data.pullRequests) ? data.pullRequests : [];
    var activePrs = prs.filter(function(p) {
      return p && (p.status === 'active' || p.status === 'linked');
    });
    var failingPrs = activePrs.filter(function(p) { return p.buildStatus === 'failing'; });
    var prDetail = activePrs.length === 0
      ? 'no open PRs'
      : (failingPrs.length ? failingPrs.length + ' failing build' + (failingPrs.length === 1 ? '' : 's')
                           : 'all healthy');
    updateTile(
      'prs',
      activePrs.length,
      prDetail,
      activePrs.length === 0 ? null : (failingPrs.length ? 'red' : 'blue')
    );

    // ── Watches tile ───────────────────────────────────────────
    var watches = Array.isArray(data.watches) ? data.watches : [];
    var activeWatches = watches.filter(function(w) { return w && w.status === 'active'; });
    updateTile(
      'watches',
      activeWatches.length,
      activeWatches.length ? 'monitoring' : 'no watches set',
      activeWatches.length ? 'blue' : null
    );

    // ── Pinned context tile ────────────────────────────────────
    var pinned = Array.isArray(data.pinned) ? data.pinned : [];
    updateTile(
      'pinned',
      pinned.length,
      pinned.length ? (pinned.length === 1 ? '1 note for agents' : pinned.length + ' notes for agents') : 'nothing pinned',
      pinned.length ? 'blue' : null
    );

    // ── Team member cards ──────────────────────────────────────
    renderMembers(Array.isArray(data.agents) ? data.agents : []);

    // ── Stamps + history ───────────────────────────────────────
    var stamp = document.getElementById('cockpit-stamp');
    if (stamp) stamp.textContent = 'updated ' + relTime(data.timestamp || Date.now());

    renderHistoryFeed({ active: active, completed: completed, prs: activePrs });
    var hStamp = document.getElementById('history-stamp');
    if (hStamp) hStamp.textContent = relTime(data.timestamp || Date.now());
  }

