/* ============================================================================
   DIVONCI WORLD — AGENT MODEL ROUTING  (screens_agent_model_routing.jsx)
   ----------------------------------------------------------------------------
   A governance/config surface inside Agent Development. Three lenses:

     1. Routing roster      — every Council seat: role, default + max tier,
                              default/fallback profile, protected flag, runner.
     2. Model profile library — provider · family · model · tier · bands ·
                              strengths · limits · active.
     3. Mission routing preview — pick mission type / risk / protected runtime;
                              shows which agent Viiera picks, which rung (Eagle /
                              Falcon / Hawk …) comes out, why, the runner target
                              and the escalation path.

   Doctrine (option B): agent = persona, provider family = engine, tier = the
   "version" that comes out. Viiera is the master router; she executes nothing.

   Data: window.DWSnapshot → agentModelProfiles, agentRoutingPolicies,
   routingRunners (+ DW.agent for Council persona). Live Worker snapshot OR the
   labelled fixture mirror. This surface is display-first — no model execution,
   no DB writes, no secrets.
   ========================================================================== */
const { useState: useStateAmr, useMemo: useMemoAmr, useEffect: useEffectAmr } = React;

/* ── snapshot hook (unique name) ──────────────────────────────────────────── */
function useAmrSnapshot() {
  const [, force] = useStateAmr(0);
  useEffectAmr(() => {
    const un = DWSnapshot.subscribe(() => force((n) => n + 1));
    DWSnapshot.load();
    return un;
  }, []);
  return { snap: DWSnapshot.get(), state: DWSnapshot.state(), source: DWSnapshot.source() };
}

/* council persona resolver (the real roster lives in DW.AGENTS) */
function amrAgent(id) {
  return (typeof DW !== "undefined" && DW.agent && DW.agent(id)) ||
    { id, name: id, ac: "var(--ink-3)", role: "", domain: "" };
}

/* tier vocabulary — fast | balanced | deep | max */
const AMR_TIER_ORDER = ["fast", "balanced", "deep", "max"];
const AMR_TIER_META = {
  fast:     { label: "Fast",     c: "var(--state-clear)" },
  balanced: { label: "Balanced", c: "var(--state-focus)" },
  deep:     { label: "Deep",     c: "var(--state-active)" },
  max:      { label: "Max",      c: "var(--gold)" },
};
const AMR_BAND_C = { low: "var(--state-clear)", moderate: "var(--state-focus)", high: "var(--state-caution)", premium: "var(--state-crisis)", slow: "var(--state-caution)", fast: "var(--state-clear)" };

/* ── escalation chain derives PURELY from the snapshot policy row.
   Edits are not written from the browser — the path editor drafts a structured
   Worker payload (see AmrPathEditor) that Codex/the Worker applies to
   agent_routing_policies. Until then the snapshot (fixture today) is the truth. */
function amrDerivedChain(pol) {
  if (Array.isArray(pol.escalation_chain) && pol.escalation_chain.length) return pol.escalation_chain.slice();
  return AMR_TIER_ORDER.filter((t) => pol.tier_ladder && pol.tier_ladder[t]).map((t) => pol.tier_ladder[t]);
}
function amrApprovalMode(pol) { return pol.human_approval || "auto"; } // auto | always | never

function AmrAvatar({ agent, size = 32 }) {
  const ac = agent.ac || agent.accent || "var(--violet-bright)";
  const head = agent.head && typeof window.assetUrl === "function" ? window.assetUrl(agent.head) : agent.head;
  if (head) return <img src={head} alt={agent.name} style={{ width: size, height: size, borderRadius: 8, objectFit: "cover", border: `1px solid color-mix(in srgb, ${ac} 55%, transparent)`, flex: "none" }} />;
  return <span style={{ width: size, height: size, borderRadius: 8, flex: "none", display: "grid", placeItems: "center", background: `color-mix(in srgb, ${ac} 20%, var(--panel-2))`, border: `1px solid color-mix(in srgb, ${ac} 45%, transparent)`, color: ac, fontFamily: "var(--font-display)", fontWeight: 700, fontSize: size * 0.42 }}>{(agent.name || "?").slice(0, 1).toUpperCase()}</span>;
}

function TierBadge({ tier, small }) {
  const m = AMR_TIER_META[tier] || AMR_TIER_META.fast;
  return <span className="amr-tier" style={{ color: m.c, borderColor: `color-mix(in srgb, ${m.c} 42%, transparent)`, fontSize: small ? 9 : 10 }}><span className="led" style={{ background: m.c }} />{m.label}</span>;
}

/* profile chip — codename (Eagle/Falcon/Hawk) when present, else model name */
function ProfileChip({ profile, dim }) {
  if (!profile) return <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--ink-4)" }}>—</span>;
  const m = AMR_TIER_META[profile.tier] || AMR_TIER_META.fast;
  return (
    <span className="amr-profchip" style={{ opacity: dim ? 0.6 : 1, borderColor: `color-mix(in srgb, ${m.c} 36%, transparent)` }} title={`${profile.provider} · ${profile.model_name}`}>
      {profile.codename && <b style={{ color: m.c }}>{profile.codename}</b>}
      <span style={{ color: profile.codename ? "var(--ink-3)" : "var(--ink-2)" }}>{profile.model_name}</span>
    </span>
  );
}

/* ════════════════════════════════════════════════════════════════════════════
   1 · ROUTING ROSTER
   ════════════════════════════════════════════════════════════════════════ */
