/* ============================================================================
   DIVONCI WORLD — SCREENS: COUNCIL + AGENT PROFILES
   Agent management is first-class. Crown Gem state system (Viiera) and
   VV mode system (Butler / Battle / Agent) are live & interactive.
   ========================================================================== */

/* --------------------------------------------------------- AGENT SIGIL -- */
function Sigil({ a, size = 46 }) {
  if (a && a.head) {
    return (
      <div style={{
        width: size, height: size, flex: "none", borderRadius: size * 0.26, overflow: "hidden",
        border: `1px solid color-mix(in srgb, ${a.ac} 50%, var(--hairline-2))`,
        boxShadow: `0 0 14px color-mix(in srgb, ${a.ac} 28%, transparent)`, background: "var(--graphite)",
      }}>
        <img src={a.head} alt={a.name} style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }} />
      </div>
    );
  }
  return (
    <div style={{
      width: size, height: size, flex: "none", borderRadius: size * 0.26, position: "relative",
      background: `radial-gradient(circle at 32% 28%, color-mix(in srgb, ${a.ac} 60%, transparent), transparent 70%), var(--panel-3)`,
      border: `1px solid color-mix(in srgb, ${a.ac} 45%, var(--hairline-2))`, display: "grid", placeItems: "center",
    }}>
      <span style={{ width: size * 0.34, height: size * 0.34, borderRadius: size * 0.1, background: a.ac, boxShadow: `0 0 12px ${a.ac}` }} />
    </div>
  );
}

/* ---------------------------------------------------- COUNCIL OVERVIEW -- */
function CouncilOverview({ nav }) {
  return (
    <div className="screen">
      <div className="screen-head">
        <div className="title"><span className="sub">Agent Management</span>The Council</div>
        <div className="meta">Six sovereign agents, each owning a domain. Not interchangeable bots — a circuit. Domains do not cross uninvited. Optimus is the sixth seat — he audits every cycle and sets the new standard.</div>
      </div>

      {/* living circuit */}
      <CircuitView nav={nav} />

      {/* agent cards */}
      <div className="cols" style={{ gridTemplateColumns: "repeat(3, 1fr)", marginTop: "var(--s-6)" }}>
        {DW.AGENTS.map(a => (
          <div key={a.id} className="panel agent" style={{ "--ac": a.ac, cursor: "pointer" }}
            onClick={() => nav(a.id)}>
            <div className="head"><Sigil a={a} /><div><div className="name">{a.name}</div><div className="domain">{a.domain}</div></div></div>
            <p className="role">{a.role}</p>
            <div style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, color: "var(--ink-3)", marginBottom: 10, lineHeight: 1.5, minHeight: 44 }}>{a.task}</div>
            <div className="foot">
              <span style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--ink-3)" }}>{a.indicatorLabel.split("—")[0]}</span>
              <StateChip state={a.state} label={a.stateLabel} />
            </div>
          </div>
        ))}
      </div>

      <div className="cols c-2" style={{ marginTop: "var(--s-6)" }}>
        <Panel className="tight">
          <PHead icon="log" eyebrow="Council activity" title="Live circuit events" right={<button className="minilink" onClick={() => nav("log")}>full log →</button>} />
          <div className="log">
            {DW.LOG.slice(0, 6).map((e, i) => (
              <div className="logrow" key={i}>
                <span className="t">{e.t}</span><Led state={e.state} />
                <span className="msg"><b>{e.agent}</b> {e.msg}</span>
                <span className="agent-tag">{e.kind}</span>
              </div>
            ))}
          </div>
        </Panel>
        <Panel>
          <PHead icon="council" eyebrow="Circuit law" title="How work moves" />
          <div className="pbody">
            <p className="body" style={{ fontSize: 13 }}>The Council is not a hierarchy — it is a circuit. Every piece of work travels the same path, and each agent may only act inside its own domain.</p>
            <div className="kv" style={{ marginTop: 16 }}>
              <dt>Nova</dt><dd>sparks the idea — never deploys</dd>
              <dt>Viiera</dt><dd>validates & commands — sole approval gate</dd>
              <dt>Claws</dt><dd>shapes the language — editorial veto</dd>
              <dt>BroDex</dt><dd>verifies the knowledge — may block</dd>
              <dt>VV</dt><dd>executes & deploys — only what Viiera approves</dd>
              <dt>Optimus</dt><dd>audits & optimizes — sets the new standard</dd>
            </div>
          </div>
        </Panel>
      </div>
    </div>
  );
}

