// Page 3 — Team

function TeamPage({ alerts, pushToast }) {
  const [expanded, setExpanded] = useState(() => new Set(["kostya"]));
  const [confirmRestart, setConfirmRestart] = useState(null);

  const alertsByAgent = useMemo(() => {
    const m = {};
    alerts.forEach(a => {
      if (a.status === "active" && a.agent) (m[a.agent] = m[a.agent] || []).push(a);
    });
    return m;
  }, [alerts]);

  const toggle = (id) => {
    setExpanded((prev) => {
      const n = new Set(prev);
      n.has(id) ? n.delete(id) : n.add(id);
      return n;
    });
  };

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <h1 className="page-title">Команда</h1>
          <div className="page-sub">{TEAM.length} агентов · {TEAM.filter(t => t.watcherOnline).length} watcher'ов онлайн</div>
        </div>
        <div style={{ display: "flex", gap: 6 }}>
          <button className="btn btn-ghost" onClick={() => setExpanded(new Set(TEAM.map(t => t.id)))}>Раскрыть все</button>
          <button className="btn btn-ghost" onClick={() => setExpanded(new Set())}>Свернуть все</button>
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: expanded.size > 0 ? "1fr" : "1fr 1fr", gap: 16 }}>
        {/* Render rows; expanded ones go full width */}
        <TeamGrid
          team={TEAM}
          expanded={expanded}
          toggle={toggle}
          alertsByAgent={alertsByAgent}
          onRestart={(a) => setConfirmRestart(a)}
        />
      </div>

      <ConfirmDialog
        open={!!confirmRestart}
        title={`Перезапустить watcher ${confirmRestart?.name}?`}
        message={`Watcher и сессия Claude будут остановлены и запущены заново. Текущая задача останется в Plane без изменений, но контекст агента сбросится. PID: ${confirmRestart?.watcherPid || "—"}.`}
        danger
        onCancel={() => setConfirmRestart(null)}
        onConfirm={() => {
          pushToast(`Watcher ${confirmRestart.name} перезапускается…`, "warn");
          setConfirmRestart(null);
        }}
      />
    </div>
  );
}

function TeamGrid({ team, expanded, toggle, alertsByAgent, onRestart }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
      {team.map((a) => (
        expanded.has(a.id) ? (
          <AgentBigCard
            key={a.id}
            agent={a}
            alerts={alertsByAgent[a.id] || []}
            onCollapse={() => toggle(a.id)}
            onRestart={() => onRestart(a)}
          />
        ) : (
          <AgentRow key={a.id} agent={a} alerts={alertsByAgent[a.id] || []} onExpand={() => toggle(a.id)} />
        )
      ))}
    </div>
  );
}

function AgentRow({ agent, alerts, onExpand }) {
  const health = agent.health;
  const bar =
    health === "crit" ? "var(--crit)" :
    health === "warn" ? "var(--warn)" : "var(--ok)";
  return (
    <div
      onClick={onExpand}
      className="card"
      style={{ display: "flex", alignItems: "center", padding: "12px 16px 12px 12px", cursor: "pointer", gap: 16 }}
    >
      <div style={{ width: 3, height: 36, borderRadius: 3, background: bar }} />
      <Avatar agentId={agent.id} size={42} />
      <div style={{ width: 180 }}>
        <div style={{ fontSize: 14, fontWeight: 600 }}>{agent.name}</div>
        <div className="muted" style={{ fontSize: 12 }}>{agent.roleLabel}</div>
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        {agent.currentTask ? (
          <div style={{ fontSize: 13 }}>
            <span className="mono" style={{ color: "var(--accent)" }}>PB-{agent.currentTask.seq}</span>
            <span className="dim" style={{ marginLeft: 8 }}>{agent.currentTask.title}</span>
          </div>
        ) : (
          <div className="muted" style={{ fontSize: 13 }}>— свободен —</div>
        )}
        <div style={{ display: "flex", gap: 6, marginTop: 4 }}>
          {agent.modulesCurrent.map(m => <ModuleTag key={m} name={m} small />)}
        </div>
      </div>
      <div style={{ width: 140, display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 2 }}>
        <div className="muted" style={{ fontSize: 10, textTransform: "uppercase", letterSpacing: "0.05em" }}>context</div>
        <div className="mono" style={{ fontSize: 14, fontWeight: 600, color: agent.contextPct >= 70 ? "var(--ok)" : agent.contextPct >= 30 ? "var(--warn)" : "var(--crit)" }}>{agent.contextPct}%</div>
      </div>
      <div style={{ width: 140, display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 2 }}>
        <div className="muted" style={{ fontSize: 10, textTransform: "uppercase", letterSpacing: "0.05em" }}>watcher</div>
        <div style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 12 }}>
          <span className={`dot ${agent.watcherOnline ? "ok" : "off"}`} />
          {agent.watcherOnline ? <span className="mono">{Math.floor(agent.watcherUptimeMin/60)}ч {agent.watcherUptimeMin%60}м</span> : <span style={{ color: "var(--crit)" }}>offline</span>}
        </div>
      </div>
      <div style={{ width: 110, display: "flex", justifyContent: "flex-end" }}>
        {alerts.length > 0 && <span className="pill crit">⚠ {alerts.length} алерт{alerts.length === 1 ? "" : "а"}</span>}
      </div>
      <div className="muted" style={{ fontSize: 18 }}>›</div>
    </div>
  );
}