function AmrRoster({ policies, profilesById, runnersById, onEdit }) {
  return (
    <Panel className="tight" style={{ gridColumn: "1 / -1" }}>
      <PHead icon="crown" eyebrow="Routing roster · who Viiera can route to"
        right={<span style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, color: "var(--ink-3)" }}>{policies.length} seats</span>} />
      <div className="amr-roster">
        <div className="amr-rrow amr-rhead">
          <span>Agent · role</span><span className="amr-hide-sm">Policy</span>
          <span>Default → max</span><span>Default profile</span><span className="amr-hide-md">Fallback</span>
          <span style={{ textAlign: "center" }}>Protected</span><span className="amr-hide-md">Preferred runner</span>
          <span></span>
        </div>
        {policies.map((p) => {
          const a = amrAgent(p.agent_id);
          const chain = amrDerivedChain(p).filter((id) => profilesById[id]);
          const def = profilesById[chain[0]] || profilesById[p.default_profile];
          const fb = profilesById[p.fallback_profile];
          const runner = p.preferred_runner ? runnersById[p.preferred_runner] : null;
          return (
            <div key={p.agent_id} className="amr-rrow" style={{ "--ac": a.ac || a.accent }}>
              <span className="amr-rid">
                <AmrAvatar agent={a} size={30} />
                <span style={{ minWidth: 0 }}>
                  <span className="nm">{a.name}{p.router && <span className="amr-routertag">router</span>}</span>
                  <span className="rl">{p.role_summary}</span>
                </span>
              </span>
              <span className="amr-hide-sm"><span className="amr-policy">{p.policy}</span></span>
              <span style={{ display: "inline-flex", alignItems: "center", gap: 6, flexWrap: "wrap" }}><TierBadge tier={p.default_tier} small /><span style={{ color: "var(--ink-4)" }}>→</span><TierBadge tier={p.max_tier} small /></span>
              <span><ProfileChip profile={def} dim={def && !def.active} /></span>
              <span className="amr-hide-md"><ProfileChip profile={fb} dim /></span>
              <span style={{ textAlign: "center" }}>
                {p.protected_execution_required
                  ? <span className="amr-yes" title="Protected execution required"><Icon name="lock" style={{ width: 11, height: 11 }} /> yes</span>
                  : <span style={{ color: "var(--ink-4)", fontFamily: "var(--font-mono)", fontSize: 11 }}>no</span>}
              </span>
              <span className="amr-hide-md">
                {runner
                  ? <span className="amr-runner" title={`owned by ${amrAgent(runner.owner_agent_id).name}`}><Icon name={runner.protected ? "shield" : "device"} style={{ width: 11, height: 11, color: runner.protected ? "var(--state-caution)" : "var(--ink-3)" }} />{runner.label}</span>
                  : <span style={{ color: "var(--ink-4)", fontFamily: "var(--font-mono)", fontSize: 10.5 }}>—</span>}
              </span>
              <span style={{ textAlign: "right" }}>
                <button className="amr-editbtn-sm focusable" title={`Edit ${a.name}'s escalation path`} onClick={() => onEdit(p.agent_id)}><Icon name="branch" style={{ width: 13, height: 13 }} /></button>
              </span>
            </div>
          );
        })}
      </div>
    </Panel>
  );
}

/* ════════════════════════════════════════════════════════════════════════════
   2 · MODEL PROFILE LIBRARY (grouped by provider family)
   ════════════════════════════════════════════════════════════════════════ */
