// PRE — Agent Feed Panel
(() => {
  // In-memory agent activity store (accumulates from WS events)
  const agentFeedEntries = [];
  let agentFeedHistoryLoaded = false;

  // ── Render ──

  function renderAgentFeedPanel(container) {
    if (agentFeedEntries.length === 0) {
      container.innerHTML = '<div class="agent-feed-empty">No agent activity yet.<br>Agents will appear here when the model spawns sub-agents or background jobs run.</div>';
      return;
    }

    let html = '<div class="settings-section">';
    html += '<div class="settings-section-title" style="margin-bottom:12px">Agent Activity</div>';

    // Render newest first (sort by startedAt descending)
    const sorted = [...agentFeedEntries].sort((a, b) => (b.startedAt || 0) - (a.startedAt || 0));
    for (const entry of sorted) {
      const statusClass = entry.status === 'cancelled' ? 'failed'
        : entry.status === 'queued' ? 'running'
        : entry.status === 'running' ? 'running'
        : entry.status === 'failed' ? 'failed'
        : 'completed';
      const dur = entry.duration || '';
      const toolCount = entry.isBgAgent ? (entry.toolCalls || 0) : entry.tools.length;
      let time = '';
      if (entry.startedAt) {
        const d = new Date(entry.startedAt);
        const today = new Date();
        const isToday = d.toDateString() === today.toDateString();
        time = isToday
          ? d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
          : d.toLocaleDateString([], { month: 'short', day: 'numeric' }) + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
      }

      // Status badge for background agents
      let statusBadge = '';
      if (entry.isBgAgent) {
        const badgeColors = { queued: '#f59e0b', running: '#3b82f6', completed: '#10b981', failed: '#ef4444', cancelled: '#6b7280', paused: '#a855f7', interrupted: '#f97316' };
        const badgeLabels = { queued: 'Queued', running: 'Running', completed: 'Completed', failed: 'Failed', cancelled: 'Cancelled', paused: 'Paused', interrupted: 'Interrupted' };
        const c = badgeColors[entry.status] || '#6b7280';
        const l = badgeLabels[entry.status] || entry.status;
        statusBadge = `<span style="display:inline-block;font-size:0.65rem;padding:1px 6px;border-radius:8px;background:${c}22;color:${c};border:1px solid ${c}44;margin-left:6px;vertical-align:middle">${l}</span>`;
      }

      // Running info for background agents
      let runningInfo = '';
      if (entry.isBgAgent && entry.status === 'running' && entry.currentTool) {
        runningInfo = `<span style="color:var(--text-muted);font-size:0.75rem"> — ${PRE.escapeHtml(entry.currentTool)}</span>`;
      }

      const sessionBtn = entry.sessionId
        ? `<button class="btn btn-ghost btn-sm agent-feed-session-btn" onclick="window.AgentFeed.openSession('${PRE.escapeHtml(entry.sessionId)}')">Open Session</button>`
        : '';

      const cancelBtn = entry.isBgAgent && (entry.status === 'running' || entry.status === 'queued' || entry.status === 'paused')
        ? `<button class="btn btn-ghost btn-sm" style="color:var(--danger)" onclick="window.AgentFeed.cancelBgAgent('${PRE.escapeHtml(entry.id)}')">Cancel</button>`
        : '';

      html += `<div class="agent-feed-entry ${statusClass}" data-agent-feed-id="${PRE.escapeHtml(entry.id)}">
        <div class="agent-feed-header" onclick="this.parentElement.classList.toggle('expanded')">
          <span class="agent-feed-status"></span>
          <div class="agent-feed-info">
            <div class="agent-feed-task">${PRE.escapeHtml(entry.task)}${statusBadge}</div>
            <div class="agent-feed-meta">
              <span>${toolCount} tool${toolCount !== 1 ? 's' : ''}</span>
              ${dur ? `<span>${dur}</span>` : ''}
              <span>${time}</span>
              ${runningInfo}
            </div>
          </div>
          <svg class="agent-feed-chevron" width="12" height="12" viewBox="0 0 16 16" fill="currentColor"><path d="M6.5 3l5 5-5 5V3z"/></svg>
        </div>
        <div class="agent-feed-body">
          ${!entry.isBgAgent && toolCount > 0 ? '<ul class="agent-feed-tools">' + entry.tools.map(t => `<li>${PRE.escapeHtml(t)}</li>`).join('') + '</ul>' : ''}
          ${entry.result ? `<div class="agent-feed-result"><pre><code>${PRE.escapeHtml(entry.result.length > 2000 ? entry.result.slice(0, 2000) + '\n...' : entry.result)}</code></pre></div>` : ''}
          ${entry.error ? `<div style="color:var(--danger);font-size:0.82rem">Error: ${PRE.escapeHtml(entry.error)}</div>` : ''}
          <div style="display:flex;gap:8px;margin-top:6px">${sessionBtn}${cancelBtn}</div>
        </div>
      </div>`;
    }

    html += '</div>';
    container.innerHTML = html;
  }

  // ── Refresh visible panel ──

  function refreshFeedPanelIfOpen() {
    const panel = document.getElementById('right-panel');
    const title = document.getElementById('panel-title');
    if (!panel.classList.contains('hidden') && title.textContent === 'Agent Feed') {
      renderAgentFeedPanel(document.getElementById('panel-content'));
    }
  }

  // ── Open panel ──

  async function openAgentFeedPanel() {
    const content = PRE.openPanel('Agent Feed', null);

    // On first open, seed the feed with historical cron/agent sessions
    if (!agentFeedHistoryLoaded) {
      agentFeedHistoryLoaded = true;
      content.innerHTML = '<div class="agent-feed-empty">Loading agent history...</div>';
      try {
        const existingIds = new Set(agentFeedEntries.map(e => e.id));

        // Load background agents
        const [sessionsRes, agentsRes] = await Promise.all([
          fetch('/api/sessions'),
          fetch('/api/agents').catch(() => ({ ok: false })),
        ]);
        const sessions = await sessionsRes.json();

        // Background agents from REST API
        if (agentsRes.ok) {
          const agents = await agentsRes.json();
          for (const a of agents) {
            if (existingIds.has(a.id)) continue;
            existingIds.add(a.id);
            agentFeedEntries.push({
              id: a.id,
              task: a.name || a.task || 'Background agent',
              sessionId: a.sessionId || null,
              status: a.status,
              tools: [],
              result: a.resultPreview || null,
              error: a.error || null,
              duration: a.duration ? PRE.formatDuration(a.duration) : null,
              startedAt: a.startedAt || a.createdAt,
              isBgAgent: true,
              toolCalls: a.toolCalls || 0,
              currentTool: a.currentTool || null,
            });
          }
        }

        // Cron/scheduled job sessions
        const cronSessions = sessions
          .filter(s => s.projectSlug === 'scheduled-jobs' && !existingIds.has(s.id))
          .slice(0, 50);

        for (const s of cronSessions) {
          agentFeedEntries.push({
            id: s.id,
            task: s.displayName || s.preview || s.channel || 'Scheduled job',
            sessionId: s.id,
            status: 'completed',
            tools: [],
            result: s.preview || null,
            error: null,
            duration: null,
            startedAt: new Date(s.modified).getTime(),
          });
        }
      } catch (err) {
        console.warn('[agent-feed] Failed to load history:', err);
      }
    }

    renderAgentFeedPanel(content);
  }

  // ── Handle background agent WebSocket events ──

  function handleBgAgentEvent(msg) {
    const { event, id, name, status, sessionId, task, toolCalls, currentTool, duration, result, error } = msg;
    const existing = agentFeedEntries.find(e => e.id === id);

    if (event === 'queued' || event === 'running') {
      if (!existing) {
        agentFeedEntries.push({
          id,
          task: name || task || 'Background agent',
          sessionId: sessionId || null,
          status: status || event,
          tools: [],
          result: null,
          error: null,
          duration: null,
          startedAt: event === 'running' ? Date.now() : null,
          isBgAgent: true,
          toolCalls: toolCalls || 0,
          currentTool: currentTool || null,
        });
      } else {
        existing.status = status || event;
        if (event === 'running') existing.startedAt = existing.startedAt || Date.now();
      }
      refreshFeedPanelIfOpen();
    } else if (event === 'progress' && existing) {
      existing.toolCalls = toolCalls || existing.toolCalls;
      existing.currentTool = currentTool || null;
      existing.status = 'running';
      refreshFeedPanelIfOpen();
    } else if (event === 'completed') {
      if (existing) {
        existing.status = 'completed';
        existing.result = result || null;
        existing.duration = duration ? PRE.formatDuration(duration) : null;
        existing.currentTool = null;
      }
      refreshFeedPanelIfOpen();
      // Notify app.js for toast + session list refresh
      PRE.emit('bgAgentCompleted', { name: name || task || 'Background agent', sessionId, result });
    } else if (event === 'failed') {
      if (existing) {
        existing.status = 'failed';
        existing.error = error || 'Unknown error';
        existing.duration = duration ? PRE.formatDuration(duration) : null;
        existing.currentTool = null;
      }
      refreshFeedPanelIfOpen();
      PRE.emit('bgAgentFailed', { name: name || task || 'Background agent', sessionId, error });
    } else if (event === 'cancelled') {
      if (existing) {
        existing.status = 'cancelled';
        existing.duration = duration ? PRE.formatDuration(duration) : null;
        existing.currentTool = null;
      }
      refreshFeedPanelIfOpen();
    } else if (event === 'paused') {
      if (existing) {
        existing.status = 'paused';
        existing.currentTool = null;
      }
      refreshFeedPanelIfOpen();
    }
  }

  // ── Bind sidebar button ──

  const btn = document.getElementById('agent-feed-btn');
  if (btn) btn.addEventListener('click', openAgentFeedPanel);

  // ── Global API ──

  window.AgentFeed = {
    add(agentId, task, sessionId) {
      agentFeedEntries.push({
        id: agentId,
        task,
        sessionId: sessionId || null,
        status: 'running',
        tools: [],
        result: null,
        error: null,
        duration: null,
        startedAt: Date.now(),
      });
      refreshFeedPanelIfOpen();
    },
    updateId(oldId, newId) {
      const entry = agentFeedEntries.find(e => e.id === oldId);
      if (entry) entry.id = newId;
    },
    setSessionId(agentId, sessionId) {
      const entry = agentFeedEntries.find(e => e.id === agentId);
      if (entry) entry.sessionId = sessionId;
    },
    addTool(agentId, toolName) {
      const entry = agentFeedEntries.find(e => e.id === agentId);
      if (entry) entry.tools.push(toolName);
      refreshFeedPanelIfOpen();
    },
    setResult(agentId, result) {
      const entry = agentFeedEntries.find(e => e.id === agentId);
      if (entry) entry.result = result;
      refreshFeedPanelIfOpen();
    },
    complete(agentId, duration) {
      const entry = agentFeedEntries.find(e => e.id === agentId);
      if (entry) {
        entry.status = 'completed';
        entry.duration = duration;
      }
      refreshFeedPanelIfOpen();
    },
    fail(agentId, error) {
      const entry = agentFeedEntries.find(e => e.id === agentId);
      if (entry) {
        entry.status = 'failed';
        entry.error = error;
      }
      refreshFeedPanelIfOpen();
    },
    open(agentId) {
      openAgentFeedPanel();
      // Expand the entry after render
      setTimeout(() => {
        const el = document.querySelector(`[data-agent-feed-id="${agentId}"]`);
        if (el) {
          el.classList.add('expanded');
          el.scrollIntoView({ behavior: 'smooth', block: 'center' });
        }
      }, 50);
    },
    async openSession(sessionId) {
      // Close the feed panel and switch to the agent/cron session
      PRE.closePanel();
      PRE.emit('navigateSession', sessionId);
    },
    async cancelBgAgent(agentId) {
      try {
        const res = await fetch(`/api/agents/${encodeURIComponent(agentId)}`, { method: 'DELETE' });
        const data = await res.json();
        if (!data.success) console.warn('[agent-feed] Cancel failed:', data.error);
      } catch (err) {
        console.warn('[agent-feed] Cancel error:', err);
      }
    },
    handleEvent: handleBgAgentEvent,
    get entries() { return agentFeedEntries; },
  };
})();
