const { useState, useEffect, useRef, useCallback } = React;

// ─── CONFIG ──────────────────────────────────────────────────────────────────
const SUPABASE_URL  = "https://nwxfoisdrnpkotenbqfr.supabase.co";
const SUPABASE_ANON = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Im53eGZvaXNkcm5wa290ZW5icWZyIiwicm9sZSI6ImFub24iLCJpYXQiOjE3ODI2NzE3NzcsImV4cCI6MjA5ODI0Nzc3N30.cCMlsBXY5eqydJtxohM5tX26cZey75_3GKL41EFHh8Y";
const POLL_MS = 8000;

// ─── FETCH ────────────────────────────────────────────────────────────────────
async function sbFetch(path, params = {}) {
  const url = new URL(`${SUPABASE_URL}/rest/v1/${path}`);
  Object.entries(params).forEach(([k, v]) => url.searchParams.set(k, v));
  const res = await fetch(url.toString(), {
    headers: { apikey: SUPABASE_ANON, Authorization: `Bearer ${SUPABASE_ANON}` },
  });
  if (!res.ok) throw new Error(`${res.status} ${path}`);
  return res.json();
}

// ─── HELPERS ─────────────────────────────────────────────────────────────────
function timeAgo(iso) {
  const s = Math.floor((Date.now() - new Date(iso)) / 1000);
  if (s < 60) return `${s}s atrás`;
  if (s < 3600) return `${Math.floor(s/60)}m atrás`;
  if (s < 86400) return `${Math.floor(s/3600)}h atrás`;
  return `${Math.floor(s/86400)}d atrás`;
}

const EVENT_META = {
  session_start:     { label: "Sessão iniciada",    color: "#4C8EC9" },
  session_end:       { label: "Sessão encerrada",   color: "#555"    },
  task_started:      { label: "Tarefa iniciada",    color: "#C9A84C" },
  task_completed:    { label: "Tarefa concluída",   color: "#4CC98E" },
  task_failed:       { label: "Erro",               color: "#FF6B6B" },
  cron_fired:        { label: "Cron disparado",     color: "#9B4CC9" },
  cron_completed:    { label: "Cron concluído",     color: "#4CC98E" },
  memory_updated:    { label: "Memória atualizada", color: "#C9A84C" },
  escalation:        { label: "Escalado",           color: "#FF6B6B" },
  awaiting_approval: { label: "Aguarda aprovação",  color: "#FF9B3D" },
  heartbeat:         { label: "Heartbeat",          color: "#4CC98E" },
  skill_loaded:      { label: "Skill carregada",    color: "#7A99CC" },
};

const PRIO_COLOR   = { critica:"#FF6B6B", alta:"#C9A84C", media:"#4C8EC9", baixa:"#555" };
const STATUS_COLOR = {
  running:"#4CC98E", stopped:"#FF6B6B",
  em_andamento:"#C9A84C", pendente:"#555",
  concluida:"#4CC98E", bloqueada:"#FF6B6B",
  aguardando_aprovacao:"#FF9B3D",
};
const STATUS_LABEL = {
  em_andamento:"Em andamento", pendente:"Pendente",
  concluida:"Concluída", bloqueada:"Bloqueada",
  aguardando_aprovacao:"Aguarda aprovação",
};

// ─── ATOMS ───────────────────────────────────────────────────────────────────
function Pulse({ color, size = 8 }) {
  return (
    <span style={{ position:"relative", display:"inline-flex", width:size+2, height:size+2, alignItems:"center", justifyContent:"center", flexShrink:0 }}>
      <span style={{ position:"absolute", inset:0, borderRadius:"50%", background:color, opacity:0.2, animation:"hcm-pulse 2s infinite" }} />
      <span style={{ width:size, height:size, borderRadius:"50%", background:color, display:"block" }} />
    </span>
  );
}
function Dot({ color, size = 7 }) {
  return <span style={{ width:size, height:size, borderRadius:"50%", background:color, display:"inline-block", flexShrink:0 }} />;
}
function Badge({ children, color }) {
  return (
    <span style={{ padding:"2px 8px", borderRadius:4, fontSize:10, fontWeight:600, background:color+"18", border:`1px solid ${color}30`, color, whiteSpace:"nowrap", lineHeight:"16px" }}>
      {children}
    </span>
  );
}

