// Configure agents modal – overlay with three sub-tabs:
//   Sources · Responders · Scouts
// Lives outside the normal layout (z-index above everything else).

const { useState: useStateA, useEffect: useEffectA, useRef: useRefA } = React;

const CADENCE_LABELS = { hourly: "every hour", daily: "every day", weekly: "every week" };
const SOURCE_LABELS = (typeof SIGNAL_SOURCES !== "undefined" ? SIGNAL_SOURCES : []).reduce((m, s) => { m[s.key] = s; return m; }, {});

// Inline brand icons (small stroke-based SVGs that render consistently across systems).
const BrandIcon = ({ kind, size = 18 }) => {
  const common = { width: size, height: size, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 1.7, strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true" };
  switch (kind) {
    case "error-tracking":
      return (<svg {...common}><path d="M12 2 4 5v6c0 5 3.5 9 8 11 4.5-2 8-6 8-11V5l-8-3Z"></path><path d="M12 8v4"></path><circle cx="12" cy="15" r=".5" fill="currentColor"></circle></svg>);
    case "session-replay":
      return (<svg {...common}><rect x="3" y="5" width="18" height="14" rx="2"></rect><path d="m11 9 4 3-4 3z" fill="currentColor" stroke="none"></path></svg>);
    case "support":
      return (<svg {...common}><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5Z"></path></svg>);
    case "funnel":
      return (<svg {...common}><path d="M22 3H2l8 9.46V19l4 2v-8.54L22 3Z"></path></svg>);
    case "github":
      return (<svg {...common}><path d="M9 19c-5 1.5-5-2.5-7-3m14 6v-3.87a3.37 3.37 0 0 0-.94-2.61c3.14-.35 6.44-1.54 6.44-7A5.44 5.44 0 0 0 20 4.77 5.07 5.07 0 0 0 19.91 1S18.73.65 16 2.48a13.38 13.38 0 0 0-7 0C6.27.65 5.09 1 5.09 1A5.07 5.07 0 0 0 5 4.77a5.44 5.44 0 0 0-1.5 3.78c0 5.42 3.3 6.61 6.44 7A3.37 3.37 0 0 0 9 18.13V22"></path></svg>);
    case "linear":
      return (<svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M2.4 13.1c-.2-.3.2-.7.5-.5l8.6 8.6c.3.3-.1.7-.5.5a10 10 0 0 1-8.6-8.6Zm-.4-3.5c0-.2.1-.4.3-.4l12.5 12.5c.2.2.2.4-.1.4a10 10 0 0 1-1.5.1c-.3 0-.6-.1-.8-.3L2.3 10.4a.6.6 0 0 1-.3-.8Zm.7-3.4c0-.1.1-.2.2-.2L18.5 21.1c.1.1.1.2 0 .3l-1.6 1c-.2.1-.5.1-.7-.1L1.6 7.6c-.2-.2-.2-.5-.1-.7l1-1.6c.1-.1.2-.1.3 0Zm1.7-2.4 16.9 16.9.9-.9c1.6-1.7 2.7-3.9 2.7-6.3A10 10 0 0 0 5.2 2.9c.1.2-.1.7-.7.9Z"></path></svg>);
    case "slack":
      return (<svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M5 15.2a2.5 2.5 0 1 1-2.5-2.5H5v2.5Zm1.3 0a2.5 2.5 0 1 1 5 0v6.3a2.5 2.5 0 1 1-5 0v-6.3Zm2.5-10a2.5 2.5 0 1 1 2.5-2.5V5H8.8Zm0 1.3a2.5 2.5 0 1 1 0 5H2.5a2.5 2.5 0 1 1 0-5h6.3ZM19 8.8a2.5 2.5 0 1 1 2.5 2.5H19V8.8Zm-1.3 0a2.5 2.5 0 1 1-5 0V2.5a2.5 2.5 0 1 1 5 0v6.3Zm-2.5 10a2.5 2.5 0 1 1-2.5 2.5V19h2.5Zm0-1.3a2.5 2.5 0 1 1 0-5h6.3a2.5 2.5 0 1 1 0 5h-6.3Z"></path></svg>);
    case "zendesk":
      return (<svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M11 9 1 22h10V9Zm2 0v13h10L13 9Zm-2-7a5 5 0 0 1-10 0h10Zm12 0a5 5 0 0 1-10 0h10Z"></path></svg>);
    case "pagerduty":
      return (<svg {...common}><path d="M5 8a7 7 0 0 1 14 0v5l2 3H3l2-3V8Z"></path><path d="M9 19a3 3 0 0 0 6 0"></path></svg>);
    case "notion":
      return (<svg {...common}><rect x="3" y="3" width="18" height="18" rx="2"></rect><path d="M8 8v8"></path><path d="m8 8 8 8"></path><path d="M16 8v8"></path></svg>);
    case "intercom":
      return (<svg {...common}><rect x="3" y="3" width="18" height="18" rx="3"></rect><path d="M8 8v6"></path><path d="M12 7v9"></path><path d="M16 8v6"></path></svg>);
    case "pganalyze":
      return (<svg {...common}><ellipse cx="12" cy="5" rx="8" ry="3"></ellipse><path d="M4 5v6c0 1.7 3.6 3 8 3s8-1.3 8-3V5"></path><path d="M4 11v6c0 1.7 3.6 3 8 3s8-1.3 8-3v-6"></path></svg>);
    default:
      return (<svg {...common}><circle cx="12" cy="12" r="6"></circle></svg>);
  }
};

// ---- Scouts sub-tab ----
const ScoutCard = ({ s, onEdit, onToggle }) => {
  const u = TEAMMATES[s.createdBy] || { name: s.createdBy, initials: s.createdBy.slice(0,2).toUpperCase(), color: "#8a8d99" };
  return (
    <div className={"scout-card" + (s.enabled ? "" : " paused")}>
      <div className="scout-card-head">
        <div className="scout-card-title-row">
          <span className={"scout-pulse" + (s.enabled ? " live" : "")} title={s.enabled ? "Active" : "Paused"} />
          <span className="scout-card-name">{s.name}</span>
          <span className="scout-card-cadence">{CADENCE_LABELS[s.cadence]}</span>
        </div>
        <div className="scout-card-actions">
          <button className="t-btn ghost" onClick={() => onToggle(s.id)} title={s.enabled ? "Pause" : "Resume"}>
            {s.enabled ? "Pause" : "Resume"}
          </button>
          <button className="t-btn ghost" onClick={() => onEdit(s)}>Edit</button>
        </div>
      </div>
      <div className="scout-card-prompt">{s.prompt}</div>
      {s.recentReports && s.recentReports.length > 0 && (
        <div className="scout-card-spark">
          <span className="scout-spark-label">Reports / day · last 14d</span>
          <Sparkline values={s.recentReports} width={132} height={26} color="#3858d6" />
          <span className="scout-spark-total">{s.recentReports.reduce((a, b) => a + b, 0)} total</span>
        </div>
      )}
      <div className="scout-card-foot">
        <span className="scout-foot-item">
          <span style={{ width: 18, height: 18, borderRadius: "50%", background: u.color, color: "#fff", fontSize: 8, fontWeight: 700, display: "inline-flex", alignItems: "center", justifyContent: "center" }}>{u.initials}</span>
          by {u.name.split(" ")[0]}
        </span>
        <span className="scout-foot-sep">·</span>
        <span className="scout-foot-item">ran {s.runCount}×</span>
        <span className="scout-foot-sep">·</span>
        <span className="scout-foot-item">last run {s.lastRun.at}</span>
        {s.lastRun.findingsCount > 0 && (
          <>
            <span className="scout-foot-sep">·</span>
            <span className="scout-foot-item" style={{ color: "#b88800" }}>
              {s.lastRun.findingsCount} finding{s.lastRun.findingsCount === 1 ? "" : "s"}
              {s.lastRun.reportsOpened > 0 && ` → ${s.lastRun.reportsOpened} report${s.lastRun.reportsOpened === 1 ? "" : "s"}`}
            </span>
          </>
        )}
        <span style={{ flex: 1 }} />
        <span className="scout-foot-item" style={{ color: "#8a8d99" }}>
          next {s.nextRun}
        </span>
      </div>
    </div>
  );
};

const ScoutEditor = ({ initial, onCancel, onSave }) => {
  const isNew = !initial;
  const [name, setName] = useStateA(initial?.name || "");
  const [prompt, setPrompt] = useStateA(initial?.prompt || "");
  const [cadence, setCadence] = useStateA(initial?.cadence || "daily");
  const [sources, setSources] = useStateA(initial?.sources || ["session-replay", "support"]);
  const [outputs, setOutputs] = useStateA(initial?.outputs || ["report"]);

  const toggleSource = (k) => setSources(arr => arr.includes(k) ? arr.filter(x => x !== k) : [...arr, k]);

  return (
    <div className="scout-editor">
      <div className="scout-editor-head">
        <h3>{isNew ? "New Scout" : "Edit Scout"}</h3>
        <span className="caption">Scouts watch on a schedule. Findings show up as Reports in your Inbox.</span>
      </div>

      <label className="field">
        <span className="field-label">Name</span>
        <input className="field-input" placeholder="e.g. Pricing page friction" value={name} onChange={e => setName(e.target.value)} />
      </label>

      <label className="field">
        <span className="field-label">What should I keep an eye on?</span>
        <textarea
          className="field-textarea"
          rows="4"
          placeholder="Write it like you'd tell a teammate. e.g. 'Tell me if anyone in #help mentions our pricing page being slow, or if any support ticket touches checkout.'"
          value={prompt}
          onChange={e => setPrompt(e.target.value)}
        />
        <span className="field-hint">Plain English. The Scout will quote your wording back when it surfaces a finding.</span>
      </label>

      <div className="field-row">
        <label className="field">
          <span className="field-label">How often</span>
          <div className="seg">
            {["hourly", "daily", "weekly"].map(c => (
              <button key={c} className={"seg-btn" + (cadence === c ? " active" : "")} onClick={() => setCadence(c)}>
                {CADENCE_LABELS[c]}
              </button>
            ))}
          </div>
        </label>
      </div>

      <div className="field">
        <span className="field-label">What sources can I read?</span>
        <div className="source-grid">
          {(SIGNAL_SOURCES || []).filter(s => s.key !== "other").map(s => (
            <label key={s.key} className={"source-check" + (sources.includes(s.key) ? " on" : "")}>
              <input type="checkbox" checked={sources.includes(s.key)} onChange={() => toggleSource(s.key)} />
              <span className="source-icon" style={{ color: s.color }}><BrandIcon kind={s.key} size={18} /></span>
              <span>{s.label}</span>
            </label>
          ))}
        </div>
      </div>

      <div className="field">
        <span className="field-label">When I find something</span>
        <div className="output-options">
          <label className={"output-opt selected"} title="Always on">
            <input type="checkbox" checked readOnly />
            <span>Open a Report in the Inbox</span>
            <span className="output-opt-hint">Always on</span>
          </label>
          <label className={"output-opt" + (outputs.includes("ping") ? " selected" : "")}>
            <input type="checkbox" checked={outputs.includes("ping")} onChange={() => setOutputs(o => o.includes("ping") ? o.filter(x => x !== "ping") : [...o, "ping"])} />
            <span>Also ping me in Slack (#me)</span>
          </label>
        </div>
      </div>

      <div className="scout-editor-foot">
        <button className="t-btn ghost" onClick={onCancel}>Cancel</button>
        <span style={{ flex: 1 }} />
        <button className="t-btn">Test now</button>
        <button
          className="t-btn primary"
          disabled={!name.trim() || !prompt.trim()}
          onClick={() => onSave({ ...(initial || {}), name, prompt, cadence, sources, outputs, enabled: true })}
        >
          {isNew ? "Save & turn on" : "Save changes"}
        </button>
      </div>
    </div>
  );
};

const ScoutsSubTab = () => {
  const [editing, setEditing] = useStateA(null); // null | "new" | scout obj
  const [scouts, setScouts] = useStateA(SCOUTS);
  if (editing) {
    return (
      <ScoutEditor
        initial={editing === "new" ? null : editing}
        onCancel={() => setEditing(null)}
        onSave={(s) => {
          if (editing === "new") setScouts(arr => [{ ...s, id: "scout_" + Math.random().toString(36).slice(2, 8), runCount: 0, lastRun: { at: "–", findingsCount: 0, runId: "–", reportsOpened: 0 }, nextRun: "first run in 1m", createdBy: ME.handle }, ...arr]);
          else setScouts(arr => arr.map(x => x.id === s.id ? { ...x, ...s } : x));
          setEditing(null);
        }}
      />
    );
  }
  const toggle = (id) => setScouts(arr => arr.map(s => s.id === id ? { ...s, enabled: !s.enabled, nextRun: s.enabled ? "paused" : "in 1m" } : s));
  return (
    <div className="scouts-tab">
      <div className="scouts-head">
        <div>
          <div className="scouts-h3">Your Scouts</div>
          <div className="scouts-blurb">Standing agents that watch the product for things you care about. Each finding becomes a Report.</div>
        </div>
        <button className="t-btn primary" onClick={() => setEditing("new")}>+ New Scout</button>
      </div>
      <div className="scout-list">
        {scouts.map(s => <ScoutCard key={s.id} s={s} onEdit={setEditing} onToggle={toggle} />)}
        {scouts.length === 0 && (
          <div className="empty-state">
            <p>No Scouts yet. Set one up to have the agent keep watch on something specific while you focus on other work.</p>
            <button className="t-btn primary" onClick={() => setEditing("new")}>Create your first Scout</button>
          </div>
        )}
      </div>
    </div>
  );
};

// ---- Responders sub-tab ----
const RespondersSubTab = ({ onJumpToScouts, onJumpToMcp }) => {
  const eligible = (SIGNAL_SOURCES || []).filter(s => s.responderEligible);
  const [state, setState] = useStateA(() => {
    const init = {};
    for (const s of eligible) {
      // Externals: connected status simulated; internals: always available.
      init[s.key] = { enabled: s.internal, connected: s.internal };
    }
    // Demo: Zendesk is already connected by user
    if (init.zendesk) init.zendesk.connected = true;
    return init;
  });
  const toggle = (k) => setState(st => ({ ...st, [k]: { ...st[k], enabled: !st[k].enabled } }));
  return (
    <div className="sources-tab">
      <div className="resp-head">
        <div>
          <div className="scouts-h3">Responders</div>
          <div className="scouts-blurb">A new Responder spins up per signal from a Responder-enabled source. It researches, drafts a fix or report, and tags reviewers – then it's done.</div>
        </div>
      </div>
      <div className="source-list">
        {eligible.map(s => {
          const st = state[s.key];
          const isExternal = !s.internal;
          return (
            <div key={s.key} className="source-row">
              <span className="source-icon" style={{ color: s.color }}><BrandIcon kind={s.key} size={18} /></span>
              <div className="source-row-body">
                <div className="source-row-title">
                  {s.label}
                  {isExternal && <span className="src-tag">external · MCP</span>}
                </div>
                <div className="source-row-sub">
                  {s.description}
                  {isExternal && !st.connected && <> <button className="link-btn" onClick={onJumpToMcp}>Connect in MCP servers →</button></>}
                </div>
              </div>
              <div className="source-row-controls">
                {isExternal && !st.connected ? (
                  <button className="t-btn primary" onClick={onJumpToMcp}>Connect</button>
                ) : (
                  <div className="source-control">
                    <span className="source-control-label">Run Responders</span>
                    <label className="toggle">
                      <input type="checkbox" checked={st.enabled} onChange={() => toggle(s.key)} />
                      <span className="toggle-track"><span className="toggle-thumb" /></span>
                    </label>
                  </div>
                )}
              </div>
            </div>
          );
        })}
      </div>
      <div className="source-foot-note">
        Need eyes on a source that isn't here? Set up a <strong>Scout</strong> – they can watch any source on a schedule and surface findings as Reports.
        {" "}<button className="src-menu-clear" style={{ padding: 0, font: "inherit", fontWeight: 600 }} onClick={onJumpToScouts}>Browse Scouts →</button>
      </div>
    </div>
  );
};

// ---- MCP servers sub-tab ----
const MCP_SERVERS = [
  { key: "zendesk",   label: "Zendesk",   blurb: "Watch incoming support tickets.",                    connected: true,  meta: "421 tickets/day · last sync 2m ago", color: "#1f8a5b", icon: "✉" },
  { key: "github",    label: "GitHub",    blurb: "Monitor new issues and updates.",                    connected: true,  meta: "posthog/ org · last sync 30s ago", color: "#3a3d4a", icon: "◯" },
  { key: "linear",    label: "Linear",    blurb: "Monitor new issues and updates.",                    connected: true,  meta: "posthog workspace · last sync 1m ago", color: "#3858d6", icon: "▤" },
  { key: "slack",     label: "Slack",     blurb: "Listen to conversations in connected channels.",      connected: true,  meta: "4 channels · last sync 12s ago", color: "#7c5cff", icon: "#" },
  { key: "notion",    label: "Notion",    blurb: "Pull docs and runbooks for Scout context.",            connected: false, meta: "", color: "#3a3d4a", icon: "✎" },
  { key: "pagerduty", label: "PagerDuty", blurb: "React to pages and incidents.",                       connected: false, meta: "", color: "#d8503a", icon: "⛐" },
  { key: "intercom",  label: "Intercom",  blurb: "Watch customer conversations and tickets.",           connected: false, meta: "", color: "#3858d6", icon: "¶" },
  { key: "pganalyze", label: "pganalyze", blurb: "Postgres performance findings, slow queries, and index recommendations.", connected: false, meta: "", color: "#3858d6", icon: "◍" },
];

const MCPServersSubTab = () => {
  const [servers, setServers] = useStateA(MCP_SERVERS);
  const toggle = (k) => setServers(arr => arr.map(s => s.key === k ? { ...s, connected: !s.connected, meta: !s.connected ? "just connected · syncing…" : "" } : s));
  const connected = servers.filter(s => s.connected);
  const available = servers.filter(s => !s.connected);
  return (
    <div className="sources-tab">
      <div className="resp-head">
        <div>
          <div className="scouts-h3">MCP servers</div>
          <div className="scouts-blurb">External tools the agents can read from. PostHog data is always available; this is everything else.</div>
        </div>
      </div>

      {connected.length > 0 && (
        <div className="mcp-section">
          <div className="mcp-section-head">Connected <span className="col-count">{connected.length}</span></div>
          <div className="source-list">
            {connected.map(s => (
              <div key={s.key} className="source-row">
                <span className="source-icon" style={{ color: s.color }}><BrandIcon kind={s.key} size={18} /></span>
                <div className="source-row-body">
                  <div className="source-row-title">
                    {s.label}
                    <span className="src-tag connected">connected</span>
                  </div>
                  <div className="source-row-sub">{s.blurb}{s.meta && <> – <span style={{ fontFamily: "var(--font-mono)", fontSize: 11 }}>{s.meta}</span></>}</div>
                </div>
                <div className="source-row-controls">
                  <button className="t-btn ghost" onClick={() => toggle(s.key)}>Disconnect</button>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {available.length > 0 && (
        <div className="mcp-section">
          <div className="mcp-section-head">Available <span className="col-count">{available.length}</span></div>
          <div className="source-list">
            {available.map(s => (
              <div key={s.key} className="source-row available">
                <span className="source-icon" style={{ color: s.color }}><BrandIcon kind={s.key} size={18} /></span>
                <div className="source-row-body">
                  <div className="source-row-title">{s.label}</div>
                  <div className="source-row-sub">{s.blurb}</div>
                </div>
                <div className="source-row-controls">
                  <button className="t-btn primary" onClick={() => toggle(s.key)}>Connect</button>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}
      <div className="source-foot-note">
        Adding a new server? Drop a custom MCP endpoint URL. We'll validate read access before turning it on.
        <button className="link-btn" style={{ marginLeft: 6 }}>+ Custom MCP endpoint</button>
      </div>
    </div>
  );
};

// ---- Modal shell ----
const ConfigureAgentsModal = ({ onClose }) => {
  const [sub, setSub] = useStateA("responders");
  useEffectA(() => {
    const onEsc = (e) => { if (e.key === "Escape") onClose(); };
    document.addEventListener("keydown", onEsc);
    return () => document.removeEventListener("keydown", onEsc);
  }, [onClose]);
  return (
    <div className="agents-overlay" onClick={onClose}>
      <div className="agents-modal" onClick={e => e.stopPropagation()}>
        <div className="agents-head">
          <div>
            <div className="agents-eyebrow">Configure agents</div>
            <div className="agents-title">Tell the agents what you want them to do – and what they can see.</div>
          </div>
          <button className="t-btn ghost" onClick={onClose} title="Close (Esc)">✕</button>
        </div>

        <div className="agents-integrations">
          <div className="integ-row">
            <span className="integ-ico">
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                <circle cx="18" cy="5" r="3"></circle>
                <circle cx="6" cy="12" r="3"></circle>
                <circle cx="18" cy="19" r="3"></circle>
                <line x1="8.59" y1="13.51" x2="15.42" y2="17.49"></line>
                <line x1="15.41" y1="6.51" x2="8.59" y2="10.49"></line>
              </svg>
            </span>
            <div className="integ-body">
              <div className="integ-title">Project-level code access</div>
              <div className="integ-sub">Connected and active (604 repos) <span className="integ-info" title="Agents can read and open PRs against any of these repos.">ⓘ</span></div>
            </div>
            <span className="integ-status connected" title="Connected">✓</span>
            <button className="integ-action" onClick={(e) => e.stopPropagation()}>Update in GitHub ↗</button>
          </div>

          <div className="integ-row">
            <span className="integ-ico slack">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
                <path d="M5.042 15.165a2.528 2.528 0 0 1-2.52 2.523A2.528 2.528 0 0 1 0 15.165a2.527 2.527 0 0 1 2.522-2.52h2.52v2.52zM6.313 15.165a2.527 2.527 0 0 1 2.521-2.52 2.527 2.527 0 0 1 2.521 2.52v6.313A2.528 2.528 0 0 1 8.834 24a2.528 2.528 0 0 1-2.521-2.522v-6.313zM8.834 5.042a2.528 2.528 0 0 1-2.521-2.52A2.528 2.528 0 0 1 8.834 0a2.528 2.528 0 0 1 2.521 2.522v2.52H8.834zM8.834 6.313a2.528 2.528 0 0 1 2.521 2.521 2.528 2.528 0 0 1-2.521 2.521H2.522A2.528 2.528 0 0 1 0 8.834a2.528 2.528 0 0 1 2.522-2.521h6.312zM18.956 8.834a2.528 2.528 0 0 1 2.522-2.521A2.528 2.528 0 0 1 24 8.834a2.528 2.528 0 0 1-2.522 2.521h-2.522V8.834zM17.688 8.834a2.528 2.528 0 0 1-2.523 2.521 2.527 2.527 0 0 1-2.52-2.521V2.522A2.527 2.527 0 0 1 15.165 0a2.528 2.528 0 0 1 2.523 2.522v6.312zM15.165 18.956a2.528 2.528 0 0 1 2.523 2.522A2.528 2.528 0 0 1 15.165 24a2.527 2.527 0 0 1-2.52-2.522v-2.522h2.52zM15.165 17.688a2.527 2.527 0 0 1-2.52-2.523 2.526 2.526 0 0 1 2.52-2.52h6.313A2.527 2.527 0 0 1 24 15.165a2.528 2.528 0 0 1-2.522 2.523h-6.313z"></path>
              </svg>
            </span>
            <div className="integ-body">
              <div className="integ-title">Slack notifications</div>
              <div className="integ-sub">Get pinged in Slack when you're a suggested reviewer on a new inbox item.</div>
            </div>
            <button className="integ-action" onClick={(e) => e.stopPropagation()}>Connect Slack workspace</button>
          </div>
        </div>
        <div className="agents-subtabs">
          <button className={"subtab" + (sub === "responders" ? " active" : "")} onClick={() => setSub("responders")}>Responders</button>
          <button className={"subtab" + (sub === "scouts" ? " active" : "")} onClick={() => setSub("scouts")}>Scouts <span className="subtab-count">{SCOUTS.length}</span></button>
          <button className={"subtab" + (sub === "mcp" ? " active" : "")} onClick={() => setSub("mcp")}>MCP servers</button>
        </div>
        <div className="agents-body">
          {sub === "responders" && <RespondersSubTab onJumpToScouts={() => setSub("scouts")} onJumpToMcp={() => setSub("mcp")} />}
          {sub === "scouts" && <ScoutsSubTab />}
          {sub === "mcp" && <MCPServersSubTab />}
        </div>
      </div>
    </div>
  );
};
// ---- Agents tab (inside the Inbox view) ----
// Two sections: Scouts (user-defined, anchored top) + Live Responders (in progress).
const AgentsTab = ({ scouts, liveResponders, onConfigure }) => {
  const activeScouts = scouts.filter(s => s.enabled);
  const pausedScouts = scouts.filter(s => !s.enabled);
  return (
    <div className="agents-tab-body">
      <section className="agents-tab-section">
        <div className="agents-tab-section-head">
          <div>
            <h3>Scouts</h3>
            <p>Standing agents that watch on a schedule. Each finding becomes a Report.</p>
          </div>
          <div style={{ display: "inline-flex", gap: 8 }}>
            <button className="t-btn primary" onClick={onConfigure}>+ New Scout</button>
            <button className="t-btn" onClick={onConfigure}>Manage all</button>
          </div>
        </div>
        <div className="scout-list compact">
          {activeScouts.map(s => (
            <div key={s.id} className="scout-mini">
              <div className="scout-mini-row">
                <span className="scout-pulse live" />
                <span className="scout-mini-name">{s.name}</span>
                <span className="scout-mini-cadence">{CADENCE_LABELS[s.cadence]}</span>
                <span className="scout-foot-sep">·</span>
                <span className="scout-mini-meta">next {s.nextRun}</span>
                <span style={{ flex: 1 }} />
                {s.lastRun.findingsCount > 0 ? (
                  <span className="scout-mini-finding">
                    last run: {s.lastRun.findingsCount} finding{s.lastRun.findingsCount === 1 ? "" : "s"} → {s.lastRun.reportsOpened} report{s.lastRun.reportsOpened === 1 ? "" : "s"}
                  </span>
                ) : (
                  <span className="scout-mini-meta">last run: clean</span>
                )}
              </div>
              <div className="scout-mini-prompt">"{s.prompt}"</div>
            </div>
          ))}
          {pausedScouts.length > 0 && (
            <div className="scout-paused-divider">{pausedScouts.length} paused</div>
          )}
          {pausedScouts.map(s => (
            <div key={s.id} className="scout-mini paused">
              <div className="scout-mini-row">
                <span className="scout-pulse" />
                <span className="scout-mini-name">{s.name}</span>
                <span className="scout-mini-cadence">{CADENCE_LABELS[s.cadence]}</span>
                <span className="scout-foot-sep">·</span>
                <span className="scout-mini-meta">paused</span>
              </div>
              <div className="scout-mini-prompt">"{s.prompt}"</div>
            </div>
          ))}
        </div>
      </section>

      <section className="agents-tab-section">
        <div className="agents-tab-section-head">
          <div>
            <h3>Responder runs in progress</h3>
            <p>Each one was triggered by a signal. They'll surface as a Pull request or a Report when done.</p>
          </div>
        </div>
        <div className="live-resp-list">
          {liveResponders.length === 0 && (
            <div className="empty-state" style={{ background: "#fbfbf6" }}>Quiet. No Responders are running right now.</div>
          )}
          {liveResponders.map(r => (
            <div key={r.id} className="live-resp">
              <div className="live-resp-head">
                <span className="live-resp-pulse" />
                <span className="live-resp-trigger">{r.triggeredBy}</span>
                <span className="scout-foot-sep">·</span>
                <span className="live-resp-meta">{r.repo}</span>
                <span style={{ flex: 1 }} />
                <span className="live-resp-eta">eta {r.eta}</span>
              </div>
              <div className="live-resp-step">{r.step}</div>
              <div className="live-resp-progress">
                <span style={{ width: Math.round(r.progress * 100) + "%" }} />
              </div>
              <div className="live-resp-foot">
                <span>started {r.startedAt}</span>
                <span style={{ flex: 1 }} />
                <a href="#" onClick={(e) => e.preventDefault()}>{r.id} ↗</a>
              </div>
            </div>
          ))}
        </div>
      </section>
    </div>
  );
};

Object.assign(window, { ConfigureAgentsModal, AgentsTab });