/* --------------------------------------------------------- CIRCUIT VIEW - */
function CircuitView({ nav }) {
  const order = ["nova", "viiera", "claws", "brodex", "vv", "optimus"];
  const [pulse, setPulse] = useState(0);
  useEffect(() => {
    const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    if (reduce) return;
    const id = setInterval(() => setPulse(p => (p + 1) % order.length), 1400);
    return () => clearInterval(id);
  }, []);
  return (
    <Panel>
      <PHead icon="bolt" eyebrow="The Council circuit" title="Nova → Viiera → Claws → BroDex → VV → Optimus ↺" right={<span style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--ink-4)" }}>live flow</span>} />
      <div className="pbody" style={{ display: "flex", alignItems: "stretch", gap: 0, flexWrap: "wrap" }}>
        {order.map((id, i) => {
          const a = DW.agent(id), on = pulse === i;
          return (
            <React.Fragment key={id}>
              <div onClick={() => nav(id)}
                style={{
                  flex: "1 1 0", minWidth: 150, cursor: "pointer", padding: "16px 14px", borderRadius: 10,
                  border: `1px solid ${on ? `color-mix(in srgb, ${a.ac} 60%, transparent)` : "var(--hairline-2)"}`,
                  background: on ? `linear-gradient(180deg, color-mix(in srgb, ${a.ac} 14%, transparent), transparent)` : "var(--panel-2)",
                  boxShadow: on ? `0 0 24px color-mix(in srgb, ${a.ac} 30%, transparent)` : "none",
                  transition: "all .5s var(--ease-out)", textAlign: "center",
                }}>
                <div style={{ display: "flex", justifyContent: "center", marginBottom: 10 }}><Sigil a={a} size={38} /></div>
                <div style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 15 }}>{a.name}</div>
                <div style={{ fontFamily: "var(--font-mono)", fontSize: 9.5, color: "var(--ink-3)", marginTop: 4, letterSpacing: "0.04em" }}>{a.circuit}</div>
              </div>
              {i < order.length - 1 && (
                <div style={{ display: "flex", alignItems: "center", padding: "0 6px", color: pulse === i || pulse === i + 1 ? DW.agent(order[i]).ac : "var(--ink-4)", transition: "color .4s" }}>
                  <Icon name="arrow" style={{ width: 18, height: 18 }} />
                </div>
              )}
            </React.Fragment>
          );
        })}
      </div>
    </Panel>
  );
}