// ─── TELA QG (principal) ─────────────────────────────────────────────────────
function QGScreen({ agents, gwMap, events, missions, approvals, newIds, lastPoll, isLive, ticks, error, onSelectAgent }) {
  const running = Object.values(gwMap).filter(g => g?.status === "running").length;

  const lastEventMap = {};
  events.forEach(ev => { if (!lastEventMap[ev.agent_id]) lastEventMap[ev.agent_id] = ev; });

  const pendingByAgent = {};
  events.filter(e => e.event_type === "awaiting_approval").forEach(e => {
    pendingByAgent[e.agent_id] = (pendingByAgent[e.agent_id] || 0) + 1;
  });

  return (
    <div style={{ minHeight:"100vh", background:"#09090E", color:"#E8E4D8", fontFamily:"'Inter',system-ui,sans-serif", fontSize:13 }}>

      {/* HEADER */}
      <div style={{ borderBottom:"1px solid #141420", padding:"14px 22px", display:"flex", alignItems:"center", gap:12 }}>
        <div style={{ width:30, height:30, borderRadius:8, background:"linear-gradient(135deg,#C9A84C,#9B4CC9)", display:"flex", alignItems:"center", justifyContent:"center", fontSize:15, flexShrink:0 }}>⚡</div>
        <div>
          <div style={{ fontSize:15, fontWeight:700, letterSpacing:"-0.3px", color:"#E8E4D8" }}>Hermes Control Mission</div>
          <div style={{ fontSize:10, color:"#3A3A4A", letterSpacing:"0.8px", textTransform:"uppercase" }}>Grupo Marcandali · QG</div>
        </div>
        <div style={{ marginLeft:"auto", display:"flex", alignItems:"center", gap:14 }}>
          <div style={{ display:"flex", gap:10 }}>
            <span style={{ fontSize:11, color:"#4CC98E", display:"flex", alignItems:"center", gap:5 }}><Dot color="#4CC98E" />{running} ativo{running!==1?"s":""}</span>
            <span style={{ fontSize:11, color:"#FF6B6B", display:"flex", alignItems:"center", gap:5 }}><Dot color="#FF6B6B" />{agents.length-running} parado{(agents.length-running)!==1?"s":""}</span>
            {approvals.length > 0 && <span style={{ fontSize:11, color:"#FF9B3D", display:"flex", alignItems:"center", gap:5 }}><Dot color="#FF9B3D" />{approvals.length} aguardando</span>}
          </div>
          <div style={{ display:"flex", alignItems:"center", gap:6 }}>
            {isLive ? <Pulse color="#4CC98E" /> : <Dot color="#C9A84C" />}
            <span style={{ fontSize:10, color: isLive?"#4CC98E":"#C9A84C" }}>
              {isLive ? `${lastPoll?.toLocaleTimeString("pt-BR")} · ${ticks}` : "conectando…"}
            </span>
          </div>
          {error && <span style={{ fontSize:10, color:"#FF6B6B", background:"#1A0808", padding:"3px 8px", borderRadius:4 }}>⚠ erro</span>}
        </div>
      </div>

      <div style={{ padding:"20px 22px", maxWidth:1100, margin:"0 auto" }}>

        {/* APROVAÇÕES PENDENTES */}
        {approvals.length > 0 && (
          <div style={{ background:"#120A00", border:"1px solid #FF9B3D44", borderRadius:10, padding:"13px 18px", marginBottom:20 }}>
            <div style={{ fontSize:12, fontWeight:700, color:"#FF9B3D", marginBottom:10 }}>
              ⏳ {approvals.length} {approvals.length===1?"ação aguarda":"ações aguardam"} sua aprovação
            </div>
            {approvals.map((a, i) => (
              <div key={a.id} style={{ display:"flex", alignItems:"center", gap:10, padding:"7px 0", borderTop: i>0?"1px solid #1A1200":"none" }}>
                <span style={{ fontSize:16 }}>{a.agent_emoji}</span>
                <div style={{ flex:1 }}>
                  <div style={{ fontSize:12, color:"#DDD" }}>{a.description}</div>
                  <div style={{ fontSize:10, color:"#555", marginTop:2 }}>{a.agent_name} · {timeAgo(a.created_at)}</div>
                </div>
                <Badge color={a.risk_level==="critico"?"#FF6B6B":a.risk_level==="alto"?"#C9A84C":"#4C8EC9"}>{a.risk_level}</Badge>
              </div>
            ))}
          </div>
        )}

        {/* GRID DE AGENTES */}
        <div style={{ display:"grid", gridTemplateColumns:"repeat(auto-fill, minmax(210px, 1fr))", gap:13, marginBottom:22 }}>
          {agents.map(ag => {
            const gw      = gwMap[ag.id];
            const running = gw?.status === "running";
            const color   = ag.accent_color || "#666";
            const last    = lastEventMap[ag.id];
            const pending = pendingByAgent[ag.id] || 0;
            const agMissions = missions.filter(m => m.agent_id === ag.id && m.status !== "concluida");

            return (
              <div
                key={ag.id}
                onClick={() => onSelectAgent(ag.id)}
                style={{
                  background:"#0D0D12",
                  border:`1px solid ${running ? color+"44" : "#1C1C26"}`,
                  borderRadius:11, padding:"16px 17px",
                  cursor:"pointer", transition:"all 0.12s",
                  position:"relative",
                }}
                onMouseEnter={e => e.currentTarget.style.border = `1px solid ${color}66`}
                onMouseLeave={e => e.currentTarget.style.border = `1px solid ${running ? color+"44" : "#1C1C26"}`}
              >
                {/* badge de pendência */}
                {pending > 0 && (
                  <div style={{ position:"absolute", top:12, right:12, width:18, height:18, borderRadius:"50%", background:"#FF9B3D", display:"flex", alignItems:"center", justifyContent:"center", fontSize:10, fontWeight:700, color:"#000" }}>
                    {pending}
                  </div>
                )}

                <div style={{ display:"flex", gap:11, marginBottom:12 }}>
                  <div style={{ width:40, height:40, borderRadius:9, background:color+"18", border:`1px solid ${color}28`, display:"flex", alignItems:"center", justifyContent:"center", fontSize:22, flexShrink:0 }}>
                    {ag.emoji}
                  </div>
                  <div style={{ flex:1, minWidth:0 }}>
                    <div style={{ fontSize:13, fontWeight:700, color:"#E8E4D8", marginBottom:1 }}>{ag.name}</div>
                    <div style={{ fontSize:10, color:"#555", lineHeight:1.4 }}>{ag.role}</div>
                  </div>
                </div>

                <div style={{ display:"flex", alignItems:"center", gap:6, marginBottom:10 }}>
                  {running ? <Pulse color="#4CC98E" size={7} /> : <Dot color="#FF6B6B" size={7} />}
                  <span style={{ fontSize:10, color: running?"#4CC98E":"#FF6B6B", fontWeight:600 }}>
                    {running ? "gateway ativo" : "gateway parado"}
                  </span>
                </div>

                <div style={{ borderTop:"1px solid #161622", paddingTop:10 }}>
                  {last ? (
                    <>
                      <div style={{ fontSize:11, color:"#888", lineHeight:1.4, marginBottom:3 }}>{last.summary}</div>
                      <div style={{ fontSize:10, color:"#3A3A4A" }}>{timeAgo(last.created_at)}</div>
                    </>
                  ) : (
                    <div style={{ fontSize:11, color:"#2A2A38" }}>Sem atividade recente</div>
                  )}
                </div>

                {agMissions.length > 0 && (
                  <div style={{ marginTop:10, borderTop:"1px solid #161622", paddingTop:10, display:"flex", justifyContent:"space-between", alignItems:"center" }}>
                    <span style={{ fontSize:10, color:"#444" }}>{agMissions.length} missão{agMissions.length!==1?"ões":""} ativa{agMissions.length!==1?"s":""}</span>
                    <span style={{ fontSize:10, color:color, fontWeight:600 }}>ver →</span>
                  </div>
                )}
              </div>
            );
          })}
        </div>

        {/* FEED GERAL */}
        <div style={{ background:"#0D0D12", border:"1px solid #1C1C26", borderRadius:10, overflow:"hidden" }}>
          <div style={{ padding:"11px 18px", borderBottom:"1px solid #161622", display:"flex", alignItems:"center", gap:8 }}>
            <span style={{ fontSize:12, fontWeight:700, color:"#E8E4D8", flex:1 }}>Feed geral</span>
            <Pulse color="#4CC98E" size={7} />
            <span style={{ fontSize:10, color:"#4CC98E" }}>ao vivo</span>
          </div>
          <div style={{ maxHeight:300, overflowY:"auto" }}>
            {events.length === 0
              ? <div style={{ padding:24, textAlign:"center", fontSize:12, color:"#333" }}>Aguardando eventos…</div>
              : events.slice(0, 30).map((ev, i) => {
                  const m = EVENT_META[ev.event_type] || { label: ev.event_type, color:"#666" };
                  const isNew = newIds?.has(ev.id);
                  return (
                    <div
                      key={ev.id}
                      onClick={() => onSelectAgent(ev.agent_id)}
                      style={{ display:"flex", gap:10, padding:"9px 18px", borderBottom: i < 29 ? "1px solid #0F0F14":"none", background: isNew?"#0C140A":"transparent", transition:"background 0.5s", cursor:"pointer" }}
                      onMouseEnter={e => e.currentTarget.style.background = "#111118"}
                      onMouseLeave={e => e.currentTarget.style.background = isNew?"#0C140A":"transparent"}
                    >
                      <span style={{ fontSize:15, lineHeight:"18px", flexShrink:0 }}>{ev.agent_emoji}</span>
                      <div style={{ flex:1, minWidth:0 }}>
                        <div style={{ display:"flex", alignItems:"center", gap:6, marginBottom:2, flexWrap:"wrap" }}>
                          <span style={{ fontSize:11, fontWeight:700, color: ev.accent_color }}>{ev.agent_name}</span>
                          <Badge color={m.color}>{m.label}</Badge>
                          {isNew && <Badge color="#4CC98E">novo</Badge>}
                        </div>
                        <div style={{ fontSize:11, color:"#999", lineHeight:1.4 }}>{ev.summary}</div>
                      </div>
                      <div style={{ fontSize:10, color:"#333", flexShrink:0, paddingTop:1 }}>{timeAgo(ev.created_at)}</div>
                    </div>
                  );
                })
            }
          </div>
        </div>
      </div>

      <div style={{ borderTop:"1px solid #0F0F14", padding:"8px 22px", display:"flex", justifyContent:"space-between", marginTop:8 }}>
        <span style={{ fontSize:10, color:"#1E1E28" }}>Hermes v0.17.0 · polling {POLL_MS/1000}s</span>
        <span style={{ fontSize:10, color:"#1E1E28" }}>Rafael Marcandali · Comandante Máximo</span>
      </div>
    </div>
  );
}