function AmrProfileLibrary({ profiles }) {
  const families = useMemoAmr(() => {
    const order = ["Claude", "Codex", "Gemini", "Nemotron", "Manus", "Nova"];
    const m = {};
    profiles.forEach((p) => (m[p.family] || (m[p.family] = [])).push(p));
    Object.values(m).forEach((list) => list.sort((a, b) => AMR_TIER_ORDER.indexOf(a.tier) - AMR_TIER_ORDER.indexOf(b.tier)));
    return Object.keys(m).sort((a, b) => { const i = order.indexOf(a), j = order.indexOf(b); return (i < 0 ? 99 : i) - (j < 0 ? 99 : j); }).map((k) => [k, m[k]]);
  }, [profiles]);

  return (
    <Panel className="tight" style={{ gridColumn: "1 / -1" }}>
      <PHead icon="layers" eyebrow="Model profile library"
        right={<span style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, color: "var(--ink-3)" }}>{profiles.length} profiles · {families.length} families</span>} />
      <div className="amr-lib">
        {families.map(([fam, list]) => (
          <div key={fam} className="amr-fam">
            <div className="amr-fam-head">
              <span className="amr-fam-name">{fam}</span>
              <span className="amr-fam-provider">{list[0].provider}</span>
              <span className="amr-fam-count">{list.length}</span>
            </div>
            <div className="amr-cards">
              {list.map((p) => {
                const m = AMR_TIER_META[p.tier] || AMR_TIER_META.fast;
                return (
                  <div key={p.id} className={"amr-card" + (p.active ? "" : " planned")} style={{ "--tc": m.c }}>
                    <div className="amr-card-top">
                      <div style={{ minWidth: 0 }}>
                        {p.codename
                          ? <div className="amr-card-code" style={{ color: m.c }}>{p.codename}</div>
                          : <div className="amr-card-code" style={{ color: "var(--ink-2)" }}>{p.model_name}</div>}
                        <div className="amr-card-model">{p.codename ? p.model_name : p.provider}</div>
                      </div>
                      <div style={{ display: "flex", flexDirection: "column", gap: 5, alignItems: "flex-end", flex: "none" }}>
                        <TierBadge tier={p.tier} />
                        {p.protected && <span className="amr-protpill"><Icon name="lock" style={{ width: 9, height: 9 }} /> protected</span>}
                        {p.planned && <span className="amr-protpill" style={{ color: "var(--ink-3)", borderColor: "var(--hairline-3)" }}>not subscribed</span>}
                      </div>
                    </div>
                    <div className="amr-bands">
                      <span><i>cost</i><b style={{ color: AMR_BAND_C[p.cost_band] || "var(--ink-2)" }}>{p.cost_band}</b></span>
                      <span><i>latency</i><b style={{ color: AMR_BAND_C[p.latency_band] || "var(--ink-2)" }}>{p.latency_band}</b></span>
                      <span><i>context</i><b>{p.context_band}</b></span>
                    </div>
                    <div className="amr-sl">
                      <div className="amr-sl-h" style={{ color: "var(--state-clear)" }}>strengths</div>
                      <ul>{p.strengths.map((s, i) => <li key={i}>{s}</li>)}</ul>
                    </div>
                    <div className="amr-sl">
                      <div className="amr-sl-h" style={{ color: "var(--state-caution)" }}>limits</div>
                      <ul>{p.limits.map((s, i) => <li key={i}>{s}</li>)}</ul>
                    </div>
                    <div className="amr-card-foot">
                      <span className="amr-active"><Led state={p.active ? "clear" : "standby"} size={6} />{p.active ? "active" : p.planned ? "planned · not subscribed" : "inactive"}</span>
                      <span className="amr-pid">{p.id}</span>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        ))}
      </div>
    </Panel>
  );
}

/* ════════════════════════════════════════════════════════════════════════════
   3 · MISSION ROUTING PREVIEW
   ════════════════════════════════════════════════════════════════════════ */
const AMR_MISSIONS = [
  { id: "frontend", label: "Frontend / UI build", agent: "claws", icon: "comms" },
  { id: "backend", label: "Backend / data + migrations", agent: "brodex", icon: "database" },
  { id: "ops", label: "Deploy / ops automation", agent: "vv", icon: "power" },
  { id: "audit", label: "Workflow audit / optimization", agent: "optimus", icon: "chart" },
  { id: "creative", label: "Creative / ideation", agent: "nova", icon: "spark" },
  { id: "command", label: "Strategy / command decision", agent: "viiera", icon: "crown" },
];
const AMR_RISKS = [
  { id: "low", label: "Low" }, { id: "medium", label: "Medium" },
  { id: "high", label: "High" }, { id: "critical", label: "Critical" },
];
const AMR_RISK_IDX = { low: 0, medium: 1, high: 2, critical: 2 };

/* deterministic router: which agent, which profile (resolving around inactive /
   not-yet-subscribed engines), runner, escalation chain — honouring a manual
   override when one is saved. */
function amrRoute(missionId, risk, protectedRT, policies, profilesById, runnersById) {
  const mission = AMR_MISSIONS.find((m) => m.id === missionId) || AMR_MISSIONS[0];
  const pol = policies.find((p) => p.agent_id === mission.agent);
  if (!pol) return null;
  let chain = amrDerivedChain(pol).filter((id) => profilesById[id]);
  if (!chain.length) chain = [pol.default_profile].filter((id) => profilesById[id]);

  // risk indexes into the chain: low → first rung, high/critical → last
  let idx = (risk === "high" || risk === "critical") ? chain.length - 1 : AMR_RISK_IDX[risk];
  idx = Math.max(0, Math.min(idx, chain.length - 1));

  // resolve to the first ACTIVE profile from idx onward (skips Manus etc. until
  // subscribed); else search the whole chain; else the policy fallback.
  let profile = null, chosenIdx = idx, skippedInactive = false;
  for (let i = idx; i < chain.length; i++) { const p = profilesById[chain[i]]; if (p && p.active) { profile = p; chosenIdx = i; break; } if (p) skippedInactive = true; }
  if (!profile) for (let i = 0; i < chain.length; i++) { const p = profilesById[chain[i]]; if (p && p.active) { profile = p; chosenIdx = i; break; } }
  let fellBackOut = false;
  const fb = profilesById[pol.fallback_profile];
  if (!profile && fb && fb.active && !chain.includes(pol.fallback_profile)) { profile = fb; fellBackOut = true; }

  const intended = profilesById[chain[idx]] || null;
  const defaultIdx = Math.max(0, chain.indexOf((pol.tier_ladder && pol.tier_ladder[pol.default_tier]) || pol.default_profile));
  const atDefault = chosenIdx === defaultIdx && !skippedInactive;

  const needProtected = !!(protectedRT || pol.protected_execution_required || (profile && profile.protected));
  let runner = pol.preferred_runner ? runnersById[pol.preferred_runner] : null;
  if (needProtected && (!runner || !runner.protected)) runner = Object.values(runnersById).find((r) => r.owner_agent_id === pol.agent_id && r.protected) || runner;
  const runnerReady = runner && runner.state === "online" && runner.health !== "down";
  const blocked = needProtected && !runnerReady;

  const appMode = amrApprovalMode(pol);
  const humanApproval = appMode === "always" ? true : appMode === "never" ? false : (risk === "critical" || needProtected);

  const steps = chain.map((id, i) => ({ kind: "profile", profile: profilesById[id], current: i === chosenIdx, inactive: profilesById[id] && !profilesById[id].active }));
  if (fellBackOut) steps.push({ kind: "fallback", profile: fb, current: true });
  if (humanApproval) steps.push({ kind: "approval" });

  return { mission, pol, agent: amrAgent(pol.agent_id), profile, intended, chosenIdx, atDefault, skippedInactive, fellBackOut, needProtected, runner, runnerReady, blocked, humanApproval, appMode, steps, chain };
}

function AmrMissionPreview({ policies, profilesById, runnersById, onEdit }) {
  const [missionId, setMissionId] = useStateAmr("frontend");
  const [risk, setRisk] = useStateAmr("medium");
  const [protectedRT, setProtectedRT] = useStateAmr(false);
  const r = useMemoAmr(() => amrRoute(missionId, risk, protectedRT, policies, profilesById, runnersById),
    [missionId, risk, protectedRT, policies, profilesById, runnersById]);
  if (!r) return null;
  const ac = r.agent.ac || r.agent.accent || "var(--violet-bright)";

  return (
    <Panel className="tight" style={{ gridColumn: "1 / -1" }}>
      <PHead icon="branch" eyebrow="Mission routing preview · what Viiera would choose"
        right={<span className="amr-routerby"><Icon name="crown" style={{ width: 12, height: 12, color: "var(--violet-ink)" }} /> routed by Viiera</span>} />
      <div className="amr-preview">
        {/* controls */}
        <div className="amr-controls">
          <div className="amr-ctl">
            <div className="eyebrow">Mission type</div>
            <div className="amr-mlist">
              {AMR_MISSIONS.map((m) => (
                <button key={m.id} className={"amr-mbtn focusable" + (missionId === m.id ? " on" : "")} onClick={() => setMissionId(m.id)}>
                  <Icon name={m.icon} style={{ width: 14, height: 14 }} />{m.label}
                </button>
              ))}
            </div>
          </div>
          <div className="amr-ctl">
            <div className="eyebrow">Mission risk</div>
            <div className="amr-seg">
              {AMR_RISKS.map((rk) => (
                <button key={rk.id} className={"focusable" + (risk === rk.id ? " on" : "")} onClick={() => setRisk(rk.id)}
                  style={risk === rk.id ? { "--seg": rk.id === "critical" ? "var(--state-crisis)" : rk.id === "high" ? "var(--state-caution)" : "var(--violet-bright)" } : null}>{rk.label}</button>
              ))}
            </div>
            <div className="eyebrow" style={{ marginTop: 12 }}>Protected runtime</div>
            <button className={"amr-toggle focusable" + (protectedRT ? " on" : "")} onClick={() => setProtectedRT((v) => !v)} aria-pressed={protectedRT}>
              <span className="amr-toggle-track"><span className="amr-toggle-knob" /></span>
              <span>{protectedRT ? "Required" : "Not required"}</span>
              <Icon name="lock" style={{ width: 12, height: 12, color: protectedRT ? "var(--state-caution)" : "var(--ink-4)", marginLeft: "auto" }} />
            </button>
          </div>
        </div>

        {/* result */}
        <div className="amr-result" style={{ "--ac": ac }}>
          <div className="amr-res-head">
            <AmrAvatar agent={r.agent} size={42} />
            <div style={{ minWidth: 0, flex: 1 }}>
              <div className="amr-res-name">{r.agent.name}{r.pol.router && <span className="amr-routertag">router · self</span>}</div>
              <div className="amr-res-role">{r.agent.role}</div>
            </div>
            <div className="amr-res-tier">{r.profile ? <TierBadge tier={r.profile.tier} /> : <span className="amr-tier" style={{ color: "var(--state-crisis)", borderColor: "color-mix(in srgb, var(--state-crisis) 42%, transparent)" }}>no engine</span>}<span className="amr-defnote" style={r.atDefault ? null : { color: "var(--state-caution)" }}>{r.atDefault ? "default rung" : "escalated"}</span></div>
          </div>

          <div className="amr-res-grid">
            <div className="amr-res-cell">
              <div className="k">Profile that comes out</div>
              <div className="v"><ProfileChip profile={r.profile} /></div>
            </div>
            <div className="amr-res-cell">
              <div className="k">Runner target</div>
              <div className="v">
                {r.runner
                  ? <span className="amr-runner" style={{ fontSize: 11.5 }}><Icon name={r.runner.protected ? "shield" : "device"} style={{ width: 12, height: 12, color: r.runnerReady ? "var(--state-clear)" : "var(--state-crisis)" }} />{r.runner.label}<span style={{ color: "var(--ink-4)" }}> · {amrAgent(r.runner.owner_agent_id).name || "shared"}</span></span>
                  : <span style={{ fontFamily: "var(--font-mono)", fontSize: 11.5, color: "var(--ink-3)" }}>in-console · no external runner</span>}
              </div>
            </div>
            <div className="amr-res-cell">
              <div className="k">Protected execution</div>
              <div className="v">{r.needProtected
                ? <span style={{ color: "var(--state-caution)", display: "inline-flex", alignItems: "center", gap: 6, fontSize: 12 }}><Icon name="lock" style={{ width: 12, height: 12 }} /> required</span>
                : <span style={{ color: "var(--ink-3)", fontSize: 12 }}>not required</span>}</div>
            </div>
          </div>

          {/* why */}
          <div className="amr-why">
            <Icon name="bolt" style={{ width: 14, height: 14, color: "var(--violet-ink)", flex: "none", marginTop: 1 }} />
            <span>{amrWhy(r, risk)}</span>
          </div>

          {/* escalation path */}
          <div className="amr-esc">
            <div className="amr-esc-top">
              <span className="eyebrow">Escalation path</span>
              <button className="amr-editbtn focusable" onClick={() => onEdit(r.agent.id)}><Icon name="branch" style={{ width: 12, height: 12 }} /> Edit path</button>
            </div>
            <div className="amr-esc-chain">
              {r.steps.map((s, i) => (
                <React.Fragment key={i}>
                  {i > 0 && <Icon name="arrow" className="amr-esc-arrow" style={{ width: 14, height: 14, color: "var(--ink-4)" }} />}
                  {s.kind === "approval"
                    ? <span className="amr-esc-step approval"><Icon name="crown" style={{ width: 11, height: 11 }} /> Diego approval</span>
                    : <span className={"amr-esc-step" + (s.current ? " on" : "") + (s.kind === "fallback" ? " fallback" : "") + (s.inactive ? " inactive" : "")}>
                        {s.kind === "fallback" && <span className="amr-esc-tag">fallback</span>}
                        {s.inactive && <span className="amr-esc-tag" style={{ color: "var(--state-caution)" }}>not subscribed</span>}
                        {s.profile && s.profile.codename ? <b>{s.profile.codename}</b> : null}
                        <span>{s.profile ? s.profile.model_name : "—"}</span>
                      </span>}
                </React.Fragment>
              ))}
            </div>
          </div>

          {/* blocked / delegation note */}
          {r.blocked ? (
            <div className="amr-blocked"><Icon name="lock" style={{ width: 14, height: 14, color: "var(--state-crisis)", flex: "none", marginTop: 1 }} /><span>No healthy protected runner with state access. Job stays <b>blocked</b> — bring {r.agent.name}'s owned runner online. Viiera delegates; she never falls back to chat execution.</span></div>
          ) : r.needProtected ? (
            <div className="amr-deleg"><Icon name="handshake" style={{ width: 14, height: 14, color: "var(--state-caution)", flex: "none", marginTop: 1 }} /><span>Viiera <b>delegates</b> this to {amrAgent(r.runner.owner_agent_id).name} on <span style={{ fontFamily: "var(--font-mono)" }}>{r.runner.id}</span>. She routes and tracks evidence — she does not execute protected work herself.</span></div>
          ) : null}
        </div>
      </div>
    </Panel>
  );
}

function amrWhy(r, risk) {
  if (!r.profile) return `${r.agent.name}'s path has no active engine right now — every profile in the chain is inactive or not yet subscribed. Bring one online to route this mission.`;
  const which = r.profile.codename ? `${r.profile.codename} (${r.profile.model_name})` : r.profile.model_name;
  const riskWord = { low: "a light", medium: "a standard", high: "a high-risk", critical: "a critical" }[risk];
  let base;
  if (r.pol.router) { base = `Command sits with Viiera herself — for ${riskWord} decision she reasons on ${which}. She routes execution to the seat that owns the work.`; }
  else {
    base = `${riskWord} ${r.mission.label.toLowerCase()} belongs to ${r.agent.name}. Viiera pulls ${which} from the escalation path`;
    if (r.skippedInactive) base += ` (the intended ${r.intended ? r.intended.model_name : "engine"} isn't subscribed yet, so it steps to the next active rung)`;
    else if (!r.atDefault) base += " — stepped up by the risk";
    base += ".";
  }
  if (r.needProtected) base += " Protected runtime forces an owned, healthy runner and human approval before anything lands.";
  return base;
}

/* ════════════════════════════════════════════════════════════════════════════
   BOARD ENTRY
   ════════════════════════════════════════════════════════════════════════ */
function AgentModelRouting() {
  const { snap, state } = useAmrSnapshot();
  const profiles = snap.agentModelProfiles || [];
  const policies = snap.agentRoutingPolicies || [];
  const runners = snap.routingRunners || [];
  const profilesById = useMemoAmr(() => { const m = {}; profiles.forEach((p) => (m[p.id] = p)); return m; }, [profiles]);
  const runnersById = useMemoAmr(() => { const m = {}; runners.forEach((r) => (m[r.id] = r)); return m; }, [runners]);

  const [editAgent, setEditAgent] = useStateAmr(null);

  const missing = profiles.length === 0 || policies.length === 0;
  const editPol = editAgent ? policies.find((p) => p.agent_id === editAgent) : null;

  return (
    <div>
      <div style={{ marginBottom: "var(--s-6)" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 11, padding: "11px 14px", borderRadius: 9, background: "color-mix(in srgb, var(--violet-bright) 8%, var(--panel-2))", border: "1px solid var(--hairline-2)" }}>
          <Icon name="shield" style={{ width: 15, height: 15, color: "var(--violet-ink)", flex: "none" }} />
          <span style={{ fontSize: 12.5, color: "var(--ink-2)", lineHeight: 1.45 }}>Governance / config view. <b>Agent = persona, provider family = engine, tier = the version that comes out.</b> Viiera routes; she executes nothing. No model is run and no secrets are read here.</span>
        </div>
      </div>

      {missing ? (
        <Panel className="tight"><div style={{ padding: "26px 18px", textAlign: "center" }}>
          <Icon name="branch" style={{ width: 20, height: 20, color: "var(--ink-4)" }} />
          <div style={{ fontSize: 13.5, color: "var(--ink-2)", marginTop: 10, fontWeight: 500 }}>Routing data not in this snapshot yet.</div>
          <div style={{ fontSize: 11.5, color: "var(--ink-4)", lineHeight: 1.55, maxWidth: 440, margin: "6px auto 0" }}>The surface expects <span style={{ fontFamily: "var(--font-mono)" }}>agentModelProfiles</span> and <span style={{ fontFamily: "var(--font-mono)" }}>agentRoutingPolicies</span> on the Worker snapshot. Showing nothing rather than fabricating routes.</div>
        </div></Panel>
      ) : (
        <div className="cols c-2" style={{ gap: "var(--s-6)" }}>
          <AmrRoster policies={policies} profilesById={profilesById} runnersById={runnersById} onEdit={setEditAgent} />
          <AmrMissionPreview policies={policies} profilesById={profilesById} runnersById={runnersById} onEdit={setEditAgent} />
          <AmrProfileLibrary profiles={profiles} />
        </div>
      )}

      {editPol && <AmrPathEditor pol={editPol} profiles={profiles} profilesById={profilesById}
        onClose={() => setEditAgent(null)} />}
    </div>
  );
}

/* ── path editor — drafts a Worker payload that updates agent_routing_policies.
   Browser never writes Supabase: compose the chain + approval, then queue the
   exact route + JSON for Codex / the Worker to apply. Same doctrine as the
   New Training Target composer. ──────────────────────────────────────────── */
function AmrPathEditor({ pol, profiles, profilesById, onClose }) {
  const agent = amrAgent(pol.agent_id);
  const init = amrDerivedChain(pol).filter((id) => profilesById[id]);
  const [chain, setChain] = useStateAmr(init);
  const [approval, setApproval] = useStateAmr(amrApprovalMode(pol));
  const [queued, setQueued] = useStateAmr(null);

  const pool = profiles.filter((p) => !chain.includes(p.id))
    .sort((a, b) => (a.active === b.active ? 0 : a.active ? -1 : 1) || AMR_TIER_ORDER.indexOf(a.tier) - AMR_TIER_ORDER.indexOf(b.tier));
  const move = (i, d) => setChain((c) => { const n = c.slice(); const j = i + d; if (j < 0 || j >= n.length) return c; [n[i], n[j]] = [n[j], n[i]]; return n; });
  const remove = (id) => setChain((c) => c.filter((x) => x !== id));
  const add = (id) => setChain((c) => [...c, id]);
  const dirty = JSON.stringify(chain) !== JSON.stringify(init) || approval !== amrApprovalMode(pol);
  const valid = chain.length > 0 && dirty;
  const ac = agent.ac || agent.accent || "var(--violet-bright)";

  const ROUTE = "PATCH /api/divonci-world/agent-development/routing-policies/" + pol.agent_id;
  const payload = {
    action: "agent_development.update_routing_policy",
    table: "agent_routing_policies",
    match: { agent_id: pol.agent_id },
    patch: { escalation_chain: chain, human_approval: approval },
    routed_through: "viiera",
    authority: "viiera",
    audit_event: true,
  };

  return (
    <div className="dev-modal-scrim" onClick={onClose}>
      <div className="dev-modal amr-editor" style={{ "--ac": ac }} onClick={(e) => e.stopPropagation()}>
        <div className="dev-modal-head">
          <div style={{ display: "flex", alignItems: "center", gap: 12, minWidth: 0 }}>
            <AmrAvatar agent={agent} size={36} />
            <div style={{ minWidth: 0 }}>
              <div style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 17 }}>Edit escalation path · {agent.name}</div>
              <div style={{ fontSize: 11.5, color: "var(--ink-3)", marginTop: 3 }}>Order Viiera climbs for this seat. Low risk uses the first rung, high / critical the last; inactive engines are skipped until subscribed. Submitting drafts a Worker payload — the browser never writes Supabase.</div>
            </div>
          </div>
          <button className="dev-modal-x focusable" onClick={onClose} aria-label="Close"><Icon name="close" style={{ width: 15, height: 15 }} /></button>
        </div>
        {queued ? (
          <div className="dev-modal-body">
            <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 14 }}>
              <span style={{ width: 30, height: 30, borderRadius: 9, display: "grid", placeItems: "center", background: "color-mix(in srgb, var(--state-caution) 16%, transparent)", border: "1px solid color-mix(in srgb, var(--state-caution) 40%, transparent)", flex: "none" }}><Icon name="lock" style={{ width: 15, height: 15, color: "var(--state-caution)" }} /></span>
              <div><div style={{ fontSize: 14, fontWeight: 600 }}>Queued — pending Worker endpoint</div><div style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, color: "var(--ink-3)" }}>{ROUTE}</div></div>
            </div>
            <div style={{ fontSize: 12, color: "var(--ink-3)", marginBottom: 10, lineHeight: 1.5 }}>Exact payload the routing action receives once wired. Viiera-gated; writes an audit_event in the same transaction:</div>
            <pre className="dev-payload">{JSON.stringify(queued, null, 2)}</pre>
            <div className="dev-modal-foot"><button className="btn ghost" onClick={() => setQueued(null)}>← Edit</button><button className="btn primary" onClick={onClose}>Done</button></div>
          </div>
        ) : (
        <div className="dev-modal-body">
          <div className="dev-field"><span>Escalation chain · low → high risk</span></div>
          <div className="amr-ed-chain">
            {chain.map((id, i) => { const p = profilesById[id]; if (!p) return null; const m = AMR_TIER_META[p.tier] || AMR_TIER_META.fast; return (
              <div key={id} className={"amr-ed-item" + (p.active ? "" : " inactive")}>
                <span className="amr-ed-idx">{i + 1}</span>
                <span style={{ minWidth: 0, flex: 1 }}>
                  <span className="amr-ed-name">{p.codename ? <b style={{ color: m.c }}>{p.codename} · </b> : null}{p.model_name}</span>
                  <span className="amr-ed-sub">{p.provider} · {(AMR_TIER_META[p.tier] || {}).label}{!p.active && " · not subscribed"}</span>
                </span>
                <span className="amr-ed-ctl">
                  <button className="focusable" disabled={i === 0} onClick={() => move(i, -1)} aria-label="Move up"><Icon name="chevron" style={{ width: 13, height: 13, transform: "rotate(-90deg)" }} /></button>
                  <button className="focusable" disabled={i === chain.length - 1} onClick={() => move(i, 1)} aria-label="Move down"><Icon name="chevron" style={{ width: 13, height: 13, transform: "rotate(90deg)" }} /></button>
                  <button className="focusable amr-ed-rm" onClick={() => remove(id)} aria-label="Remove"><Icon name="close" style={{ width: 13, height: 13 }} /></button>
                </span>
              </div>
            ); })}
            {chain.length === 0 && <div className="amr-ed-empty">Add at least one engine to the path.</div>}
          </div>

          {pool.length > 0 && (
            <React.Fragment>
              <div className="dev-field" style={{ marginTop: 4 }}><span>Add engine</span></div>
              <div className="amr-ed-pool">
                {pool.map((p) => { const m = AMR_TIER_META[p.tier] || AMR_TIER_META.fast; return (
                  <button key={p.id} className={"amr-ed-add focusable" + (p.active ? "" : " inactive")} onClick={() => add(p.id)} title={`${p.provider} · ${p.model_name}`}>
                    <Icon name="plus" style={{ width: 11, height: 11 }} />
                    {p.codename ? <b style={{ color: m.c }}>{p.codename}</b> : null}
                    <span>{p.model_name}</span>
                    {!p.active && <span className="amr-ed-pooltag">soon</span>}
                  </button>
                ); })}
              </div>
            </React.Fragment>
          )}

          <div className="dev-field" style={{ marginTop: 6 }}><span>Human approval</span></div>
          <div className="amr-seg" style={{ gridTemplateColumns: "repeat(3, 1fr)" }}>
            {[["auto", "Auto"], ["always", "Always"], ["never", "Never"]].map(([id, label]) => (
              <button key={id} className={"focusable" + (approval === id ? " on" : "")} onClick={() => setApproval(id)}
                style={approval === id ? { "--seg": id === "always" ? "var(--gold)" : id === "never" ? "var(--state-crisis)" : "var(--violet-bright)" } : null}>{label}</button>
            ))}
          </div>
          <div style={{ fontSize: 11, color: "var(--ink-4)", lineHeight: 1.5 }}>Auto requires approval on critical or protected-runtime missions. Always / Never force it regardless.</div>

          <span className="todochip" style={{ alignSelf: "flex-start" }}><Icon name="lock" style={{ width: 10, height: 10 }} /> Worker-gated · no direct DB write</span>
          <div className="dev-modal-foot">
            <button className="btn ghost" onClick={onClose}>Cancel</button>
            <button className="btn primary" disabled={!valid} style={!valid ? { opacity: 0.5, pointerEvents: "none" } : null}
              onClick={() => setQueued(payload)}><Icon name="lock" className="glyph" style={{ width: 13, height: 13 }} /> Queue routing change</button>
          </div>
        </div>
        )}
      </div>
    </div>
  );
}