/* ------------------------------------------------------------ CROWN GEM - */
const GEM_STATES = [
  { s: "active",  label: "Active",  desc: "Present, engaged, in command." },
  { s: "crisis",  label: "Crisis",  desc: "Alert. Urgent action required now." },
  { s: "caution", label: "Caution", desc: "Pending decision · incomplete information." },
  { s: "clear",   label: "Clear",   desc: "Task complete · systems optimal." },
  { s: "focus",   label: "Focus",   desc: "Deep focus · research · do not interrupt." },
  { s: "standby", label: "Standby", desc: "Awaiting command · systems idle." },
];
function CrownGem({ state, onState }) {
  const c = DW.STATE_META[state].c;
  const cur = GEM_STATES.find(g => g.s === state);
  return (
    <div style={{ display: "flex", flexDirection: "column", alignItems: "center" }}>
      <div style={{ width: 132, height: 132, position: "relative", margin: "6px 0 14px" }}>
        <div style={{ position: "absolute", inset: 0, borderRadius: 26, background: c, boxShadow: `0 0 0 1px color-mix(in srgb, ${c} 60%, transparent), 0 0 56px color-mix(in srgb, ${c} 55%, transparent)`, transition: "all .42s var(--ease-out)" }} className="pulse" />
        <div style={{ position: "absolute", inset: 28, borderRadius: 17, background: "rgba(8,7,14,0.62)", backdropFilter: "blur(3px)" }} />
        <div style={{ position: "absolute", inset: 50, borderRadius: 10, background: c, boxShadow: `0 0 24px ${c}`, transition: "all .42s var(--ease-out)" }} />
      </div>
      <div className="mono" style={{ fontSize: 13, color: "var(--ink)", letterSpacing: "0.1em", textTransform: "uppercase" }}>{cur.label}</div>
      <div className="note" style={{ marginTop: 6, textAlign: "center", maxWidth: "24ch" }}>{cur.desc}</div>
      <div style={{ display: "flex", flexWrap: "wrap", gap: 6, justifyContent: "center", marginTop: 16 }}>
        {GEM_STATES.map(g => (
          <button key={g.s} className="focusable" onClick={() => onState(g.s)} title={g.label}
            style={{ width: 26, height: 26, borderRadius: 8, cursor: "pointer", border: `1px solid ${state === g.s ? DW.STATE_META[g.s].c : "var(--hairline-2)"}`, background: state === g.s ? `color-mix(in srgb, ${DW.STATE_META[g.s].c} 30%, var(--panel-2))` : "var(--panel-2)", display: "grid", placeItems: "center" }}>
            <span style={{ width: 9, height: 9, borderRadius: 99, background: DW.STATE_META[g.s].c, boxShadow: `0 0 8px ${DW.STATE_META[g.s].c}` }} />
          </button>
        ))}
      </div>
      <div className="note" style={{ marginTop: 10, color: "var(--ink-4)" }}>click a state · the whole Council reads through this light</div>
    </div>
  );
}

/* --------------------------------------------------------- VV MASK/MODE - */
const VV_MODES = [
  { id: "butler", label: "Butler", icon: "agent", state: "clear", title: "Butler Mode",
    desc: "Casual execution. Warm operating assistant — organising, responding, keeping the house in order.", mask: "open",
    perms: ["responds to Diego directly", "light automation", "no destructive deploys"] },
  { id: "battle", label: "Battle / DND", icon: "shield", state: "caution", title: "Battle Mode · DND",
    desc: "Deployment focus. Mask closed. No interruption unless critical. Currently holding deploy #A7F2 for Viiera.", mask: "closed",
    perms: ["deployment focus", "interrupts suppressed", "critical-only escalation"] },
  { id: "agent", label: "Agent Swarm", icon: "nexus", state: "focus", title: "Agent Mode",
    desc: "Coordinates smaller bot crews and parallel execution threads. 4 sub-agents currently active.", mask: "half",
    perms: ["spawns sub-agents", "parallel threads", "aggregates results"] },
];
function VVMask({ mode }) {
  const m = VV_MODES.find(x => x.id === mode);
  const c = DW.STATE_META[m.state].c;
  const eyeOpen = m.mask === "open" ? 1 : m.mask === "half" ? 0.45 : 0.08;
  return (
    <div style={{ display: "flex", flexDirection: "column", alignItems: "center" }}>
      <div style={{ width: 132, height: 132, position: "relative", margin: "6px 0 14px" }}>
        <div style={{ position: "absolute", inset: 0, borderRadius: 30, background: `radial-gradient(circle at 50% 35%, color-mix(in srgb, ${m.id==='execute'?c:'var(--magenta)'} 30%, transparent), transparent 70%), var(--panel-3)`, border: `1px solid color-mix(in srgb, var(--magenta) 45%, var(--hairline-2))`, boxShadow: `0 0 40px color-mix(in srgb, var(--magenta) ${m.mask==='closed'?15:30}%, transparent)`, transition: "all .42s var(--ease-out)" }} />
        {/* eyes */}
        <div style={{ position: "absolute", inset: 0, display: "flex", justifyContent: "center", alignItems: "center", gap: 18 }}>
          {[0, 1].map(i => (
            <div key={i} style={{ width: 22, height: 22 * eyeOpen + 3, borderRadius: 99, background: c, boxShadow: `0 0 14px ${c}`, transition: "all .42s var(--ease-out)" }} />
          ))}
        </div>
        {/* mask visor line */}
        <div style={{ position: "absolute", left: 22, right: 22, top: m.mask === "closed" ? "50%" : m.mask === "half" ? "62%" : "72%", height: 2, background: `linear-gradient(90deg, transparent, var(--magenta), transparent)`, transition: "all .42s var(--ease-out)" }} />
      </div>
      <div className="mono" style={{ fontSize: 13, color: "var(--ink)", letterSpacing: "0.1em", textTransform: "uppercase" }}>{m.title}</div>
      <div className="note" style={{ marginTop: 6, textAlign: "center", maxWidth: "30ch" }}>Mask {m.mask}</div>
    </div>
  );
}