function AgentBigCard({ agent, alerts, onCollapse, onRestart }) {
  const health = agent.health;
  const accent =
    health === "crit" ? "var(--crit)" :
    health === "warn" ? "var(--warn)" : "var(--ok)";

  // Mock comments
  const comments = [
    { ts: "2026-05-17T14:28:04Z", text: "progress: правлю Footer.tsx, осталось header" },
    { ts: "2026-05-17T14:18:30Z", text: "взял задачу, начинаю с поиска вхождений Print-X" },
    { ts: "2026-05-17T13:45:11Z", text: "вернулся к PB-47, всё ещё тыкаю интеграцию FastAPI" },
  ];

  return (
    <div className="card" style={{ overflow: "hidden" }}>
      {/* Header bar with health stripe */}
      <div style={{ display: "flex", alignItems: "center", padding: "14px 18px", gap: 16, borderBottom: "1px solid var(--border-soft)", background: `linear-gradient(90deg, ${accent}11, transparent 30%)` }}>
        <Avatar agentId={agent.id} size={56} />
        <div style={{ flex: 1 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <div style={{ fontSize: 20, fontWeight: 600 }}>{agent.name}</div>
            <span className="pill accent">{agent.roleLabel}</span>
            <span className="mono muted" style={{ fontSize: 12 }}>{agent.email}</span>
          </div>
          <div style={{ display: "flex", gap: 16, marginTop: 6, fontSize: 12, color: "var(--text-muted)" }}>
            <span><span className={`dot ${agent.watcherOnline ? "ok" : "off"}`} style={{ marginRight: 6 }} /> watcher {agent.watcherOnline ? "online" : "offline"}</span>
            {agent.watcherOnline && (
              <>
                <span>PID: <span className="mono">{agent.watcherPid}</span></span>
                <span>uptime: <span className="mono">{Math.floor(agent.watcherUptimeMin/60)}ч {agent.watcherUptimeMin%60}м</span></span>
                <span>heartbeat: <span className="mono">{agent.lastHeartbeatMin.toFixed(1)}с назад</span></span>
              </>
            )}
            {!agent.watcherOnline && (
              <span style={{ color: "var(--crit)" }}>последний heartbeat: <span className="mono">{Math.round(agent.lastHeartbeatMin)} мин назад</span></span>
            )}
          </div>
        </div>
        <div style={{ display: "flex", gap: 6 }}>
          <button className="btn">Открыть в Plane ↗</button>
          <button className="btn btn-danger" onClick={onRestart}>↻ Перезапустить watcher</button>
          <button className="btn btn-ghost" onClick={onCollapse}>Свернуть ↑</button>
        </div>
      </div>

      {/* Body — 3 columns */}
      <div style={{ display: "grid", gridTemplateColumns: "1.2fr 1fr 1fr", gap: 0 }}>
        {/* Column 1 — current task & comments */}
        <div style={{ padding: 20, borderRight: "1px solid var(--border-soft)" }}>
          <div className="muted" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.06em", marginBottom: 8 }}>Сейчас занимается</div>
          {agent.currentTask ? (
            <>
              <div style={{ fontSize: 16, fontWeight: 600 }}>
                <span className="mono" style={{ color: "var(--accent)" }}>PB-{agent.currentTask.seq}</span>
                <span style={{ marginLeft: 10 }}>{agent.currentTask.title}</span>
              </div>
              <div style={{ marginTop: 16 }}>
                <div className="muted" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.06em", marginBottom: 8 }}>Последние комментарии в Plane</div>
                {comments.slice(0, 3).map((c, i) => (
                  <div key={i} style={{ padding: "8px 12px", background: "var(--bg-elev)", borderRadius: 6, marginBottom: 6, borderLeft: "2px solid var(--border)" }}>
                    <div className="mono muted" style={{ fontSize: 11, marginBottom: 2 }}>{fmtTime(c.ts)}</div>
                    <div style={{ fontSize: 13 }}>{c.text}</div>
                  </div>
                ))}
              </div>
            </>
          ) : (
            <div className="muted" style={{ fontSize: 14 }}>— свободен — ждёт следующей задачи</div>
          )}

          {alerts.length > 0 && (
            <div style={{ marginTop: 16 }}>
              <div className="muted" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.06em", marginBottom: 8 }}>Активные алерты</div>
              {alerts.map(al => (
                <div key={al.id} style={{ display: "flex", gap: 10, padding: "8px 10px", background: "rgba(239,68,68,0.06)", border: "1px solid rgba(239,68,68,0.2)", borderRadius: 6, marginBottom: 6 }}>
                  <SeverityChip severity={al.severity} />
                  <div style={{ fontSize: 12 }}>{al.text}</div>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* Column 2 — context + tool calls */}
        <div style={{ padding: 20, borderRight: "1px solid var(--border-soft)" }}>
          <div className="muted" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.06em", marginBottom: 8 }}>Контекст</div>
          <div style={{ display: "flex", alignItems: "center", gap: 24 }}>
            <Gauge pct={agent.contextPct} size={100} />
            <div>
              <div className="muted" style={{ fontSize: 11, marginBottom: 4 }}>За день</div>
              <Sparkline data={agent.contextHistory} width={140} height={40} color={agent.contextPct >= 70 ? "var(--ok)" : agent.contextPct >= 30 ? "var(--warn)" : "var(--crit)"} />
              <div className="mono muted" style={{ fontSize: 10, marginTop: 2 }}>
                с {agent.contextHistory[0]}% до {agent.contextHistory[agent.contextHistory.length - 1]}%
              </div>
            </div>
          </div>

          <div style={{ marginTop: 20 }}>
            <div className="muted" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.06em", marginBottom: 8 }}>Среднее tool-calls на задачу</div>
            <div style={{ fontSize: 28, fontWeight: 600, fontFamily: "var(--font-mono)" }}>{agent.avgToolCalls}</div>
            <div className="muted" style={{ fontSize: 11 }}>
              {agent.avgToolCalls < 15 ? "лёгкие задачи" : agent.avgToolCalls < 25 ? "средняя сложность" : "тяжёлые задачи / debugging"}
            </div>
          </div>

          <div style={{ marginTop: 20 }}>
            <div className="muted" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.06em", marginBottom: 8 }}>Нагрузка сегодня</div>
            <Bars data={agent.todayLoad} width={220} height={28} color="var(--accent)" />
          </div>
        </div>

        {/* Column 3 — expertise */}
        <div style={{ padding: 20 }}>
          <div className="muted" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.06em", marginBottom: 8 }}>Сейчас в работе</div>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 6, marginBottom: 18 }}>
            {agent.modulesCurrent.map(m => <ModuleTag key={m} name={m} />)}
          </div>

          <div className="muted" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.06em", marginBottom: 8 }}>Историческая экспертиза</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
            {agent.modulesHistorical.map((h) => (
              <div key={h.module} style={{ display: "flex", justifyContent: "space-between", padding: "4px 0", borderBottom: "1px dashed var(--border-soft)" }}>
                <ModuleTag name={h.module} small />
                <span className="mono muted" style={{ fontSize: 11 }}>{h.lastSeen}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

window.TeamPage = TeamPage;
