/* ============================================================================
   DIVONCI WORLD — APP SHELL + ROUTER + TWEAKS
   ========================================================================== */
const { useState: useStateA, useEffect: useEffectA, useRef: useRefA } = React;

/* Top-level IA — the agency operating system.
   World Map · War Room · Clients · Projects · Foundry(group) · WorkRate ·
   Deployments · Arsenal · Evidence & Risk · Council(group) · Settings */
const NAV_TREE = [
  { id: "world", label: "World Map", icon: "globe", pip: "live" },
  { id: "office", label: "The Office", icon: "users", pip: "live" },
  { id: "terminal9", label: "Terminal 9", icon: "ops", pip: "live" },
  { id: "warroom", label: "War Room", icon: "warroom", pip: "alert", pipText: "3" },
  { id: "clients", label: "Clients", icon: "users" },
  { id: "projects", label: "Projects", icon: "project" },
  { group: "foundry", label: "Foundry", icon: "foundry", children: [
    { id: "foundry", label: "Overview", icon: "foundry" },
    { id: "foundryctl", label: "Foundry Control", icon: "device", pip: "live" },
    { id: "fbuild:control", label: "Change Control", icon: "branch" },
    { id: "fbuild:packets", label: "Foundry Packets", icon: "cube" },
    { id: "fbuild:blueprints", label: "AppBlueprints", icon: "layers" },
    { id: "fbuild:handoff", label: "Claude / Codex Handoff", icon: "code" },
    { id: "studio", label: "Viiera Studio", icon: "studio" },
  ] },
  { id: "workrate", label: "WorkRate", icon: "workrate" },
  { id: "ops", label: "Deployments", icon: "ops" },
  { id: "arsenal", label: "Arsenal", icon: "chip", pip: "live" },
  { id: "agent-development", label: "Agent Development", icon: "skill", pip: "live" },
  { id: "evidence", label: "Evidence & Risk", icon: "evidence", pip: "warn", pipText: "1" },
  { group: "council", label: "Council", icon: "council", children: [
    { id: "council", label: "The Council", icon: "council" },
    { id: "nova", label: "Nova", icon: "spark" },
    { id: "viiera", label: "Viiera", icon: "crown" },
    { id: "vconsole", label: "Command Console", icon: "shield", pip: "live" },
    { id: "claws", label: "Claws", icon: "comms" },
    { id: "brodex", label: "BroDex", icon: "eye" },
    { id: "vv", label: "VV", icon: "mask" },
    { id: "optimus", label: "Optimus", icon: "power" },
    { id: "skill:viiera", label: "Skill Trees", icon: "skill" },
    { id: "comms", label: "Council Comms", icon: "comms" },
    { id: "nexus", label: "Nexus · Memory", icon: "nexus" },
  ] },
  { id: "settings", label: "Settings", icon: "settings" },
];

function childActive(id, route, baseRoute) {
  if (id.includes(":")) return route === id;
  if (id === "foundryctl") return route === "foundryctl";
  return baseRoute === id || route === "profile:" + id || route === id;
}

function RailNav({ route, baseRoute, onNav }) {
  const activeGroup = NAV_TREE.find((g) => g.group && g.children.some((c) => childActive(c.id, route, baseRoute)));
  const [open, setOpen] = useStateA(() => (activeGroup ? { [activeGroup.group]: true } : {}));
  useEffectA(() => { if (activeGroup) setOpen((o) => (o[activeGroup.group] ? o : { ...o, [activeGroup.group]: true })); }, [activeGroup && activeGroup.group]);
  const RailBtn = (n) => (
    <button key={n.id} className={"railbtn " + (childActive(n.id, route, baseRoute) ? "active" : "")} onClick={() => onNav(n.id)} style={{ position: "relative" }}>
      <Icon name={n.icon} />
      <span className="lbl">{n.label}</span>
      {n.pip && <span className={"pip " + n.pip}>{n.pipText || (n.pip === "live" ? "LIVE" : "")}</span>}
    </button>
  );
  return (
    <nav className="nav-scroll" style={{ padding: "10px 10px 0" }}>
      {NAV_TREE.map((n) => {
        if (!n.group) return RailBtn(n);
        const isOpen = !!open[n.group];
        return (
          <div key={n.group}>
            <button className={"nav-group " + (isOpen ? "open" : "")} onClick={() => setOpen((o) => ({ ...o, [n.group]: !o[n.group] }))}>
              <Icon name={n.icon} /><span style={{ fontWeight: 600 }}>{n.label}</span><Icon name="chevron" className="chev" />
            </button>
            {isOpen && <div className="nav-children">{n.children.map(RailBtn)}</div>}
          </div>
        );
      })}
    </nav>
  );
}