/* ----------------------------------------------------------- AGENT PROFILE */
function AgentProfile({ agentId, nav }) {
  const a = DW.agent(agentId);
  const [gemState, setGemState] = useState(a.state);
  const [vvMode, setVVMode] = useState("battle");
  const isViiera = a.id === "viiera", isVV = a.id === "vv";
  const liveState = isViiera ? gemState : isVV ? VV_MODES.find(m => m.id === vvMode).state : a.state;

  return (
    <div className="screen">
      <div className="screen-head">
        <div className="title"><span className="sub">{a.domain} Domain</span>{a.name}</div>
        <div className="screen-actions">
          <button className="btn ghost" onClick={() => nav("council")}>← Council</button>
          <button className="btn ghost" onClick={() => nav("skill:" + a.id)}>Skill tree</button>
          <button className="btn ghost" onClick={() => nav("agent-development")}>Development</button>
          <button className="btn primary" onClick={() => nav("log")}>Activity log</button>
        </div>
      </div>

      {/* profile header — surface tints toward domain colour */}
      <Panel style={{ overflow: "hidden", "--ac": a.ac }}>
        <div style={{ height: 3, background: `linear-gradient(90deg, transparent, ${a.ac}, transparent)` }} />
        <div style={{ display: "grid", gridTemplateColumns: "230px 1fr 240px", minHeight: 300 }}>
          {/* portrait slot — character key art */}
          {a.art ? (
            <div style={{ position: "relative", borderRight: "1px solid var(--hairline)", overflow: "hidden", background: "var(--graphite)" }}>
              <img src={a.art} alt={a.name + " key art"} style={{ width: "100%", height: "100%", objectFit: "cover", objectPosition: "center top", display: "block" }} />
              <div style={{ position: "absolute", inset: 0, background: `linear-gradient(180deg, transparent 55%, color-mix(in srgb, var(--obsidian) 78%, transparent))`, pointerEvents: "none" }} />
              <div style={{ position: "absolute", left: 14, right: 14, bottom: 12 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                  <span style={{ width: 7, height: 7, borderRadius: 99, background: a.ac, boxShadow: `0 0 8px ${a.ac}`, flex: "none" }} />
                  <span style={{ fontFamily: "var(--font-mono)", fontSize: 9, letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--ink-2)" }}>{a.domain} · key art</span>
                </div>
              </div>
            </div>
          ) : (
            <div className="slot" style={{ border: "none", borderRight: "1px solid var(--hairline)", borderRadius: 0, background: `repeating-linear-gradient(135deg, color-mix(in srgb, ${a.ac} 7%, transparent) 0 10px, transparent 10px 20px), var(--graphite)` }}>
              <div className="tag" style={{ color: "var(--ink-3)" }}>{a.name.toUpperCase()}<small>portrait / key art<br />character render<br /><span style={{ color: a.ac }}>drop asset here</span></small></div>
            </div>
          )}
          {/* identity + boundaries */}
          <div style={{ padding: "var(--s-7)" }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 12 }}>
              <div>
                <div style={{ fontFamily: "var(--font-display)", fontSize: 26, fontWeight: 600 }}>{a.name}</div>
                <div className="mono" style={{ color: "var(--violet-ink)", letterSpacing: "0.1em", fontSize: 11, marginTop: 5, textTransform: "uppercase" }}>{a.role}</div>
              </div>
              <StateChip state={liveState} label={isViiera ? GEM_STATES.find(g=>g.s===gemState).label : a.stateLabel} tag={a.indicator} />
            </div>
            <p className="body" style={{ marginTop: 14, fontSize: 13.5 }}>{a.desc}</p>
            <div className="hr tight" />
            <div className="eyebrow">Current task</div>
            <div style={{ display: "flex", alignItems: "center", gap: 10, marginTop: 10, padding: "11px 14px", borderRadius: 8, background: "var(--graphite)", border: "1px solid var(--hairline)" }}>
              <Led state={liveState} /><span style={{ fontSize: 13, color: "var(--ink)" }}>{a.task}</span>
            </div>
            <div className="eyebrow" style={{ marginTop: 18 }}>Operating boundaries · domain does not cross uninvited</div>
            <div className="chips" style={{ marginTop: 10 }}>
              {a.boundaries.map((b, i) => <span key={i} className="evchip"><Icon name={i === 0 ? "check" : "shield"} style={{ width: 11, height: 11, color: a.ac }} />{b}</span>)}
            </div>
          </div>
          {/* state instrument: gem / mask / generic */}
          <div className="well" style={{ borderRadius: 0, border: "none", borderLeft: "1px solid var(--hairline)", padding: "var(--s-7) var(--s-6)", display: "flex", flexDirection: "column", justifyContent: "center" }}>
            <div className="eyebrow" style={{ justifyContent: "center", marginBottom: 6 }}>{isViiera ? "Crown Gem" : isVV ? "VV Core · Mask" : "State indicator"}</div>
            {isViiera ? <CrownGem state={gemState} onState={setGemState} />
              : isVV ? <VVMask mode={vvMode} />
                : <div style={{ textAlign: "center", padding: 20 }}><div style={{ width: 90, height: 90, margin: "0 auto", borderRadius: 24, background: a.ac, boxShadow: `0 0 50px ${a.ac}` }} className="pulse" /><div className="note" style={{ marginTop: 14 }}>{a.indicatorLabel}</div></div>}
          </div>
        </div>
      </Panel>

      {/* VV mode selector */}
      {isVV && (
        <Panel style={{ marginTop: "var(--s-6)" }}>
          <PHead icon="mask" eyebrow="Mode selector" title="Butler · Battle / DND · Agent" right={<StateChip state={VV_MODES.find(m=>m.id===vvMode).state} label={VV_MODES.find(m=>m.id===vvMode).label} />} />
          <div className="pbody">
            <div className="seg" style={{ marginBottom: 16 }}>
              {VV_MODES.map(m => <button key={m.id} className={vvMode === m.id ? "on" : ""} onClick={() => setVVMode(m.id)}><Icon name={m.icon} style={{ width: 12, height: 12, marginRight: 6, verticalAlign: "-2px" }} />{m.label}</button>)}
            </div>
            <div className="cols c-3">
              {VV_MODES.map(m => (
                <div key={m.id} style={{ padding: 16, borderRadius: 10, border: `1px solid ${vvMode === m.id ? "color-mix(in srgb, var(--magenta) 45%, transparent)" : "var(--hairline-2)"}`, background: vvMode === m.id ? "linear-gradient(180deg, color-mix(in srgb, var(--magenta) 10%, transparent), transparent)" : "var(--panel-2)", opacity: vvMode === m.id ? 1 : 0.6, transition: "all .3s" }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 8 }}><Icon name={m.icon} style={{ width: 16, height: 16, color: DW.STATE_META[m.state].c }} /><b style={{ fontSize: 14 }}>{m.title}</b></div>
                  <p style={{ fontSize: 12.5, color: "var(--ink-2)", margin: "0 0 10px", lineHeight: 1.5 }}>{m.desc}</p>
                  {m.perms.map((p, i) => <div key={i} style={{ display: "flex", gap: 7, fontSize: 11.5, color: "var(--ink-3)", marginBottom: 4 }}><Icon name="check" style={{ width: 12, height: 12, color: DW.STATE_META[m.state].c, flex: "none" }} />{p}</div>)}
                </div>
              ))}
            </div>
          </div>
        </Panel>
      )}

      {/* lower grid: telemetry, tools, memory, recent activity */}
      <div className="cols c-4" style={{ marginTop: "var(--s-6)" }}>
        <Panel className="tight">
          <PHead icon="workrate" eyebrow="Live telemetry" />
          <div className="pbody">
            {a.stats.map((s, i) => (
              <div key={i} style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", padding: "8px 0", borderBottom: i < a.stats.length - 1 ? "1px solid var(--hairline)" : "none" }}>
                <span style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--ink-3)", textTransform: "uppercase", letterSpacing: "0.08em" }}>{s.k}</span>
                <span style={{ fontFamily: "var(--font-mono)", fontSize: 18, fontWeight: 600, color: s.state ? DW.STATE_META[s.state].c : "var(--ink)" }}>{s.v}</span>
              </div>
            ))}
            <div style={{ marginTop: 10 }}><Sparkline data={[5,6,5,7,6,8,7,9]} color={a.ac} h={36} /></div>
          </div>
        </Panel>
        <Panel className="tight">
          <PHead icon="settings" eyebrow="Tool permissions" />
          <div className="pbody tight">
            {a.tools.map((t, i) => (
              <div key={i} style={{ display: "flex", alignItems: "center", gap: 9, padding: "10px 16px", borderBottom: i < a.tools.length - 1 ? "1px solid var(--hairline)" : "none", opacity: t.ok ? 1 : 0.55 }}>
                <Icon name={t.ok ? "check" : "lock"} style={{ width: 14, height: 14, color: t.ok ? "var(--state-clear)" : "var(--ink-4)", flex: "none" }} />
                <span style={{ flex: 1, fontSize: 12.5, color: t.ok ? "var(--ink)" : "var(--ink-3)" }}>{t.n}</span>
                {t.gated && <span className="todochip" style={{ fontSize: 8.5 }}>gated</span>}
                {t.why && <span title={t.why} style={{ fontFamily: "var(--font-mono)", fontSize: 9, color: "var(--ink-4)" }}>{t.why}</span>}
              </div>
            ))}
          </div>
        </Panel>
        <Panel className="tight">
          <PHead icon="nexus" eyebrow="Memory areas" />
          <div className="pbody" style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            {a.memory.map((m, i) => (
              <div key={i} style={{ display: "flex", alignItems: "center", gap: 9, padding: "9px 11px", borderRadius: 7, background: "var(--panel-2)", border: "1px solid var(--hairline)" }}>
                <span style={{ width: 7, height: 7, borderRadius: 99, background: a.ac, boxShadow: `0 0 7px ${a.ac}`, flex: "none" }} />
                <span style={{ fontSize: 12.5 }}>{m}</span>
              </div>
            ))}
          </div>
        </Panel>
        <Panel className="tight">
          <PHead icon="log" eyebrow="Recent activity" right={<button className="minilink" onClick={() => nav("log")}>all →</button>} />
          <div className="log">
            {DW.LOG.filter(e => e.agent === a.name).slice(0, 5).map((e, i) => (
              <div key={i} style={{ display: "grid", gridTemplateColumns: "62px 10px 1fr", gap: 8, alignItems: "center", padding: "9px 16px", borderBottom: "1px solid var(--hairline)" }}>
                <span style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--ink-4)" }}>{e.t}</span>
                <Led state={e.state} size={7} />
                <span style={{ fontSize: 12, color: "var(--ink-2)" }}>{e.msg}</span>
              </div>
            ))}
            {DW.LOG.filter(e => e.agent === a.name).length === 0 && <div className="emptystate" style={{ padding: 28 }}><div className="note">No recent events</div></div>}
          </div>
        </Panel>
      </div>

      {/* capability tree + token budget */}
      <div className="cols c-8-4" style={{ marginTop: "var(--s-6)" }}>
        <SkillTreeInline a={a} nav={nav} />
        <AgentTokenPanel a={a} />
      </div>

      {/* Development Record — competence / proof / promotion history */}
      {typeof AgentDevelopmentRecord === "function" && <AgentDevelopmentRecord agentId={a.id} nav={nav} />}
    </div>
  );
}