// ─── TELA AGENTE (detalhe) ────────────────────────────────────────────────────
function AgentScreen({ agentId, agents, gwMap, events, missions, approvals, onBack }) {
  const agent   = agents.find(a => a.id === agentId);
  const gw      = gwMap[agentId];
  const running = gw?.status === "running";

  if (!agent) return null;

  const color       = agent.accent_color || "#666";
  const agEvents    = events.filter(e => e.agent_id === agentId);
  const agMissions  = missions.filter(m => m.agent_id === agentId);
  const agApprovals = approvals.filter(a => a.agent_id === agentId);
  const pendingEvts = agEvents.filter(e => e.event_type === "awaiting_approval");

  const openMissions   = agMissions.filter(m => m.status !== "concluida");
  const closedMissions = agMissions.filter(m => m.status === "concluida");

  return (
    <div style={{ minHeight:"100vh", background:"#09090E", color:"#E8E4D8", fontFamily:"'Inter',system-ui,sans-serif", fontSize:13 }}>

      {/* HEADER AGENTE */}
      <div style={{ borderBottom:`1px solid ${color}22`, padding:"14px 22px", display:"flex", alignItems:"center", gap:14 }}>
        <button
          onClick={onBack}
          style={{ background:"#1A1A22", border:"1px solid #2A2A38", borderRadius:7, padding:"6px 12px", color:"#888", fontSize:12, cursor:"pointer", display:"flex", alignItems:"center", gap:6 }}
        >
          ← QG
        </button>
        <div style={{ width:36, height:36, borderRadius:9, background:color+"18", border:`1px solid ${color}30`, display:"flex", alignItems:"center", justifyContent:"center", fontSize:22 }}>
          {agent.emoji}
        </div>
        <div>
          <div style={{ fontSize:15, fontWeight:700, color:"#E8E4D8" }}>{agent.name}</div>
          <div style={{ fontSize:10, color:"#555" }}>{agent.role}</div>
        </div>
        <div style={{ marginLeft:"auto", display:"flex", alignItems:"center", gap:8 }}>
          {running ? <Pulse color="#4CC98E" /> : <Dot color="#FF6B6B" />}
          <span style={{ fontSize:11, color: running?"#4CC98E":"#FF6B6B", fontWeight:600 }}>
            {running ? "gateway ativo" : "gateway parado"}
          </span>
          {gw?.telegram_connected && (
            <span style={{ fontSize:10, color:"#4C8EC9", marginLeft:6 }}>📱 {gw.telegram_bot}</span>
          )}
        </div>
      </div>

      <div style={{ padding:"20px 22px", maxWidth:1000, margin:"0 auto" }}>

        {/* PENDÊNCIAS DO AGENTE */}
        {(agApprovals.length > 0 || pendingEvts.length > 0) && (
          <div style={{ background:"#120A00", border:"1px solid #FF9B3D44", borderRadius:10, padding:"13px 18px", marginBottom:18 }}>
            <div style={{ fontSize:12, fontWeight:700, color:"#FF9B3D", marginBottom:10 }}>
              ⏳ Pendências aguardando você
            </div>
            {agApprovals.map((a, i) => (
              <div key={a.id} style={{ display:"flex", alignItems:"flex-start", gap:10, padding:"7px 0", borderTop: i>0?"1px solid #1A1200":"none" }}>
                <div style={{ flex:1 }}>
                  <div style={{ fontSize:12, color:"#DDD" }}>{a.description}</div>
                  <div style={{ fontSize:10, color:"#555", marginTop:2 }}>{a.action_type} · {timeAgo(a.created_at)}</div>
                </div>
                <Badge color={a.risk_level==="critico"?"#FF6B6B":a.risk_level==="alto"?"#C9A84C":"#4C8EC9"}>{a.risk_level}</Badge>
              </div>
            ))}
            {pendingEvts.map((e, i) => (
              <div key={e.id} style={{ display:"flex", alignItems:"flex-start", gap:10, padding:"7px 0", borderTop:"1px solid #1A1200" }}>
                <div style={{ flex:1 }}>
                  <div style={{ fontSize:12, color:"#DDD" }}>{e.summary}</div>
                  <div style={{ fontSize:10, color:"#555", marginTop:2 }}>{timeAgo(e.created_at)}</div>
                </div>
                <Badge color="#FF9B3D">aguarda aprovação</Badge>
              </div>
            ))}
          </div>
        )}

        <div style={{ display:"grid", gridTemplateColumns:"1fr 320px", gap:16, alignItems:"start" }}>
          <div style={{ display:"flex", flexDirection:"column", gap:14 }}>

            {/* MISSÕES ABERTAS */}
            <div style={{ background:"#0D0D12", border:"1px solid #1C1C26", borderRadius:10, overflow:"hidden" }}>
              <div style={{ padding:"11px 16px", borderBottom:"1px solid #161622" }}>
                <span style={{ fontSize:12, fontWeight:700, color:"#E8E4D8" }}>Missões abertas</span>
                <span style={{ fontSize:10, color:"#444", marginLeft:8 }}>{openMissions.length}</span>
              </div>
              {openMissions.length === 0
                ? <div style={{ padding:18, fontSize:12, color:"#333", textAlign:"center" }}>Nenhuma missão aberta</div>
                : openMissions.map((m, i) => {
                    const sc = STATUS_COLOR[m.status] || "#666";
                    const pc = PRIO_COLOR[m.priority] || "#666";
                    return (
                      <div key={m.id} style={{ padding:"12px 16px", borderBottom: i < openMissions.length-1?"1px solid #111116":"none" }}>
                        <div style={{ display:"flex", alignItems:"center", gap:8, marginBottom:8 }}>
                          <code style={{ fontSize:10, color:"#3A3A4A", fontFamily:"monospace" }}>{m.id}</code>
                          <span style={{ fontSize:12, color:"#DDD", flex:1 }}>{m.title}</span>
                          <Badge color={pc}>{m.priority}</Badge>
                          <Badge color={sc}>{STATUS_LABEL[m.status] || m.status}</Badge>
                        </div>
                        {m.notes && <div style={{ fontSize:11, color:"#666", marginBottom:8, lineHeight:1.5 }}>{m.notes}</div>}
                        <div style={{ display:"flex", alignItems:"center", gap:8 }}>
                          <div style={{ flex:1, height:4, background:"#1A1A22", borderRadius:2, overflow:"hidden" }}>
                            <div style={{ height:"100%", borderRadius:2, width:`${m.progress_pct}%`, background: m.progress_pct===100?"#4CC98E":sc, transition:"width 0.4s" }} />
                          </div>
                          <span style={{ fontSize:10, color:sc, minWidth:30, textAlign:"right" }}>{m.progress_pct}%</span>
                        </div>
                      </div>
                    );
                  })
              }
            </div>

            {/* FEED DO AGENTE */}
            <div style={{ background:"#0D0D12", border:"1px solid #1C1C26", borderRadius:10, overflow:"hidden" }}>
              <div style={{ padding:"11px 16px", borderBottom:"1px solid #161622", display:"flex", alignItems:"center", gap:8 }}>
                <span style={{ fontSize:12, fontWeight:700, color:"#E8E4D8", flex:1 }}>Atividade</span>
                <Pulse color={color} size={6} />
              </div>
              <div style={{ maxHeight:380, overflowY:"auto" }}>
                {agEvents.length === 0
                  ? <div style={{ padding:20, textAlign:"center", fontSize:12, color:"#333" }}>Sem registros ainda</div>
                  : agEvents.map((ev, i) => {
                      const m = EVENT_META[ev.event_type] || { label: ev.event_type, color:"#666" };
                      return (
                        <div key={ev.id} style={{ display:"flex", gap:10, padding:"9px 16px", borderBottom: i < agEvents.length-1?"1px solid #0F0F14":"none" }}>
                          <div style={{ width:6, height:6, borderRadius:"50%", background:m.color, marginTop:6, flexShrink:0 }} />
                          <div style={{ flex:1 }}>
                            <div style={{ display:"flex", alignItems:"center", gap:6, marginBottom:2 }}>
                              <Badge color={m.color}>{m.label}</Badge>
                            </div>
                            <div style={{ fontSize:12, color:"#AAA", lineHeight:1.4 }}>{ev.summary}</div>
                          </div>
                          <div style={{ fontSize:10, color:"#333", flexShrink:0, paddingTop:1 }}>{timeAgo(ev.created_at)}</div>
                        </div>
                      );
                    })
                }
              </div>
            </div>
          </div>

          {/* COLUNA DIREITA */}
          <div style={{ display:"flex", flexDirection:"column", gap:14 }}>

            {/* PERFIL */}
            <div style={{ background:"#0D0D12", border:`1px solid ${color}22`, borderRadius:10, padding:"14px 16px" }}>
              <div style={{ fontSize:10, color:"#444", letterSpacing:"0.8px", textTransform:"uppercase", marginBottom:12 }}>Perfil Hermes</div>
              {[
                ["Perfil",    agent.profile_name],
                ["Superior",  agent.superior || "Rafael"],
                ["Gateway",   running ? "ativo" : "parado"],
              ].map(([label, val]) => (
                <div key={label} style={{ display:"flex", justifyContent:"space-between", padding:"5px 0", borderBottom:"1px solid #111116" }}>
                  <span style={{ fontSize:11, color:"#555" }}>{label}</span>
                  <span style={{ fontSize:11, color: label==="Gateway" ? (running?"#4CC98E":"#FF6B6B") : "#999", fontFamily: label==="Perfil"?"monospace":"inherit" }}>{val}</span>
                </div>
              ))}
            </div>

            {/* MISSÕES CONCLUÍDAS */}
            {closedMissions.length > 0 && (
              <div style={{ background:"#0D0D12", border:"1px solid #1C1C26", borderRadius:10, overflow:"hidden" }}>
                <div style={{ padding:"11px 16px", borderBottom:"1px solid #161622" }}>
                  <span style={{ fontSize:12, fontWeight:700, color:"#E8E4D8" }}>Concluídas</span>
                  <span style={{ fontSize:10, color:"#444", marginLeft:8 }}>{closedMissions.length}</span>
                </div>
                {closedMissions.map((m, i) => (
                  <div key={m.id} style={{ padding:"10px 16px", borderBottom: i < closedMissions.length-1?"1px solid #0F0F14":"none", display:"flex", alignItems:"center", gap:8 }}>
                    <span style={{ fontSize:12, color:"#4CC98E" }}>✓</span>
                    <span style={{ fontSize:11, color:"#555", flex:1 }}>{m.title}</span>
                  </div>
                ))}
              </div>
            )}

            {/* STATS */}
            <div style={{ background:"#0D0D12", border:"1px solid #1C1C26", borderRadius:10, padding:"14px 16px" }}>
              <div style={{ fontSize:10, color:"#444", letterSpacing:"0.8px", textTransform:"uppercase", marginBottom:12 }}>Atividade recente</div>
              <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:10 }}>
                {[
                  ["Eventos",   agEvents.length],
                  ["Missões",   agMissions.length],
                  ["Pendentes", agApprovals.length + pendingEvts.length],
                  ["Concluídas", closedMissions.length],
                ].map(([label, val]) => (
                  <div key={label} style={{ background:"#080810", border:"1px solid #1A1A22", borderRadius:7, padding:"10px 12px" }}>
                    <div style={{ fontSize:18, fontWeight:700, color: val > 0 ? color : "#333" }}>{val}</div>
                    <div style={{ fontSize:10, color:"#444" }}>{label}</div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ─── APP PRINCIPAL ────────────────────────────────────────────────────────────
function App() {
  const [agents,    setAgents]    = useState([]);
  const [gws,       setGws]       = useState([]);
  const [events,    setEvents]    = useState([]);
  const [missions,  setMissions]  = useState([]);
  const [approvals, setApprovals] = useState([]);
  const [newIds,    setNewIds]    = useState(new Set());
  const [lastPoll,  setLastPoll]  = useState(null);
  const [error,     setError]     = useState(null);
  const [isLive,    setIsLive]    = useState(false);
  const [ticks,     setTicks]     = useState(0);
  const [screen,    setScreen]    = useState("qg");   // "qg" | agentId
  const prevIds = useRef(new Set());

  const poll = useCallback(async () => {
    try {
      const [ag, gw, ev, ms, ap] = await Promise.all([
        sbFetch("hcm_agents",            { select:"*", order:"id" }),
        sbFetch("hcm_gateway_latest",    { select:"*" }),
        sbFetch("hcm_events_feed",       { select:"*" }),
        sbFetch("hcm_missions",          { select:"*", order:"priority,id" }),
        sbFetch("hcm_approvals_pending", { select:"*" }),
      ]);
      const ids   = new Set(ev.map(e => e.id));
      const fresh = new Set([...ids].filter(id => !prevIds.current.has(id)));
      prevIds.current = ids;
      if (ag.length) setAgents(ag);
      if (gw.length) setGws(gw);
      setEvents(ev);
      if (ms.length) setMissions(ms);
      setApprovals(ap);
      if (fresh.size) { setNewIds(fresh); setTimeout(() => setNewIds(new Set()), 5000); }
      setLastPoll(new Date());
      setError(null);
      setIsLive(true);
      setTicks(t => t + 1);
    } catch (e) { setError(e.message); }
  }, []);

  useEffect(() => { poll(); const t = setInterval(poll, POLL_MS); return () => clearInterval(t); }, [poll]);

  const gwMap = Object.fromEntries(gws.map(g => [g.agent_id, g]));

  const commonProps = { agents, gwMap, events, missions, approvals, newIds, lastPoll, isLive, ticks, error };

  if (screen === "qg") {
    return <QGScreen {...commonProps} onSelectAgent={id => setScreen(id)} />;
  }
  return <AgentScreen {...commonProps} agentId={screen} onBack={() => setScreen("qg")} />;
}