const CRUMBS = {
  world: ["Command", "World Map"], office: ["Command", "The Office"], terminal9: ["Command", "Terminal 9"], warroom: ["Command", "War Room"],
  clients: ["Agency", "Clients"], projects: ["Agency", "Projects"],
  foundry: ["Foundry", "Overview"], foundryctl: ["Foundry", "Foundry Control"], blueprints: ["Foundry", "AppBlueprints"], studio: ["Foundry", "Viiera Studio"],
  workrate: ["Execution", "WorkRate"], ops: ["Execution", "Deployments"], arsenal: ["Arsenal", "Command Room"],
  evidence: ["Truth", "Evidence & Risk"], risk: ["Truth", "Evidence & Risk"], log: ["Truth", "Evidence & Risk"],
  council: ["Council", "The Council"],
  nova: ["Council", "Nova"], viiera: ["Council", "Viiera"], claws: ["Council", "Claws"], brodex: ["Council", "BroDex"],
  vv: ["Council", "VV"], optimus: ["Council", "Optimus"], comms: ["Council", "Council Comms"], nexus: ["Council", "Nexus"],
  vconsole: ["Council", "Viiera Command Console"],
  "agent-development": ["Governance", "Agent Development"],
  settings: ["System", "Settings"],
};

const SYS_STATES = [
  { id: "live", label: "Live", state: "clear" },
  { id: "crisis", label: "Crisis", state: "crisis" },
  { id: "degraded", label: "Degraded", state: "caution" },
  { id: "offline", label: "Offline", state: "standby" },
];

function Clock() {
  const [now, setNow] = useStateA(new Date());
  useEffectA(() => { const id = setInterval(() => setNow(new Date()), 1000); return () => clearInterval(id); }, []);
  const hh = String(now.getUTCHours()).padStart(2, "0");
  const mm = String(now.getUTCMinutes()).padStart(2, "0");
  const ss = String(now.getUTCSeconds()).padStart(2, "0");
  return <span className="clock"><span className="dot">●</span> {hh}:{mm}:{ss} <span style={{ color: "var(--ink-4)" }}>UTC</span></span>;
}

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "sysState": "live",
  "accent": "#A855F7",
  "glow": 1,
  "density": "regular",
  "motion": true
}/*EDITMODE-END*/;