/* ----------------------------------------------- skill tree (inline) ---- */
function skillTreeFor(a) {
  if (DW.SKILLS[a.id]) return DW.SKILLS[a.id];
  const ok = a.tools.filter(t => t.ok), locked = a.tools.find(t => !t.ok);
  return { tiers: [
    [{ n: a.domain + " Core", s: "lit" }],
    ok.slice(0, 3).map((t, i) => ({ n: t.n, s: i < 2 ? "lit" : "avail" })),
    [{ n: "Autonomy L3", s: "locked", why: "requires Diego grant" }].concat(locked ? [{ n: locked.n, s: "locked", why: locked.why }] : []),
  ] };
}
function SkillTreeInline({ a, nav }) {
  const tiers = skillTreeFor(a).tiers;
  const [sel, setSel] = useState(null);
  return (
    <Panel style={{ "--ac": a.ac }}>
      <PHead icon="skill" eyebrow="Capability tree" title={`${a.name} — unlock path`} right={
        <div style={{ display: "flex", gap: 12 }}>
          <span style={{ fontFamily: "var(--font-mono)", fontSize: 9, color: "var(--ink-3)", display: "inline-flex", gap: 5, alignItems: "center" }}><span style={{ width: 8, height: 8, borderRadius: 99, background: a.ac, boxShadow: `0 0 8px ${a.ac}` }} />lit</span>
          <span style={{ fontFamily: "var(--font-mono)", fontSize: 9, color: "var(--ink-3)", display: "inline-flex", gap: 5, alignItems: "center" }}><span style={{ width: 8, height: 8, borderRadius: 99, background: "var(--ink-3)" }} />avail</span>
          <span style={{ fontFamily: "var(--font-mono)", fontSize: 9, color: "var(--ink-4)", display: "inline-flex", gap: 5, alignItems: "center" }}><Icon name="lock" style={{ width: 10, height: 10 }} />locked</span>
        </div>} />
      <div className="pbody">
        <div style={{ display: "grid", gridTemplateColumns: `repeat(${tiers.length}, 1fr)`, gap: 14, alignItems: "center" }}>
          {tiers.map((tier, ti) => (
            <div key={ti} style={{ display: "flex", flexDirection: "column", gap: 12, alignItems: "center" }}>
              <div style={{ fontFamily: "var(--font-mono)", fontSize: 8.5, color: "var(--ink-4)", letterSpacing: "0.1em", textTransform: "uppercase" }}>Tier {ti + 1}</div>
              {tier.map((node, ni) => {
                const lit = node.s === "lit", locked = node.s === "locked";
                return (
                  <button key={ni} className="focusable" onClick={() => setSel({ ...node, tier: ti + 1 })} style={{
                    display: "inline-flex", alignItems: "center", gap: 8, padding: "9px 13px", borderRadius: 99, fontSize: 12, cursor: "pointer", width: "100%", justifyContent: "center",
                    border: `1px solid ${lit ? `color-mix(in srgb, ${a.ac} 55%, transparent)` : "var(--hairline-2)"}`,
                    background: sel && sel.n === node.n ? "var(--panel-3)" : "var(--panel-2)", color: locked ? "var(--ink-4)" : "var(--ink)",
                    boxShadow: lit ? `0 0 16px color-mix(in srgb, ${a.ac} 28%, transparent)` : "none",
                  }}>
                    {locked ? <Icon name="lock" style={{ width: 11, height: 11 }} /> : <span style={{ width: 7, height: 7, borderRadius: 99, background: lit ? a.ac : "var(--ink-3)", boxShadow: lit ? `0 0 8px ${a.ac}` : "none", flex: "none" }} />}
                    {node.n}
                  </button>
                );
              })}
            </div>
          ))}
        </div>
        <div style={{ marginTop: 14, padding: "11px 13px", borderRadius: 8, background: "var(--panel-2)", border: "1px solid var(--hairline)", minHeight: 52 }}>
          {sel ? (
            <div>
              <div style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
                {sel.s === "locked" ? <Icon name="lock" style={{ width: 14, height: 14, color: "var(--ink-4)" }} /> : <span style={{ width: 9, height: 9, borderRadius: 99, background: sel.s === "lit" ? a.ac : "var(--ink-3)", boxShadow: sel.s === "lit" ? `0 0 8px ${a.ac}` : "none" }} />}
                <b style={{ fontSize: 13.5 }}>{sel.n}</b>
                <span className="sbadge" style={{ color: sel.s === "lit" ? "var(--violet-ink)" : sel.s === "locked" ? "var(--ink-4)" : "var(--ink-2)", fontSize: 8.5 }}>{sel.s === "lit" ? "Unlocked" : sel.s === "locked" ? "Locked" : "Available"}</span>
                <span className="evchip" style={{ fontSize: 9 }}>Tier {sel.tier}</span>
              </div>
              <p style={{ fontSize: 12, color: "var(--ink-2)", margin: "8px 0 0", lineHeight: 1.5 }}>{sel.s === "lit" ? "Active — contributes to live telemetry." : sel.s === "locked" ? (sel.why ? "Locked · requires " + sel.why + "." : "Locked by doctrine — needs a Diego grant.") : "Reachable next. No glow until unlocked."}</p>
            </div>
          ) : <div className="note">Select a node to inspect its capability.</div>}
        </div>
      </div>
    </Panel>
  );
}