/* ── scoped styles ────────────────────────────────────────────────────────── */
(function injectAmrStyles() {
  if (document.getElementById("amr-surface-styles")) return;
  const css = `
  .amr-tier { display: inline-flex; align-items: center; gap: 5px; font-family: var(--font-mono); font-weight: 600; letter-spacing: 0.04em; text-transform: uppercase; padding: 2px 8px; border-radius: 99px; border: 1px solid var(--hairline-2); background: var(--panel); white-space: nowrap; }
  .amr-tier .led { width: 6px; height: 6px; border-radius: 99px; box-shadow: 0 0 6px currentColor; }
  .amr-profchip { display: inline-flex; align-items: center; gap: 6px; font-family: var(--font-mono); font-size: 11px; padding: 3px 9px; border-radius: 7px; border: 1px solid var(--hairline-2); background: var(--panel); white-space: nowrap; }
  .amr-policy { font-family: var(--font-mono); font-size: 10.5px; color: var(--violet-ink); background: color-mix(in srgb, var(--violet-bright) 12%, var(--panel-2)); border: 1px solid color-mix(in srgb, var(--violet-bright) 28%, transparent); padding: 2px 8px; border-radius: 6px; white-space: nowrap; }
  .amr-routertag { font-family: var(--font-mono); font-size: 8px; letter-spacing: 0.06em; text-transform: uppercase; color: var(--gold-bright); border: 1px solid color-mix(in srgb, var(--gold) 42%, transparent); padding: 1px 6px; border-radius: 99px; margin-left: 8px; }
  .amr-yes { display: inline-flex; align-items: center; gap: 4px; font-family: var(--font-mono); font-size: 11px; color: var(--state-caution); }
  .amr-runner { display: inline-flex; align-items: center; gap: 6px; font-family: var(--font-mono); font-size: 10.5px; color: var(--ink-2); }

  /* roster table */
  .amr-roster { display: flex; flex-direction: column; }
  .amr-rrow { display: grid; grid-template-columns: minmax(0,2.1fr) 116px 128px minmax(0,1.1fr) minmax(0,0.95fr) 70px minmax(0,1.2fr) 40px; gap: 12px; align-items: center; padding: 11px 16px; border-bottom: 1px solid var(--hairline); }
  .amr-rrow:last-child { border-bottom: none; }
  .amr-rhead { font-family: var(--font-mono); font-size: 9px; letter-spacing: 0.1em; text-transform: uppercase; color: var(--ink-4); }
  .amr-rid { display: inline-flex; align-items: center; gap: 11px; min-width: 0; border-left: 2px solid color-mix(in srgb, var(--ac) 70%, transparent); padding-left: 11px; margin-left: -2px; }
  .amr-rid .nm { display: block; font-family: var(--font-display); font-weight: 600; font-size: 13.5px; }
  .amr-rid .rl { display: block; font-size: 10.5px; color: var(--ink-3); line-height: 1.4; margin-top: 2px; overflow: hidden; text-overflow: ellipsis; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; }

  /* profile library */
  .amr-lib { padding: 6px 16px 16px; display: flex; flex-direction: column; gap: 18px; }
  .amr-fam-head { display: flex; align-items: center; gap: 10px; padding-bottom: 9px; margin-bottom: 12px; border-bottom: 1px solid var(--hairline); }
  .amr-fam-name { font-family: var(--font-display); font-weight: 600; font-size: 15px; }
  .amr-fam-provider { font-family: var(--font-mono); font-size: 10px; color: var(--ink-4); letter-spacing: 0.04em; text-transform: uppercase; }
  .amr-fam-count { margin-left: auto; font-family: var(--font-mono); font-size: 10px; color: var(--ink-3); background: var(--panel-2); border: 1px solid var(--hairline-2); padding: 1px 8px; border-radius: 99px; }
  .amr-cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(248px, 1fr)); gap: 11px; }
  .amr-card { padding: 13px 14px; border-radius: 12px; background: var(--panel-2); border: 1px solid var(--hairline-2); border-top: 2px solid color-mix(in srgb, var(--tc) 70%, transparent); display: flex; flex-direction: column; gap: 11px; }
  .amr-card-top { display: flex; align-items: flex-start; justify-content: space-between; gap: 10px; }
  .amr-card-code { font-family: var(--font-display); font-weight: 700; font-size: 16px; line-height: 1.1; }
  .amr-card-model { font-family: var(--font-mono); font-size: 10px; color: var(--ink-4); margin-top: 3px; }
  .amr-protpill { display: inline-flex; align-items: center; gap: 4px; font-family: var(--font-mono); font-size: 8px; letter-spacing: 0.04em; text-transform: uppercase; color: var(--state-caution); border: 1px solid color-mix(in srgb, var(--state-caution) 38%, transparent); padding: 2px 6px; border-radius: 99px; white-space: nowrap; }
  .amr-bands { display: grid; grid-template-columns: repeat(3, 1fr); gap: 1px; background: var(--hairline); border: 1px solid var(--hairline-2); border-radius: 8px; overflow: hidden; }
  .amr-bands > span { background: var(--panel); padding: 7px 9px; display: flex; flex-direction: column; gap: 3px; }
  .amr-bands i { font-family: var(--font-mono); font-size: 8px; letter-spacing: 0.08em; text-transform: uppercase; color: var(--ink-4); font-style: normal; }
  .amr-bands b { font-family: var(--font-mono); font-size: 11.5px; font-weight: 600; color: var(--ink-2); text-transform: capitalize; }
  .amr-sl { display: flex; flex-direction: column; gap: 4px; }
  .amr-sl-h { font-family: var(--font-mono); font-size: 8.5px; letter-spacing: 0.1em; text-transform: uppercase; }
  .amr-sl ul { margin: 0; padding-left: 15px; display: flex; flex-direction: column; gap: 3px; }
  .amr-sl li { font-size: 11.5px; color: var(--ink-2); line-height: 1.4; }
  .amr-card-foot { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding-top: 10px; border-top: 1px solid var(--hairline); }
  .amr-active { display: inline-flex; align-items: center; gap: 6px; font-family: var(--font-mono); font-size: 10px; color: var(--ink-3); }
  .amr-pid { font-family: var(--font-mono); font-size: 9.5px; color: var(--ink-4); }

  /* mission preview */
  .amr-preview { padding: 6px 16px 16px; display: grid; grid-template-columns: minmax(260px, 340px) minmax(0, 1fr); gap: 18px; align-items: start; }
  .amr-controls { display: flex; flex-direction: column; gap: 16px; }
  .amr-mlist { display: flex; flex-direction: column; gap: 6px; margin-top: 8px; }
  .amr-mbtn { display: flex; align-items: center; gap: 9px; padding: 10px 12px; border-radius: 9px; border: 1px solid var(--hairline-2); background: var(--panel-2); color: var(--ink-2); font: inherit; font-size: 12.5px; cursor: pointer; text-align: left; transition: all .15s; }
  .amr-mbtn:hover { color: var(--ink); background: var(--panel-3); }
  .amr-mbtn.on { color: var(--ink); background: color-mix(in srgb, var(--violet-bright) 14%, var(--panel-2)); border-color: color-mix(in srgb, var(--violet-bright) 46%, transparent); }
  .amr-mbtn svg { color: var(--ink-4); flex: none; }
  .amr-mbtn.on svg { color: var(--violet-ink); }
  .amr-seg { display: grid; grid-template-columns: repeat(4, 1fr); gap: 5px; margin-top: 8px; }
  .amr-seg button { padding: 8px 4px; border-radius: 8px; border: 1px solid var(--hairline-2); background: var(--panel-2); color: var(--ink-3); font: inherit; font-size: 11.5px; cursor: pointer; transition: all .15s; }
  .amr-seg button:hover { color: var(--ink-2); background: var(--panel-3); }
  .amr-seg button.on { color: var(--ink); background: color-mix(in srgb, var(--seg) 16%, var(--panel-2)); border-color: color-mix(in srgb, var(--seg) 50%, transparent); }
  .amr-toggle { display: flex; align-items: center; gap: 10px; width: 100%; box-sizing: border-box; margin-top: 8px; padding: 9px 12px; border-radius: 9px; border: 1px solid var(--hairline-2); background: var(--panel-2); color: var(--ink-2); font: inherit; font-size: 12.5px; cursor: pointer; transition: all .15s; }
  .amr-toggle.on { border-color: color-mix(in srgb, var(--state-caution) 46%, transparent); color: var(--ink); }
  .amr-toggle-track { width: 32px; height: 18px; border-radius: 99px; background: var(--panel-4); border: 1px solid var(--hairline-3); position: relative; flex: none; transition: background .15s; }
  .amr-toggle.on .amr-toggle-track { background: color-mix(in srgb, var(--state-caution) 40%, var(--panel-4)); }
  .amr-toggle-knob { position: absolute; top: 1px; left: 1px; width: 14px; height: 14px; border-radius: 99px; background: var(--ink-2); transition: transform .18s var(--ease-out); }
  .amr-toggle.on .amr-toggle-knob { transform: translateX(14px); background: var(--state-caution); }

  .amr-result { border-radius: 13px; background: var(--panel); border: 1px solid var(--hairline-2); border-left: 3px solid color-mix(in srgb, var(--ac) 72%, transparent); padding: 16px; display: flex; flex-direction: column; gap: 15px; }
  .amr-res-head { display: flex; align-items: center; gap: 13px; }
  .amr-res-name { font-family: var(--font-display); font-weight: 600; font-size: 18px; }
  .amr-res-role { font-family: var(--font-mono); font-size: 10px; color: var(--ink-3); letter-spacing: 0.04em; text-transform: uppercase; margin-top: 3px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
  .amr-res-tier { display: flex; flex-direction: column; align-items: flex-end; gap: 5px; flex: none; }
  .amr-defnote { font-family: var(--font-mono); font-size: 8.5px; letter-spacing: 0.06em; text-transform: uppercase; color: var(--ink-4); }
  .amr-res-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 1px; background: var(--hairline); border: 1px solid var(--hairline-2); border-radius: 10px; overflow: hidden; }
  .amr-res-cell { background: var(--panel-2); padding: 11px 13px; }
  .amr-res-cell .k { font-family: var(--font-mono); font-size: 8.5px; letter-spacing: 0.1em; text-transform: uppercase; color: var(--ink-4); }
  .amr-res-cell .v { margin-top: 7px; }
  .amr-routerby { display: inline-flex; align-items: center; gap: 6px; font-family: var(--font-mono); font-size: 10px; color: var(--violet-ink); letter-spacing: 0.04em; text-transform: uppercase; }
  .amr-why { display: flex; gap: 9px; padding: 11px 13px; border-radius: 10px; background: color-mix(in srgb, var(--violet-bright) 7%, var(--panel-2)); border: 1px solid var(--hairline-2); font-size: 12.5px; color: var(--ink-2); line-height: 1.5; }
  .amr-esc-chain { display: flex; align-items: center; gap: 7px; flex-wrap: wrap; margin-top: 9px; }
  .amr-esc-arrow { flex: none; }
  .amr-esc-step { display: inline-flex; align-items: center; gap: 6px; font-family: var(--font-mono); font-size: 11px; color: var(--ink-3); padding: 5px 10px; border-radius: 8px; border: 1px solid var(--hairline-2); background: var(--panel-2); }
  .amr-esc-step b { color: var(--ink); }
  .amr-esc-step.on { border-color: color-mix(in srgb, var(--violet-bright) 55%, transparent); background: color-mix(in srgb, var(--violet-bright) 13%, var(--panel-2)); color: var(--ink); box-shadow: 0 0 0 1px color-mix(in srgb, var(--violet-bright) 30%, transparent); }
  .amr-esc-step.fallback { border-style: dashed; }
  .amr-esc-step.approval { color: var(--gold-bright); border-color: color-mix(in srgb, var(--gold) 45%, transparent); background: color-mix(in srgb, var(--gold) 10%, var(--panel-2)); }
  .amr-esc-tag { font-size: 8px; letter-spacing: 0.06em; text-transform: uppercase; color: var(--ink-4); }
  .amr-deleg, .amr-blocked { display: flex; gap: 9px; padding: 11px 13px; border-radius: 10px; font-size: 12px; line-height: 1.5; }
  .amr-deleg { background: color-mix(in srgb, var(--state-caution) 8%, var(--panel-2)); border: 1px solid color-mix(in srgb, var(--state-caution) 30%, transparent); color: var(--ink-2); }
  .amr-blocked { background: color-mix(in srgb, var(--state-crisis) 8%, var(--panel-2)); border: 1px solid color-mix(in srgb, var(--state-crisis) 32%, transparent); color: var(--ink-2); }

  .amr-editedtag { font-family: var(--font-mono); font-size: 8px; letter-spacing: 0.06em; text-transform: uppercase; color: var(--state-caution); border: 1px solid color-mix(in srgb, var(--state-caution) 40%, transparent); padding: 1px 6px; border-radius: 99px; margin-left: 8px; }
  .amr-editbtn-sm { width: 30px; height: 30px; display: grid; place-items: center; border-radius: 8px; border: 1px solid var(--hairline-2); background: var(--panel-2); color: var(--ink-3); cursor: pointer; transition: all .15s; }
  .amr-editbtn-sm:hover { color: var(--ink); background: var(--panel-3); border-color: color-mix(in srgb, var(--violet-bright) 40%, transparent); }
  .amr-editbtn { display: inline-flex; align-items: center; gap: 6px; padding: 5px 11px; border-radius: 8px; border: 1px solid var(--hairline-2); background: var(--panel-2); color: var(--ink-2); font: inherit; font-size: 11.5px; cursor: pointer; transition: all .15s; }
  .amr-editbtn:hover { color: var(--ink); background: var(--panel-3); border-color: color-mix(in srgb, var(--violet-bright) 45%, transparent); }
  .amr-esc-top { display: flex; align-items: center; justify-content: space-between; gap: 10px; }
  .amr-esc-step.inactive { opacity: 0.55; border-style: dashed; }
  .amr-card.planned { opacity: 0.62; }
  .amr-card.planned .amr-card-code { color: var(--ink-3) !important; }

  /* path editor */
  .amr-editor { width: min(600px, 100%); }
  .amr-ed-chain { display: flex; flex-direction: column; gap: 7px; }
  .amr-ed-item { display: flex; align-items: center; gap: 11px; padding: 9px 11px; border-radius: 10px; background: var(--panel-2); border: 1px solid var(--hairline-2); border-left: 3px solid color-mix(in srgb, var(--ac) 60%, transparent); }
  .amr-ed-item.inactive { border-left-color: color-mix(in srgb, var(--state-caution) 50%, transparent); }
  .amr-ed-idx { width: 22px; height: 22px; flex: none; display: grid; place-items: center; border-radius: 7px; background: var(--panel); border: 1px solid var(--hairline-2); font-family: var(--font-mono); font-size: 11px; color: var(--ink-3); }
  .amr-ed-name { display: block; font-size: 13px; color: var(--ink); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
  .amr-ed-sub { display: block; font-family: var(--font-mono); font-size: 9.5px; color: var(--ink-4); margin-top: 2px; text-transform: capitalize; }
  .amr-ed-ctl { display: inline-flex; gap: 4px; flex: none; }
  .amr-ed-ctl button { width: 28px; height: 28px; display: grid; place-items: center; border-radius: 7px; border: 1px solid var(--hairline-2); background: var(--panel); color: var(--ink-3); cursor: pointer; transition: all .15s; }
  .amr-ed-ctl button:hover:not(:disabled) { color: var(--ink); background: var(--panel-3); }
  .amr-ed-ctl button:disabled { opacity: 0.35; cursor: not-allowed; }
  .amr-ed-ctl .amr-ed-rm:hover { color: var(--state-crisis); border-color: color-mix(in srgb, var(--state-crisis) 40%, transparent); }
  .amr-ed-empty { padding: 14px; text-align: center; font-size: 12px; color: var(--state-caution); border: 1px dashed var(--hairline-3); border-radius: 10px; }
  .amr-ed-pool { display: flex; flex-wrap: wrap; gap: 7px; }
  .amr-ed-add { display: inline-flex; align-items: center; gap: 6px; padding: 6px 10px; border-radius: 8px; border: 1px solid var(--hairline-2); background: var(--panel-2); color: var(--ink-2); font: inherit; font-size: 11.5px; cursor: pointer; transition: all .15s; }
  .amr-ed-add:hover { color: var(--ink); background: var(--panel-3); border-color: color-mix(in srgb, var(--violet-bright) 40%, transparent); }
  .amr-ed-add svg { color: var(--ink-4); }
  .amr-ed-add.inactive { opacity: 0.6; }
  .amr-ed-pooltag { font-family: var(--font-mono); font-size: 8px; letter-spacing: 0.05em; text-transform: uppercase; color: var(--state-caution); }

  @media (max-width: 1080px) {
    .amr-preview { grid-template-columns: 1fr; }
    .amr-rrow { grid-template-columns: minmax(0,2fr) 112px 122px minmax(0,1fr) 70px 40px; }
    .amr-hide-md { display: none; }
  }
  @media (max-width: 720px) {
    .amr-rrow { grid-template-columns: minmax(0,1.7fr) 116px minmax(0,0.95fr) 60px 40px; }
    .amr-hide-sm { display: none; }
    .amr-res-grid { grid-template-columns: 1fr; }
  }`;
  const el = document.createElement("style"); el.id = "amr-surface-styles"; el.textContent = css; document.head.appendChild(el);
})();

Object.assign(window, { AgentModelRouting });