function App() {
  const [route, setRoute] = useStateA("world");
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const sys = t.sysState;

  // deterministically remove the boot splash once mounted
  useEffectA(() => {
    const b = document.getElementById("boot");
    if (b) { b.style.opacity = "0"; b.style.pointerEvents = "none"; setTimeout(() => b.remove(), 450); }
  }, []);

  // apply tweaks to :root
  useEffectA(() => {
    const root = document.documentElement;
    root.style.setProperty("--violet-bright", t.accent);
    root.style.setProperty("--state-active", t.accent);
    root.style.setProperty("--active-dim", `color-mix(in srgb, ${t.accent} 16%, transparent)`);
    // glow intensity scales the violet glow ring
    const g = t.glow;
    root.style.setProperty("--glow-violet", `0 0 0 1px color-mix(in srgb, ${t.accent} ${35*g}%, transparent), 0 0 ${24*g}px color-mix(in srgb, ${t.accent} ${30*g}%, transparent)`);
    root.style.setProperty("--glow-soft", `0 0 ${30*g}px rgba(139,92,246,${0.1*g})`);
  }, [t.accent, t.glow]);

  useEffectA(() => {
    document.documentElement.style.scrollBehavior = "auto";
    const mq = "(prefers-reduced-motion: reduce)";
    // motion tweak toggles a class that pauses ambient animations
    document.body.classList.toggle("no-motion", !t.motion);
  }, [t.motion]);

  function nav(r) {
    if (r && r.startsWith("profile:")) { setRoute(r); }
    else setRoute(r);
    const canvas = document.querySelector(".canvas");
    if (canvas) canvas.scrollTop = 0;
  }

  const baseRoute = route.split(":")[0];
  const FB_CRUMB = { control: "Change Control", packets: "Foundry Packets", blueprints: "AppBlueprints", handoff: "Claude / Codex Handoff" };
  const crumb = baseRoute === "fbuild" ? ["Foundry", FB_CRUMB[route.split(":")[1] || "control"]]
    : CRUMBS[baseRoute] || (route.startsWith("profile") ? ["Agents", DW.agent(route.split(":")[1]).name] : route.startsWith("skill") ? ["Agents", "Skill Tree"] : route.startsWith("project") ? ["Projects", (DW.PROJECTS.find(p => p.id === route.split(":")[1]) || {}).name || "Project"] : ["", route]);

  function render() {
    if (route.startsWith("arsenal")) return <ArsenalScreen nav={nav} sub={route.split(":").slice(1).join(":")} />;
    if (route.startsWith("profile:")) return <AgentProfile agentId={route.split(":")[1]} nav={nav} />;
    if (route.startsWith("skill:")) return <SkillTree agentId={route.split(":")[1]} nav={nav} />;
    if (route.startsWith("project:")) return <ProjectDetail id={route.split(":")[1]} nav={nav} />;
    if (route.startsWith("fbuild")) return <FoundryControlBoard nav={nav} lens={route.split(":")[1] || "control"} />;
    switch (route) {
      case "clients": return <ClientsScreen nav={nav} />;
      case "settings": return <SettingsScreen nav={nav} />;
      case "foundryctl": return <FoundryControlScreen nav={nav} />;
      case "world": return <WorldMap nav={nav} sys={sys} />;
      case "office": return <OfficeScreen />;
      case "terminal9": return <Terminal9Gate />;
      case "warroom": return <WarRoom nav={nav} />;
      case "council": return <CouncilOverview nav={nav} />;
      case "nova": return <AgentProfile agentId="nova" nav={nav} />;
      case "viiera": return <AgentProfile agentId="viiera" nav={nav} />;
      case "claws": return <AgentProfile agentId="claws" nav={nav} />;
      case "brodex": return <AgentProfile agentId="brodex" nav={nav} />;
      case "vv": return <AgentProfile agentId="vv" nav={nav} />;
      case "optimus": return <AgentProfile agentId="optimus" nav={nav} />;
      case "workrate": return <WorkRate nav={nav} />;
      case "ops": return <OpsScreen nav={nav} />;
      case "projects": return <ProjectsScreen nav={nav} />;
      case "comms": return <CommsScreen nav={nav} />;
      case "foundry": return <ModulePage id="foundry" nav={nav} />;
      case "studio": return <ModulePage id="studio" nav={nav} />;
      case "nexus": return <Nexus nav={nav} />;
      case "vconsole": return <ViieraConsole nav={nav} />;
      case "agent-development": return <AgentDevelopmentScreen nav={nav} />;
      case "evidence": return <EvidenceRisk nav={nav} lens="evidence" />;
      case "risk": return <EvidenceRisk nav={nav} lens="risk" />;
      case "log": return <EvidenceRisk nav={nav} lens="activity" />;
      default: return <WorldMap nav={nav} sys={sys} />;
    }
  }

  const sysMeta = SYS_STATES.find(s => s.id === sys);

  return (
    <div className={"os " + (t.density === "compact" ? "dense" : "")} data-sys={sys}>
      {/* ---- LEFT RAIL ---- */}
      <aside className="rail">
        <div style={{ display: "flex", alignItems: "center", gap: 11, padding: "16px 16px 14px" }}>
          <div style={{ width: 30, height: 30, borderRadius: 9, background: "linear-gradient(150deg, var(--violet-bright), var(--violet-deep))", display: "grid", placeItems: "center", boxShadow: "var(--glow-violet)", flex: "none" }}>
            <Icon name="crown" style={{ width: 17, height: 17, color: "#fff" }} />
          </div>
          <div>
            <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 15, letterSpacing: "-0.01em" }}>Divonci<span style={{ color: "var(--violet-ink)" }}>World</span></div>
            <div style={{ fontFamily: "var(--font-mono)", fontSize: 8.5, color: "var(--ink-4)", letterSpacing: "0.14em", textTransform: "uppercase" }}>Command OS · v0.1</div>
          </div>
        </div>
        <div style={{ height: 1, background: "var(--hairline)" }} />
        <RailNav route={route} baseRoute={baseRoute} onNav={nav} />
        <div className="rail-foot">
          <div className="d-avatar">D</div>
          <div className="who"><div className="nm">Diego</div><div className="rl">Sovereign · Diovinci</div></div>
          <Icon name="settings" style={{ width: 15, height: 15, color: "var(--ink-4)" }} />
        </div>
      </aside>

      {/* ---- WORK COLUMN ---- */}
      <div className="work">
        <header className="topbar">
          <div className="crumb">{crumb[0]} <span style={{ color: "var(--ink-4)" }}>/</span> <b>{crumb[1]}</b></div>
          <div className="spacer" />
          <div className="cmd">
            <Icon name="search" style={{ width: 14, height: 14 }} />
            <input placeholder="Command the empire…" onKeyDown={(e) => { if (e.key === "Enter") { const v = e.target.value; e.target.value = ""; if (v.trim()) { if (route === "world" && window.__worldCmd) window.__worldCmd(v); else { window.__pendingCmd = v; nav("world"); } } } }} />
            <span className="slash">/</span>
          </div>
          <button className="sysled focusable" title="System state — change in Tweaks" onClick={() => { const idx = SYS_STATES.findIndex(s => s.id === sys); setTweak("sysState", SYS_STATES[(idx + 1) % SYS_STATES.length].id); }}>
            <span className="led" style={{ background: DW.STATE_META[sysMeta.state].c, color: DW.STATE_META[sysMeta.state].c }} />
            <span>{sysMeta.label}</span>
            <span className="tag">SYS</span>
          </button>
          <Clock />
          <div className="iconbtn"><Icon name="bell" /><span className="badge-dot" /></div>
        </header>
        <main className="canvas">{render()}</main>
      </div>

      {/* ---- TWEAKS ---- */}
      <TweaksPanel title="Tweaks">
        <TweakSection label="System state" />
        <TweakRadio label="Empire status" value={t.sysState} options={["live", "crisis", "degraded", "offline"]} onChange={(v) => setTweak("sysState", v)} />
        <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--ink-3)", padding: "2px 2px 6px", lineHeight: 1.5 }}>Ripples across the World Map, the SYS badge, and degraded/offline tints.</div>
        <TweakSection label="Identity glow" />
        <TweakColor label="Accent" value={t.accent} options={["#A855F7", "#D946EF", "#4D9FFF", "#2FE0A1", "#D4B062"]} onChange={(v) => setTweak("accent", v)} />
        <TweakSlider label="Glow intensity" value={t.glow} min={0} max={2} step={0.1} onChange={(v) => setTweak("glow", v)} />
        <TweakSection label="Layout" />
        <TweakRadio label="Density" value={t.density} options={["compact", "regular"]} onChange={(v) => setTweak("density", v)} />
        <TweakToggle label="Ambient motion" value={t.motion} onChange={(v) => setTweak("motion", v)} />
        <TweakSection label="Reference" />
        <TweakButton label="Open handoff doc" onClick={() => window.open("Divonci World Handoff.html", "_blank")} />
      </TweaksPanel>
    </div>
  );
}