/* -------------------------------------------- agent token budget panel -- */
function AgentTokenPanel({ a }) {
  const base = DW.AGENT_TOKENS[a.id] || { spent: 0, limit: 1000000 };
  const [limit, setLimit] = useState(base.limit);
  const pct = Math.min(100, Math.round(base.spent / limit * 100));
  const over = base.spent > limit;
  return (
    <Panel glow style={{ "--ac": a.ac }}>
      <PHead icon="finance" eyebrow="Token budget" right={over ? <StateChip state="crisis" label="Over" /> : <StateChip state={pct > 85 ? "caution" : "clear"} label={pct + "%"} />} />
      <div className="pbody">
        <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between" }}>
          <span style={{ fontFamily: "var(--font-mono)", fontSize: 26, fontWeight: 600, color: over ? "var(--state-crisis)" : "var(--ink)" }}>{DW.fmtTok(base.spent)}</span>
          <span style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--ink-3)" }}>/ {DW.fmtTok(limit)} limit</span>
        </div>
        <div className="riskbar" style={{ height: 8, marginTop: 10 }}><i style={{ width: `${pct}%`, background: over ? "var(--state-crisis)" : pct > 85 ? "var(--state-caution)" : a.ac }} /></div>
        <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--ink-4)", marginTop: 7 }}>spend across all {a.name} work · 30-day window</div>
        <div className="eyebrow" style={{ marginTop: 16 }}>Set limit</div>
        <div style={{ display: "flex", alignItems: "center", gap: 10, marginTop: 8 }}>
          <button className="btn ghost" onClick={() => setLimit(l => Math.max(250000, l - 250000))} style={{ padding: "6px 14px", fontSize: 16 }}>−</button>
          <div style={{ flex: 1, textAlign: "center", fontFamily: "var(--font-mono)", fontSize: 15, fontWeight: 600 }}>{DW.fmtTok(limit)}</div>
          <button className="btn ghost" onClick={() => setLimit(l => l + 250000)} style={{ padding: "6px 14px", fontSize: 16 }}>+</button>
        </div>
        <div className="note" style={{ marginTop: 8 }}>Hard cap halts {a.name} at the limit until you raise it.</div>
      </div>
    </Panel>
  );
}

Object.assign(window, { CouncilOverview, CircuitView, AgentProfile, Sigil, CrownGem, VVMask, VV_MODES, GEM_STATES, SkillTreeInline, AgentTokenPanel });