/* ---------------------------------------------- small auxiliary screens -- */
function OpsScreen({ nav }) {
  return (
    <div className="screen">
      <div className="screen-head"><div className="title"><span className="sub">Execution · ops</span>Deployments</div>
        <div className="meta">Live deployment surfaces across the empire. VV owns these; BroDex gates anything flagged.</div></div>
      <div className="cols c-4" style={{ marginBottom: "var(--s-6)" }}>
        {[["Live","clear","3"],["Degraded","caution","1"],["Held","crisis","1"],["Uptime","clear","99.9%"]].map(([k,s,v],i)=>(
          <Panel key={i}><div className="mtile"><div className="k"><Led state={s} size={7} />{k}</div><div className="v" style={{color:DW.STATE_META[s].c}}>{v}</div></div></Panel>
        ))}
      </div>
      <Panel className="tight">
        <PHead icon="ops" eyebrow="Deployment surfaces" />
        {DW.DEPLOYS.map(d=>(
          <div key={d.id} style={{display:"grid",gridTemplateColumns:"12px 1fr 120px 90px 110px",gap:14,alignItems:"center",padding:"15px 18px",borderBottom:"1px solid var(--hairline)"}}>
            <Led state={d.state} /><span style={{fontSize:13.5,color:"var(--ink)"}}>{d.name}</span>
            <span style={{fontFamily:"var(--font-mono)",fontSize:11,color:"var(--ink-3)",textTransform:"uppercase",letterSpacing:"0.06em"}}>{d.env}</span>
            <span style={{fontFamily:"var(--font-mono)",fontSize:11,color:"var(--ink-3)"}}>{d.v}</span>
            <span style={{textAlign:"right"}}><span className="sbadge" style={{color:DW.STATE_META[d.state].c}}>{d.label}</span></span>
          </div>
        ))}
      </Panel>
    </div>
  );
}
function ProjectsScreen({ nav }) {
  const [packets, setPackets] = useStateA(() => (window.PacketStore ? window.PacketStore.all() : []));
  const [drawer, setDrawer] = useStateA(false);
  useEffectA(() => {
    if (!window.PacketStore) return;
    return window.PacketStore.subscribe(setPackets);
  }, []);

  return (
    <div className="screen">
      <div className="screen-head">
        <div><div className="title"><span className="sub">Portfolio</span>Projects</div>
        <div className="meta">Every active project the empire is moving, with health and owning agent.</div></div>
        <div className="screen-actions">
          <button className="btn primary pkt-cta" onClick={() => setDrawer(true)}>
            <Icon name="plus" className="glyph" /> Create Project
          </button>
        </div>
      </div>
      <div className="cols c-3">
        {packets.map(p => { const a = DW.agent(p.owner); const c = DW.STATE_META[p.state].c; return (
          <Panel key={p.id} className="agent pcard-draft" style={{ "--ac": a.ac, cursor: "pointer" }} onClick={() => nav("foundry")}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 12 }}>
              <span className="pcard-badge"><Icon name="foundry" className="glyph" style={{ width: 10, height: 10 }} /> Draft · Packet</span>
              <Led state={p.state} />
            </div>
            <div style={{ fontFamily: "var(--font-display)", fontSize: 16, fontWeight: 600, marginBottom: 4 }}>{p.name}</div>
            <div style={{ fontFamily: "var(--font-mono)", fontSize: 9.5, color: "var(--ink-4)", letterSpacing: "0.06em", textTransform: "uppercase", marginBottom: 10 }}>{p.stage} · {p.decisions ? p.decisions.length : 0} open decision{(p.decisions && p.decisions.length === 1) ? "" : "s"}</div>
            <div className="riskbar" style={{ height: 6, marginBottom: 10 }}><i style={{ width: `${Math.max(6, p.health)}%`, background: c }} /></div>
            <div style={{ display: "flex", justifyContent: "space-between", fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--ink-3)" }}><span>readiness {p.health}</span><span>owner · {a.name}</span></div>
          </Panel>
        ); })}
        {DW.PROJECTS.map(p=>{const a=DW.agent(p.owner);return(
          <Panel key={p.id} className="agent" style={{"--ac":a.ac,cursor:"pointer"}} onClick={()=>nav("project:"+p.id)}>
            <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:12}}><span className="sbadge" style={{color:DW.STATE_META[p.state].c,fontSize:9}}>{p.stage}</span><Led state={p.state} /></div>
            <div style={{fontFamily:"var(--font-display)",fontSize:16,fontWeight:600,marginBottom:10}}>{p.name}</div>
            <div className="riskbar" style={{height:6,marginBottom:10}}><i style={{width:`${p.health}%`,background:DW.STATE_META[p.state].c}} /></div>
            <div style={{display:"flex",justifyContent:"space-between",fontFamily:"var(--font-mono)",fontSize:10,color:"var(--ink-3)"}}><span>health {p.health}</span><span>owner · {a.name}</span></div>
          </Panel>
        );})}
      </div>
      <FoundryPacketDrawer open={drawer} onClose={() => setDrawer(false)} nav={nav} />
    </div>
  );
}

Object.assign(window, { App, OpsScreen, ProjectsScreen });
ReactDOM.createRoot(document.getElementById("root")).render(<App />);
