@useorgx/openclaw-plugin 0.7.2 → 0.7.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dashboard/dist/assets/{CgaottFX.js → B1mDqDdy.js} +1 -1
- package/dashboard/dist/assets/B1mDqDdy.js.br +0 -0
- package/dashboard/dist/assets/B1mDqDdy.js.gz +0 -0
- package/dashboard/dist/assets/BDMstdfu.js +1 -0
- package/dashboard/dist/assets/BDMstdfu.js.br +0 -0
- package/dashboard/dist/assets/BDMstdfu.js.gz +0 -0
- package/dashboard/dist/assets/BTAEErUY.js +1 -0
- package/dashboard/dist/assets/BTAEErUY.js.br +0 -0
- package/dashboard/dist/assets/BTAEErUY.js.gz +0 -0
- package/dashboard/dist/assets/{8dksYiq4.js → BXapfumA.js} +1 -1
- package/dashboard/dist/assets/BXapfumA.js.br +0 -0
- package/dashboard/dist/assets/BXapfumA.js.gz +0 -0
- package/dashboard/dist/assets/BZZKPNDb.css +1 -0
- package/dashboard/dist/assets/BZZKPNDb.css.br +0 -0
- package/dashboard/dist/assets/BZZKPNDb.css.gz +0 -0
- package/dashboard/dist/assets/{rttbDbEx.js → BdusVDcP.js} +1 -1
- package/dashboard/dist/assets/BdusVDcP.js.br +0 -0
- package/dashboard/dist/assets/BdusVDcP.js.gz +0 -0
- package/dashboard/dist/assets/{D8JNX8kq.js → BwkNYH6r.js} +1 -1
- package/dashboard/dist/assets/BwkNYH6r.js.br +0 -0
- package/dashboard/dist/assets/BwkNYH6r.js.gz +0 -0
- package/dashboard/dist/assets/{CzCxAZlW.js → CRhvoVeH.js} +1 -1
- package/dashboard/dist/assets/CRhvoVeH.js.br +0 -0
- package/dashboard/dist/assets/CRhvoVeH.js.gz +0 -0
- package/dashboard/dist/assets/{B6wPWJ35.js → CYchPSem.js} +1 -1
- package/dashboard/dist/assets/CYchPSem.js.br +0 -0
- package/dashboard/dist/assets/CYchPSem.js.gz +0 -0
- package/dashboard/dist/assets/Cn07669c.js +212 -0
- package/dashboard/dist/assets/Cn07669c.js.br +0 -0
- package/dashboard/dist/assets/Cn07669c.js.gz +0 -0
- package/dashboard/dist/assets/{C8uM3AX8.js → DBG89Wsz.js} +1 -1
- package/dashboard/dist/assets/DBG89Wsz.js.br +0 -0
- package/dashboard/dist/assets/DBG89Wsz.js.gz +0 -0
- package/dashboard/dist/assets/{CZaT3ob_.js → DHoYGJ9i.js} +1 -1
- package/dashboard/dist/assets/DHoYGJ9i.js.br +0 -0
- package/dashboard/dist/assets/DHoYGJ9i.js.gz +0 -0
- package/dashboard/dist/assets/DHtZPEKd.js +1 -0
- package/dashboard/dist/assets/DHtZPEKd.js.br +0 -0
- package/dashboard/dist/assets/DHtZPEKd.js.gz +0 -0
- package/dashboard/dist/assets/{B5zYRHc3.js → DUaqjbT7.js} +1 -1
- package/dashboard/dist/assets/DUaqjbT7.js.br +0 -0
- package/dashboard/dist/assets/DUaqjbT7.js.gz +0 -0
- package/dashboard/dist/assets/{IUexzymk.js → Dlz0Cm_E.js} +1 -1
- package/dashboard/dist/assets/Dlz0Cm_E.js.br +0 -0
- package/dashboard/dist/assets/Dlz0Cm_E.js.gz +0 -0
- package/dashboard/dist/assets/{CC63EwFD.js → E8q3xNGK.js} +1 -1
- package/dashboard/dist/assets/E8q3xNGK.js.br +0 -0
- package/dashboard/dist/assets/E8q3xNGK.js.gz +0 -0
- package/dashboard/dist/assets/VH0fzk6I.js +1 -0
- package/dashboard/dist/assets/VH0fzk6I.js.br +0 -0
- package/dashboard/dist/assets/VH0fzk6I.js.gz +0 -0
- package/dashboard/dist/assets/bxgRC96y.js +1 -0
- package/dashboard/dist/assets/bxgRC96y.js.br +0 -0
- package/dashboard/dist/assets/bxgRC96y.js.gz +0 -0
- package/dashboard/dist/index.html +2 -2
- package/dashboard/dist/index.html.br +0 -0
- package/dashboard/dist/index.html.gz +0 -0
- package/dist/http/helpers/auto-continue-engine.js +29 -11
- package/dist/http/helpers/autopilot-slice-utils.js +7 -10
- package/dist/http/helpers/openclaw-cli.js +2 -2
- package/dist/http/index.js +160 -4
- package/dist/http/routes/live-legacy.d.ts +2 -0
- package/dist/http/routes/live-legacy.js +97 -0
- package/dist/http/routes/mission-control-read.js +106 -63
- package/dist/openclaw-settings.js +3 -2
- package/dist/openclaw.plugin.json +1 -1
- package/dist/sync/outbox-replay.js +17 -8
- package/openclaw.plugin.json +1 -1
- package/package.json +1 -1
- package/dashboard/dist/assets/6mILZQ2a.js +0 -1
- package/dashboard/dist/assets/6mILZQ2a.js.br +0 -0
- package/dashboard/dist/assets/6mILZQ2a.js.gz +0 -0
- package/dashboard/dist/assets/8dksYiq4.js.br +0 -0
- package/dashboard/dist/assets/8dksYiq4.js.gz +0 -0
- package/dashboard/dist/assets/B5zYRHc3.js.br +0 -0
- package/dashboard/dist/assets/B5zYRHc3.js.gz +0 -0
- package/dashboard/dist/assets/B6wPWJ35.js.br +0 -0
- package/dashboard/dist/assets/B6wPWJ35.js.gz +0 -0
- package/dashboard/dist/assets/BWEwjt1W.js +0 -1
- package/dashboard/dist/assets/BWEwjt1W.js.br +0 -0
- package/dashboard/dist/assets/BWEwjt1W.js.gz +0 -0
- package/dashboard/dist/assets/BzRbDCAD.css +0 -1
- package/dashboard/dist/assets/BzRbDCAD.css.br +0 -0
- package/dashboard/dist/assets/BzRbDCAD.css.gz +0 -0
- package/dashboard/dist/assets/C8uM3AX8.js.br +0 -0
- package/dashboard/dist/assets/C8uM3AX8.js.gz +0 -0
- package/dashboard/dist/assets/C9jy61eu.js +0 -212
- package/dashboard/dist/assets/C9jy61eu.js.br +0 -0
- package/dashboard/dist/assets/C9jy61eu.js.gz +0 -0
- package/dashboard/dist/assets/CC63EwFD.js.br +0 -0
- package/dashboard/dist/assets/CC63EwFD.js.gz +0 -0
- package/dashboard/dist/assets/CZaT3ob_.js.br +0 -0
- package/dashboard/dist/assets/CZaT3ob_.js.gz +0 -0
- package/dashboard/dist/assets/CgaottFX.js.br +0 -0
- package/dashboard/dist/assets/CgaottFX.js.gz +0 -0
- package/dashboard/dist/assets/CzCxAZlW.js.br +0 -0
- package/dashboard/dist/assets/CzCxAZlW.js.gz +0 -0
- package/dashboard/dist/assets/D3iMTYEj.js +0 -1
- package/dashboard/dist/assets/D3iMTYEj.js.br +0 -0
- package/dashboard/dist/assets/D3iMTYEj.js.gz +0 -0
- package/dashboard/dist/assets/D8JNX8kq.js.br +0 -0
- package/dashboard/dist/assets/D8JNX8kq.js.gz +0 -0
- package/dashboard/dist/assets/DnA8dpj6.js +0 -1
- package/dashboard/dist/assets/DnA8dpj6.js.br +0 -0
- package/dashboard/dist/assets/DnA8dpj6.js.gz +0 -0
- package/dashboard/dist/assets/IUexzymk.js.br +0 -0
- package/dashboard/dist/assets/IUexzymk.js.gz +0 -0
- package/dashboard/dist/assets/ic2FaMnh.js +0 -1
- package/dashboard/dist/assets/ic2FaMnh.js.br +0 -0
- package/dashboard/dist/assets/ic2FaMnh.js.gz +0 -0
- package/dashboard/dist/assets/rttbDbEx.js.br +0 -0
- package/dashboard/dist/assets/rttbDbEx.js.gz +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{r,a as ts,j as e,u as On,b as Rt}from"./cNrhgGc1.js";import{I as zn,u as wr,o as vr,N as mn}from"./bxgRC96y.js";import{q as hs,i as fs,a as jr,t as kr,b as At,h as dt,c as Nr,E as Ge,d as W,n as Sr,u as ns,f as Oe,A as Un,s as ms,e as gs,g as _s,j as ps,I as bs,P as Cr,k as Fr,l as Wn,m as Hn,o as Qn,M as Ir,p as os,r as Er,v as pn,w as Vt,x as Jt,y as Hs,z as Vn,B as Ar,C as xn,U as Dr,D as Mr}from"./Cn07669c.js";import{S as vt}from"./DHoYGJ9i.js";import{A as ht,m as fe,R as $r,a as Tr,L as _r}from"./CxQ08qFN.js";import{E as ys}from"./DBG89Wsz.js";import"./C-KIc3Wc.js";import"./BJgZIVUQ.js";function Lr({activities:t,agents:s,initiatives:a}){return r.useMemo(()=>{const n=new Map,d=(o,c,h,f)=>{const y=n.get(o)??[];y.some(u=>u.id===c)||(y.push({id:c,name:h,confidence:f}),n.set(o,y))};return t.forEach(o=>{const c="metadata"in o&&o.metadata&&typeof o.metadata=="object"?o.metadata:null,h=c&&typeof c=="object"?c:{},f=("initiativeId"in o&&typeof o.initiativeId=="string"?o.initiativeId:void 0)??h.initiativeId??void 0,y=o.agentId??void 0,u=("agentName"in o&&typeof o.agentName=="string"?o.agentName:"agent"in o&&typeof o.agent=="string"?o.agent:void 0)??y??"Unknown";f&&y&&d(f,y,u,"high")}),a.forEach(o=>{var c;(c=o.avatars)!=null&&c.length&&o.avatars.forEach(h=>{const f=s.find(y=>y.name.toLowerCase()===h.toLowerCase());f?d(o.id,f.id,f.name,"medium"):d(o.id,`avatar:${h}`,h,"medium")})}),s.forEach(o=>{if(!o.task)return;const c=o.task.toLowerCase();a.forEach(h=>{h.name.toLowerCase().split(/\s+/).filter(F=>F.length>3).some(F=>c.includes(F))&&d(h.id,o.id,o.name,"low")})}),n},[t,s,a])}function Kn(t){const s=r.useRef(null),a=r.useCallback((n,d,o,c)=>{if(o&&s.current!==null){const h=t.indexOf(s.current),f=t.indexOf(n);if(h!==-1&&f!==-1){const y=Math.min(h,f),u=Math.max(h,f),F=t.slice(y,u+1);c(T=>{const v=new Set(T);for(const l of F)d?v.add(l):v.delete(l);return v});return}}c(h=>{const f=new Set(h);return d?f.add(n):f.delete(n),f}),s.current=n},[t]);return{lastClickedId:s,handleSelect:a}}const Br=100,Pr=5,Rr=75,qr=3,Or=["workstream","milestone","task"],zr=60;function ls(t){const s=Date.parse(t??"");return Number.isFinite(s)?s:0}function Ur(t){return t.toLowerCase().trim().split(/\s+/).filter(Boolean)}function Wr(t,s){const a=[];for(let n=0;n<t.length;n+=s)a.push(t.slice(n,n+s));return a}async function hn(t,s,a){var o;const n=[];let d=0;for(let c=0;c<a;c+=1){const h=new URLSearchParams(t);h.set("limit",String(s)),h.set("offset",String(d));const f=await fetch(`/orgx/api/entities?${h.toString()}`);if(!f.ok)break;const y=await f.json(),u=y.data??[];if(n.push(...u),!!!((o=y.pagination)!=null&&o.has_more)||u.length===0)break;d+=s}return n}function fn(t,s,a,n){const d=t.name.toLowerCase(),o=(t.description??"").toLowerCase();let c=0;n&&(c+=65),d===s&&(c+=140),d.startsWith(s)&&(c+=100),d.includes(s)&&(c+=80),o.includes(s)&&(c+=40);for(const h of a)d.includes(h)&&(c+=22),o.includes(h)&&(c+=8);return c}function Hr(t,s,a=null){const n=t.trim().toLowerCase(),d=(a==null?void 0:a.trim())??"";return ts({queryKey:hs.initiativeSearch({query:n,projectId:d||null}),enabled:s&&n.length>=2,queryFn:async()=>{var v;if(n.length<2||fs())return[];const o=l=>{const b=new URLSearchParams(l);return d.length>0&&b.set("workspace_id",d),b},c=await hn(o({type:"initiative",search:n}),Br,Pr),h=await Promise.all(Or.map(l=>hn(o({type:l,search:n}),Rr,qr))),f=new Set;for(const l of h)for(const b of l){const x=(v=b.initiative_id)==null?void 0:v.trim();x&&f.add(x)}const y=[];for(const l of Wr(Array.from(f),zr)){if(l.length===0)continue;const b=o({type:"initiative",ids:l.join(","),limit:String(l.length),offset:"0"}),x=await fetch(`/orgx/api/entities?${b.toString()}`);if(!x.ok)continue;const j=await x.json();y.push(...j.data??[])}const u=[...c,...y],F=new Map;for(const l of u){const b=F.get(l.id);if(!b){F.set(l.id,l);continue}ls(l.updated_at??l.created_at)>ls(b.updated_at??b.created_at)&&F.set(l.id,l)}const T=Ur(n);return Array.from(F.values()).filter(l=>jr(l.status)).map(kr).filter(l=>{if(f.has(l.id))return!0;const b=[l.name,l.description??"",l.rawStatus??"",l.status].join(" ").toLowerCase();return T.every(x=>b.includes(x))}).sort((l,b)=>{const x=fn(b,n,T,f.has(b.id))-fn(l,n,T,f.has(l.id));return x!==0?x:ls(b.updatedAt??b.createdAt)-ls(l.updatedAt??l.createdAt)})},staleTime:15e3})}function Qs({value:t,onChange:s,placeholder:a}){return e.jsxs("label",{className:"relative block",children:[e.jsx("span",{className:"sr-only",children:a}),e.jsxs("svg",{className:"pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-muted",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("circle",{cx:"11",cy:"11",r:"8"}),e.jsx("path",{d:"m21 21-4.3-4.3"})]}),e.jsx("input",{type:"text",value:t,onChange:n=>s(n.target.value),placeholder:a,className:"w-full rounded-xl border border-white/[0.08] bg-white/[0.03] py-2.5 pl-10 pr-8 text-body text-white placeholder:text-muted transition-all focus:border-[#BFFF00]/30 focus:bg-white/[0.05] focus:outline-none"}),t.length>0&&e.jsx("button",{type:"button",onClick:()=>s(""),className:"absolute right-2.5 top-1/2 -translate-y-1/2 rounded-full p-0.5 text-muted transition-colors hover:text-primary","aria-label":"Clear search",children:e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:e.jsx("path",{d:"M18 6 6 18M6 6l12 12"})})})]})}async function Lt(t){if(!t.ok){const s=await t.json().catch(()=>null),a=typeof(s==null?void 0:s.error)=="string"&&s.error||typeof(s==null?void 0:s.message)=="string"&&s.message||`Request failed (${t.status})`;throw new Error(dt(a))}return t}function Qr(t){const s=t.trim().toLowerCase();return s==="completed"||s==="done"?"completed":s==="blocked"||s==="at_risk"?"blocked":s==="paused"||s==="hold"?"paused":s==="deleted"||s==="archived"||s==="cancelled"?"completed":"active"}function Ls(t){const s=t.trim().toLowerCase();return s==="deleted"||s==="archived"||s==="cancelled"}function Vr(t){const s=t.trim().toLowerCase();return s==="blocked"||s==="at_risk"?"blocked":s==="paused"||s==="hold"?"paused":s==="completed"||s==="done"?"completed":"running"}function Kr(t){const s=On(),a=At({authToken:t.authToken,embedMode:t.embedMode,contentTypeJson:!0}),n=()=>{s.invalidateQueries({queryKey:["live-data"]}),s.invalidateQueries({queryKey:["live-initiatives"]}),s.invalidateQueries({queryKey:["initiative-details"]}),s.invalidateQueries({queryKey:["entities"]}),s.invalidateQueries({queryKey:["mission-control-graph"]}),s.invalidateQueries({queryKey:["mission-control-next-up"]})},d=(v,l)=>{s.setQueryData(["initiative-tombstones"],b=>{const x=Array.isArray(b)?b.filter(S=>typeof S=="string"):[],j=x.includes(v);return l?j?x:[...x,v]:j?x.filter(S=>S!==v):x})},o=(v,l)=>{const b=Qr(l),x=new Date().toISOString(),j=Ls(l);d(v,j);const S=g=>{if(!Array.isArray(g))return g;if(j){const H=g.filter(O=>{if(!O||typeof O!="object")return!0;const ee=O;return!(typeof ee.id=="string"&&ee.id===v)});return H.length===g.length?g:H}let I=!1;const q=g.map(H=>{if(!H||typeof H!="object")return H;const O=H;return typeof O.id!="string"||O.id!==v?H:(I=!0,{...O,status:b,rawStatus:l,updatedAt:x})});return I?q:g};s.setQueriesData({queryKey:["entities"]},S),s.setQueriesData({queryKey:["live-initiatives"]},S)},c=(v,l,b="status")=>{const x=Vr(l);s.setQueriesData({queryKey:["live-data"]},j=>{if(!j||typeof j!="object")return j;const S=j,g=S.sessions;if(!g||typeof g!="object")return j;const I=g,q=I.nodes;if(!Array.isArray(q))return j;let H=!1;const O=b==="delete"?q.filter(D=>{if(!D||typeof D!="object")return!0;const w=D,$=(typeof w.initiativeId=="string"?w.initiativeId:null)===v;return $&&(H=!0),!$}):q.map(D=>{if(!D||typeof D!="object")return D;const w=D;return(typeof w.initiativeId=="string"?w.initiativeId:null)!==v||w.status===x?D:(H=!0,{...w,status:x})});if(!H)return j;const ee=new Set,te=new Set;for(const D of O){if(!D||typeof D!="object")continue;const w=D;typeof w.id=="string"&&ee.add(w.id),typeof w.groupId=="string"&&te.add(w.groupId)}const J=Array.isArray(I.edges)?I.edges.filter(D=>{if(!D||typeof D!="object")return!1;const w=D,P=typeof w.parentId=="string"?w.parentId:null,$=typeof w.childId=="string"?w.childId:null;return P!==null&&$!==null&&ee.has(P)&&ee.has($)}):I.edges,Q=Array.isArray(I.groups)?I.groups.filter(D=>{if(!D||typeof D!="object")return!1;const w=D;return typeof w.id=="string"&&te.has(w.id)}):I.groups;return{...S,sessions:{...I,nodes:O,edges:J,groups:Q}}})},h={start:"in_progress",complete:"done",block:"blocked",unblock:"in_progress",pause:"paused",resume:"active"},f=Rt({mutationFn:async v=>{const{type:l,...b}=v,x=await fetch("/orgx/api/entities",{method:"POST",headers:a,body:JSON.stringify({type:l,...b})});return await Lt(x),x.json()},onSuccess:n}),y=Rt({mutationFn:async v=>{const{type:l,id:b,...x}=v,j=await fetch("/orgx/api/entities",{method:"PATCH",headers:a,body:JSON.stringify({type:l,id:b,...x})});return await Lt(j),j.json()},onSuccess:(v,l)=>{l.type.trim().toLowerCase()==="initiative"&&typeof l.status=="string"&&l.status.trim().length>0&&(o(l.id,l.status),c(l.id,l.status,Ls(l.status)?"delete":"status")),n()}}),u=Rt({mutationFn:async v=>{const l=await fetch(`/orgx/api/entities/${encodeURIComponent(v.type)}/${encodeURIComponent(v.id)}/delete`,{method:"POST",headers:a,body:"{}"});return await Lt(l),l.json()},onSuccess:(v,l)=>{l.type.trim().toLowerCase()==="initiative"&&(o(l.id,"archived"),c(l.id,"archived","delete")),n()}}),F=Rt({mutationFn:async v=>{const l=await fetch(`/orgx/api/entities/${encodeURIComponent(v.type)}/${encodeURIComponent(v.id)}/${encodeURIComponent(v.action)}`,{method:"POST",headers:a,body:JSON.stringify({force:v.force??!1})});return await Lt(l),l.json()},onSuccess:(v,l)=>{if(l.type.trim().toLowerCase()==="initiative"){const b=h[l.action.trim().toLowerCase()];b&&(o(l.id,b),c(l.id,b,"status"))}n()}}),T=Rt({mutationFn:async v=>{const l=Array.from(new Map((v.items??[]).filter(I=>typeof(I==null?void 0:I.type)=="string"&&I.type.trim().length>0&&typeof(I==null?void 0:I.id)=="string"&&I.id.trim().length>0).map(I=>[`${I.type}:${I.id}`,I])).values());if(l.length===0)return{updated:0,failed:0,errors:[]};if(v.mode==="action"&&!v.action)throw new Error("bulk action requires an action name");const b=async I=>{try{if(v.mode==="delete"){const H=await fetch(`/orgx/api/entities/${encodeURIComponent(I.type)}/${encodeURIComponent(I.id)}/delete`,{method:"POST",headers:a,body:"{}"});return await Lt(H),{ok:!0}}if(v.mode==="update"){const H=await fetch("/orgx/api/entities",{method:"PATCH",headers:a,body:JSON.stringify({type:I.type,id:I.id,...v.updates??{}})});return await Lt(H),{ok:!0}}const q=await fetch(`/orgx/api/entities/${encodeURIComponent(I.type)}/${encodeURIComponent(I.id)}/${encodeURIComponent(v.action)}`,{method:"POST",headers:a,body:JSON.stringify({force:v.force??!1})});return await Lt(q),{ok:!0}}catch(q){return{ok:!1,error:q instanceof Error?q.message:"Unknown bulk mutation failure"}}},x=await Promise.all(l.map(I=>b(I)));let j=0,S=0;const g=[];for(const I of x)I.ok?j+=1:(S+=1,g.push(I.error));return{updated:j,failed:S,errors:g}},onSuccess:(v,l)=>{var x;const b=(l.items??[]).filter(j=>j.type.trim().toLowerCase()==="initiative");if(b.length>0){if(l.mode==="update"&&typeof((x=l.updates)==null?void 0:x.status)=="string"&&l.updates.status.trim().length>0)for(const j of b)o(j.id,l.updates.status),c(j.id,l.updates.status,Ls(l.updates.status)?"delete":"status");else if(l.mode==="delete")for(const j of b)o(j.id,"archived"),c(j.id,"archived","delete");else if(l.mode==="action"&&l.action){const j=h[l.action.trim().toLowerCase()];if(j)for(const S of b)o(S.id,j),c(S.id,j,"status")}}n()}});return{createEntity:f,updateEntity:y,deleteEntity:u,entityAction:F,bulkEntityMutation:T}}const Gn=r.createContext(null);function Dt(){const t=r.useContext(Gn);if(!t)throw new Error("useMissionControl must be used within MissionControlProvider");return t}function Gr({children:t,agentEntityMap:s,authToken:a,embedMode:n}){const[d,o]=r.useState(new Set),[c,h]=r.useState(null),[f,y]=r.useState(""),[u,F]=r.useState([]),[T,v]=r.useState("target"),[l,b]=r.useState("any"),[x,j]=r.useState(""),[S,g]=r.useState(""),[I,q]=r.useState("status"),[H,O]=r.useState("default"),ee=Kr({authToken:a,embedMode:n}),te=r.useCallback(E=>{o(V=>{const ae=new Set(V);return ae.has(E)?ae.delete(E):ae.add(E),ae})},[]),J=r.useCallback(E=>{o(V=>{if(V.has(E))return V;const ae=new Set(V);return ae.add(E),ae})},[]),Q=r.useCallback(E=>{o(new Set(E))},[]),D=r.useCallback(()=>{o(new Set)},[]),w=r.useCallback(E=>{h(E)},[]),P=r.useCallback(()=>{h(null)},[]),$=r.useCallback(E=>{const V=Array.from(new Set((E??[]).map(ae=>ae.trim().toLowerCase()).filter(Boolean)));F(V)},[]),R=r.useCallback(E=>{F(V=>{const ae=E.trim().toLowerCase();return ae?V.includes(ae)?V.filter(De=>De!==ae):[...V,ae]:V})},[]),_=r.useCallback(()=>{y(""),F([]),v("target"),b("any"),j(""),g("")},[]),G=x.trim().length>0||S.trim().length>0,B=l!=="any"&&(l!=="custom_range"||G),X=u.length+(B?1:0),ie=f.trim().length>0||X>0,ue=r.useMemo(()=>({agentEntityMap:s,expandedInitiatives:d,modalTarget:c,searchQuery:f,statusFilters:u,dateField:T,datePreset:l,dateStart:x,dateEnd:S,activeFilterCount:X,hasActiveFilters:ie,groupBy:I,sortBy:H,authToken:a,embedMode:n,mutations:ee,toggleExpanded:te,expandInitiative:J,expandAll:Q,collapseAll:D,openModal:w,closeModal:P,setSearchQuery:y,setStatusFilters:$,toggleStatusFilter:R,setDateField:v,setDatePreset:b,setDateStart:j,setDateEnd:g,setGroupBy:q,setSortBy:O,clearFilters:_}),[s,d,c,f,u,T,l,x,S,X,ie,I,H,a,n,ee,te,J,Q,D,w,P,$,R,v,b,j,g,q,O,_]);return e.jsx(Gn.Provider,{value:ue,children:t})}function Jr(t){if(typeof t!="number"||!Number.isFinite(t))return;const s=Math.max(0,Math.trunc(t));return s>0?s-1:s}function Yr(t){return t==="workstream"?"W":t==="milestone"?"M":t==="task"?"T":"I"}function Bs(t){return{initiative:{id:t,title:"Initiative",status:"active",summary:null,assignedAgents:[]},nodes:[],edges:[],recentTodos:[]}}function Xr(t){const s=new Date().toISOString(),a=t==="init-2"?"Black Friday Email":"Q4 Feature Ship",n=`${t}:ws:design`,d=`${t}:ms:polish`,o=`${t}:task:tokens`,c=`${t}:task:qa`;return{initiative:{id:t,title:a,status:"active",summary:"Demo mode graph from local fixture data.",assignedAgents:[{id:"dana",name:"Dana",domain:"design"}]},nodes:[{id:n,type:"workstream",title:"Dashboard UI pass",status:"active",parentId:t,initiativeId:t,workstreamId:n,milestoneId:null,priorityNum:1,priorityLabel:"P1",dependencyIds:[],dueDate:null,etaEndAt:null,expectedDurationHours:8,expectedBudgetUsd:1500,assignedAgents:[{id:"dana",name:"Dana",domain:"design"}],updatedAt:s},{id:d,type:"milestone",title:"Polish pass",status:"active",parentId:n,initiativeId:t,workstreamId:n,milestoneId:d,priorityNum:1,priorityLabel:"P1",dependencyIds:[n],dueDate:null,etaEndAt:null,expectedDurationHours:4,expectedBudgetUsd:900,assignedAgents:[{id:"dana",name:"Dana",domain:"design"}],updatedAt:s},{id:o,type:"task",title:"Refine queue action ergonomics",status:"todo",parentId:d,initiativeId:t,workstreamId:n,milestoneId:d,priorityNum:1,priorityLabel:"P1",dependencyIds:[d],dueDate:null,etaEndAt:null,expectedDurationHours:2,expectedBudgetUsd:450,assignedAgents:[{id:"dana",name:"Dana",domain:"design"}],updatedAt:s},{id:c,type:"task",title:"Mobile QA sweep",status:"active",parentId:d,initiativeId:t,workstreamId:n,milestoneId:d,priorityNum:2,priorityLabel:"P2",dependencyIds:[o],dueDate:null,etaEndAt:null,expectedDurationHours:2,expectedBudgetUsd:420,assignedAgents:[{id:"mark",name:"Mark",domain:"engineering"}],updatedAt:s}],edges:[{from:n,to:d,kind:"depends_on"},{from:d,to:o,kind:"depends_on"},{from:o,to:c,kind:"depends_on"}],recentTodos:[o,c]}}function Zr({initiativeId:t,authToken:s=null,embedMode:a=!1,enabled:n=!0}){var y,u;const d=fs(),o=Nr(t),c=r.useMemo(()=>hs.missionControlGraph({initiativeId:t,authToken:s,embedMode:a}),[t,s,a]),h=ts({queryKey:c,enabled:n&&!!t&&o,queryFn:async()=>{if(!t)throw new Error("initiativeId is required");if(d)return Xr(t);if(!o)return Bs(t);const F=new URLSearchParams({initiative_id:t}),T={};a&&(T["X-Orgx-Embed"]="true"),s&&(T.Authorization=`Bearer ${s}`);const v=Object.keys(T).length>0?T:void 0,l=await fetch(`/orgx/api/mission-control/graph?${F.toString()}`,{headers:v});if(!l.ok){const j=await l.json().catch(()=>null),S=typeof(j==null?void 0:j.error)=="string"&&j.error||typeof(j==null?void 0:j.message)=="string"&&j.message||`Failed to fetch Mission Control graph (${l.status})`;return{...Bs(t),degraded:[S]}}const b=await l.json(),x=Array.isArray(b.nodes)?b.nodes.map(j=>{const S=j,g=Jr(S.sequenceIndex??S.sequence);if(typeof g!="number")return j;const I=typeof S.hierarchyLabel=="string"&&S.hierarchyLabel.trim().length>0;return{...S,sequenceIndex:g,hierarchyLabel:I?S.hierarchyLabel:`${Yr(String(S.type??"initiative"))}${g+1}`}}):[];return{...b,nodes:x.length>0?x:b.nodes}}});return{graph:h.data??(t?Bs(t):null),isLoading:o?h.isLoading:!1,error:o?((y=h.error)==null?void 0:y.message)??null:null,degraded:o?((u=h.data)==null?void 0:u.degraded)??[]:[],refetch:h.refetch}}function xs({type:t,className:s=""}){return e.jsx(Ge,{type:t,className:s,size:14})}function ea(t){return t==="initiative"?"Initiatives":t==="workstream"?"Workstreams":t==="milestone"?"Milestones":"Tasks"}function ta({nodes:t,edges:s,selectedNodeId:a,focusedWorkstreamId:n,onSelectNode:d}){const o=r.useMemo(()=>new Map(t.map(g=>[g.id,g])),[t]),[c,h]=r.useState(""),[f,y]=r.useState(!1),u=c.trim().toLowerCase(),F=r.useMemo(()=>{if(!n)return new Set(t.map(q=>q.id));const g=new Set;for(const q of t)(q.type==="initiative"||q.id===n||q.workstreamId===n)&&g.add(q.id);let I=!0;for(;I;){I=!1;for(const q of s)(g.has(q.from)||g.has(q.to))&&(!g.has(q.from)||!g.has(q.to))&&(g.add(q.from),g.add(q.to),I=!0)}return g},[n,t,s]),T=t.filter(g=>F.has(g.id)),v=s.filter(g=>F.has(g.from)&&F.has(g.to)),l=r.useMemo(()=>{if(!a)return new Set;const g=new Set([a]);for(const I of v)I.from===a&&g.add(I.to),I.to===a&&g.add(I.from);return g},[a,v]),b=r.useMemo(()=>{let g=new Set(Array.from(F));return f&&a&&(g=new Set(Array.from(g).filter(I=>l.has(I)))),u.length>0&&(g=new Set(Array.from(g).filter(I=>{const q=o.get(I);return q?q.title.toLowerCase().includes(u):!1}))),g},[o,u,l,f,a,F]),x=t.filter(g=>b.has(g.id)),j=s.filter(g=>b.has(g.from)&&b.has(g.to)),S={initiative:x.filter(g=>g.type==="initiative"),workstream:x.filter(g=>g.type==="workstream"),milestone:x.filter(g=>g.type==="milestone"),task:x.filter(g=>g.type==="task")};return T.length===0?null:e.jsxs("section",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:[x.length," nodes · ",j.length," links"]}),n&&e.jsx("span",{className:"status-pill","data-tone":"active",children:"Focused workstream"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("input",{value:c,onChange:g=>h(g.target.value),placeholder:"Filter nodes...",className:"h-9 flex-1 min-w-[200px] rounded-lg border border-strong bg-black/30 px-3 text-caption text-primary placeholder:text-faint transition-colors focus:border-[#BFFF00]/35 focus:outline-none"}),a&&e.jsx("button",{type:"button",onClick:()=>y(g=>!g),"aria-pressed":f,"data-state":f?"active":"idle",className:"control-pill px-3 text-caption font-semibold",title:"Show only the selected node and its direct neighbors",children:"Related only"}),(c.trim().length>0||f)&&e.jsx("button",{type:"button",onClick:()=>{h(""),y(!1)},className:"control-pill px-3 text-caption",children:"Reset"})]}),x.length===0?e.jsx("div",{className:"rounded-xl border border-white/[0.07] bg-black/[0.14] px-3 py-3 text-caption text-secondary",children:"No nodes match this view. Clear filters or select a different node to see connected work."}):e.jsx("div",{className:`grid gap-2 ${Object.values(S).filter(g=>g.length>0).length<=2?"grid-cols-1 sm:grid-cols-2":"md:grid-cols-2 xl:grid-cols-4"}`,children:Object.keys(S).filter(g=>S[g].length>0).map(g=>e.jsxs("div",{className:"rounded-xl border border-white/[0.07] bg-black/[0.14] p-2.5",children:[e.jsxs("div",{className:"mb-1.5 text-micro uppercase tracking-[0.09em] text-secondary",children:[ea(g)," (",S[g].length,")"]}),e.jsxs("div",{className:"space-y-1",children:[S[g].slice(0,10).map(I=>{const q=a===I.id,H=!q&&l.has(I.id);return e.jsxs("button",{type:"button",onClick:()=>d(I.id),title:I.title,className:`flex w-full items-center gap-1.5 rounded-md border px-2 py-1 text-left transition-colors ${q?"border-[#BFFF00]/35 bg-[#BFFF00]/12":H?"border-[#14B8A6]/35 bg-[#14B8A6]/12":"border-strong bg-white/[0.03] hover:bg-white/[0.08]"}`,children:[e.jsx(xs,{type:I.type}),e.jsx("span",{className:"truncate text-caption text-primary",children:I.title})]},I.id)}),S[g].length>10&&e.jsxs("div",{className:"px-1 text-micro text-muted",children:["+",S[g].length-10," more"]})]})]},g))}),j.length>0&&e.jsxs("div",{className:"rounded-xl border border-white/[0.07] bg-black/[0.14] px-2.5 py-2",children:[e.jsx("div",{className:"mb-1 text-micro uppercase tracking-[0.08em] text-muted",children:"Dependency links"}),e.jsx("div",{className:"max-h-[110px] space-y-1 overflow-auto pr-1",children:j.slice(0,36).map(g=>{const I=o.get(g.from),q=o.get(g.to);if(!I||!q)return null;const H=a===I.id||a===q.id;return e.jsxs("button",{type:"button",onClick:()=>d(q.id),className:"flex w-full items-center gap-1 rounded-md px-1.5 py-1 text-left hover:bg-white/[0.06]",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full",style:{backgroundColor:H?W.lime:"rgba(255,255,255,0.35)"}}),e.jsx("span",{className:"truncate text-micro text-primary",children:I.title}),e.jsx("span",{className:"text-micro text-muted",children:"→"}),e.jsx("span",{className:"truncate text-micro text-primary",children:q.title})]},`${g.from}-${g.to}`)})})]})]})}const sa=new Set(["completed","complete","done","resolved","success","succeeded","archived","cancelled","canceled","stopped","deleted"]);function na(t){return sa.has(Sr(t))}function tt(t){return na(t)}function ws(t){return Number.isFinite(t)?Math.max(0,Math.min(100,Math.round(t))):0}function qt(t,s){return s<=0?0:ws(t/s*100)}function ra({dependencies:t,allNodes:s,disabled:a=!1,onSave:n}){const[d,o]=r.useState(!1),[c,h]=r.useState(""),[f,y]=r.useState(t),u=r.useMemo(()=>new Map(s.map(l=>[l.id,l])),[s]),F=r.useMemo(()=>{const l=c.trim().toLowerCase(),b=[...s].sort((x,j)=>x.title.localeCompare(j.title));return l?b.filter(x=>x.title.toLowerCase().includes(l)||x.id.toLowerCase().includes(l)).slice(0,16):b.slice(0,16)},[s,c]),T=()=>{n(Array.from(new Set(f))),o(!1)},v=l=>{y(b=>b.includes(l)?b.filter(x=>x!==l):[...b,l])};return e.jsxs("div",{className:"relative",children:[e.jsx("button",{type:"button",disabled:a,onClick:()=>{h(""),y(t),o(l=>!l)},className:"rounded-md border border-strong bg-white/[0.04] px-2 py-1 text-micro text-primary transition-colors hover:bg-white/[0.08] disabled:opacity-40",children:t.length>0?`${t.length} linked`:"Set links"}),d&&e.jsxs("div",{className:"surface-tier-2 absolute right-0 z-20 mt-1.5 w-[320px] rounded-xl p-2.5 shadow-[0_20px_40px_rgba(0,0,0,0.45)]",children:[e.jsx("label",{className:"text-micro uppercase tracking-[0.08em] text-secondary",children:"Link dependencies"}),e.jsx("input",{value:c,onChange:l=>h(l.target.value),placeholder:"Search by title or id...",className:"mt-1.5 h-9 w-full rounded-md border border-strong bg-black/25 px-2.5 text-caption text-bright outline-none transition-colors placeholder:text-muted focus:border-[#BFFF00]/35"}),e.jsx("div",{className:"mt-2 flex max-h-[84px] flex-wrap gap-1.5 overflow-y-auto rounded-md border border-white/[0.08] bg-black/20 p-1.5",children:f.length===0?e.jsx("span",{className:"text-micro text-muted",children:"No links selected"}):f.map(l=>{var x;const b=((x=u.get(l))==null?void 0:x.title)??l;return e.jsxs("button",{type:"button",onClick:()=>v(l),className:"inline-flex items-center gap-1 rounded-full border border-strong bg-white/[0.05] px-2 py-0.5 text-micro text-primary transition-colors hover:bg-white/[0.1]",title:b,children:[e.jsx("span",{className:"max-w-[180px] truncate",children:b}),e.jsx("span",{className:"text-secondary",children:"×"})]},l)})}),e.jsx("div",{className:"mt-2 max-h-[150px] space-y-1 overflow-y-auto rounded-md border border-white/[0.08] bg-black/20 p-1.5",children:F.length===0?e.jsx("div",{className:"px-1 text-micro text-muted",children:"No matching nodes"}):F.map(l=>{const b=f.includes(l.id);return e.jsxs("button",{type:"button",onClick:()=>v(l.id),className:`flex w-full items-center justify-between rounded-md border px-2 py-1 text-left text-micro transition-colors ${b?"border-[#BFFF00]/32 bg-[#BFFF00]/12 text-[#D8FFA1]":"border-white/[0.1] bg-white/[0.03] text-primary hover:bg-white/[0.08]"}`,children:[e.jsxs("span",{className:"min-w-0 pr-2",children:[e.jsx("span",{className:"block truncate",children:l.title}),e.jsxs("span",{className:"block truncate text-muted",children:[l.id.slice(0,8),"…"]})]}),e.jsx("span",{className:"font-semibold",children:b?"Linked":"Link"})]},l.id)})}),e.jsxs("div",{className:"mt-2 flex items-center justify-end gap-1.5",children:[e.jsx("button",{type:"button",onClick:()=>o(!1),className:"rounded-md border border-strong px-2 py-1 text-micro text-secondary transition-colors hover:bg-white/[0.08]",children:"Cancel"}),e.jsx("button",{type:"button",onClick:T,className:"rounded-md border border-[#BFFF00]/30 bg-[#BFFF00]/15 px-2 py-1 text-micro text-[#D8FFA1] transition-colors hover:bg-[#BFFF00]/22",children:"Save links"})]})]})]})}const aa={bottom:"Add to queue"},ia=[{scope:"task",label:"Play next",description:"task scope"},{scope:"milestone",label:"Play milestone",description:"milestone scope"},{scope:"workstream",label:"Play workstream",description:"workstream scope"}];function oa({scope:t,size:s=12}){const a=s,n=Math.round(a*.14),d=Math.round(a*.06);if(t==="task")return e.jsx("svg",{width:a,height:a,viewBox:`0 0 ${a} ${a}`,fill:"currentColor","aria-hidden":!0,children:e.jsx("circle",{cx:a/2,cy:a/2,r:n+1})});if(t==="milestone"){const c=a/2;return e.jsxs("svg",{width:a,height:a,viewBox:`0 0 ${a} ${a}`,fill:"currentColor","aria-hidden":!0,children:[e.jsx("circle",{cx:c,cy:n+d,r:n}),e.jsx("circle",{cx:c,cy:a/2,r:n}),e.jsx("circle",{cx:c,cy:a-n-d,r:n})]})}const o=n+d+1;return e.jsxs("svg",{width:a,height:a,viewBox:`0 0 ${a} ${a}`,fill:"currentColor","aria-hidden":!0,children:[e.jsx("circle",{cx:o,cy:o,r:n}),e.jsx("circle",{cx:a-o,cy:o,r:n}),e.jsx("circle",{cx:o,cy:a-o,r:n}),e.jsx("circle",{cx:a-o,cy:a-o,r:n})]})}function vs({label:t="Queue",defaultPlacement:s="bottom",size:a="sm",align:n="right",menuDirection:d="up",disabled:o=!1,busy:c=!1,className:h="",menuClassName:f="",title:y,stopPropagation:u=!1,onSelectPlacement:F}){const[T,v]=r.useState(!1),l=r.useRef(null),b=r.useRef(`queue-placement-${Math.random().toString(36).slice(2,10)}`),x=o||c,j=a==="md"?"h-8 text-caption":"h-7 text-micro",S=a==="md"?"px-3":"px-2.5",g=a==="md"?"h-8 w-8":"h-7 w-7",I=n==="left"?"left-0":"right-0",q=d==="up"?"bottom-[calc(100%+6px)]":"top-[calc(100%+6px)]";r.useEffect(()=>{if(!T)return;const O=te=>{var Q;const J=te.target;J&&((Q=l.current)!=null&&Q.contains(J)||v(!1))},ee=te=>{te.key==="Escape"&&v(!1)};return document.addEventListener("mousedown",O),document.addEventListener("touchstart",O),document.addEventListener("keydown",ee),()=>{document.removeEventListener("mousedown",O),document.removeEventListener("touchstart",O),document.removeEventListener("keydown",ee)}},[T]);const H=(O,ee,te)=>{u&&O.stopPropagation(),v(!1),F(ee,te)};return e.jsxs("div",{ref:l,className:`relative inline-flex items-center ${h}`,children:[e.jsxs("button",{type:"button",title:y??`Queue ${s==="top"?"to top":"to end"}`,onClick:O=>H(O,s),disabled:x,className:`control-pill ${j} ${S} rounded-r-none border-r-0 font-semibold text-primary disabled:opacity-45`,children:[e.jsxs("svg",{width:a==="md"?13:12,height:a==="md"?13:12,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"opacity-90","aria-hidden":!0,children:[e.jsx("path",{d:"M4 6h16"}),e.jsx("path",{d:"M4 12h11"}),e.jsx("path",{d:"M4 18h9"}),e.jsx("path",{d:"m17 15 3 3 3-3"}),e.jsx("path",{d:"M20 8v10"})]}),e.jsx("span",{children:c?"Queueing...":t})]}),e.jsx("button",{type:"button","aria-label":"Choose queue placement","aria-haspopup":"menu","aria-expanded":T,"aria-controls":b.current,onClick:O=>{u&&O.stopPropagation(),!x&&v(ee=>!ee)},disabled:x,className:`control-pill ${g} rounded-l-none px-0 text-secondary disabled:opacity-45`,children:e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",strokeLinejoin:"round",className:`transition-transform ${T?"rotate-180":""}`,"aria-hidden":!0,children:e.jsx("path",{d:"m6 9 6 6 6-6"})})}),T&&e.jsxs("div",{id:b.current,role:"menu",className:`absolute ${I} ${q} z-[260] min-w-[196px] rounded-lg border border-strong bg-[#0B0F16]/95 p-1 shadow-[0_16px_32px_rgba(0,0,0,0.38)] backdrop-blur ${f}`,children:[ia.map(O=>e.jsxs("button",{type:"button",role:"menuitem",onClick:ee=>H(ee,"top",O.scope),className:"flex w-full items-center gap-2 rounded-md px-2.5 py-1.5 text-left transition-colors hover:bg-white/[0.07]",children:[e.jsx(oa,{scope:O.scope,size:12}),e.jsx("span",{className:"text-caption font-medium text-primary",children:O.label}),e.jsx("span",{className:"ml-auto text-micro text-tertiary",children:O.description})]},O.scope)),e.jsx("div",{className:"my-1 border-t border-strong"}),e.jsx("button",{type:"button",role:"menuitem",onClick:O=>H(O,"bottom"),className:"flex w-full items-center rounded-md px-2.5 py-1.5 text-left transition-colors hover:bg-white/[0.07]",children:e.jsx("span",{className:"text-caption font-medium text-primary",children:aa.bottom})})]})]})}function la(t){if(!t)return"";const s=new Date(t);if(Number.isNaN(s.getTime()))return"";const a=s.getFullYear(),n=String(s.getMonth()+1).padStart(2,"0"),d=String(s.getDate()).padStart(2,"0"),o=String(s.getHours()).padStart(2,"0"),c=String(s.getMinutes()).padStart(2,"0");return`${a}-${n}-${d}T${o}:${c}`}const gn=["not_started","planned","todo","in_progress","active","blocked","done"];function ca(t){const s=t.trim().toLowerCase();return s==="blocked"?"blocked":s==="done"||s==="completed"?"done":s==="in_progress"||s==="active"||s==="running"||s==="queued"?"active":"planned"}function cs(t){const s=t.trim().toLowerCase();return s==="completed"?"done":s==="running"||s==="queued"?"active":s==="pending"||s==="backlog"?"todo":s}function da(t,s){return s==="all"?!0:s==="blocked"?t==="blocked":s==="done"?t==="done":t!=="blocked"&&t!=="done"}function ua(t){const s=Number.isFinite(t)?Math.max(1,Math.min(100,Math.round(t))):50;return s<=12?{label:"P1 Urgent",toneClass:"border-red-300/35 bg-red-500/[0.14] text-red-100"}:s<=30?{label:"P2 High",toneClass:"border-amber-300/35 bg-amber-500/[0.14] text-amber-100"}:s<=60?{label:"P3 Medium",toneClass:"border-[#BFFF00]/35 bg-[#BFFF00]/14 text-[#E1FFB2]"}:{label:"P4 Low",toneClass:"border-white/[0.2] bg-white/[0.08] text-white/70"}}function ma(t,s){const a=new Map(s.map(o=>[o.id,o])),n=new Set,d=[t];for(;d.length>0;){const o=d.shift(),c=a.get(o);c&&(c.parentId&&!n.has(c.parentId)&&(n.add(c.parentId),d.push(c.parentId)),c.workstreamId&&!n.has(c.workstreamId)&&(n.add(c.workstreamId),d.push(c.workstreamId)),c.milestoneId&&!n.has(c.milestoneId)&&(n.add(c.milestoneId),d.push(c.milestoneId)))}return n}function pa(t,s,a,n){let d=0;if(a==="title")d=t.title.localeCompare(s.title);else if(a==="status")d=ms(t.status)-ms(s.status);else if(a==="priority")d=t.priorityNum-s.priorityNum;else if(a==="eta"){const o=t.etaEndAt?Date.parse(t.etaEndAt):1/0,c=s.etaEndAt?Date.parse(s.etaEndAt):1/0;d=o-c}return n==="desc"?-d:d}function Yt(t,s){return!t||t.trim().length===0?s:dt(t.trim())||s}function xa({nodes:t,edges:s,selectedNodeId:a,highlightedNodeIds:n,editMode:d,onToggleEditMode:o,onSelectNode:c,onFocusWorkstream:h,onOpenNode:f,onUpdateNode:y,mutations:u}){const{authToken:F,embedMode:T}=Dt(),v=ns({authToken:F,embedMode:T}),[l,b]=r.useState(""),[x,j]=r.useState(new Set),[S,g]=r.useState("all"),[I,q]=r.useState(!1),[H,O]=r.useState(null),[ee,te]=r.useState("asc"),[J,Q]=r.useState(new Set),[D,w]=r.useState(!1),[P,$]=r.useState(null),R=r.useRef(null),_=r.useRef(null),G=r.useRef(null),B=r.useRef(null),X=r.useRef(null),ie=r.useRef(null),[ue,E]=r.useState(!1);r.useEffect(()=>{if(!P)return;const i=P.tone==="success"?6500:9e3,C=window.setTimeout(()=>$(null),i);return()=>window.clearTimeout(C)},[P==null?void 0:P.message,P==null?void 0:P.tone]),r.useEffect(()=>{if(!P)return;const i=P.tone==="success"?6500:9e3,C=window.setTimeout(()=>$(null),i);return()=>window.clearTimeout(C)},[P==null?void 0:P.message,P==null?void 0:P.tone]);const V=r.useMemo(()=>new Map(t.map(i=>[i.id,i])),[t]),ae=r.useMemo(()=>t.map(i=>({id:i.id,title:i.title})),[t]),De=r.useMemo(()=>{const i=new Map;for(const C of t){const A=cs(C.status);i.set(A,(i.get(A)??0)+1)}return i},[t]),Ve=r.useMemo(()=>{let i=0,C=0,A=0;for(const z of t){const se=cs(z.status);se==="blocked"?C+=1:se==="done"?A+=1:i+=1}return{all:t.length,open:i,blocked:C,done:A}},[t]),ze=r.useMemo(()=>{const i=l.trim().toLowerCase(),C=i.length>0,A=x.size>0;if(!C&&!A&&!(S!=="all"))return null;const se=new Set;for(const ke of t){const $e=cs(ke.status),Ce=!C||ke.title.toLowerCase().includes(i)||ke.assignedAgents.some(et=>et.name.toLowerCase().includes(i)),Le=!A||x.has($e),ge=da($e,S);Ce&&Le&&ge&&se.add(ke.id)}const me=new Set(se);for(const ke of se)for(const $e of ma(ke,t))me.add($e);return me},[x,t,l,S]),p=r.useMemo(()=>t.filter(i=>i.type==="workstream").sort((i,C)=>i.priorityNum-C.priorityNum||i.title.localeCompare(C.title)),[t]),ne=r.useMemo(()=>{const i=new Map;for(const C of t.filter(A=>A.type==="milestone")){const A=C.workstreamId??"unscoped",z=i.get(A)??[];z.push(C),i.set(A,z)}for(const C of i.values())C.sort((A,z)=>A.priorityNum-z.priorityNum||A.title.localeCompare(z.title));return i},[t]),K=r.useMemo(()=>{const i=new Map;for(const C of t.filter(A=>A.type==="task"&&A.milestoneId)){const A=C.milestoneId??"unscoped",z=i.get(A)??[];z.push(C),i.set(A,z)}for(const C of i.values())C.sort((A,z)=>A.priorityNum-z.priorityNum||A.title.localeCompare(z.title));return i},[t]),pe=r.useMemo(()=>{const i=new Map;for(const C of t.filter(A=>A.type==="task"&&!A.milestoneId)){const A=C.workstreamId??"unscoped",z=i.get(A)??[];z.push(C),i.set(A,z)}for(const C of i.values())C.sort((A,z)=>A.priorityNum-z.priorityNum||A.title.localeCompare(z.title));return i},[t]),Fe=r.useMemo(()=>{const i=new Set;for(const C of p)i.add(C.id);for(const C of t.filter(A=>A.type==="milestone"))i.add(C.id);return i},[t,p]),[Ie,Me]=r.useState(Fe);r.useEffect(()=>{Me(Fe)},[Fe]);const Be=i=>H?[...i].sort((C,A)=>pa(C,A,H,ee)):i,he=r.useMemo(()=>{const i=[],C=se=>ze===null||ze.has(se);for(const se of Be(p)){if(!C(se.id))continue;const me=Be(ne.get(se.id)??[]),ke=Be(pe.get(se.id)??[]),$e=me.length>0||ke.length>0;if(i.push({node:se,depth:0,canCollapse:$e}),!!Ie.has(se.id)){for(const Ce of me){if(!C(Ce.id))continue;const Le=Be(K.get(Ce.id)??[]);if(i.push({node:Ce,depth:1,canCollapse:Le.length>0}),Ie.has(Ce.id))for(const ge of Le)C(ge.id)&&i.push({node:ge,depth:2,canCollapse:!1})}for(const Ce of ke)C(Ce.id)&&i.push({node:Ce,depth:1,canCollapse:!1})}}const A=Be(ne.get("unscoped")??[]),z=Be(pe.get("unscoped")??[]);for(const se of A)if(C(se.id)&&(i.push({node:se,depth:0,canCollapse:(K.get(se.id)??[]).length>0}),Ie.has(se.id)))for(const me of Be(K.get(se.id)??[]))C(me.id)&&i.push({node:me,depth:1,canCollapse:!1});for(const se of z)C(se.id)&&i.push({node:se,depth:0,canCollapse:!1});return i},[pe,Ie,ze,ne,H,ee,K,p]),Pe=r.useMemo(()=>he.map(({node:i})=>i.id),[he]),{handleSelect:Re}=Kn(Pe),Ne=r.useMemo(()=>new Set(Pe),[Pe]),He=r.useMemo(()=>he.filter(({node:i})=>J.has(i.id)),[he,J]),ft=(S!=="all"?1:0)+x.size,St=l.trim().length>0||S!=="all"||x.size>0,je=He.length,Je=he.length>0&&je===he.length,Te=(u==null?void 0:u.bulkEntityMutation.isPending)??!1;r.useEffect(()=>{Q(i=>{if(i.size===0)return i;const C=new Set(Array.from(i).filter(A=>Ne.has(A)));return C.size===i.size?i:C})},[Ne]),r.useEffect(()=>{R.current&&(R.current.indeterminate=je>0&&!Je)},[Je,je]),r.useEffect(()=>{je===0&&D&&w(!1)},[D,je]),r.useEffect(()=>{if(!I)return;const i=A=>{var se;const z=A.target;z&&((se=_.current)!=null&&se.contains(z)||q(!1))},C=A=>{A.key==="Escape"&&q(!1)};return document.addEventListener("mousedown",i),document.addEventListener("touchstart",i),document.addEventListener("keydown",C),()=>{document.removeEventListener("mousedown",i),document.removeEventListener("touchstart",i),document.removeEventListener("keydown",C)}},[I]);const st=i=>i.dependencyIds.length,gt=v.isPinning||v.isMoving,jt=async i=>{await v.pin({initiativeId:i.initiativeId,workstreamId:i.workstreamId,taskId:i.taskId??null,milestoneId:i.milestoneId??null}),await v.move({initiativeId:i.initiativeId,workstreamId:i.workstreamId,placement:i.placement})},Ye=async(i,C="bottom")=>{if(i.type==="initiative"){const ke=p.filter(et=>et.initiativeId===i.id);if(ke.length===0){$({tone:"error",message:"Cannot queue initiative: no workstreams found."});return}const $e=C==="top"?[...ke].reverse():ke;let Ce=0,Le=0,ge=null;for(const et of $e)try{await jt({initiativeId:i.id,workstreamId:et.id,placement:C}),Ce+=1}catch(we){Le+=1,ge||(ge=Yt(we instanceof Error?we.message:"","Failed to add initiative workstream to queue."))}Le>0?$({tone:Ce>0?"success":"error",message:Ce>0?`Queued ${Ce}/${ke.length} workstreams (${Le} failed). ${ge??""}`.trim():ge??"Failed to queue initiative workstreams."}):$({tone:"success",message:`Queued ${Ce} workstream${Ce===1?"":"s"} to ${C==="top"?"top":"end"}.`}),window.setTimeout(()=>$(null),Le>0?4200:2400);return}const A=i.initiativeId??"",z=i.type==="workstream"?i.id:i.workstreamId??"",se=i.type==="task"?i.id:null,me=i.type==="milestone"?i.id:null;if(!A||!z){$({tone:"error",message:"Cannot add to queue: missing initiative/workstream id."});return}try{await jt({initiativeId:A,workstreamId:z,taskId:se,milestoneId:me,placement:C}),$({tone:"success",message:i.type==="task"?`Queued task workstream to ${C==="top"?"top":"end"}.`:i.type==="milestone"?`Queued milestone workstream to ${C==="top"?"top":"end"}.`:`Queued workstream to ${C==="top"?"top":"end"}.`}),window.setTimeout(()=>$(null),2e3)}catch(ke){$({tone:"error",message:Yt(ke instanceof Error?ke.message:"","Failed to add workstream to queue.")}),window.setTimeout(()=>$(null),2400)}},Qe=i=>{if(i.type==="workstream")return i.id;if(i.type==="milestone"||i.type==="task")return i.workstreamId??null;if(i.type==="initiative"){const C=p.filter(z=>z.initiativeId===i.id);if(C.length===0)return null;const A=C.find(z=>!tt(z.status))??C[0];return(A==null?void 0:A.id)??null}return null},Ue=async(i,C)=>{const A=i.type==="initiative"?i.id:i.initiativeId??"",z=C??(i.type==="workstream"?i.id:i.workstreamId??"");if(!A||!z){$({tone:"error",message:"Cannot start now: missing initiative/workstream id."});return}try{const se=await fetch("/orgx/api/mission-control/next-up/play",{method:"POST",headers:At({authToken:F,embedMode:T,contentTypeJson:!0}),body:JSON.stringify({initiativeId:A,workstreamId:z,fastAck:!0,ignoreSpawnGuardRateLimit:!0})}),me=await se.json().catch(()=>null);if(!se.ok)throw new Error((me==null?void 0:me.error)??(me==null?void 0:me.message)??`Failed to start workstream (${se.status})`);$({tone:"success",message:`Started ${i.title}.`}),window.setTimeout(()=>$(null),1800)}catch(se){$({tone:"error",message:Yt(se instanceof Error?se.message:"","Failed to start workstream now.")}),window.setTimeout(()=>$(null),2400)}},ut=r.useMemo(()=>{const i=new Map,C=(A,z)=>{if(A.length>0){const se=A.filter(me=>tt(me.status)).length;return qt(se,A.length)}return tt(z)?100:0};for(const A of t.filter(z=>z.type==="milestone")){const z=K.get(A.id)??[];i.set(A.id,C(z,A.status))}for(const A of p){const se=(ne.get(A.id)??[]).flatMap(ke=>K.get(ke.id)??[]),me=pe.get(A.id)??[];i.set(A.id,C([...me,...se],A.status))}return i},[pe,ne,t,K,p]),nt=i=>{H===i?te(C=>C==="asc"?"desc":"asc"):(O(i),te("asc"))},rt=i=>{j(C=>{const A=new Set(C);return A.has(i)?A.delete(i):A.add(i),A})},Ot=()=>{b(""),g("all"),j(new Set)},kt=(i,C,A)=>{$(null),w(!1),Re(i,C,A,Q)},mt=()=>{$(null),w(!1),Q(()=>he.length===0||Je?new Set:new Set(Pe))},Ct=()=>{w(!1),Q(new Set)},at=async i=>{if(!(!u||He.length===0)){w(!1),$(null);try{const C=await u.bulkEntityMutation.mutateAsync({items:He.map(({node:A})=>({type:A.type,id:A.id})),mode:"update",updates:{status:i}});C.failed>0?$({tone:"error",message:`Updated ${C.updated}, failed ${C.failed}.`}):$({tone:"success",message:`Updated ${C.updated} item${C.updated===1?"":"s"} to ${Oe(i)}.`})}catch(C){$({tone:"error",message:Yt(C instanceof Error?C.message:"","Bulk status update failed.")})}}},Mt=async()=>{if(!(!u||He.length===0)){$(null);try{const i=await u.bulkEntityMutation.mutateAsync({items:He.map(({node:C})=>({type:C.type,id:C.id})),mode:"delete"});i.failed>0?$({tone:"error",message:`Deleted ${i.updated}, failed ${i.failed}.`}):($({tone:"success",message:`Deleted ${i.updated} item${i.updated===1?"":"s"}.`}),Q(new Set),w(!1))}catch(i){$({tone:"error",message:Yt(i instanceof Error?i.message:"","Bulk delete failed.")})}}},ye=({field:i})=>H!==i?e.jsx("span",{className:"text-faint ml-0.5",children:"↕"}):e.jsx("span",{className:"text-[#BFFF00] ml-0.5",children:ee==="asc"?"↑":"↓"}),Xe=ue?"0px":"calc(var(--mc-toolbar-offset, 0px) + 12px)",Ze=i=>{if(ie.current==="body"){ie.current=null;return}const C=i.currentTarget.scrollLeft,A=B.current;!A||A.scrollLeft===C||(ie.current="header",A.scrollLeft=C)},ot=i=>{if(ie.current==="header"){ie.current=null;return}const C=i.currentTarget.scrollLeft,A=G.current;!A||A.scrollLeft===C||(ie.current="body",A.scrollLeft=C)};r.useEffect(()=>{const i=B.current,C=G.current;!i||!C||C.scrollLeft!==i.scrollLeft&&(C.scrollLeft=i.scrollLeft)},[he.length]),r.useEffect(()=>{if(typeof window>"u")return;const i=X.current;if(!i)return;const C=()=>{const z=Math.min(window.innerHeight*.62,560),se=i.scrollHeight;E(se>z+1)};C();const A=typeof ResizeObserver<"u"?new ResizeObserver(()=>C()):null;return A==null||A.observe(i),window.addEventListener("resize",C),()=>{A==null||A.disconnect(),window.removeEventListener("resize",C)}},[he.length]);const bt=()=>e.jsxs("colgroup",{children:[e.jsx("col",{style:{width:40}}),e.jsx("col",{style:{width:360}}),e.jsx("col",{style:{width:188}}),e.jsx("col",{style:{width:124}}),e.jsx("col",{style:{width:120}}),e.jsx("col",{style:{width:96}}),e.jsx("col",{style:{width:156}}),e.jsx("col",{style:{width:100}}),e.jsx("col",{style:{width:100}}),e.jsx("col",{style:{width:180}})]});return e.jsxs("section",{className:"space-y-2.5",children:[e.jsxs("div",{className:"mb-3.5 flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between",children:[e.jsx("div",{className:"w-full xl:max-w-[380px]",children:e.jsx(Qs,{value:l,onChange:b,placeholder:"Search items or agents..."})}),e.jsxs("div",{className:"flex min-h-[40px] min-w-0 flex-wrap items-center gap-2.5",children:[o&&e.jsxs("button",{type:"button",onClick:o,"data-state":d?"active":"idle",className:`control-pill inline-flex h-8 items-center gap-1.5 px-3.5 text-caption font-semibold ${d?"text-[#D8FFA1]":"text-secondary hover:text-bright"}`,children:[e.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e.jsx("path",{d:"M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"})}),d?"Editing":"Edit"]}),e.jsxs("div",{ref:_,className:"relative",children:[e.jsxs("button",{type:"button",onClick:()=>q(i=>!i),"data-state":I||ft>0?"active":"idle",className:"control-pill flex items-center gap-1.5 px-3.5 text-caption font-semibold",children:[e.jsx("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e.jsx("path",{d:"M22 3H2l8 9.46V19l4 2v-8.54L22 3z"})}),e.jsx("span",{children:"Filters"}),ft>0&&e.jsx("span",{className:"inline-flex min-w-[16px] items-center justify-center rounded-full border border-current/30 bg-black/25 px-1 text-micro leading-4",children:ft})]}),e.jsx(ht,{children:I&&e.jsxs(fe.div,{initial:{opacity:0,y:-4,scale:.97},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:-4,scale:.97},transition:{duration:.16,ease:[.22,1,.36,1]},className:"surface-tier-2 absolute left-0 top-10 z-30 w-[360px] max-w-[86vw] rounded-xl p-3 shadow-[0_16px_40px_rgba(0,0,0,0.45)] backdrop-blur-xl",children:[e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"text-micro font-semibold uppercase tracking-[0.08em] text-muted",children:"Scope"}),e.jsx("div",{className:"mt-1.5 flex flex-wrap gap-1.5",children:[{id:"all",label:"All",count:Ve.all},{id:"open",label:"Open",count:Ve.open},{id:"blocked",label:"Blocked",count:Ve.blocked},{id:"done",label:"Done",count:Ve.done}].map(i=>{const C=S===i.id;return e.jsxs("button",{type:"button",onClick:()=>g(i.id),className:`inline-flex h-7 items-center gap-1.5 rounded-full border px-2.5 text-micro font-semibold transition-colors ${C?"border-[#BFFF00]/30 bg-[#BFFF00]/10 text-[#D8FFA1]":"border-strong bg-white/[0.03] text-secondary hover:bg-white/[0.07] hover:text-white/82"}`,children:[e.jsx("span",{children:i.label}),e.jsx("span",{className:"text-micro text-current/80",children:i.count})]},i.id)})})]}),e.jsxs("div",{className:"mb-2 border-t border-white/[0.08] pt-2",children:[e.jsx("div",{className:"text-micro font-semibold uppercase tracking-[0.08em] text-muted",children:"Status"}),e.jsx("div",{className:"mt-1.5 flex flex-wrap gap-1.5",children:gn.map(i=>{const C=x.has(i),A=De.get(i)??0;return e.jsxs("button",{type:"button",onClick:()=>rt(i),className:`inline-flex h-7 items-center gap-1 rounded-full border px-2.5 text-micro transition-colors ${C?"border-[#14B8A6]/35 bg-[#14B8A6]/12 text-[#8FF7EC]":"border-strong bg-white/[0.03] text-white/58 hover:bg-white/[0.07] hover:text-bright"}`,children:[e.jsx("span",{children:Oe(i)}),e.jsx("span",{className:"text-micro text-current/75",children:A})]},i)})})]}),(S!=="all"||x.size>0)&&e.jsx("button",{type:"button",onClick:()=>{g("all"),j(new Set)},className:"text-micro text-secondary transition-colors hover:text-primary",children:"Reset filters"})]})})]}),e.jsx(ht,{initial:!1,children:St&&e.jsx(fe.button,{type:"button",onClick:Ot,initial:{opacity:0,x:-4},animate:{opacity:1,x:0},exit:{opacity:0,x:-4},transition:{duration:.16,ease:[.22,1,.36,1]},className:"control-pill inline-flex h-8 items-center px-2.5 text-caption font-medium text-primary hover:text-bright",children:"Clear"},"hierarchy-clear-filters")}),e.jsx("button",{type:"button",onClick:mt,"data-state":Je?"active":"idle",className:"control-pill inline-flex h-8 items-center gap-1.5 px-3.5 text-caption font-semibold",children:Je?"Clear all":"Select all"})]})]}),e.jsx("div",{className:"mb-1.5",children:e.jsx("div",{className:`rounded-xl border px-3 ${je>0?"border-[#BFFF00]/24 bg-[#BFFF00]/[0.08]":"border-white/[0.08] bg-white/[0.02]"}`,children:e.jsxs("div",{className:"flex h-[48px] min-w-max flex-nowrap items-center gap-2 overflow-x-auto py-1 whitespace-nowrap",children:[e.jsxs("label",{className:"inline-flex flex-shrink-0 items-center gap-2 text-caption text-primary",children:[e.jsx("input",{ref:R,type:"checkbox",checked:Je,onChange:mt,className:"h-3.5 w-3.5 rounded border-white/20 bg-black/40 text-[#BFFF00] focus:ring-[#BFFF00]/35"}),"Select all"]}),e.jsx("span",{className:"flex-shrink-0 text-caption text-white/58",children:je>0?`${je} selected`:`${he.length} visible`}),je>0&&e.jsxs("div",{className:"flex flex-shrink-0 items-center gap-2 whitespace-nowrap",children:[e.jsx("button",{type:"button",onClick:()=>{at("planned")},disabled:Te,className:"control-pill h-8 flex-shrink-0 px-3 text-caption font-semibold disabled:opacity-45",children:"Plan"}),e.jsx("button",{type:"button",onClick:()=>{at("in_progress")},disabled:Te,className:"control-pill h-8 flex-shrink-0 px-3 text-caption font-semibold disabled:opacity-45","data-state":"active",children:"Start"}),e.jsx("button",{type:"button",onClick:()=>{at("blocked")},disabled:Te,className:"control-pill h-8 flex-shrink-0 px-3 text-caption font-semibold disabled:opacity-45",children:"Block"}),e.jsx("button",{type:"button",onClick:()=>{at("done")},disabled:Te,className:"control-pill h-8 flex-shrink-0 px-3 text-caption font-semibold disabled:opacity-45",children:"Complete"}),D?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-micro text-white/58",children:"Delete selected?"}),e.jsx("button",{type:"button",onClick:()=>{Mt()},disabled:Te,className:"control-pill h-8 flex-shrink-0 border-red-400/35 bg-red-500/14 px-3 text-caption font-semibold text-red-100 disabled:opacity-45",children:"Delete"}),e.jsx("button",{type:"button",onClick:()=>w(!1),disabled:Te,className:"control-pill h-8 flex-shrink-0 px-2.5 text-caption disabled:opacity-45",children:"Keep"})]}):e.jsx("button",{type:"button",onClick:()=>w(!0),disabled:Te,className:"control-pill h-8 flex-shrink-0 border-red-400/24 bg-red-500/[0.08] px-3 text-caption font-semibold text-red-100/85 disabled:opacity-45",children:"Delete"}),e.jsx("button",{type:"button",onClick:Ct,disabled:Te,className:"text-caption text-secondary transition-colors hover:text-primary disabled:opacity-45",children:"Clear"})]})]})})}),P&&e.jsx("div",{role:"status","aria-live":"polite",className:"rounded-lg border border-white/[0.08] bg-white/[0.02] px-3 py-2 text-caption text-white/72",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex min-w-0 items-start gap-2",children:[e.jsx("span",{"aria-hidden":!0,className:`mt-[3px] h-1.5 w-1.5 flex-shrink-0 rounded-full ${P.tone==="success"?"bg-emerald-300/90":"bg-amber-300/90"}`}),e.jsx("span",{className:"min-w-0 leading-snug",children:P.message})]}),e.jsx("button",{type:"button",onClick:()=>$(null),className:"inline-flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-md text-secondary transition-colors hover:bg-white/[0.06] hover:text-primary","aria-label":"Dismiss notice",title:"Dismiss",children:e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("path",{d:"M18 6 6 18"}),e.jsx("path",{d:"m6 6 12 12"})]})})]})}),d&&e.jsx("div",{className:"mb-2 text-micro text-secondary",children:"Edit mode: select a row to edit its fields inline."}),e.jsx("div",{className:"relative min-w-0 max-w-full overflow-visible rounded-xl border border-white/[0.07] bg-black/[0.14] p-2",children:e.jsxs("div",{ref:X,"data-hierarchy-table-viewport":!0,className:`${ue?"max-h-[min(62vh,560px)] overflow-y-auto":"overflow-visible"} overflow-x-hidden rounded-lg`,children:[e.jsx("div",{"data-hierarchy-table-header":!0,className:"sticky z-30 rounded-t-lg border-b border-subtle bg-[#090B11]/92 backdrop-blur-xl",style:{top:Xe},children:e.jsx("div",{ref:G,onScroll:Ze,className:"overflow-x-auto overflow-y-hidden [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",children:e.jsxs("table",{className:"w-full min-w-[1464px] table-fixed border-separate border-spacing-y-0",children:[bt(),e.jsx("thead",{children:e.jsxs("tr",{className:"text-left text-micro uppercase tracking-[0.08em] text-muted",children:[e.jsx("th",{className:"px-2 py-1.5",children:e.jsx("span",{className:"sr-only",children:"Select rows"})}),e.jsxs("th",{className:"px-2 py-1.5 cursor-pointer select-none",onClick:()=>nt("title"),children:["Item ",e.jsx(ye,{field:"title"})]}),e.jsx("th",{className:"px-2 py-1.5",children:"Assigned"}),e.jsxs("th",{className:"px-2 py-1.5 cursor-pointer select-none",onClick:()=>nt("status"),children:["Status ",e.jsx(ye,{field:"status"})]}),e.jsx("th",{className:"px-2 py-1.5",children:"Progress"}),e.jsxs("th",{className:"px-2 py-1.5 cursor-pointer select-none",onClick:()=>nt("priority"),children:["Priority ",e.jsx(ye,{field:"priority"})]}),e.jsxs("th",{className:"px-2 py-1.5 cursor-pointer select-none",onClick:()=>nt("eta"),children:["ETA ",e.jsx(ye,{field:"eta"})]}),e.jsx("th",{className:"px-2 py-1.5",children:"Duration (h)"}),e.jsx("th",{className:"px-2 py-1.5",children:"Budget ($)"}),e.jsx("th",{className:"px-2 py-1.5",children:"Dependencies"})]})})]})})}),e.jsx("div",{ref:B,onScroll:ot,className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full min-w-[1464px] table-fixed border-separate border-spacing-y-1.5",children:[bt(),e.jsx("tbody",{children:he.map(({node:i,depth:C,canCollapse:A})=>{var k;const z=a===i.id,se=n.has(i.id),me=J.has(i.id),ke=i.assignedAgents.map(N=>N.name).join(", "),$e=i.dependencyIds.map(N=>{var oe;return((oe=V.get(N))==null?void 0:oe.title)??N}).slice(0,3).join(", "),Ce=ut.get(i.id),Le=ua(i.priorityNum),ge=d&&z,et=i.type==="initiative"||i.type==="workstream"||i.type==="milestone"||i.type==="task",we=Qe(i),yt=!!we;return e.jsxs("tr",{onClick:()=>{c(i.id),i.type==="workstream"&&h(i.id)},className:`group/row cursor-pointer rounded-lg border transition-colors ${z?"border-[#BFFF00]/[0.22] bg-[#BFFF00]/[0.08]":se?"border-[#14B8A6]/[0.2] bg-[#14B8A6]/[0.08]":"border-subtle bg-white/[0.02] hover:border-strong hover:bg-white/[0.05]"}`,children:[e.jsx("td",{className:"rounded-l-lg px-2 py-1.5",children:e.jsx("input",{type:"checkbox",checked:me,onChange:N=>{N.stopPropagation();const oe=N.nativeEvent.shiftKey??!1;kt(i.id,N.currentTarget.checked,oe)},onClick:N=>N.stopPropagation(),"aria-label":`Select ${i.type}: ${i.title}`,className:"h-3.5 w-3.5 rounded border-white/20 bg-black/40 text-[#BFFF00] focus:ring-[#BFFF00]/35"})}),e.jsx("td",{className:"px-2 py-1.5",children:e.jsxs("div",{className:"flex min-w-0 items-center",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5 pr-2",children:[e.jsx("div",{style:{width:C*14}}),A?e.jsx("button",{type:"button",onClick:N=>{N.stopPropagation(),Me(oe=>{const be=new Set(oe);return be.has(i.id)?be.delete(i.id):be.add(i.id),be})},"aria-label":`${Ie.has(i.id)?"Collapse":"Expand"} ${i.type}: ${i.title}`,className:"rounded text-secondary focus:outline-none focus-visible:ring-2 focus-visible:ring-[#BFFF00]/35 focus-visible:ring-offset-2 focus-visible:ring-offset-[#02040A]",children:Ie.has(i.id)?"▾":"▸"}):e.jsx("span",{className:"w-2.5"}),e.jsx(xs,{type:i.type}),e.jsx("button",{type:"button",onClick:N=>{N.stopPropagation(),f(i)},"aria-label":`Open ${i.type} details: ${i.title}`,className:"min-w-0 max-w-[560px] flex-1 truncate rounded text-left text-body text-bright hover:text-white focus:outline-none focus-visible:ring-2 focus-visible:ring-[#BFFF00]/35 focus-visible:ring-offset-2 focus-visible:ring-offset-[#02040A]",children:i.title})]}),!d&&e.jsxs("div",{className:"ml-1 grid w-[168px] min-w-[168px] grid-cols-[124px_34px] items-center justify-end gap-2",children:[et?e.jsx(vs,{label:"Queue",size:"sm",busy:gt,stopPropagation:!0,title:`Queue ${i.type}: ${i.title}`,onSelectPlacement:N=>Ye(i,N)}):e.jsx("span",{className:"h-7 w-[124px]"}),e.jsx("button",{type:"button",disabled:!yt,title:yt?"Start":"No runnable workstream",onClick:N=>{N.stopPropagation(),we&&Ue(i,we)},"aria-label":yt?`Start ${i.type}: ${i.title}`:`${i.type} has no runnable workstream`,className:"control-pill flex h-7 w-[34px] items-center justify-center px-0 text-[#D8FFA1] hover:text-[#E9FFBD] disabled:cursor-not-allowed disabled:text-white/25 disabled:hover:text-white/25",children:e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("path",{d:"M8 5v14l11-7z"})})})]})]})}),e.jsx("td",{className:"px-2 py-1.5 text-caption text-primary whitespace-nowrap",children:ge?e.jsx("input",{type:"text",defaultValue:ke,placeholder:"Agent A, Agent B",onClick:N=>N.stopPropagation(),onBlur:N=>{const oe=N.currentTarget.value.split(",").map(be=>be.trim()).filter(Boolean);y(i,{assigned_agent_names:oe,assigned_agent_ids:oe.map(be=>`name:${be}`),assignment_source:"manual"})},className:"w-[190px] rounded border border-strong bg-white/[0.06] px-2 py-1 text-micro text-white/82"}):e.jsx("div",{className:"flex items-center gap-2",children:i.assignedAgents.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex items-center -space-x-1.5",children:i.assignedAgents.slice(0,3).map(N=>e.jsx("div",{title:N.name,className:"rounded-full ring-1 ring-[#02040A]",children:e.jsx(Un,{name:N.name,hint:`${N.id} ${i.title}`,size:"xs"})},`${i.id}:${N.id}`))}),e.jsxs("span",{className:"max-w-[110px] truncate text-micro text-white/62",title:ke,children:[(k=i.assignedAgents[0])==null?void 0:k.name,i.assignedAgents.length>1?` +${i.assignedAgents.length-1}`:""]})]}):e.jsx("span",{className:"text-muted",children:"Unassigned"})})}),e.jsx("td",{className:"px-2 py-1.5 text-caption text-primary",children:ge?e.jsx("select",{defaultValue:cs(i.status),onClick:N=>N.stopPropagation(),onChange:N=>{y(i,{status:N.target.value})},className:"rounded border border-strong bg-white/[0.06] px-2 py-1 text-micro text-white/82",children:gn.map(N=>e.jsx("option",{value:N,children:Oe(N)},N))}):e.jsx("span",{className:"status-pill whitespace-nowrap","data-tone":ca(i.status),children:Oe(i.status)})}),e.jsx("td",{className:"px-2 py-1.5 text-caption text-primary",children:Ce!==void 0&&(i.type==="workstream"||i.type==="milestone")?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-1 w-[72px] rounded-full bg-white/[0.06] overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${Ce}%`,backgroundColor:i.type==="milestone"?W.teal:W.lime}})}),e.jsxs("span",{className:"text-micro text-secondary",style:{fontVariantNumeric:"tabular-nums"},children:[Ce,"%"]})]}):e.jsx("span",{className:"text-muted",children:"—"})}),e.jsx("td",{className:"px-2 py-1.5 text-caption text-primary",children:ge?e.jsx("input",{type:"number",min:1,max:100,defaultValue:i.priorityNum,onClick:N=>N.stopPropagation(),onBlur:N=>{const oe=Number(N.currentTarget.value);Number.isFinite(oe)&&y(i,{priority_num:oe})},className:"w-[72px] rounded border border-strong bg-white/[0.06] px-2 py-1 text-micro text-white/82"}):e.jsx("span",{className:`inline-flex items-center rounded-full border px-2 py-0.5 text-micro font-semibold uppercase tracking-[0.08em] ${Le.toneClass}`,title:`Priority ${Le.label}`,children:Le.label})}),e.jsx("td",{className:"px-2 py-1.5 text-caption text-primary",children:ge?e.jsx("input",{type:"datetime-local",defaultValue:la(i.etaEndAt),onClick:N=>N.stopPropagation(),onBlur:N=>{const oe=N.currentTarget.value;y(i,{eta_end_at:oe?new Date(oe).toISOString():null})},className:"w-[176px] rounded border border-strong bg-white/[0.06] px-2 py-1 text-micro text-white/82"}):e.jsx("span",{children:i.etaEndAt?new Date(i.etaEndAt).toLocaleString():"—"})}),e.jsx("td",{className:"px-2 py-1.5 text-caption text-primary",children:ge&&i.type!=="task"?e.jsx("input",{type:"number",min:0,step:.5,defaultValue:i.expectedDurationHours,onClick:N=>N.stopPropagation(),onBlur:N=>{const oe=Number(N.currentTarget.value);Number.isFinite(oe)&&y(i,{expected_duration_hours:oe})},className:"w-[82px] rounded border border-strong bg-white/[0.06] px-2 py-1 text-micro text-white/82"}):e.jsx("span",{children:i.expectedDurationHours})}),e.jsx("td",{className:"px-2 py-1.5 text-caption text-primary",children:ge&&i.type!=="task"?e.jsx("input",{type:"number",min:0,step:1,defaultValue:i.expectedBudgetUsd,onClick:N=>N.stopPropagation(),onBlur:N=>{const oe=Number(N.currentTarget.value);Number.isFinite(oe)&&y(i,{expected_budget_usd:oe})},className:"w-[92px] rounded border border-strong bg-white/[0.06] px-2 py-1 text-micro text-white/82"}):e.jsxs("span",{children:["$",i.expectedBudgetUsd.toLocaleString(),ge&&i.type==="task"?" (from task spec)":""]})}),e.jsx("td",{className:"rounded-r-lg px-2 py-1.5 text-caption text-primary",children:ge?e.jsx("div",{onClick:N=>N.stopPropagation(),children:e.jsx(ra,{dependencies:i.dependencyIds,allNodes:ae,onSave:N=>void y(i,{depends_on:N})})}):e.jsx("div",{className:"max-w-[250px] truncate",children:st(i)>0?`${st(i)} · ${$e}`:"—"})})]},i.id)})})]})})]})}),he.length===0&&e.jsxs("div",{className:"flex flex-col items-center py-10",children:[e.jsxs("svg",{width:"32",height:"32",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",className:"text-faint",children:[e.jsx("path",{d:"M9 5H7a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2h-2"}),e.jsx("rect",{x:"9",y:"3",width:"6",height:"4",rx:"1"}),e.jsx("path",{d:"M9 14h6M9 18h4"})]}),e.jsx("div",{className:"mt-3 text-body font-medium text-secondary",children:l||x.size>0||S!=="all"?"No items match the current filters":"No work items yet"}),e.jsx("div",{className:"mt-1 text-caption text-muted",children:l||x.size>0||S!=="all"?"Try adjusting your search or filter criteria.":"Workstreams, milestones, and tasks will appear here."})]})]})}function bn(t){if(!t)return"No target date";const s=new Date(t);return Number.isNaN(s.getTime())?"No target date":`Due ${s.toLocaleDateString()}`}function ha({recentTodoIds:t,nodesById:s,selectedNodeId:a,onSelectNode:n}){const d=t.map(h=>s.get(h)).filter(h=>!!h).sort((h,f)=>{if(h.priorityNum!==f.priorityNum)return h.priorityNum-f.priorityNum;const y=h.dueDate?Date.parse(h.dueDate):Number.POSITIVE_INFINITY,u=f.dueDate?Date.parse(f.dueDate):Number.POSITIVE_INFINITY;return y-u}).slice(0,14);if(d.length===0)return null;const o=d[0],c=d.slice(1,7);return e.jsxs("section",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:"Queue overview"}),e.jsxs("span",{className:"rounded-full border border-white/15 bg-black/20 px-2 py-0.5 text-micro text-secondary",children:[d.length," in queue"]})]}),e.jsx("button",{type:"button",onClick:()=>n(o.id),className:`surface-hero group w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${a===o.id?"border-[#BFFF00]/35 bg-[#BFFF00]/14":"border-white/15 bg-black/25 hover:border-white/30 hover:bg-white/[0.08]"}`,children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"inline-flex items-center gap-1.5 text-micro uppercase tracking-[0.1em] text-secondary",children:[e.jsx(xs,{type:o.type}),e.jsx("span",{children:"Priority task"})]}),e.jsx("p",{className:"mt-1 line-clamp-2 text-body font-semibold leading-snug text-white",children:o.title}),e.jsx("p",{className:"mt-1 text-caption text-secondary",children:bn(o.dueDate)})]}),e.jsxs("span",{className:"inline-flex flex-shrink-0 rounded-full border px-2 py-0.5 text-micro font-semibold",style:{borderColor:`${W.amber}44`,backgroundColor:`${W.amber}22`,color:W.amber},children:["P",o.priorityNum]})]})}),c.length>0&&e.jsx("div",{className:"space-y-1.5",children:c.map(h=>e.jsxs("button",{type:"button",onClick:()=>n(h.id),className:`flex min-h-[62px] min-w-0 items-start justify-between gap-2 rounded-lg border px-2.5 py-2 text-left transition-colors ${a===h.id?"border-[#BFFF00]/30 bg-[#BFFF00]/12":"border-strong bg-black/20 hover:bg-white/[0.08]"}`,children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"inline-flex items-center gap-1.5 text-micro uppercase tracking-[0.08em] text-secondary",children:[e.jsx(xs,{type:h.type}),e.jsx("span",{children:"Queued"})]}),e.jsx("p",{className:"mt-1 line-clamp-1 break-words text-caption leading-snug text-bright",title:h.title,children:h.title}),e.jsx("p",{className:"mt-1 text-micro text-secondary",children:bn(h.dueDate)})]}),e.jsxs("span",{className:"inline-flex flex-shrink-0 rounded-full px-1.5 py-0.5 text-micro",style:{backgroundColor:`${W.amber}22`,color:`${W.amber}`},children:["P",h.priorityNum]})]},h.id))})]})}function fa(t,s){try{const a=localStorage.getItem(`orgx.section.${t}`);if(a==="0")return!1;if(a==="1")return!0}catch{}return s}function ga(t,s){try{localStorage.setItem(`orgx.section.${t}`,s?"1":"0")}catch{}}function ds({title:t,defaultOpen:s=!0,storageKey:a,sticky:n=!1,stickyOffsetClass:d="top-0",stickyTop:o,contentOverflowVisible:c=!1,children:h}){const[f,y]=r.useState(()=>a?fa(a,s):s),[u,F]=r.useState(!1),T=r.useRef(null),[v,l]=r.useState(40),b=()=>{const x=!f;y(x),a&&ga(a,x)};return r.useEffect(()=>{if(!n)return;const x=T.current;if(!x)return;const j=()=>{const g=Math.max(34,x.offsetHeight);l(I=>I===g?I:g)};if(j(),typeof ResizeObserver>"u")return;const S=new ResizeObserver(()=>j());return S.observe(x),()=>S.disconnect()},[n,o,t]),e.jsxs("div",{style:n?{"--mc-collapsible-header-offset":`${v}px`}:void 0,children:[e.jsxs("button",{ref:n?T:void 0,type:"button","data-mc-section-header":t,onClick:b,className:`flex w-full items-center gap-2 rounded-lg border px-2 py-2 text-left transition-colors ${n?`sticky ${d} z-20 border-white/[0.08] bg-[#090B11]/92 shadow-[0_8px_18px_rgba(0,0,0,0.24)] backdrop-blur-xl`:"border-transparent hover:border-subtle hover:bg-white/[0.03]"}`,style:n&&o?{top:o}:void 0,children:[e.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",className:`text-muted transition-transform duration-200 ${f?"rotate-180":""}`,children:e.jsx("path",{d:"m6 9 6 6 6-6"})}),e.jsx("span",{className:"text-caption font-semibold tracking-[0.02em] text-white/68",children:t})]}),e.jsx(ht,{initial:!1,children:f&&e.jsx(fe.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{type:"spring",stiffness:400,damping:35},onAnimationStart:()=>F(!0),onAnimationComplete:()=>F(!1),className:c&&!u?"overflow-visible":"overflow-hidden",children:h})})]})}function ba(t){if(!t)return{priorityNum:60,priorityLabel:null};const s=t.trim().toLowerCase();if(s==="urgent"||s==="p0")return{priorityNum:10,priorityLabel:"urgent"};if(s==="high"||s==="p1")return{priorityNum:25,priorityLabel:"high"};if(s==="medium"||s==="p2")return{priorityNum:50,priorityLabel:"medium"};if(s==="low"||s==="p3"||s==="p4")return{priorityNum:75,priorityLabel:"low"};const a=Number(s.replace(/^p/,""));return Number.isFinite(a)?{priorityNum:Math.max(1,Math.min(100,Math.round(a))),priorityLabel:null}:{priorityNum:60,priorityLabel:null}}function ya(t){const s=t.toLowerCase();return["todo","not_started","planned","pending","backlog"].includes(s)}function wa(t){const s=t.toLowerCase();return["in_progress","active","running","queued"].includes(s)}function va(t,s){const a={id:t.id,type:"initiative",title:t.name,status:t.rawStatus??t.status,parentId:null,initiativeId:t.id,workstreamId:null,milestoneId:null,priorityNum:60,priorityLabel:null,dependencyIds:[],dueDate:t.targetDate??null,etaEndAt:t.targetDate??null,expectedDurationHours:40,expectedBudgetUsd:1500,assignedAgents:[],updatedAt:t.updatedAt??t.createdAt??null},d=(s.workstreams.length>0?s.workstreams:(t.workstreams??[]).map(u=>({id:u.id,name:u.name,summary:null,status:u.status,progress:null,initiativeId:t.id,createdAt:null}))).map(u=>({id:u.id,type:"workstream",title:u.name,status:u.status,parentId:t.id,initiativeId:t.id,workstreamId:u.id,milestoneId:null,priorityNum:50,priorityLabel:"medium",dependencyIds:[],dueDate:null,etaEndAt:null,expectedDurationHours:16,expectedBudgetUsd:300,assignedAgents:[],updatedAt:u.createdAt,sequenceIndex:typeof u.sequenceIndex=="number"?u.sequenceIndex??void 0:void 0,hierarchyLabel:typeof u.hierarchyLabel=="string"?u.hierarchyLabel??void 0:void 0})),o=new Set(d.map(u=>u.id)),c=s.milestones.map(u=>({id:u.id,type:"milestone",title:u.title,status:u.status,parentId:u.workstreamId&&o.has(u.workstreamId)?u.workstreamId:t.id,initiativeId:t.id,workstreamId:u.workstreamId&&o.has(u.workstreamId)?u.workstreamId:null,milestoneId:u.id,priorityNum:50,priorityLabel:"medium",dependencyIds:[],dueDate:u.dueDate,etaEndAt:u.dueDate,expectedDurationHours:6,expectedBudgetUsd:120,assignedAgents:[],updatedAt:u.createdAt,sequenceIndex:u.sequenceIndex,hierarchyLabel:u.hierarchyLabel})),h=new Set(c.map(u=>u.id)),f=s.tasks.map(u=>{const F=ba(u.priority),T=u.milestoneId&&h.has(u.milestoneId),v=u.workstreamId&&o.has(u.workstreamId);return{id:u.id,type:"task",title:u.title,status:u.status,parentId:T?u.milestoneId:v?u.workstreamId:t.id,initiativeId:t.id,workstreamId:v?u.workstreamId:null,milestoneId:T?u.milestoneId:null,priorityNum:F.priorityNum,priorityLabel:F.priorityLabel,dependencyIds:[],dueDate:u.dueDate,etaEndAt:u.dueDate,expectedDurationHours:2,expectedBudgetUsd:40,assignedAgents:[],updatedAt:u.createdAt,sequenceIndex:u.sequenceIndex,hierarchyLabel:u.hierarchyLabel}}),y=f.filter(u=>["todo","not_started","planned","pending","backlog"].includes(u.status.toLowerCase())).sort((u,F)=>{const T=u.priorityNum-F.priorityNum;if(T!==0)return T;const v=u.etaEndAt?Date.parse(u.etaEndAt):1/0,l=F.etaEndAt?Date.parse(F.etaEndAt):1/0;if(v!==l)return v-l;const b=u.updatedAt?Date.parse(u.updatedAt):0;return(F.updatedAt?Date.parse(F.updatedAt):0)-b}).map(u=>u.id);return{nodes:[a,...d,...c,...f],edges:[],recentTodos:y}}function ja(t,s){if(!t)return new Set;const a=new Map(s.map(c=>[c.id,c])),n=new Map;for(const c of s)for(const h of c.dependencyIds){const f=n.get(h)??[];f.push(c.id),n.set(h,f)}const d=new Set,o=[t];for(;o.length>0;){const c=o.shift();if(d.has(c))continue;d.add(c);const h=a.get(c);if(h){for(const f of h.dependencyIds)d.has(f)||o.push(f);for(const f of n.get(c)??[])d.has(f)||o.push(f)}}return d}function ka(t,s){return{id:t.id,name:t.title,summary:null,status:t.status,progress:null,initiativeId:s.id,createdAt:t.updatedAt,sequenceIndex:t.sequenceIndex,hierarchyLabel:t.hierarchyLabel}}function Na(t,s){return{id:t.id,title:t.title,description:null,status:t.status,dueDate:t.dueDate,initiativeId:s.id,workstreamId:t.workstreamId,createdAt:t.updatedAt,sequenceIndex:t.sequenceIndex,hierarchyLabel:t.hierarchyLabel}}function Sa(t,s){return{id:t.id,title:t.title,description:null,status:t.status,priority:t.priorityLabel??`p${t.priorityNum}`,dueDate:t.dueDate,initiativeId:s.id,milestoneId:t.milestoneId,workstreamId:t.workstreamId,createdAt:t.updatedAt,sequenceIndex:t.sequenceIndex,hierarchyLabel:t.hierarchyLabel}}const Xt={hidden:{opacity:0},show:{opacity:1}};function us({label:t,value:s}){return e.jsxs("div",{className:"rounded-lg border border-white/[0.08] bg-white/[0.03] px-2.5 py-2",children:[e.jsx("div",{className:"text-micro text-secondary",children:t}),e.jsx("div",{className:"mt-0.5 text-body font-semibold text-bright",children:s})]})}function Ca({initiative:t,selected:s=!1,onSelectionChange:a,isSquished:n=!1,runtimeActivity:d=null}){var yt;const{expandedInitiatives:o,toggleExpanded:c,openModal:h,agentEntityMap:f,authToken:y,embedMode:u,mutations:F}=Dt(),[T,v]=r.useState(!1),[l,b]=r.useState(null),[x,j]=r.useState(null),[S,g]=r.useState(!1),[I,q]=r.useState(!1),[H,O]=r.useState(null),[ee,te]=r.useState(!1),J=r.useRef(null),[Q,D]=r.useState(52),[w,P]=r.useState(0),$=o.has(t.id),{graph:R,isLoading:_,degraded:G,error:B,refetch:X}=Zr({initiativeId:t.id,authToken:y,embedMode:u,enabled:$}),{details:ie,isLoading:ue,error:E}=gs({initiativeId:t.id,authToken:y,embedMode:u,enabled:$}),V=ns({authToken:y,embedMode:u}),ae=r.useMemo(()=>va(t,ie),[t,ie]),De=!!(R&&R.nodes.length>0),Ve=ae.nodes.length>0,ze=!De&&Ve,p=ze?ae.nodes:De?(R==null?void 0:R.nodes)??[]:ae.nodes,ne=ze?ae.edges:De?(R==null?void 0:R.edges)??[]:ae.edges,K=ze?ae.recentTodos:De?(R==null?void 0:R.recentTodos)??[]:ae.recentTodos,pe=G.some(k=>/401|unauthorized/i.test(k))||!!(B&&/401|unauthorized/i.test(B))||!!(E&&/401|unauthorized/i.test(E)),Fe=B&&/unknown api endpoint/i.test(B)?"Graph API unavailable. Showing session-derived data.":B,Ie=E,Me=[...G,...Fe?[Fe]:[],...Ie?[`Entity data partially unavailable: ${Ie}`]:[],...pe?["OrgX auth is missing or expired in this local plugin instance. Reconnect in onboarding to load full workstreams/milestones/tasks."]:[]],Be=Me.filter(k=>/cyclic dependency edge/i.test(k)),he=Be.reduce((k,N)=>{const oe=/detected\s+(\d+)\s+cyclic dependency edge/i.exec(N);return k+(oe&&Number(oe[1])||0)},0),Pe=Be.length>0,Re=async()=>{if(!ee){te(!0);try{const k=await fetch("/orgx/api/mission-control/graph/cycles/auto-fix",{method:"POST",headers:At({authToken:y,embedMode:u,contentTypeJson:!0}),body:JSON.stringify({initiativeId:t.id})}),N=await k.json().catch(()=>null);if(!k.ok)throw new Error((N==null?void 0:N.error)??(N==null?void 0:N.message)??`Failed to auto-fix dependency cycles (${k.status})`);const oe=typeof(N==null?void 0:N.cycleEdgesDetected)=="number"?N.cycleEdgesDetected:he,be=typeof(N==null?void 0:N.nodesUpdated)=="number"?N.nodesUpdated:0,We=typeof(N==null?void 0:N.nodesFailed)=="number"?N.nodesFailed:0;O({tone:We>0?"error":"success",message:We>0?`Auto-fix removed ${oe} cyclic edge${oe===1?"":"s"} and updated ${be} nodes (${We} failed).`:`Auto-fix removed ${oe} cyclic edge${oe===1?"":"s"} and updated ${be} nodes.`}),X()}catch(k){O({tone:"error",message:k instanceof Error?k.message:"Failed to auto-fix dependency cycles."})}finally{te(!1)}}},Ne=r.useMemo(()=>new Map(p.map(k=>[k.id,k])),[p]),He=r.useMemo(()=>ja(l,p),[l,p]),ft=r.useMemo(()=>K.some(k=>Ne.has(k)),[Ne,K]);r.useEffect(()=>{const k=J.current;if(!k||!$)return;const N=()=>{const be=Math.max(48,k.offsetHeight);D(We=>We===be?We:be)};if(N(),typeof ResizeObserver>"u")return;const oe=new ResizeObserver(()=>N());return oe.observe(k),()=>oe.disconnect()},[$,t.status,t.targetDate,t.name]),r.useEffect(()=>{const k=J.current;if(!k||!$){P(0);return}const N=k.closest('[data-mc-scroll-host="true"]')??k.closest(".h-full.overflow-y-auto.overflow-x-hidden"),oe=N??window;let be=0;const We=()=>{be=0;const Ee=Number.parseFloat(getComputedStyle(k).top||"0"),ks=k.getBoundingClientRect(),pt=(N==null?void 0:N.getBoundingClientRect().top)??0,U=1-(ks.top-pt-Ee)/56,Se=Math.pow(Math.max(0,Math.min(1,U)),1.2);P(Z=>Math.abs(Z-Se)<.015?Z:Se)},Nt=()=>{be||(be=window.requestAnimationFrame(We))};return We(),oe.addEventListener("scroll",Nt,{passive:!0}),window.addEventListener("resize",Nt),()=>{be&&window.cancelAnimationFrame(be),oe.removeEventListener("scroll",Nt),window.removeEventListener("resize",Nt)}},[$,t.id]),r.useEffect(()=>{var k;$&&!l&&p.length>0&&b(((k=p[0])==null?void 0:k.id)??null)},[$,p,l]),r.useEffect(()=>{if(!H)return;const k=window.setTimeout(()=>O(null),H.tone==="success"?2800:4200);return()=>window.clearTimeout(k)},[H]);const St=((R==null?void 0:R.initiative.assignedAgents)??[]).map(k=>({id:k.id,name:k.name,confidence:"high"})),je=f.get(t.id)??[],Je=St.length>0?St:je,Te=p.filter(k=>k.type==="task"),st=Te.filter(k=>wa(k.status)).length,gt=Te.filter(k=>ya(k.status)).length,jt=Te.filter(k=>tt(k.status)).length,Ye=(d==null?void 0:d.activeCount)??0,Qe=(d==null?void 0:d.totalCount)??0,Ue=st>0||Ye>0,ut=t.status==="active"&&Ue?"in_progress":t.status,nt=ut==="in_progress"?ps.active:ps[ut],rt=ut==="in_progress"?"In Progress":Oe(ut),Ot=Te.length>0?Te:p.some(k=>k.type==="milestone")?p.filter(k=>k.type==="milestone"):p.filter(k=>k.type==="workstream"),kt=Math.round(Ot.reduce((k,N)=>k+(N.expectedDurationHours||0),0)*10)/10,mt=Math.round(Ot.reduce((k,N)=>k+(N.expectedBudgetUsd||0),0)*100)/100,Ct=p.filter(k=>k.type==="milestone"),at=p.filter(k=>k.type==="workstream"),Mt=V.isPinning||V.isMoving,ye=(t.rawStatus??t.status??"").trim().toLowerCase().replace(/[\s-]+/g,"_"),Xe=new Set(["paused","draft","planned","todo","backlog","queued"]).has(ye),Ze=ye==="paused"?"Resume":"Start",ot=!n,bt=n,i=r.useMemo(()=>at.filter(k=>k.initiativeId===t.id).sort((k,N)=>k.priorityNum-N.priorityNum||k.title.localeCompare(N.title)),[t.id,at]),C=$&&(De||ie.workstreams.length>0||ie.milestones.length>0||ie.tasks.length>0),A=Te.length>0?qt(jt,Te.length):Ct.length>0?qt(Ct.filter(k=>tt(k.status)).length,Ct.length):C&&at.length>0?qt(at.filter(k=>tt(k.status)).length,at.length):null,z=ws(A===null?t.health:A),se=z===0?2:z,me=Math.pow(w,.82),ke=Math.max(0,Number((16*(1-me)).toFixed(2))),$e=`0 10px 26px rgba(0,0,0,${(.18+me*.24).toFixed(3)}), 0 1px 0 rgba(191,255,0,${(me*.09).toFixed(3)})`,Ce=async k=>{if(i.length===0){O({tone:"error",message:"No workstreams available to queue for this initiative."});return}const N=k==="top"?[...i].reverse():i;let oe=0,be=0,We=null;for(const Nt of N)try{await V.pin({initiativeId:t.id,workstreamId:Nt.id}),await V.move({initiativeId:t.id,workstreamId:Nt.id,placement:k}),oe+=1}catch(Ee){be+=1,We||(We=Ee instanceof Error?Ee.message:"Failed to queue this initiative.")}if(be>0){O({tone:oe>0?"success":"error",message:oe>0?`Queued ${oe}/${i.length} workstreams (${be} failed).`:We??"Failed to queue initiative workstreams."});return}O({tone:"success",message:`Queued ${oe} workstream${oe===1?"":"s"} to ${k==="top"?"top":"end"}.`})},Le=k=>{if(k.type==="initiative"){h({type:"initiative",entity:t});return}if(k.type==="workstream"){h({type:"workstream",entity:ka(k,t),initiative:t});return}if(k.type==="milestone"){h({type:"milestone",entity:Na(k,t),initiative:t});return}h({type:"task",entity:Sa(k,t),initiative:t})},ge=async(k,N)=>{await F.updateEntity.mutateAsync({type:k.type,id:k.id,...N})},et=k=>N=>{N.stopPropagation(),F.entityAction.mutate({type:"initiative",id:t.id,action:k})},we=k=>{k.stopPropagation(),F.updateEntity.mutate({type:"initiative",id:t.id,status:"active"})};return e.jsxs("div",{id:`initiative-${t.id}`,className:`surface-tier-1 overflow-visible rounded-2xl transition-[background-color,border-color,box-shadow] duration-200 ${$?"bg-[--orgx-surface-elevated]":"bg-[--orgx-surface]"} ${s?"ring-1 ring-[#BFFF00]/30 shadow-[0_0_0_1px_rgba(191,255,0,0.12)]":""}`,style:{"--mc-initiative-header-offset":`${Q}px`},children:[e.jsxs("div",{ref:J,role:"button",tabIndex:0,"aria-expanded":$,onClick:()=>c(t.id),onKeyDown:k=>{(k.key==="Enter"||k.key===" ")&&(k.preventDefault(),c(t.id))},className:`group flex min-h-[66px] w-full min-w-0 items-center gap-2.5 overflow-visible px-3 py-3 text-left transition-[background-color,border-radius,box-shadow] duration-300 hover:bg-white/[0.035] sm:gap-3 sm:px-4 ${$?"sticky z-30 border-b border-subtle bg-[#0C0E14]/95 shadow-[0_8px_20px_rgba(0,0,0,0.3)] backdrop-blur-xl":""}`,style:$?{top:"var(--mc-toolbar-offset, 88px)",borderTopLeftRadius:`${ke}px`,borderTopRightRadius:`${ke}px`,boxShadow:$e}:void 0,children:[e.jsx(fe.div,{animate:{rotate:$?90:0},transition:{type:"spring",stiffness:400,damping:25},className:"flex-shrink-0 flex items-center justify-center w-6 h-6 rounded-md transition-colors group-hover:bg-white/[0.06]",children:e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",className:"text-muted",children:e.jsx("path",{d:"m9 18 6-6-6-6"})})}),a&&e.jsx("div",{className:"flex h-6 w-6 flex-shrink-0 items-center justify-center",children:e.jsx("input",{type:"checkbox",checked:s,onChange:k=>{const N=k.nativeEvent.shiftKey??!1;a(t.id,k.currentTarget.checked,N)},onClick:k=>k.stopPropagation(),"aria-label":`Select initiative ${t.name}`,className:"h-3.5 w-3.5 rounded border-white/20 bg-black/40 text-[#BFFF00] focus:ring-[#BFFF00]/35"})}),e.jsx("span",{className:`w-2 h-2 rounded-full flex-shrink-0 ${Ue?"status-breathe":""}`,style:{backgroundColor:_s(ut)}}),e.jsx("div",{className:"min-w-0 flex-[1_1_auto] overflow-hidden pr-1.5 sm:pr-2",children:e.jsx("button",{type:"button",onClick:k=>{k.stopPropagation(),h({type:"initiative",entity:t})},className:"block w-full max-w-full overflow-hidden text-ellipsis whitespace-nowrap text-left text-body font-semibold text-white transition-colors hover:text-primary sm:text-heading",title:t.name,children:t.name})}),e.jsx("div",{className:`ml-1 flex flex-shrink-0 justify-start ${n?"w-[80px] min-w-[80px]":"w-[90px] min-w-[90px] sm:w-[102px] sm:min-w-[102px]"}`,children:e.jsx("span",{className:`w-full truncate text-center text-micro rounded-full border py-0.5 uppercase tracking-[0.08em] leading-none whitespace-nowrap ${n?"px-1.5":"px-2"} ${nt}`,children:rt})}),e.jsx("div",{className:`ml-1.5 flex-shrink-0 ${bt?"flex":"lg:hidden"}`,title:`${z}% complete`,children:e.jsxs("svg",{viewBox:"0 0 36 36",className:"h-9 w-9","aria-label":`${z}% complete`,children:[e.jsx("circle",{cx:"18",cy:"18",r:"15",fill:"none",stroke:"rgba(255,255,255,0.06)",strokeWidth:"3"}),e.jsx(fe.circle,{cx:"18",cy:"18",r:"15",fill:"none",stroke:_s(ut),strokeWidth:"3",strokeLinecap:"round",initial:!1,animate:{strokeDasharray:`${se/100*94.25} 94.25`,opacity:z===0?.45:1},transition:{type:"spring",stiffness:260,damping:34,mass:.75},transform:"rotate(-90 18 18)"}),e.jsxs("text",{x:"18",y:"19",textAnchor:"middle",dominantBaseline:"central",fill:"currentColor",fontSize:"9",fontWeight:"600",className:"text-muted",children:[z,"%"]})]})}),e.jsxs("div",{className:`ml-1.5 hidden w-[148px] min-w-[148px] flex-shrink-0 items-center justify-end gap-2.5 pr-0.5 xl:w-[182px] xl:min-w-[182px] xl:pr-1 2xl:w-[206px] 2xl:min-w-[206px] ${bt?"hidden":"lg:flex"}`,children:[e.jsx("div",{className:"min-w-[88px] flex-1 xl:min-w-[112px] 2xl:min-w-[140px]",children:e.jsx("div",{className:"h-[2px] w-full overflow-hidden rounded-full bg-white/[0.06]",children:e.jsx(fe.div,{className:"h-full rounded-full transition-all",initial:!1,animate:{width:`${se}%`,opacity:z===0?.45:1},transition:{type:"spring",stiffness:260,damping:34,mass:.75},style:{backgroundColor:_s(ut)}})})}),e.jsxs("span",{className:"w-[42px] text-right text-micro text-muted xl:w-[48px] xl:text-caption",style:{fontVariantNumeric:"tabular-nums"},children:[z,"%"]})]}),e.jsxs("div",{className:`ml-1 hidden flex-shrink-0 items-center justify-end gap-1.5 lg:flex ${n?"w-[40px] min-w-[40px]":"w-[180px] min-w-[180px]"}`,children:[ot&&e.jsx(vs,{label:"Queue",size:"sm",busy:Mt,disabled:i.length===0,stopPropagation:!0,title:`Queue initiative: ${t.name}`,onSelectPlacement:Ce}),e.jsxs("button",{type:"button",onClick:k=>{Xe&&we(k)},disabled:!Xe||F.updateEntity.isPending,title:Xe?`${Ze} initiative`:`Cannot start while status is ${Oe(ye)}`,className:`control-pill inline-flex items-center justify-center gap-1.5 text-micro font-semibold text-[#D8FFA1] disabled:cursor-not-allowed disabled:text-white/35 disabled:opacity-55 ${n?"h-8 w-8 px-0":"h-8 px-2.5"}`,"data-state":"active",children:[e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:e.jsx("path",{d:"M8 5v14l11-7z"})}),!n&&e.jsx("span",{children:Ze})]})]}),e.jsx("div",{className:`ml-2 w-[104px] min-w-[104px] flex-shrink-0 items-center justify-end border-l border-subtle pl-2 lg:w-[116px] lg:min-w-[116px] lg:pl-2.5 xl:w-[132px] xl:min-w-[132px] ${n?"hidden":"hidden md:flex"}`,children:Ye>0?e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border border-[#BFFF00]/30 bg-[#BFFF00]/14 px-2 py-0.5 text-micro font-semibold text-[#D8FFA1]",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-[#BFFF00] status-breathe"}),Ye," live"]}):Je.length>0?e.jsx(bs,{agents:Je,max:3}):Qe>0?e.jsxs("span",{className:"w-full text-right text-micro text-muted",children:[Qe," idle"]}):e.jsx("span",{className:"w-full text-right text-micro text-white/28",children:"—"})}),e.jsxs("div",{className:"hidden w-[46px] flex-shrink-0 translate-x-1 items-center justify-end gap-1 opacity-0 transition-all duration-200 group-hover:translate-x-0 group-hover:opacity-100 group-focus-within:translate-x-0 group-focus-within:opacity-100 2xl:flex",children:[t.status==="active"&&e.jsx("button",{type:"button",onClick:et("pause"),title:"Pause",className:"flex items-center justify-center w-6 h-6 rounded-lg text-secondary hover:text-white hover:bg-white/[0.08] transition-colors",children:e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:[e.jsx("rect",{x:"6",y:"4",width:"4",height:"16",rx:"1"}),e.jsx("rect",{x:"14",y:"4",width:"4",height:"16",rx:"1"})]})}),t.status==="paused"&&e.jsx("button",{type:"button",onClick:et("resume"),title:"Resume",className:"flex items-center justify-center w-6 h-6 rounded-lg text-secondary hover:text-white hover:bg-white/[0.08] transition-colors",children:e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("path",{d:"M8 5v14l11-7z"})})}),e.jsx("button",{type:"button",onClick:k=>{k.stopPropagation(),h({type:"initiative",entity:t})},title:"Details",className:"flex items-center justify-center w-6 h-6 rounded-lg text-secondary hover:text-white hover:bg-white/[0.08] transition-colors",children:e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("circle",{cx:"12",cy:"12",r:"10"}),e.jsx("path",{d:"M12 16v-4M12 8h.01"})]})})]})]}),H&&e.jsx("div",{role:"status","aria-live":"polite",className:`mx-3 mb-2 rounded-lg border px-2.5 py-1.5 text-micro ${H.tone==="success"?"border-[#BFFF00]/24 bg-[#BFFF00]/[0.1] text-[#D8FFA1]":"border-red-400/24 bg-red-500/[0.1] text-red-100"}`,children:H.message}),e.jsx(ht,{children:$&&e.jsx(fe.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.2,ease:[.22,1,.36,1]},onAnimationStart:()=>q(!0),onAnimationComplete:()=>q(!1),className:I?"overflow-hidden":"overflow-visible",children:e.jsxs("div",{className:"space-y-2.5 px-4 pb-4 pt-2.5",children:[e.jsx("div",{className:"section-divider"}),_||!De&&ue?e.jsx("div",{className:"space-y-2",children:Array.from({length:3}).map((k,N)=>e.jsx(vt,{className:"h-24 w-full rounded-xl"},`mc-loading-${N}`))}):e.jsxs(fe.div,{initial:"hidden",animate:"show",variants:{hidden:{},show:{transition:{staggerChildren:.08}}},className:"space-y-3.5",children:[Me.length>0&&e.jsxs(fe.div,{variants:Xt,className:"overflow-hidden rounded-lg border border-amber-300/15 bg-amber-500/[0.06]",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 px-3 py-2",children:[e.jsxs("button",{type:"button",onClick:()=>g(k=>!k),className:"flex min-w-0 flex-1 items-center justify-between text-left transition-colors hover:text-white",children:[e.jsx("span",{className:"truncate text-caption text-amber-100/85",children:Pe?`Dependency loop detected (${he||Be.length} edges)`:`${Me.length} data source${Me.length>1?"s":""} unavailable`}),e.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",className:`ml-2 text-amber-100/55 transition-transform ${S?"rotate-180":""}`,children:e.jsx("path",{d:"m6 9 6 6 6-6"})})]}),Pe?e.jsx("button",{type:"button",onClick:Re,disabled:ee,className:"control-pill h-7 flex-shrink-0 px-2.5 text-micro font-semibold text-[#D8FFA1] disabled:opacity-45",children:ee?"Fixing…":"Auto-fix"}):null]}),e.jsx(ht,{children:S&&e.jsx(fe.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.15},className:"overflow-hidden",children:e.jsx("div",{className:"space-y-1 px-3 pb-2",children:Me.map((k,N)=>e.jsx("div",{className:"text-micro text-amber-100/72",children:dt(k)},N))})})})]}),(gt>0||st>0||kt>0||mt>0)&&e.jsx(fe.div,{variants:Xt,children:e.jsx(ds,{title:"Stats",storageKey:`stats.${t.id}`,defaultOpen:!0,children:e.jsxs("div",{className:"grid gap-2 py-0.5 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsx(us,{label:"Queue",value:`${gt} todo · ${st} active`}),e.jsx(us,{label:"Completed",value:`${jt}/${Te.length||0}`}),e.jsx(us,{label:"Duration",value:`${kt}h`}),e.jsx(us,{label:"Budget",value:`$${mt.toLocaleString()}`})]})})}),x&&e.jsxs("div",{className:"subsection-shell flex items-center justify-between rounded-lg px-3 py-2 text-caption text-[#D8FFA1]",children:[e.jsxs("span",{children:["Focused on workstream ",((yt=Ne.get(x))==null?void 0:yt.title)??x]}),e.jsx("button",{type:"button",onClick:()=>j(null),className:"text-micro underline underline-offset-2",children:"Clear focus"})]}),e.jsx(fe.div,{variants:Xt,children:e.jsx(ds,{title:"Dependency Map",storageKey:`depmap.${t.id}`,defaultOpen:!0,children:e.jsx(ta,{nodes:p,edges:ne,selectedNodeId:l,focusedWorkstreamId:x,onSelectNode:k=>{b(k);const N=Ne.get(k);(N==null?void 0:N.type)==="workstream"&&j(N.id)}})})}),ft&&e.jsx(fe.div,{variants:Xt,children:e.jsx(ds,{title:"Next Up",storageKey:`nextup.${t.id}`,defaultOpen:!0,children:e.jsx(ha,{recentTodoIds:K,nodesById:Ne,selectedNodeId:l,onSelectNode:k=>{b(k);const N=Ne.get(k);(N==null?void 0:N.type)==="workstream"&&j(N.id)}})})}),e.jsx(fe.div,{variants:Xt,children:e.jsx(ds,{title:"Hierarchy",storageKey:`hierarchy.${t.id}`,defaultOpen:!0,contentOverflowVisible:!0,children:e.jsx(xa,{nodes:p,edges:ne,selectedNodeId:l,highlightedNodeIds:He,editMode:T,onSelectNode:b,onFocusWorkstream:j,onOpenNode:Le,onUpdateNode:ge,onToggleEditMode:()=>v(k=>!k),mutations:F})})})]}),e.jsxs("button",{type:"button",onClick:()=>c(t.id),className:"flex w-full items-center justify-center gap-1.5 py-1.5 text-micro text-muted transition-colors hover:text-secondary",children:[e.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",children:e.jsx("path",{d:"m18 15-6-6-6 6"})}),"Collapse"]})]})})})]})}const Fa={hidden:{opacity:0},show:{opacity:1,transition:{staggerChildren:.045,delayChildren:.02}}},Ia={hidden:{opacity:0,y:10,scale:.995},show:{opacity:1,y:0,scale:1,transition:{type:"spring",stiffness:320,damping:28,mass:.7}}};function yn({initiatives:t,selectedInitiativeIds:s,onToggleInitiativeSelection:a,isSquished:n=!1,runtimeActivityByInitiativeId:d}){return e.jsx(fe.div,{variants:Fa,initial:"hidden",animate:"show",className:"space-y-2",children:t.map(o=>e.jsx(fe.div,{variants:Ia,layout:!0,transition:{type:"spring",stiffness:280,damping:32,mass:.75},children:e.jsx(Ca,{initiative:o,selected:(s==null?void 0:s.has(o.id))??!1,onSelectionChange:a,isSquished:n,runtimeActivity:(d==null?void 0:d.get(o.id))??null})},o.id))})}function Ps({mode:t="empty",hasActiveFilters:s=!1,detail:a=null,onClearFilters:n,onCreateInitiative:d,onPlayNextUp:o,onStartAutopilot:c,onRefresh:h,onOpenSettings:f}){const[y,u]=r.useState(null),[F,T]=r.useState(null),v=r.useCallback(async(x,j)=>{if(j){T(null),u(x);try{await j()}catch(S){const g=S instanceof Error?S.message:"";T(g?dt(g):"Action failed")}finally{u(S=>S===x?null:S)}}},[]),l=t==="filtered"?"No initiatives match this view":t==="degraded"?"Initiatives are temporarily unavailable":"No initiatives yet",b=t==="filtered"?s?"Adjust filters or clear them to return to the full hierarchy.":"Try a broader search or create a new initiative.":t==="degraded"?"Live sync is reconnecting, so initiative and Next Up data may be stale.":"Create an initiative to unlock hierarchy, Next Up routing, and slice-level tracking.";return e.jsx("div",{className:"flex-1 flex items-center justify-center p-6 sm:p-10",children:e.jsx(Cr,{className:"w-full max-w-xl p-6 sm:p-7",children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"flex items-start gap-3.5",children:[e.jsx("div",{className:"relative flex h-12 w-12 items-center justify-center rounded-xl",style:{backgroundColor:`${W.iris}1a`,border:`1px solid ${W.iris}33`},children:e.jsxs("svg",{width:"22",height:"22",viewBox:"0 0 24 24",fill:"none",stroke:W.iris,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("circle",{cx:"12",cy:"12",r:"10"}),e.jsx("path",{d:"M12 6v6l4 2"})]})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h3",{className:"text-heading font-semibold text-white",children:l}),e.jsx("p",{className:"mt-1 text-body leading-relaxed text-secondary",children:b})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[t==="filtered"&&n&&e.jsx("button",{type:"button",onClick:n,className:"rounded-full border border-strong bg-white/[0.03] px-3 py-1.5 text-caption font-semibold text-primary transition hover:bg-white/[0.08]",children:"Clear filters"}),t==="degraded"&&f&&e.jsx("button",{type:"button",onClick:f,className:"rounded-full border border-white/[0.12] bg-white/[0.03] px-3 py-1.5 text-caption font-semibold text-primary transition hover:bg-white/[0.08]",children:"Open settings"}),d&&e.jsx("button",{type:"button",onClick:d,className:"rounded-full border border-[#BFFF00]/30 bg-[#BFFF00]/12 px-3 py-1.5 text-caption font-semibold text-[#D8FFA1] transition hover:bg-[#BFFF00]/18",children:"Create initiative"}),o&&e.jsx("button",{type:"button",onClick:()=>void v("play",o),disabled:y!==null,className:"rounded-full border border-white/[0.12] bg-white/[0.03] px-3 py-1.5 text-caption font-semibold text-primary transition hover:bg-white/[0.08] disabled:opacity-45",children:y==="play"?"Dispatching...":"Play Next Up"}),c&&e.jsx("button",{type:"button",onClick:()=>void v("autopilot",c),disabled:y!==null,className:"rounded-full border border-[#0AD4C4]/30 bg-[#0AD4C4]/10 px-3 py-1.5 text-caption font-semibold text-[#98FFF5] transition hover:bg-[#0AD4C4]/16 disabled:opacity-45",children:y==="autopilot"?"Starting...":"Start Autopilot"}),h&&e.jsx("button",{type:"button",onClick:h,className:"rounded-full border border-strong bg-white/[0.03] px-3 py-1.5 text-caption font-semibold text-secondary transition hover:bg-white/[0.08] hover:text-primary",children:"Refresh"})]}),t==="degraded"&&a&&e.jsx("p",{className:"text-caption text-secondary",children:dt(a)}),F&&e.jsx("p",{className:"text-caption text-amber-200/80",children:F})]})})})}function re({label:t,icon:s,color:a="#BFFF00",variant:n="secondary",size:d="md",className:o="",type:c="button",...h}){const f=d==="sm"?"px-2.5 py-1 text-micro":"px-3 py-1.5 text-caption",y=n==="primary"?{backgroundColor:a,color:"#05060A",borderColor:`${a}CC`}:n==="destructive"?{backgroundColor:`${a}18`,color:a,borderColor:`${a}45`}:n==="ghost"?{backgroundColor:"rgba(255,255,255,0.03)",color:"rgba(255,255,255,0.75)",borderColor:"rgba(255,255,255,0.12)"}:{backgroundColor:`${a}20`,color:a,borderColor:`${a}30`};return e.jsxs("button",{type:c,className:`inline-flex items-center gap-1.5 rounded-lg border transition-colors disabled:cursor-not-allowed disabled:opacity-50 ${f} ${o}`,style:y,...h,children:[s,t&&e.jsx("span",{children:t})]})}const wn={draft:W.textMuted,in_review:W.amber,approved:W.lime,changes_requested:W.red,superseded:W.textMuted,archived:W.textMuted};function Ea(t,s){const a=new Date().toISOString();return t==="initiative"&&s==="init-1"?[{id:"artifact-demo-init-1-brief",name:"Q4 dashboard polish brief",description:"Summary of final polish checklist and open items.",artifact_url:"#",artifact_type:"shared.project_handbook",status:"approved",metadata:{source:"demo"},created_at:a,updated_at:a},{id:"artifact-demo-init-1-copy",name:"Launch copy variants",description:"Three launch-ready copy variants for review.",artifact_url:"#",artifact_type:"document",status:"in_review",metadata:{source:"demo"},created_at:a,updated_at:a}]:t==="initiative"&&s==="init-2"?[{id:"artifact-demo-init-2-subjects",name:"Subject line variants",description:"Email subject line candidates with performance notes.",artifact_url:"#",artifact_type:"document",status:"approved",metadata:{source:"demo"},created_at:a,updated_at:a}]:[]}function Aa(){return e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"flex-shrink-0 opacity-80",children:[e.jsx("path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"}),e.jsx("path",{d:"M14 2v4a2 2 0 0 0 2 2h4"})]})}async function vn(t,s,a){if(fs())return Ea(t,s);try{const n=At(a),d=new URLSearchParams({entity_type:t,entity_id:s,limit:"20"}),o=await fetch(`/orgx/api/work-artifacts/by-entity?${d.toString()}`,{headers:n});if(!o.ok)return[];const c=await o.json();return(c==null?void 0:c.artifacts)??[]}catch{return[]}}function js({entityType:t,entityId:s,title:a="Artifacts",authToken:n=null,embedMode:d=!1,finalOnly:o=!1,milestoneIds:c}){const{open:h}=Fr(),[f,y]=r.useState(!o),u=!!(c!=null&&c.length),F=ts({queryKey:hs.artifactsByEntity({entityType:t,entityId:s,authToken:n,embedMode:d}),enabled:!u&&!!s,queryFn:()=>vn(t,s,{authToken:n,embedMode:d})}),T=ts({queryKey:["artifacts-by-milestones",c,n,d],enabled:u,queryFn:async()=>{if(!(c!=null&&c.length))return[];const x=await Promise.all(c.map(S=>vn("milestone",S,{authToken:n,embedMode:d}))),j=new Map;for(const S of x)for(const g of S)j.has(g.id)||j.set(g.id,g);return[...j.values()].sort((S,g)=>Date.parse(g.updated_at)-Date.parse(S.updated_at))}}),v=u?T:F,l=v.data??[],b=f?l:l.filter(x=>x.status==="approved");return v.isLoading?e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-caption font-medium text-secondary",children:a}),e.jsx("div",{className:"shimmer-skeleton h-10 w-full rounded-lg"})]}):l.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h4",{className:"text-caption font-medium text-secondary",children:[a," (",b.length,")"]}),o&&e.jsx("button",{type:"button",onClick:()=>y(x=>!x),className:"text-micro text-faint transition-colors hover:text-secondary",children:f?"Final only":"Show all"})]}),e.jsxs("div",{className:"space-y-1.5",children:[b.slice(0,10).map(x=>e.jsxs("button",{type:"button",onClick:()=>h(x.id,{entityType:t,entityId:s}),className:"flex w-full items-center gap-2.5 rounded-lg border border-white/[0.06] bg-white/[0.02] px-3 py-2 text-left transition-colors hover:bg-white/[0.05]",children:[e.jsx(Aa,{}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-body text-primary",children:x.name}),e.jsx("span",{className:"text-micro text-faint",children:x.artifact_type})]}),e.jsx("span",{className:"flex-shrink-0 rounded-full px-1.5 py-0.5 text-micro font-medium uppercase tracking-wider",style:{color:wn[x.status]??W.textMuted,backgroundColor:`${wn[x.status]??W.textMuted}15`},children:x.status})]},x.id)),b.length>10&&e.jsxs("p",{className:"text-micro text-faint pl-2",children:["+",b.length-10," more"]})]})]})}function Da({initiative:t}){const{agentEntityMap:s,openModal:a,closeModal:n,authToken:d,embedMode:o,mutations:c}=Dt(),h=s.get(t.id)??[],[f,y]=r.useState(!1),[u,F]=r.useState(""),[T,v]=r.useState(!1),[l,b]=r.useState(!1),[x,j]=r.useState(null),[S,g]=r.useState(t.name),[I,q]=r.useState(t.description??""),[H,O]=r.useState(Zt(t.priority)),[ee,te]=r.useState(Rs(t.targetDate)),[J,Q]=r.useState(null),{details:D,isLoading:w}=gs({initiativeId:t.id,authToken:d,embedMode:o}),P=ns({authToken:d,embedMode:o}),$=D.tasks.filter(p=>["active","in_progress"].includes(p.status.toLowerCase())).length,R=D.tasks.filter(p=>p.status.toLowerCase()==="blocked").length,_=D.tasks.filter(p=>tt(p.status)).length,G=J??t.status,B=Ma(J??t.rawStatus??t.status),X=["active","in_progress","running","queued"].includes(B),ie=["paused","draft","planned","todo","backlog","pending","not_started"].includes(B),ue=c.entityAction.isPending||c.createEntity.isPending||c.updateEntity.isPending||c.deleteEntity.isPending,E=P.isPinning||P.isMoving,V=r.useMemo(()=>D.workstreams.length>0?D.workstreams.map(p=>({id:p.id,name:p.name})):(t.workstreams??[]).map(p=>({id:p.id,name:p.name})),[D.workstreams,t.workstreams]),ae=(p,ne)=>p&&p.trim().length>0?dt(p.trim()):ne;r.useEffect(()=>{T||(g(t.name),q(t.description??""),te(Rs(t.targetDate)),O(Zt(t.priority)))},[T,t.description,t.name,t.priority,t.targetDate]),r.useEffect(()=>{Q(null),b(!1)},[t.id,t.status,t.rawStatus]);const De=(p,ne,K)=>{j(null),c.entityAction.mutate({type:"initiative",id:t.id,action:p},{onSuccess:()=>{Q(ne),j(K)},onError:pe=>{j(ae(pe instanceof Error?pe.message:"",`Failed to ${p} initiative.`))}})},Ve=()=>{const p=S.trim();if(!p){j("Initiative title is required.");return}j(null),c.updateEntity.mutate({type:"initiative",id:t.id,title:p,summary:I.trim()||null,priority:H,target_date:ee||null},{onSuccess:()=>{v(!1),j("Initiative updated.")},onError:ne=>{j(ae(ne instanceof Error?ne.message:"","Failed to update initiative."))}})},ze=async p=>{if(V.length===0){j("No workstreams available to queue.");return}const ne=p==="top"?[...V].reverse():V;let K=0,pe=0,Fe=null;for(const Ie of ne)try{await P.pin({initiativeId:t.id,workstreamId:Ie.id}),await P.move({initiativeId:t.id,workstreamId:Ie.id,placement:p}),K+=1}catch(Me){pe+=1,Fe||(Fe=ae(Me instanceof Error?Me.message:"","Failed to queue initiative workstream."))}if(pe>0){j(K>0?`Queued ${K}/${V.length} workstreams (${pe} failed).`:Fe??"Failed to queue initiative workstreams.");return}j(`Queued ${K} workstream${K===1?"":"s"} to ${p==="top"?"top":"end"}.`)};return e.jsxs("div",{className:"flex h-full w-full min-h-0 flex-col",children:[e.jsxs("div",{className:"min-h-0 flex-1 space-y-5 overflow-y-auto p-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Ge,{type:"initiative",size:16}),e.jsx("h2",{className:"text-title font-semibold text-white",children:t.name}),e.jsx("span",{className:`text-micro px-2.5 py-0.5 rounded-full border uppercase tracking-[0.08em] ${ps[G]??ps.active}`,children:Oe(G)}),e.jsx("span",{className:"rounded-full border border-strong bg-white/[0.04] px-2 py-0.5 text-micro uppercase tracking-[0.08em] text-white/68",children:$a(t.priority)})]}),T?e.jsxs("div",{className:"space-y-2 rounded-xl border border-white/[0.08] bg-white/[0.02] p-3",children:[e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:"Title"}),e.jsx("input",{type:"text",value:S,onChange:p=>g(p.target.value),className:"mt-1 w-full rounded-lg border border-white/15 bg-white/[0.06] px-3 py-2 text-body text-bright outline-none focus:border-white/30"})]}),e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:"Summary"}),e.jsx("textarea",{value:I,onChange:p=>q(p.target.value),rows:3,className:"mt-1 w-full resize-y rounded-lg border border-white/15 bg-white/[0.06] px-3 py-2 text-body text-bright outline-none focus:border-white/30"})]}),e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:"Target date"}),e.jsx("input",{type:"date",value:ee,onChange:p=>te(p.target.value),className:"mt-1 w-full rounded-lg border border-white/15 bg-white/[0.06] px-3 py-2 text-body text-bright outline-none focus:border-white/30"})]}),e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:"Priority"}),e.jsxs("select",{value:H,onChange:p=>O(Zt(p.target.value)),className:"mt-1 w-full rounded-lg border border-white/15 bg-white/[0.06] px-3 py-2 text-body text-bright outline-none focus:border-white/30",children:[e.jsx("option",{value:"critical",children:"Critical (P0)"}),e.jsx("option",{value:"high",children:"High (P1)"}),e.jsx("option",{value:"medium",children:"Medium (P2)"}),e.jsx("option",{value:"low",children:"Low (P3)"})]})]})]}):t.description?e.jsx("p",{className:"text-body text-secondary leading-relaxed",children:t.description}):e.jsx("p",{className:"text-body text-muted",children:"No summary yet."}),h.length>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-micro text-muted uppercase tracking-wider",children:"Agents"}),e.jsx(bs,{agents:h,max:6})]}),x&&e.jsx("div",{className:"text-caption text-secondary",children:x})]}),(()=>{const p=D.tasks.length||0,ne=p>0?Math.round(_/p*100):0,K=[];return D.workstreams.length>0&&K.push(`${D.workstreams.length} workstream${D.workstreams.length===1?"":"s"}`),D.milestones.length>0&&K.push(`${D.milestones.length} milestone${D.milestones.length===1?"":"s"}`),$>0&&K.push(`${$} active`),R>0&&K.push(`${R} blocked`),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-caption text-secondary",children:[K.join(" · "),p>0?` · ${ne}% complete`:""]}),p>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-1 flex-1 rounded-full bg-white/[0.06] overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full transition-all duration-500",style:{width:`${Math.max(ne,2)}%`,background:`linear-gradient(90deg, ${W.teal}, ${W.lime})`}})}),e.jsxs("span",{className:"text-micro text-secondary tabular-nums",children:[ne,"%"]})]})]})})(),w?e.jsx("div",{className:"space-y-2",children:Array.from({length:3}).map((p,ne)=>e.jsx(vt,{className:"h-14 w-full rounded-lg"},`init-detail-${ne}`))}):e.jsxs(e.Fragment,{children:[D.workstreams.length>0&&e.jsx("div",{className:"space-y-1",children:D.workstreams.map(p=>{const ne=D.tasks.filter(Me=>Me.workstreamId===p.id),K=ne.filter(Me=>tt(Me.status)).length,pe=ne.length>0?qt(K,ne.length):typeof p.progress=="number"?ws(p.progress<=1?p.progress*100:p.progress):tt(p.status)?100:null,Fe=p.status.toLowerCase(),Ie=["active","in_progress","running"].includes(Fe)?W.lime:Fe==="blocked"?W.red:["done","completed"].includes(Fe)?W.teal:"rgba(255,255,255,0.08)";return e.jsxs("button",{onClick:()=>a({type:"workstream",entity:p,initiative:t}),className:"flex w-full items-center justify-between gap-2 rounded-lg border-l-2 py-2.5 pl-3 pr-2 text-left transition-colors hover:bg-white/[0.04]",style:{borderLeftColor:Ie},children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("span",{className:"text-body text-bright break-words",children:p.name}),e.jsxs("div",{className:"mt-0.5 flex items-center gap-2 text-micro text-muted",children:[e.jsxs("span",{children:[ne.length," tasks"]}),pe!==null&&e.jsxs("span",{children:["· ",pe,"%"]})]})]}),e.jsx("span",{className:`text-micro px-1.5 py-0.5 rounded-full border uppercase tracking-[0.08em] flex-shrink-0 ${Wn(p.status)}`,children:Oe(p.status)})]},p.id)})}),D.milestones.length>0&&e.jsx("div",{className:"space-y-1",children:D.milestones.map(p=>e.jsxs("button",{onClick:()=>a({type:"milestone",entity:p,initiative:t}),className:"flex w-full items-center justify-between gap-2 rounded-lg py-2 pl-3 pr-2 text-left transition-colors hover:bg-white/[0.04]",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("span",{className:"text-body text-bright break-words",children:p.title}),p.dueDate&&e.jsxs("span",{className:"text-micro text-muted mt-0.5 block",children:["Due ",new Date(p.dueDate).toLocaleDateString()]})]}),e.jsx("span",{className:"text-micro text-muted uppercase tracking-[0.08em] flex-shrink-0",children:Oe(p.status)})]},p.id))}),e.jsx("div",{className:"h-px bg-gradient-to-r from-transparent via-white/[0.06] to-transparent"}),e.jsx(js,{entityType:"initiative",entityId:t.id,authToken:d,embedMode:o}),e.jsx("div",{className:"space-y-2",children:e.jsx(ys,{entityType:"initiative",entityId:t.id,authToken:d,embedMode:o})})]})]}),e.jsx("div",{className:"border-t border-subtle bg-[#070b12]/85 px-6 py-3 backdrop-blur",children:e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[X&&e.jsx(re,{label:"Pause",color:W.amber,onClick:()=>De("pause","paused","Initiative paused."),disabled:ue}),ie&&e.jsx(re,{label:B==="paused"?"Resume":"Start",color:W.lime,variant:"primary",onClick:()=>De("resume","active",B==="paused"?"Initiative resumed.":"Initiative started."),disabled:ue}),e.jsx(vs,{label:"Queue",size:"md",busy:E,disabled:ue||V.length===0,title:`Queue initiative: ${t.name}`,onSelectPlacement:ze}),T?e.jsxs(e.Fragment,{children:[e.jsx(re,{label:"Save",color:W.teal,variant:"primary",onClick:Ve,disabled:ue||!S.trim()}),e.jsx(re,{label:"Cancel",variant:"ghost",onClick:()=>{v(!1),g(t.name),q(t.description??""),O(Zt(t.priority)),te(Rs(t.targetDate)),j(null)},disabled:ue})]}):e.jsx(re,{label:"Edit",variant:"ghost",onClick:()=>{v(!0),j(null)},disabled:ue}),e.jsx("div",{className:"flex-1"}),l?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-caption text-secondary",children:"Delete initiative?"}),e.jsx(re,{label:"Delete",color:W.red,variant:"destructive",onClick:()=>c.deleteEntity.mutate({type:"initiative",id:t.id},{onSuccess:()=>n(),onError:p=>j(p instanceof Error?p.message:"Failed to delete initiative.")}),disabled:ue}),e.jsx(re,{label:"Keep",variant:"ghost",onClick:()=>b(!1),disabled:ue})]}):e.jsx(re,{label:"Delete",color:W.red,variant:"destructive",onClick:()=>b(!0),disabled:ue}),f?e.jsxs("form",{className:"flex flex-wrap items-center gap-2",onSubmit:p=>{p.preventDefault(),u.trim()&&c.createEntity.mutate({type:"workstream",title:u.trim(),initiative_id:t.id,status:"not_started"},{onSuccess:()=>{F(""),y(!1)}})},children:[e.jsx("input",{type:"text",value:u,onChange:p=>F(p.target.value),placeholder:"Workstream name...",autoFocus:!0,className:"text-body bg-white/5 border border-white/10 rounded-lg px-2.5 py-1.5 text-primary placeholder-white/30 w-[180px] outline-none focus:border-white/25"}),e.jsx(re,{type:"submit",label:"Add",color:W.lime,disabled:!u.trim()||c.createEntity.isPending,size:"sm"}),e.jsx(re,{label:"Cancel",variant:"ghost",onClick:()=>{y(!1),F("")},size:"sm"})]}):e.jsx(re,{label:"+ Workstream",variant:"ghost",onClick:()=>y(!0),disabled:ue})]})})]})}function Rs(t){if(!t)return"";const s=Date.parse(t);return Number.isFinite(s)?new Date(s).toISOString().slice(0,10):""}function Ma(t){return(t??"").trim().toLowerCase().replace(/[\s-]+/g,"_")}function Zt(t){const s=(t??"").trim().toLowerCase();return s==="critical"||s==="p0"||s==="urgent"?"critical":s==="high"||s==="p1"?"high":s==="medium"||s==="normal"||s==="p2"?"medium":s==="low"||s==="p3"?"low":"medium"}function $a(t){const s=Zt(t);return s==="critical"?"Priority: Critical":s==="high"?"Priority: High":s==="low"?"Priority: Low":"Priority: Medium"}function Ta({workstream:t,initiative:s}){const{agentEntityMap:a,openModal:n,closeModal:d,authToken:o,embedMode:c,mutations:h}=Dt(),f=a.get(t.id)??a.get(s.id)??[],[y,u]=r.useState(!1),[F,T]=r.useState(""),[v,l]=r.useState(!1),[b,x]=r.useState(!1),[j,S]=r.useState(null),[g,I]=r.useState(t.name),[q,H]=r.useState(t.summary??""),[O,ee]=r.useState(t.status),{details:te,isLoading:J}=gs({initiativeId:s.id,authToken:o,embedMode:c}),Q=ns({authToken:o,embedMode:c}),D=r.useMemo(()=>te.milestones.filter(E=>E.workstreamId===t.id),[te.milestones,t.id]),w=r.useMemo(()=>new Set(D.map(E=>E.id)),[D]),P=r.useMemo(()=>te.tasks.filter(E=>E.workstreamId===t.id||E.milestoneId!==null&&w.has(E.milestoneId)).sort((E,V)=>{const ae=ms(E.status)-ms(V.status);if(ae!==0)return ae;const De=E.createdAt?Date.parse(E.createdAt):0;return(V.createdAt?Date.parse(V.createdAt):0)-De}),[te.tasks,w,t.id]),$=P.filter(E=>tt(E.status)).length,R=P.length>0?qt($,P.length):typeof t.progress=="number"?ws(t.progress<=1?t.progress*100:t.progress):tt(t.status)?100:null,_=t.status.toLowerCase(),G=h.entityAction.isPending||h.createEntity.isPending||h.updateEntity.isPending||h.deleteEntity.isPending,B=Q.isPinning||Q.isMoving,X=(E,V)=>E&&E.trim().length>0?dt(E.trim()):V,ie=()=>{const E=g.trim();if(!E){S("Workstream name is required.");return}S(null),h.updateEntity.mutate({type:"workstream",id:t.id,title:E,summary:q.trim()||null,status:O},{onSuccess:()=>{l(!1),S("Workstream updated.")},onError:V=>{S(X(V instanceof Error?V.message:"","Failed to update workstream."))}})},ue=async E=>{S(null);try{await Q.pin({initiativeId:s.id,workstreamId:t.id}),await Q.move({initiativeId:s.id,workstreamId:t.id,placement:E}),S(`Queued workstream to ${E==="top"?"top":"end"}.`)}catch(V){S(X(V instanceof Error?V.message:"","Failed to queue workstream."))}};return e.jsxs("div",{className:"flex h-full w-full min-h-0 flex-col",children:[e.jsxs("div",{className:"min-h-0 flex-1 space-y-5 overflow-y-auto p-6",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-caption",children:[e.jsx(Ge,{type:"initiative",size:12,className:"flex-shrink-0 opacity-80"}),e.jsx("button",{onClick:()=>n({type:"initiative",entity:s}),className:"break-words text-secondary transition-colors hover:text-white",children:s.name}),e.jsx("svg",{width:"8",height:"8",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"text-faint",children:e.jsx("path",{d:"m9 18 6-6-6-6"})}),e.jsx(Ge,{type:"workstream",size:12,className:"flex-shrink-0 opacity-95"}),e.jsx("span",{className:"break-words font-medium text-primary",children:t.name})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Ge,{type:"workstream",size:16}),e.jsx("h2",{className:"text-title font-semibold text-white",children:t.name}),e.jsx("span",{className:`text-micro px-2.5 py-0.5 rounded-full border uppercase tracking-[0.08em] ${Wn(t.status)}`,children:Oe(t.status)})]}),v?e.jsxs("div",{className:"space-y-2 rounded-xl border border-white/[0.08] bg-white/[0.02] p-3",children:[e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:"Name"}),e.jsx("input",{type:"text",value:g,onChange:E=>I(E.target.value),className:"mt-1 w-full rounded-lg border border-white/15 bg-white/[0.06] px-3 py-2 text-body text-bright outline-none focus:border-white/30"})]}),e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:"Summary"}),e.jsx("textarea",{value:q,onChange:E=>H(E.target.value),rows:3,className:"mt-1 w-full resize-y rounded-lg border border-white/15 bg-white/[0.06] px-3 py-2 text-body text-bright outline-none focus:border-white/30"})]}),e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:"Status"}),e.jsx("select",{value:O,onChange:E=>ee(E.target.value),className:"mt-1 w-full rounded-lg border border-white/15 bg-white/[0.06] px-3 py-2 text-body text-bright outline-none focus:border-white/30",children:["not_started","planned","active","in_progress","paused","blocked","done"].map(E=>e.jsx("option",{value:E,children:Oe(E)},E))})]})]}):t.summary?e.jsx("p",{className:"text-body text-secondary leading-relaxed",children:t.summary}):e.jsx("p",{className:"text-body text-muted",children:"No summary yet."}),f.length>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-micro text-muted uppercase tracking-wider",children:"Agents"}),e.jsx(bs,{agents:f,max:6})]}),j&&e.jsx("div",{className:"text-caption text-secondary",children:j})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-caption text-secondary",children:[P.length," ",P.length===1?"task":"tasks"," · ",$,"/",P.length," done",D.length>0&&` · ${D.length} milestone${D.length===1?"":"s"}`]}),R!==null&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-1 flex-1 rounded-full bg-white/[0.06] overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full transition-all duration-500",style:{width:`${Math.max(R,2)}%`,backgroundColor:W.lime}})}),e.jsxs("span",{className:"text-micro text-secondary tabular-nums",children:[R,"%"]})]})]}),J?e.jsx("div",{className:"space-y-2",children:Array.from({length:3}).map((E,V)=>e.jsx(vt,{className:"h-12 w-full rounded-lg"},`ws-detail-${V}`))}):e.jsxs(e.Fragment,{children:[D.length>0&&e.jsx("div",{className:"space-y-1",children:D.map(E=>e.jsxs("button",{onClick:()=>n({type:"milestone",entity:E,initiative:s}),className:"flex w-full items-center justify-between gap-2 rounded-lg py-2 pl-3 pr-2 text-left transition-colors hover:bg-white/[0.04]",children:[e.jsx("span",{className:"text-body text-bright break-words",children:E.title}),e.jsx("span",{className:`text-micro px-1.5 py-0.5 rounded-full border uppercase tracking-[0.08em] flex-shrink-0 ${Hn(E.status)}`,children:Oe(E.status)})]},E.id))}),P.length>0&&e.jsx("div",{className:"space-y-1",children:P.map(E=>{const V=E.status.toLowerCase(),ae=["active","in_progress"].includes(V)?W.lime:V==="blocked"?W.red:["done","completed"].includes(V)?W.teal:"rgba(255,255,255,0.08)";return e.jsxs("button",{onClick:()=>n({type:"task",entity:E,initiative:s}),className:"flex w-full items-center justify-between gap-2 rounded-lg border-l-2 py-2 pl-3 pr-2 text-left transition-colors hover:bg-white/[0.04]",style:{borderLeftColor:ae},children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("span",{className:"text-body text-bright break-words",children:E.title}),E.priority&&e.jsx("span",{className:"text-micro text-muted mt-0.5 block uppercase tracking-wider",children:E.priority})]}),e.jsx("span",{className:`text-micro px-1.5 py-0.5 rounded-full border uppercase tracking-[0.08em] flex-shrink-0 ${Qn(E.status)}`,children:Oe(E.status)})]},E.id)})}),e.jsx("div",{className:"h-px bg-gradient-to-r from-transparent via-white/[0.06] to-transparent"}),e.jsx(js,{entityType:"workstream",entityId:t.id,title:"Artifacts (from milestones)",authToken:o,embedMode:c,finalOnly:!0,milestoneIds:D.map(E=>E.id)}),e.jsx("div",{className:"space-y-2",children:e.jsx(ys,{entityType:"workstream",entityId:t.id,authToken:o,embedMode:c})})]})]}),e.jsx("div",{className:"border-t border-subtle bg-[#070b12]/85 px-6 py-3 backdrop-blur",children:e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[["not_started","planned","todo"].includes(_)&&e.jsx(re,{label:"Start",color:W.lime,variant:"primary",onClick:()=>h.entityAction.mutate({type:"workstream",id:t.id,action:"start"}),disabled:G}),["active","in_progress"].includes(_)&&e.jsxs(e.Fragment,{children:[e.jsx(re,{label:"Complete",color:W.teal,variant:"primary",onClick:()=>h.entityAction.mutate({type:"workstream",id:t.id,action:"complete"}),disabled:G}),e.jsx(re,{label:"Pause",color:W.amber,onClick:()=>h.entityAction.mutate({type:"workstream",id:t.id,action:"pause"}),disabled:G}),e.jsx(re,{label:"Block",color:W.red,variant:"destructive",onClick:()=>h.entityAction.mutate({type:"workstream",id:t.id,action:"block"}),disabled:G})]}),["paused","blocked"].includes(_)&&e.jsx(re,{label:"Resume",color:W.lime,variant:"primary",onClick:()=>h.entityAction.mutate({type:"workstream",id:t.id,action:"resume"}),disabled:G}),e.jsx(vs,{label:"Queue",size:"md",busy:B,disabled:G,title:`Queue workstream: ${t.name}`,onSelectPlacement:ue}),v?e.jsxs(e.Fragment,{children:[e.jsx(re,{label:"Save",color:W.teal,variant:"primary",onClick:ie,disabled:G||!g.trim()}),e.jsx(re,{label:"Cancel",variant:"ghost",onClick:()=>{l(!1),I(t.name),H(t.summary??""),ee(t.status),S(null)},disabled:G})]}):e.jsx(re,{label:"Edit",variant:"ghost",onClick:()=>{l(!0),S(null)},disabled:G}),e.jsx("div",{className:"flex-1"}),b?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-caption text-secondary",children:"Delete workstream?"}),e.jsx(re,{label:"Delete",color:W.red,variant:"destructive",onClick:()=>h.deleteEntity.mutate({type:"workstream",id:t.id},{onSuccess:()=>d(),onError:E=>S(X(E instanceof Error?E.message:"","Failed to delete workstream."))}),disabled:G}),e.jsx(re,{label:"Keep",variant:"ghost",onClick:()=>x(!1),disabled:G})]}):e.jsx(re,{label:"Delete",color:W.red,variant:"destructive",onClick:()=>x(!0),disabled:G}),y?e.jsxs("form",{className:"flex flex-wrap items-center gap-2",onSubmit:E=>{E.preventDefault(),F.trim()&&h.createEntity.mutate({type:"task",title:F.trim(),workstream_id:t.id,initiative_id:s.id,status:"todo"},{onSuccess:()=>{T(""),u(!1)},onError:V=>{S(X(V instanceof Error?V.message:"","Failed to create task."))}})},children:[e.jsx("input",{type:"text",value:F,onChange:E=>T(E.target.value),placeholder:"Task title...",autoFocus:!0,className:"text-body bg-white/5 border border-white/10 rounded-lg px-2.5 py-1.5 text-primary placeholder-white/30 w-[160px] outline-none focus:border-white/25"}),e.jsx(re,{label:"Add",color:W.lime,type:"submit",size:"sm",disabled:!F.trim()||h.createEntity.isPending}),e.jsx(re,{label:"Cancel",variant:"ghost",size:"sm",onClick:()=>{u(!1),T("")}})]}):e.jsx(re,{label:"+ Task",variant:"ghost",onClick:()=>u(!0),disabled:G})]})})]})}function _a({milestone:t,initiative:s}){const{openModal:a,closeModal:n,authToken:d,embedMode:o,mutations:c}=Dt(),[h,f]=r.useState(!1),[y,u]=r.useState(!1),[F,T]=r.useState(!1),[v,l]=r.useState(""),[b,x]=r.useState(null),[j,S]=r.useState(t.title),[g,I]=r.useState(t.description??""),[q,H]=r.useState(jn(t.dueDate)),[O,ee]=r.useState(t.status),{details:te}=gs({initiativeId:s.id,authToken:d,embedMode:o}),J=te.tasks.filter(_=>_.milestoneId===t.id),Q=t.status.toLowerCase()==="done"||t.status.toLowerCase()==="completed",D=J.filter(_=>tt(_.status)).length,w=J.length>0?qt(D,J.length):Q?100:0,P=c.entityAction.isPending||c.createEntity.isPending||c.updateEntity.isPending||c.deleteEntity.isPending,$=(_,G)=>_&&_.trim().length>0?dt(_.trim()):G,R=()=>{const _=j.trim();if(!_){x("Milestone title is required.");return}x(null),c.updateEntity.mutate({type:"milestone",id:t.id,title:_,description:g.trim()||null,due_date:q||null,status:O},{onSuccess:()=>{f(!1),x("Milestone updated.")},onError:G=>{x($(G instanceof Error?G.message:"","Failed to update milestone."))}})};return e.jsxs("div",{className:"flex h-full w-full min-h-0 flex-col",children:[e.jsxs("div",{className:"min-h-0 flex-1 space-y-5 overflow-y-auto p-6",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-caption",children:[e.jsx(Ge,{type:"initiative",size:12,className:"flex-shrink-0 opacity-80"}),e.jsx("button",{onClick:()=>a({type:"initiative",entity:s}),className:"break-words text-secondary transition-colors hover:text-white",children:s.name}),e.jsx("svg",{width:"8",height:"8",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"text-faint",children:e.jsx("path",{d:"m9 18 6-6-6-6"})}),e.jsx(Ge,{type:"milestone",size:12,className:"flex-shrink-0 opacity-95"}),e.jsx("span",{className:"break-words font-medium text-primary",children:t.title})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Ge,{type:"milestone",size:16}),e.jsx("h2",{className:"text-title font-semibold text-white",children:t.title}),e.jsx("span",{className:`text-micro px-2.5 py-0.5 rounded-full border uppercase tracking-[0.08em] ${Hn(t.status)}`,children:Oe(t.status)})]}),h?e.jsxs("div",{className:"space-y-2 rounded-xl border border-white/[0.08] bg-white/[0.02] p-3",children:[e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:"Title"}),e.jsx("input",{type:"text",value:j,onChange:_=>S(_.target.value),className:"mt-1 w-full rounded-lg border border-white/15 bg-white/[0.06] px-3 py-2 text-body text-bright outline-none focus:border-white/30"})]}),e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:"Description"}),e.jsx("textarea",{value:g,onChange:_=>I(_.target.value),rows:3,className:"mt-1 w-full resize-y rounded-lg border border-white/15 bg-white/[0.06] px-3 py-2 text-body text-bright outline-none focus:border-white/30"})]}),e.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:"Due date"}),e.jsx("input",{type:"date",value:q,onChange:_=>H(_.target.value),className:"mt-1 w-full rounded-lg border border-white/15 bg-white/[0.06] px-3 py-2 text-body text-bright outline-none focus:border-white/30"})]}),e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:"Status"}),e.jsx("select",{value:O,onChange:_=>ee(_.target.value),className:"mt-1 w-full rounded-lg border border-white/15 bg-white/[0.06] px-3 py-2 text-body text-bright outline-none focus:border-white/30",children:["planned","active","in_progress","at_risk","blocked","done"].map(_=>e.jsx("option",{value:_,children:Oe(_)},_))})]})]})]}):t.description?e.jsx("p",{className:"text-body text-secondary leading-relaxed",children:t.description}):e.jsx("p",{className:"text-body text-muted",children:"No description yet."}),b&&e.jsx("div",{className:"text-caption text-secondary",children:b})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-caption text-secondary",children:[e.jsxs("span",{children:[J.length," ",J.length===1?"task":"tasks"]}),e.jsx("span",{className:"text-faint",children:"·"}),e.jsxs("span",{style:{fontVariantNumeric:"tabular-nums"},children:[D,"/",J.length," done"]}),t.dueDate&&(()=>{const _=Date.parse(t.dueDate);if(!Number.isFinite(_))return null;const G=Math.ceil((_-Date.now())/864e5),B=G<0?W.red:G<=3?W.red:G<=7?W.amber:"rgba(255,255,255,0.5)",X=G<0?`${Math.abs(G)}d overdue`:`Due in ${G}d`;return e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-faint",children:"·"}),e.jsx("span",{style:{color:B},children:X})]})})()]}),J.length>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-1 flex-1 rounded-full bg-white/[0.06] overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full transition-all duration-500",style:{width:`${Math.max(w,2)}%`,backgroundColor:W.teal}})}),e.jsxs("span",{className:"text-micro text-secondary tabular-nums",children:[w,"%"]})]})]}),J.length>0&&e.jsx("div",{className:"space-y-1",children:J.map(_=>{const G=_.status.toLowerCase(),B=["active","in_progress"].includes(G)?W.lime:G==="blocked"?W.red:["done","completed"].includes(G)?W.teal:"rgba(255,255,255,0.08)";return e.jsxs("button",{onClick:()=>a({type:"task",entity:_,initiative:s}),className:"flex w-full items-center justify-between gap-2 rounded-lg border-l-2 py-2 pl-3 pr-2 text-left transition-colors hover:bg-white/[0.04]",style:{borderLeftColor:B},children:[e.jsx("span",{className:"text-body text-bright",children:_.title}),e.jsx("span",{className:`text-micro px-1.5 py-0.5 rounded-full border uppercase tracking-[0.08em] flex-shrink-0 ${Qn(_.status)}`,children:Oe(_.status)})]},_.id)})}),e.jsx("div",{className:"h-px bg-gradient-to-r from-transparent via-white/[0.06] to-transparent"}),e.jsx(js,{entityType:"milestone",entityId:t.id,authToken:d,embedMode:o}),e.jsx("div",{className:"space-y-2",children:e.jsx(ys,{entityType:"milestone",entityId:t.id,authToken:d,embedMode:o})})]}),e.jsx("div",{className:"border-t border-subtle bg-[#070b12]/85 px-6 py-3 backdrop-blur",children:e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[!Q&&t.status.toLowerCase()==="planned"&&e.jsx(re,{label:"Start",color:W.lime,variant:"primary",onClick:()=>c.entityAction.mutate({type:"milestone",id:t.id,action:"start"}),disabled:P}),!Q&&(t.status.toLowerCase()==="in_progress"||t.status.toLowerCase()==="at_risk")&&e.jsx(re,{label:J.length>0&&!J.every(_=>tt(_.status))?"Complete (force)":"Complete",color:W.teal,variant:"primary",onClick:()=>{const _=J.length===0||J.every(G=>tt(G.status));c.entityAction.mutate({type:"milestone",id:t.id,action:"complete",force:!_})},disabled:P}),h?e.jsxs(e.Fragment,{children:[e.jsx(re,{label:"Save",color:W.teal,variant:"primary",onClick:R,disabled:P||!j.trim()}),e.jsx(re,{label:"Cancel",variant:"ghost",onClick:()=>{f(!1),S(t.title),I(t.description??""),H(jn(t.dueDate)),ee(t.status),x(null)},disabled:P})]}):e.jsx(re,{label:"Edit",variant:"ghost",onClick:()=>{f(!0),x(null)},disabled:P}),e.jsx("div",{className:"flex-1"}),y?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-caption text-secondary",children:"Delete milestone?"}),e.jsx(re,{label:"Delete",color:W.red,variant:"destructive",onClick:()=>c.deleteEntity.mutate({type:"milestone",id:t.id},{onSuccess:()=>n(),onError:_=>x($(_ instanceof Error?_.message:"","Failed to delete milestone."))}),disabled:P}),e.jsx(re,{label:"Keep",variant:"ghost",onClick:()=>u(!1),disabled:P})]}):e.jsx(re,{label:"Delete",color:W.red,variant:"destructive",onClick:()=>u(!0),disabled:P}),F?e.jsxs("form",{className:"flex flex-wrap items-center gap-2",onSubmit:_=>{_.preventDefault(),v.trim()&&c.createEntity.mutate({type:"task",title:v.trim(),milestone_id:t.id,workstream_id:t.workstreamId??void 0,initiative_id:s.id,status:"todo"},{onSuccess:()=>{l(""),T(!1)},onError:G=>{x($(G instanceof Error?G.message:"","Failed to create task."))}})},children:[e.jsx("input",{type:"text",value:v,onChange:_=>l(_.target.value),placeholder:"Task title...",autoFocus:!0,className:"text-body bg-white/5 border border-white/10 rounded-lg px-2.5 py-1.5 text-primary placeholder-white/30 w-[160px] outline-none focus:border-white/25"}),e.jsx(re,{label:"Add",color:W.lime,type:"submit",size:"sm",disabled:!v.trim()||c.createEntity.isPending}),e.jsx(re,{label:"Cancel",variant:"ghost",size:"sm",onClick:()=>{T(!1),l("")}})]}):e.jsx(re,{label:"+ Task",variant:"ghost",onClick:()=>T(!0),disabled:P})]})})]})}function jn(t){if(!t)return"";const s=Date.parse(t);return Number.isFinite(s)?new Date(s).toISOString().slice(0,10):""}function La(t){if(!t)return null;const s=Date.parse(t);if(!Number.isFinite(s))return null;const a=Date.now(),n=Math.ceil((s-a)/864e5);return n<0?{text:`${Math.abs(n)}d overdue`,tone:W.red}:n<=3?{text:`Due in ${n}d`,tone:W.red}:n<=7?{text:`Due in ${n}d`,tone:W.amber}:{text:`Due ${new Date(s).toLocaleDateString()}`,tone:"rgba(255,255,255,0.5)"}}function Ba(t){const s=t.toLowerCase();return["active","in_progress","running"].includes(s)?os.active.text:["done","completed"].includes(s)?os.done.text:s==="blocked"?os.blocked.text:os.planned.text}function Pa({task:t,initiative:s}){const{agentEntityMap:a,openModal:n,mutations:d,closeModal:o,authToken:c,embedMode:h}=Dt(),f=a.get(t.id)??a.get(s.id)??[],[y,u]=r.useState(!1),[F,T]=r.useState(!1),[v,l]=r.useState(null),[b,x]=r.useState(t.title),[j,S]=r.useState(t.description??""),[g,I]=r.useState(t.priority??""),[q,H]=r.useState(kn(t.dueDate)),[O,ee]=r.useState(t.status),te=t.status.toLowerCase(),J=r.useMemo(()=>La(t.dueDate),[t.dueDate]),Q=(R,_)=>R&&R.trim().length>0?dt(R.trim()):_,D=d.entityAction.isPending||d.updateEntity.isPending||d.deleteEntity.isPending,w=R=>{l(null),d.entityAction.mutate({type:"task",id:t.id,action:R},{onError:_=>{l(Q(_ instanceof Error?_.message:"","Task action failed."))}})},P=()=>{const R=b.trim();if(!R){l("Task title is required.");return}l(null),d.updateEntity.mutate({type:"task",id:t.id,title:R,description:j.trim()||null,priority:g.trim()||null,due_date:q||null,status:O},{onSuccess:()=>{T(!1),l("Task updated.")},onError:_=>{l(Q(_ instanceof Error?_.message:"","Failed to update task."))}})},$=()=>{l(null),d.deleteEntity.mutate({type:"task",id:t.id},{onSuccess:()=>o(),onError:R=>{l(Q(R instanceof Error?R.message:"","Failed to delete task."))}})};return e.jsxs("div",{className:"flex h-full w-full min-h-0 flex-col",children:[e.jsxs("div",{className:"min-h-0 flex-1 space-y-5 overflow-y-auto p-6",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-caption",children:[e.jsx(Ge,{type:"initiative",size:12,className:"flex-shrink-0 opacity-80"}),e.jsx("button",{onClick:()=>n({type:"initiative",entity:s}),className:"break-words text-secondary transition-colors hover:text-white",children:s.name}),e.jsx("svg",{width:"8",height:"8",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"text-faint",children:e.jsx("path",{d:"m9 18 6-6-6-6"})}),e.jsx(Ge,{type:"task",size:12,className:"flex-shrink-0 opacity-95"}),e.jsx("span",{className:"break-words font-medium text-primary",children:t.title})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(Ge,{type:"task",size:16}),e.jsx("h2",{className:"break-words text-title font-semibold text-white",children:t.title})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-caption text-secondary",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx("span",{className:"inline-block h-1.5 w-1.5 rounded-full",style:{backgroundColor:Ba(t.status)}}),Oe(t.status)]}),t.priority&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-faint",children:"·"}),e.jsx("span",{className:"rounded bg-white/[0.06] px-1.5 py-0.5 text-micro font-medium uppercase tracking-wider text-secondary",children:t.priority})]}),J&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-faint",children:"·"}),e.jsx("span",{style:{color:J.tone},children:J.text})]})]}),F?e.jsxs("div",{className:"space-y-2 pt-2",children:[e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:"Title"}),e.jsx("input",{type:"text",value:b,onChange:R=>x(R.target.value),className:"mt-1 w-full rounded-lg border border-white/15 bg-white/[0.06] px-3 py-2 text-body text-bright outline-none focus:border-white/30"})]}),e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:"Description"}),e.jsx("textarea",{value:j,onChange:R=>S(R.target.value),rows:3,className:"mt-1 w-full resize-y rounded-lg border border-white/15 bg-white/[0.06] px-3 py-2 text-body text-bright outline-none focus:border-white/30"})]}),e.jsxs("div",{className:"grid gap-2 sm:grid-cols-3",children:[e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:"Priority"}),e.jsx("input",{type:"text",value:g,onChange:R=>I(R.target.value),placeholder:"p1, high, p50",className:"mt-1 w-full rounded-lg border border-white/15 bg-white/[0.06] px-3 py-2 text-body text-bright outline-none focus:border-white/30"})]}),e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:"Due date"}),e.jsx("input",{type:"date",value:q,onChange:R=>H(R.target.value),className:"mt-1 w-full rounded-lg border border-white/15 bg-white/[0.06] px-3 py-2 text-body text-bright outline-none focus:border-white/30"})]}),e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:"Status"}),e.jsx("select",{value:O,onChange:R=>ee(R.target.value),className:"mt-1 w-full rounded-lg border border-white/15 bg-white/[0.06] px-3 py-2 text-body text-bright outline-none focus:border-white/30",children:["not_started","planned","todo","in_progress","active","blocked","done"].map(R=>e.jsx("option",{value:R,children:Oe(R)},R))})]})]})]}):t.description?e.jsx(Ir,{text:t.description,mode:"block",className:"text-body text-secondary leading-relaxed"}):e.jsx("p",{className:"text-body text-muted",children:"No description yet."}),f.length>0&&e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(bs,{agents:f,max:4})})]}),v&&e.jsx("div",{className:"text-caption px-1",style:{color:`${W.red}b3`},children:v}),e.jsx("div",{className:"h-px bg-gradient-to-r from-transparent via-white/[0.06] to-transparent"}),e.jsx(js,{entityType:"task",entityId:t.id,authToken:c,embedMode:h}),e.jsx("div",{className:"space-y-2",children:e.jsx(ys,{entityType:"task",entityId:t.id,authToken:c,embedMode:h})})]}),e.jsx("div",{className:"border-t border-subtle bg-[#070b12]/85 px-6 py-3 backdrop-blur",children:e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[te==="todo"&&e.jsx(re,{label:"Start",color:W.lime,variant:"primary",onClick:()=>w("start"),disabled:D}),(te==="in_progress"||te==="active")&&e.jsx(re,{label:"Complete",color:W.teal,variant:"primary",onClick:()=>w("complete"),disabled:D}),(te==="todo"||te==="in_progress"||te==="active")&&e.jsx(re,{label:"Block",color:W.red,variant:"destructive",onClick:()=>w("block"),disabled:D}),te==="blocked"&&e.jsx(re,{label:"Unblock",color:W.amber,onClick:()=>w("unblock"),disabled:D}),F?e.jsxs(e.Fragment,{children:[e.jsx(re,{label:"Save",color:W.teal,variant:"primary",onClick:P,disabled:D||!b.trim()}),e.jsx(re,{label:"Cancel",variant:"ghost",onClick:()=>{T(!1),l(null),x(t.title),S(t.description??""),I(t.priority??""),H(kn(t.dueDate)),ee(t.status)},disabled:D})]}):e.jsx(re,{label:"Edit",variant:"ghost",onClick:()=>{T(!0),l(null)},disabled:D}),e.jsx("div",{className:"flex-1"}),y?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-caption",style:{color:`${W.red}b3`},children:"Delete?"}),e.jsx(re,{label:"Delete",color:W.red,variant:"destructive",onClick:$,disabled:D}),e.jsx(re,{label:"Keep",variant:"ghost",onClick:()=>u(!1),disabled:D})]}):e.jsx(re,{label:"Delete",color:W.red,variant:"destructive",onClick:()=>u(!0),disabled:D})]})})]})}function kn(t){if(!t)return"";const s=Date.parse(t);return Number.isFinite(s)?new Date(s).toISOString().slice(0,10):""}function Ra(t){const s=[];return t.type!=="initiative"&&t.initiative&&s.push(t.initiative.name),t.type==="initiative"||t.type==="workstream"?s.push(t.entity.name):(t.type==="milestone"||t.type==="task")&&s.push(t.entity.title),s}function qa({target:t,onClose:s}){return e.jsx(Er,{open:t!==null,onClose:s,maxWidth:"max-w-5xl",children:t&&e.jsxs("div",{className:"flex h-full w-full min-h-0 flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 border-b border-subtle px-5 py-3 sm:px-6",children:[e.jsxs("div",{className:"flex items-center gap-1.5 min-w-0 text-body text-secondary",children:[Ra(t).map((a,n,d)=>e.jsxs("span",{className:"flex items-center gap-1.5 min-w-0",children:[n>0&&e.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",className:"flex-shrink-0 text-faint",children:e.jsx("path",{d:"m9 18 6-6-6-6"})}),e.jsx("span",{className:`truncate ${n===d.length-1?"text-primary font-medium":""}`,children:a})]},n)),e.jsxs("span",{className:"ml-1 inline-flex items-center gap-1 rounded-full border border-white/[0.1] bg-white/[0.04] px-2 py-0.5 text-micro uppercase tracking-[0.06em] text-secondary",children:[e.jsx(Ge,{type:t.type,size:11,className:"opacity-90"}),t.type]})]}),e.jsx("button",{type:"button",onClick:s,"aria-label":"Close detail",className:"inline-flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-full border border-strong bg-white/[0.03] text-primary transition-colors hover:bg-white/[0.08] hover:text-white",children:e.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M18 6L6 18"}),e.jsx("path",{d:"M6 6l12 12"})]})})]}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto",children:[t.type==="initiative"&&e.jsx(Da,{initiative:t.entity}),t.type==="workstream"&&e.jsx(Ta,{workstream:t.entity,initiative:t.initiative}),t.type==="milestone"&&e.jsx(_a,{milestone:t.entity,initiative:t.initiative}),t.type==="task"&&e.jsx(Pa,{task:t.entity,initiative:t.initiative})]})]})})}function Nn(t){return(t??"").trim().toLowerCase().replace(/[\s-]+/g,"_")}function Oa(t){return t.split("_").map(s=>s.slice(0,1).toUpperCase()+s.slice(1)).join(" ")}const qs=["active","in_progress","not_started","planned","blocked","at_risk","paused","completed","done","backlog","todo","pending","draft"],za=[{value:"target",label:"Target date"},{value:"created",label:"Created at"},{value:"updated",label:"Updated at"}],Ua=[{value:"any",label:"Any time"},{value:"missing",label:"No target date"},{value:"overdue",label:"Overdue"},{value:"today",label:"Today"},{value:"next_7_days",label:"Next 7 days"},{value:"next_30_days",label:"Next 30 days"},{value:"custom_range",label:"Custom range"}],Wa=[{value:"any",label:"Any time"},{value:"missing",label:"No timestamp"},{value:"today",label:"Today"},{value:"past_7_days",label:"Past 7 days"},{value:"past_30_days",label:"Past 30 days"},{value:"custom_range",label:"Custom range"}];function Ha({initiatives:t,visibleCount:s}){const{statusFilters:a,dateField:n,datePreset:d,dateStart:o,dateEnd:c,activeFilterCount:h,groupBy:f,setGroupBy:y,sortBy:u,setSortBy:F,setStatusFilters:T,toggleStatusFilter:v,setDateField:l,setDatePreset:b,setDateStart:x,setDateEnd:j,clearFilters:S}=Dt(),[g,I]=r.useState(!1),[q,H]=r.useState(!1),O=r.useRef(null);r.useEffect(()=>{if(!g)return;const B=ie=>{var E;const ue=ie.target;ue&&((E=O.current)!=null&&E.contains(ue)||I(!1))},X=ie=>{ie.key==="Escape"&&I(!1)};return document.addEventListener("mousedown",B),document.addEventListener("keydown",X),()=>{document.removeEventListener("mousedown",B),document.removeEventListener("keydown",X)}},[g]);const ee=r.useMemo(()=>{const B=new Map;for(const ie of t){const ue=new Set([Nn(ie.status),Nn(ie.rawStatus)]);for(const E of ue)E&&B.set(E,(B.get(E)??0)+1)}for(const ie of qs)B.has(ie)||B.set(ie,0);return Array.from(B.entries()).sort((ie,ue)=>{const E=qs.indexOf(ie[0]),V=qs.indexOf(ue[0]);return E>=0&&V>=0?E-V:E>=0?-1:V>=0?1:ie[0].localeCompare(ue[0])}).map(([ie,ue])=>({key:ie,count:ue}))},[t]),te=a.length,J=r.useMemo(()=>ee.filter(B=>q||B.count>0||a.includes(B.key)),[q,a,ee]),Q=ee.length-J.length,D=r.useMemo(()=>n==="target"?Ua:Wa,[n]);r.useEffect(()=>{D.some(B=>B.value===d)||b("any")},[d,D,b]);const w=[{value:"none",label:"None"},{value:"status",label:"Status"},{value:"date",label:"Date"},{value:"category",label:"Category"}],P=[{value:"default",label:"Default"},{value:"date_asc",label:"Date (earliest)"},{value:"date_desc",label:"Date (latest)"},{value:"priority_high",label:"Priority (high first)"},{value:"priority_low",label:"Priority (low first)"}],$=f!=="status"||u!=="default",R=h>0,_=h,G=R||$;return e.jsxs("div",{ref:O,className:"relative flex items-center gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>{I(B=>{const X=!B;return X||H(!1),X})},"data-state":g||_>0?"active":"idle",className:"control-pill flex items-center gap-1.5 px-3 text-caption font-semibold",children:[e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e.jsx("path",{d:"M22 3H2l8 9.46V19l4 2v-8.54L22 3z"})}),e.jsx("span",{children:"Filters"}),_>0&&e.jsx("span",{className:"inline-flex min-w-[16px] items-center justify-center rounded-full border border-current/30 bg-black/25 px-1 text-micro leading-4",children:_})]}),s<t.length&&e.jsxs("span",{className:"text-micro text-muted whitespace-nowrap",children:[s,"/",t.length]}),e.jsx(ht,{initial:!1,children:R&&e.jsx(fe.button,{type:"button",onClick:S,initial:{opacity:0,x:-4},animate:{opacity:1,x:0},exit:{opacity:0,x:-4},transition:{duration:.15,ease:[.22,1,.36,1]},className:"text-micro text-muted transition-colors whitespace-nowrap hover:text-primary",children:"Clear"})}),e.jsx(ht,{children:g&&e.jsxs(fe.div,{initial:{opacity:0,y:-4,scale:.97},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:-4,scale:.97},transition:{duration:.16,ease:[.22,1,.36,1]},className:"surface-tier-2 fixed left-3 right-3 top-[calc(env(safe-area-inset-top)+72px)] z-[340] max-h-[calc(100dvh-104px)] overflow-y-auto overscroll-contain rounded-xl p-3.5 shadow-[0_16px_40px_rgba(0,0,0,0.45)] backdrop-blur-xl sm:absolute sm:left-auto sm:right-0 sm:top-12 sm:z-30 sm:w-[360px] sm:max-w-[94vw] sm:max-h-[min(78vh,680px)]",children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("div",{className:"text-caption font-semibold tracking-[0.01em] text-bright",children:"Filters"}),e.jsx("div",{className:"text-micro text-secondary",children:"Scope the Mission Control list view"})]}),R?e.jsxs("span",{className:"rounded-full border border-strong bg-white/[0.04] px-2 py-0.5 text-micro text-primary",children:[_," active"]}):$?e.jsx("span",{className:"rounded-full border border-strong bg-white/[0.04] px-2 py-0.5 text-micro text-secondary",children:"view modified"}):null]}),e.jsxs("div",{className:"subsection-shell p-2.5",children:[e.jsx("div",{className:"section-kicker mb-2",children:"Layout"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("label",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:"Group"}),e.jsx("select",{value:f,onChange:B=>y(B.target.value),className:"h-9 rounded-lg border border-white/[0.08] bg-black/30 px-2 text-caption text-primary focus:border-[#BFFF00]/40 focus:outline-none",children:w.map(B=>e.jsx("option",{value:B.value,children:B.label},B.value))})]}),e.jsxs("label",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:"Sort"}),e.jsx("select",{value:u,onChange:B=>F(B.target.value),className:"h-9 rounded-lg border border-white/[0.08] bg-black/30 px-2 text-caption text-primary focus:border-[#BFFF00]/40 focus:outline-none",children:P.map(B=>e.jsx("option",{value:B.value,children:B.label},B.value))})]})]})]}),e.jsxs("div",{className:"mt-2.5 subsection-shell p-2.5",children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between",children:[e.jsx("div",{className:"section-kicker",children:"Status"}),Q>0&&e.jsx("button",{type:"button",onClick:()=>H(B=>!B),className:"text-micro text-muted transition-colors hover:text-white/72",children:q?"Hide empty":`Show empty (${Q})`})]}),e.jsx("div",{className:"max-h-40 space-y-1 overflow-auto pr-1",children:J.map(B=>{const X=a.includes(B.key);return e.jsxs("label",{className:`flex cursor-pointer items-center justify-between rounded-md border px-2.5 py-1.5 text-caption transition-colors ${X?"border-[#BFFF00]/30 bg-[#BFFF00]/10 text-bright":"border-white/[0.08] bg-white/[0.02] text-primary hover:border-white/[0.15]"}`,children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"checkbox",checked:X,onChange:()=>v(B.key),className:"h-3.5 w-3.5 accent-[#BFFF00]"}),e.jsx("span",{children:Oa(B.key)})]}),e.jsx("span",{className:"text-micro text-secondary",children:B.count})]},B.key)})}),e.jsxs("div",{className:"mt-2 flex items-center justify-between",children:[e.jsx("button",{type:"button",onClick:()=>T([]),className:`text-micro uppercase tracking-[0.08em] ${te>0?"text-primary hover:text-white":"text-muted"}`,disabled:te===0,children:"Clear status"}),e.jsxs("div",{className:"text-micro text-secondary",children:[te," selected"]})]})]}),e.jsxs("div",{className:"mt-2.5 subsection-shell p-2.5",children:[e.jsx("div",{className:"section-kicker mb-2",children:"Date"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("label",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-secondary",children:"Field"}),e.jsx("select",{value:n,onChange:B=>l(B.target.value),className:"h-9 rounded-lg border border-strong bg-black/30 px-2 text-caption text-white focus:border-[#BFFF00]/40 focus:outline-none",children:za.map(B=>e.jsx("option",{value:B.value,children:B.label},B.value))})]}),e.jsxs("label",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-secondary",children:"Condition"}),e.jsx("select",{value:d,onChange:B=>b(B.target.value),className:"h-9 rounded-lg border border-strong bg-black/30 px-2 text-caption text-white focus:border-[#BFFF00]/40 focus:outline-none",children:D.map(B=>e.jsx("option",{value:B.value,children:B.label},B.value))})]})]}),d==="custom_range"&&e.jsxs("div",{className:"mt-2 grid grid-cols-2 gap-2",children:[e.jsxs("label",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-secondary",children:"Start"}),e.jsx("input",{type:"date",value:o,onChange:B=>x(B.target.value),className:"h-9 rounded-lg border border-strong bg-black/30 px-2 text-caption text-white focus:border-[#BFFF00]/40 focus:outline-none"})]}),e.jsxs("label",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-secondary",children:"End"}),e.jsx("input",{type:"date",value:c,onChange:B=>j(B.target.value),className:"h-9 rounded-lg border border-strong bg-black/30 px-2 text-caption text-white focus:border-[#BFFF00]/40 focus:outline-none"})]})]})]}),G&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-2 section-divider"}),e.jsxs("div",{className:"mt-2 flex flex-wrap justify-end gap-2",children:[$&&e.jsx("button",{type:"button",onClick:()=>{y("status"),F("default")},className:"text-micro uppercase tracking-[0.09em] text-secondary transition-colors hover:text-bright",children:"Reset layout"}),R&&e.jsx("button",{type:"button",onClick:S,className:"text-micro uppercase tracking-[0.09em] text-secondary transition-colors hover:text-bright",children:"Clear filters"})]})]})]})})]})}function wt(t){return!t||typeof t!="object"||Array.isArray(t)?null:t}function de(t){if(typeof t!="string")return null;const s=t.trim();return s.length>0?s:null}function ve(t){if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"&&t.trim().length>0){const s=Number(t);if(Number.isFinite(s))return s}return null}function Qa(t){const s=(de(t)??"").toLowerCase();return s==="assigned"||s==="inferred"||s==="fallback"?s:null}function ss(t){const s=de(t);if(!s)return null;const a=s.toLowerCase();return a==="undefined"||a==="null"||a==="main"||a==="unassigned"?null:s}function Jn(t){return ss(t)}function Va(t,s,a){if(!Array.isArray(t)){if(s||a){const o=s??a??"",c=a??s??"";if(o.trim().length>0&&c.trim().length>0)return[{id:o,name:c}]}return[]}const n=[],d=new Set;for(const o of t){const c=wt(o);if(!c)continue;const h=Jn(c.id)??ss(c.name),f=ss(c.name)??h;if(!h||!f)continue;const y=h.toLowerCase();d.has(y)||(d.add(y),n.push({id:h,name:f}))}if(n.length===0&&(s||a)){const o=s??a??"",c=a??s??"";if(o.trim().length>0&&c.trim().length>0)return[{id:o,name:c}]}return n}function zs(t,s){const a=(de(t)??"").toLowerCase();return a==="initiative"?"initiative":a==="milestone"?"milestone":a==="task"?"task":a==="workstream"?"workstream":s}function Ka(t){return(de(t)??"").toLowerCase()==="algorithmic"?"algorithmic":"manual"}function Bt(t){return Array.isArray(t)?t.map(s=>de(s)).filter(s=>!!s):[]}function Ga(t,s,a){const n=wt(t);if(!n)return null;const d=de(n.sliceId)??de(n.id);if(!d)return null;const o=zs(n.level??n.scope,s),c=de(n.title)??de(n.workstreamTitle)??de(n.milestoneTitle)??de(n.taskTitle)??de(n.initiativeTitle)??d,h=wt(n.order),f=wt(n.dispatch),y=wt(n.objectiveSnapshot??n.objective??n.ranking),u=wt(n.factors),F=wt(n.iwmt),T=wt(n.lineage),v=Jn(n.runnerAgentId??n.agentId),l=ss(n.runnerAgentName??n.agentName)??ss(n.runner),b=Va(n.runnerAgents,v,l??v),x=b[0]??null;return{sliceId:d,level:o,title:c,initiativeId:de(n.initiativeId),initiativeTitle:de(n.initiativeTitle),workstreamId:de(n.workstreamId),workstreamTitle:de(n.workstreamTitle),milestoneId:de(n.milestoneId),milestoneTitle:de(n.milestoneTitle),taskId:de(n.taskId),taskTitle:de(n.taskTitle),status:de(n.status)??de(n.queueState)??(f&&f.runnable===!1?"blocked":"queued"),priorityNum:ve(n.priorityNum??n.nextTaskPriority),dueAt:de(n.dueAt??n.nextTaskDueAt),dependencyState:de(n.dependencyState),objectiveScore:ve(n.objectiveScore)??ve(y==null?void 0:y.objectiveScore)??ve(n.mixScore),roiPerToken:ve(n.roiPerToken)??ve(y==null?void 0:y.roiPerToken),expectedTokens:ve(n.expectedTokens)??ve(y==null?void 0:y.expectedTokens),expectedValueUsd:ve(n.expectedValueUsd)??ve(y==null?void 0:y.expectedValueUsd),goalAlignment:ve(n.goalAlignment)??ve(u==null?void 0:u.goalAlignment),riskPenalty:ve(n.riskPenalty)??ve(u==null?void 0:u.riskPenalty),runnable:typeof(f==null?void 0:f.runnable)=="boolean"?f.runnable:void 0,blockReason:de((f==null?void 0:f.blockReason)??n.blockReason),suggestedScope:f&&f.suggestedScope?zs(f.suggestedScope,o):null,manualRank:ve(n.manualRank)??ve(h==null?void 0:h.manualRank),algorithmRank:ve(n.algorithmRank)??ve(h==null?void 0:h.algorithmRank)??a,finalRank:ve(n.finalRank)??ve(h==null?void 0:h.finalRank)??a,iwmt:F?{laneId:de(F.laneId),mixScore:ve(F.mixScore),factors:Array.isArray(F.factors)?F.factors.map(j=>{const S=wt(j);return S?{key:de(S.key)??void 0,label:de(S.label)??de(S.key)??void 0,value:ve(S.value)??void 0,weight:ve(S.weight)??void 0}:null}).filter(j=>!!j):void 0}:null,lineage:T?{initiativeIds:Bt(T.initiativeIds),workstreamIds:Bt(T.workstreamIds),milestoneIds:Bt(T.milestoneIds),taskIds:Bt(T.taskIds),iwmtIds:Bt(T.iwmtIds)}:null,sourceWorkstreamIds:Bt(n.sourceWorkstreamIds),queueState:de(n.queueState),sliceTaskIds:Bt(n.sliceTaskIds),sliceTaskCount:ve(n.sliceTaskCount),sliceMilestoneId:de(n.sliceMilestoneId),runnerAgentId:(x==null?void 0:x.id)??v,runnerAgentName:(x==null?void 0:x.name)??l,runnerAgents:b,runnerSource:Qa(n.runnerSource)??((x==null?void 0:x.id)??v?"inferred":"fallback"),updatedAt:de(n.updatedAt)}}function Ja(t,s,a,n){return{ok:!0,generatedAt:new Date().toISOString(),level:t,orderMode:s,mixPolicy:"iwmt_v1",total:0,items:[],degraded:["Demo mode: slice explorer uses fixture data only."],source:"local",pagination:{offset:a,limit:n,total:0,nextCursor:null,hasMore:!1}}}function Ya(t){const s=t.offset+t.limit,a=s<t.total;return{offset:t.offset,limit:t.limit,total:t.total,nextCursor:a?String(s):null,hasMore:a}}function Xa({workspaceId:t=null,initiativeId:s=null,level:a,orderMode:n=null,includeCompleted:d=!1,search:o="",offset:c=0,limit:h=24,authToken:f=null,embedMode:y=!1,enabled:u=!0}){var S,g,I,q,H,O,ee,te,J;const F=fs(),T=Math.max(0,c),v=Math.max(1,Math.min(300,h)),l=o.trim(),b=r.useMemo(()=>hs.missionControlSlices({workspaceId:t,initiativeId:s,level:a,orderMode:n,includeCompleted:d,search:l,offset:T,limit:v,authToken:f,embedMode:y}),[f,y,d,s,a,v,T,l,n,t]),x=ts({queryKey:b,enabled:u,queryFn:async()=>{if(F)return Ja(a,n??"manual",T,v);const Q=new URLSearchParams;pn(Q,t,{allTokenWhenMissing:!0}),s&&Q.set("initiative_id",s),Q.set("level",a),Q.set("include_completed",d?"1":"0"),Q.set("offset",String(T)),Q.set("limit",String(v)),Q.set("mix_policy","iwmt_v1"),n&&Q.set("order_mode",n),l.length>0&&Q.set("q",l);const D=await fetch(`/orgx/api/mission-control/slices?${Q.toString()}`,{headers:At({authToken:f,embedMode:y})}),w=await D.json().catch(()=>null);if(!D.ok){const X=w&&typeof w.error=="string"&&w.error||w&&typeof w.message=="string"&&w.message||`Failed to fetch mission-control slices (${D.status})`;throw new Error(X)}const P=Array.isArray(w==null?void 0:w.items)?w.items:[],$=zs((w==null?void 0:w.level)??(w==null?void 0:w.scope),a),R=P.map((X,ie)=>Ga(X,$,ie+1)).filter(X=>!!X),_=wt(w==null?void 0:w.pagination),G=ve(w==null?void 0:w.total)??ve(_==null?void 0:_.total)??R.length,B=_?{offset:ve(_.offset)??T,limit:ve(_.limit)??v,total:G,nextCursor:de(_.nextCursor),hasMore:typeof _.hasMore=="boolean"?_.hasMore:!1}:Ya({offset:T,limit:v,total:G});return{ok:!0,generatedAt:de(w==null?void 0:w.generatedAt)??new Date().toISOString(),workspaceId:de((w==null?void 0:w.workspaceId)??(w==null?void 0:w.workspace_id)),initiativeId:de((w==null?void 0:w.initiativeId)??(w==null?void 0:w.initiative_id)??s),level:$,mixPolicy:de((w==null?void 0:w.mixPolicy)??(w==null?void 0:w.mix_policy))??"iwmt_v1",orderMode:Ka((w==null?void 0:w.orderMode)??(w==null?void 0:w.order_mode)??(w==null?void 0:w.order)),total:G,items:R,degraded:Array.isArray(w==null?void 0:w.degraded)?w.degraded.map(X=>de(X)).filter(X=>!!X):void 0,source:de(w==null?void 0:w.source)==="canonical"?"canonical":de(w==null?void 0:w.source)==="local_fallback"?"local_fallback":"local",pagination:B}}}),j=r.useRef(null);return r.useEffect(()=>{var P;const Q=(P=x.data)==null?void 0:P.pagination;if(!u||!(Q!=null&&Q.hasMore)||!Q.nextCursor||j.current===Q.nextCursor)return;const D=Number.parseInt(Q.nextCursor,10);if(!Number.isFinite(D))return;j.current=Q.nextCursor;const w=new URLSearchParams;pn(w,t,{allTokenWhenMissing:!0}),s&&w.set("initiative_id",s),w.set("level",a),w.set("include_completed",d?"1":"0"),w.set("offset",String(D)),w.set("limit",String(v)),w.set("mix_policy","iwmt_v1"),n&&w.set("order_mode",n),l.length>0&&w.set("q",l),fetch(`/orgx/api/mission-control/slices?${w.toString()}`,{headers:At({authToken:f,embedMode:y})}).catch(()=>{})},[u,(g=(S=x.data)==null?void 0:S.pagination)==null?void 0:g.hasMore,(q=(I=x.data)==null?void 0:I.pagination)==null?void 0:q.nextCursor,t,s,a,n,d,l,v,f,y]),{...x,slices:((H=x.data)==null?void 0:H.items)??[],orderMode:((O=x.data)==null?void 0:O.orderMode)??n??"manual",degraded:((ee=x.data)==null?void 0:ee.degraded)??[],source:((te=x.data)==null?void 0:te.source)??null,pagination:((J=x.data)==null?void 0:J.pagination)??null}}function Sn(t,s){if(!s||s.trim().length===0)return;const a=s.trim();t.workspace_id=a}async function Cn(t){const s=await t.json().catch(()=>null);if(!t.ok){const a=s&&typeof s.error=="string"&&s.error||s&&typeof s.message=="string"&&s.message||`Request failed (${t.status})`;throw new Error(a)}return s??{}}function Za({workspaceId:t=null,initiativeId:s=null,level:a,authToken:n=null,embedMode:d=!1}){const o=On(),c=Rt({mutationFn:async f=>{const y={level:a,order:f.map(F=>({sliceId:F}))};Sn(y,t),s&&(y.initiative_id=s);const u=await fetch("/orgx/api/mission-control/slices/reorder",{method:"POST",headers:At({authToken:n,embedMode:d,contentTypeJson:!0,workspaceId:t}),body:JSON.stringify(y)});return Cn(u)},onMutate:async f=>{const y=o.getQueriesData({queryKey:["mission-control-slices"]});for(const[u,F]of y){if(!F||F.level!==a||s&&F.initiativeId&&F.initiativeId!==s)continue;const T=new Map(F.items.map(b=>[b.sliceId,b])),v=f.map(b=>T.get(b)??null).filter(b=>!!b);if(v.length===0)continue;const l=new Set(v.map(b=>b.sliceId));for(const b of F.items)l.has(b.sliceId)||v.push(b);o.setQueryData(u,{...F,items:v.map((b,x)=>({...b,manualRank:x+1,finalRank:x+1})),orderMode:"manual"})}return{snapshots:y}},onError:(f,y,u)=>{for(const[F,T]of(u==null?void 0:u.snapshots)??[])o.setQueryData(F,T)},onSettled:()=>{o.invalidateQueries({queryKey:["mission-control-slices"]})}}),h=Rt({mutationFn:async f=>{const y={level:a,order_mode:f};Sn(y,t),s&&(y.initiative_id=s);const u=await fetch("/orgx/api/mission-control/slices/order-mode",{method:"POST",headers:At({authToken:n,embedMode:d,contentTypeJson:!0,workspaceId:t}),body:JSON.stringify(y)});return Cn(u)},onMutate:async f=>{const y=o.getQueriesData({queryKey:["mission-control-slices"]});for(const[u,F]of y)!F||F.level!==a||s&&F.initiativeId&&F.initiativeId!==s||o.setQueryData(u,{...F,orderMode:f});return{snapshots:y}},onError:(f,y,u)=>{for(const[F,T]of(u==null?void 0:u.snapshots)??[])o.setQueryData(F,T)},onSettled:()=>{o.invalidateQueries({queryKey:["mission-control-slices"]})}});return{reorder:c.mutateAsync,setOrderMode:h.mutateAsync,isReordering:c.isPending,isSettingOrderMode:h.isPending,error:(c.error instanceof Error?c.error.message:null)??(h.error instanceof Error?h.error.message:null)}}const Us=[{value:"initiative",label:"Initiative"},{value:"workstream",label:"Workstream"},{value:"milestone",label:"Milestone"},{value:"task",label:"Task"}];function Fn(t){var s;return((s=Us.find(a=>a.value===t))==null?void 0:s.label)??"Workstream"}function In(t){const s=t.trim().toLowerCase();return s==="running"||s==="active"||s==="in_progress"?"border-teal-300/28 bg-teal-400/[0.09] text-teal-100/90":s==="blocked"||s==="failed"||s==="error"?"border-red-400/26 bg-red-500/[0.08] text-red-100/90":s==="completed"||s==="done"||s==="resolved"?"border-strong bg-white/[0.05] text-secondary":"border-[#BFFF00]/24 bg-[#BFFF00]/[0.08] text-[#E8FFD0]/92"}function En(t){const s=t.trim().toLowerCase();return s==="running"||s==="active"||s==="in_progress"?"from-teal-300/0 via-teal-300/65 to-teal-300/0":s==="blocked"||s==="failed"||s==="error"?"from-red-300/0 via-red-300/65 to-red-300/0":s==="completed"||s==="done"||s==="resolved"?"from-white/0 via-white/45 to-white/0":"from-[#BFFF00]/0 via-[#BFFF00]/70 to-[#BFFF00]/0"}function Kt(t,s=2){return typeof t!="number"||!Number.isFinite(t)?"—":t.toFixed(s)}function es(t,s){if(!t)return s;const a=t.trim();return a?Hs(a)?`${s} ${Vn(a)}`:a:s}function An(t){var a,n,d,o;const s=t.title.trim()||((a=t.taskTitle)==null?void 0:a.trim())||((n=t.milestoneTitle)==null?void 0:n.trim())||((d=t.workstreamTitle)==null?void 0:d.trim())||((o=t.initiativeTitle)==null?void 0:o.trim())||"";return s&&!Hs(s)?Jt(s):t.level==="task"?es(t.taskId??t.sliceId,"Task"):t.level==="milestone"?es(t.milestoneId??t.sliceId,"Milestone"):t.level==="initiative"?es(t.initiativeId??t.sliceId,"Initiative"):es(t.workstreamId??t.sliceId,"Workstream")}function Dn(t){const s=[t.initiativeTitle,t.workstreamTitle,t.milestoneTitle,t.taskTitle].filter(n=>!!(n&&n.trim().length>0));return s.length===0?Jt(es(t.sliceId,"Slice")):s.map(n=>Jt(n)).filter(n=>n.length>0).join(" / ")}function Mn(t){var d,o;const s=((d=t.runnerAgentName)==null?void 0:d.trim())??"",a=((o=t.runnerAgentId)==null?void 0:o.trim().toLowerCase())??"";if(!s)return a&&a!=="main"?Jt(a):"Unassigned";const n=s.toLowerCase();return n==="undefined"||n==="null"||n==="main"&&(a==="main"||t.runnerSource==="fallback")?"Unassigned":Jt(s)}function $n(t){const s=typeof t.sliceTaskCount=="number"&&Number.isFinite(t.sliceTaskCount)?Math.max(0,Math.floor(t.sliceTaskCount)):0;return s<=0?"No task":s===1?"1 task":`${s} tasks`}function Tn(t,s){return!t||t.trim().length===0?s:dt(t.trim())||s}function _n({workspaceId:t=null,initiativeId:s=null,authToken:a=null,embedMode:n=!1,className:d="",title:o="Slice Explorer",compact:c=!1,onOpenInitiative:h}){var Ve,ze;const[f,y]=r.useState("workstream"),[u,F]=r.useState(""),[T,v]=r.useState(0),[l]=r.useState(c?18:28),[b,x]=r.useState(null),[j,S]=r.useState([]),[g,I]=r.useState(!1),[q,H]=r.useState(null),[O,ee]=r.useState(!1),te=r.useRef(null),J=Xa({workspaceId:t,initiativeId:s,level:f,orderMode:q,includeCompleted:!1,search:u,offset:T,limit:l,authToken:a,embedMode:n,enabled:!!(t||s)}),Q=Za({workspaceId:t,initiativeId:s,level:f,authToken:a,embedMode:n}),D=J.slices,w=J.source,P=J.pagination,$=J.orderMode??"manual",R=(P==null?void 0:P.offset)??T,_=(P==null?void 0:P.total)??((Ve=J.data)==null?void 0:Ve.total)??D.length,G=D.length===0?0:R+1,B=D.length===0?0:R+D.length;r.useEffect(()=>{if(!b)return;const p=window.setTimeout(()=>x(null),5e3);return()=>window.clearTimeout(p)},[b]),r.useEffect(()=>{if(!O)return;const p=K=>{var Fe;const pe=K.target;pe&&((Fe=te.current)!=null&&Fe.contains(pe)||ee(!1))},ne=K=>{K.key==="Escape"&&ee(!1)};return document.addEventListener("mousedown",p),document.addEventListener("touchstart",p),document.addEventListener("keydown",ne),()=>{document.removeEventListener("mousedown",p),document.removeEventListener("touchstart",p),document.removeEventListener("keydown",ne)}},[O]),r.useEffect(()=>{v(0)},[f,u]);const X=r.useMemo(()=>D.map(p=>p.sliceId).join("|"),[D]);r.useEffect(()=>{S(D.map(p=>p.sliceId)),I(!1)},[X,$]);const ie=r.useMemo(()=>new Map(D.map(p=>[p.sliceId,p])),[D]),ue=r.useMemo(()=>{if(!g||j.length!==D.length)return D;const p=j.map(ne=>ie.get(ne)??null).filter(ne=>!!ne);return p.length!==D.length?D:p},[g,j,D,ie]),E=$==="manual"&&D.length>1&&!Q.isReordering&&R===0&&!((P==null?void 0:P.hasMore)??!1),V=async()=>{if(!(!E||!g))try{await Q.reorder(j),I(!1),x({tone:"success",message:`Saved ${j.length} slice positions.`})}catch(p){x({tone:"error",message:Tn(p instanceof Error?p.message:"","Failed to save slice order.")})}},ae=async p=>{if(!(p===$&&q===null)){H(p);try{await Q.setOrderMode(p),x({tone:"success",message:`Slice ordering set to ${p}.`})}catch(ne){x({tone:"error",message:Tn(ne instanceof Error?ne.message:"",`Failed to set ${p} ordering.`)})}finally{H(null)}}},De=p=>{!h||!p.initiativeId||h(p.initiativeId,p.initiativeTitle??void 0)};return e.jsxs("section",{className:Vt("flex min-h-0 flex-col rounded-2xl border border-strong bg-[#070b12]/88",d),children:[e.jsxs("div",{className:"flex flex-col gap-2 border-b border-strong px-3 py-3",children:[e.jsxs("div",{className:"flex min-h-[34px] items-center gap-2",children:[e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-[#BFFF00]/70"}),e.jsx("h3",{className:"text-caption font-semibold uppercase tracking-[0.1em] text-secondary",children:o}),e.jsx("span",{className:"rounded-full border border-strong bg-white/[0.04] px-2 py-0.5 text-micro text-secondary",children:_}),e.jsxs("div",{className:"ml-auto flex items-center gap-1.5",children:[e.jsxs("div",{ref:te,className:"relative",children:[e.jsxs("button",{type:"button",onClick:()=>ee(p=>!p),className:"control-pill h-8 px-2.5 text-micro font-semibold","aria-haspopup":"menu","aria-expanded":O,children:[e.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"opacity-85","aria-hidden":!0,children:[e.jsx("path",{d:"M4 6h16"}),e.jsx("path",{d:"M7 12h10"}),e.jsx("path",{d:"M10 18h4"})]}),e.jsx("span",{children:"Filters"})]}),O?e.jsx("div",{className:"surface-tier-2 absolute right-0 top-[calc(100%+8px)] z-[260] w-[300px] max-w-[88vw] rounded-xl p-3 shadow-[0_16px_40px_rgba(0,0,0,0.46)] backdrop-blur-xl",children:e.jsxs("div",{className:"space-y-2.5",children:[e.jsxs("div",{children:[e.jsx("p",{className:"section-kicker",children:"Entity level"}),e.jsx("div",{className:"mt-1.5 grid grid-cols-2 gap-1.5",children:Us.map(p=>e.jsxs("button",{type:"button",onClick:()=>{y(p.value),ee(!1)},className:Vt("control-pill flex h-8 items-center gap-1.5 px-2 text-micro font-semibold",f===p.value?"border-[#BFFF00]/34 bg-[#BFFF00]/[0.12] text-[#E8FFD0]":"text-secondary"),children:[e.jsx(Ge,{type:p.value,size:10,className:"opacity-80"}),e.jsx("span",{children:p.label})]},p.value))})]}),e.jsxs("div",{children:[e.jsx("p",{className:"section-kicker",children:"Ordering"}),e.jsxs("div",{className:"mt-1.5 flex items-center gap-1.5",children:[e.jsx("button",{type:"button",className:Vt("control-pill h-8 px-2.5 text-micro font-semibold",$==="manual"?"border-[#BFFF00]/34 bg-[#BFFF00]/[0.12] text-[#E8FFD0]":"text-secondary"),disabled:Q.isSettingOrderMode,onClick:()=>void ae("manual"),children:"Manual"}),e.jsx("button",{type:"button",className:Vt("control-pill h-8 px-2.5 text-micro font-semibold",$==="algorithmic"?"border-teal-300/34 bg-teal-400/[0.13] text-teal-100":"text-secondary"),disabled:Q.isSettingOrderMode,onClick:()=>void ae("algorithmic"),children:"Algorithmic"})]})]})]})}):null]}),$==="manual"&&e.jsx("button",{type:"button",className:"control-pill h-8 px-2.5 text-micro font-semibold disabled:opacity-45",disabled:!g||!E,onClick:()=>void V(),children:"Save order"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"min-w-0 flex-1",children:e.jsx(Qs,{value:u,onChange:F,placeholder:"Search slices, entities, or IDs..."})}),e.jsx("span",{className:"chip whitespace-nowrap text-micro",children:((ze=Us.find(p=>p.value===f))==null?void 0:ze.label)??"Workstream"})]}),(w==="local_fallback"||J.degraded.length>0)&&e.jsx("div",{className:"rounded-xl border border-amber-300/24 bg-amber-400/[0.08] px-2.5 py-1.5 text-micro text-amber-100/90",children:w==="local_fallback"?"Canonical slices unavailable; showing local fallback.":J.degraded[0]})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-2 pb-2 pt-2",children:J.isLoading?e.jsx("div",{className:"space-y-2 px-1",children:Array.from({length:c?4:7}).map((p,ne)=>e.jsxs("div",{className:"rounded-xl border border-strong bg-white/[0.02] px-3 py-2",children:[e.jsx(vt,{className:"h-3.5 w-1/2 rounded-full"}),e.jsx(vt,{className:"mt-2 h-3 w-4/5 rounded-full"})]},`slice-loading-${ne}`))}):ue.length===0?e.jsx("div",{className:"rounded-xl border border-strong bg-white/[0.02] px-3 py-3 text-caption text-secondary",children:"No slices match this view."}):E?e.jsx($r,{axis:"y",values:j,onReorder:p=>{S(p),I(!0)},className:"space-y-2",children:j.map((p,ne)=>{var Re;const K=ie.get(p);if(!K)return null;const pe=K.finalRank??K.manualRank??K.algorithmRank??ne+1,Ie=(((Re=K.iwmt)==null?void 0:Re.factors)??[]).filter(Ne=>typeof Ne.value=="number"&&Number.isFinite(Ne.value)),Me=typeof K.roiPerToken=="number"&&Number.isFinite(K.roiPerToken),Be=typeof K.objectiveScore=="number"&&Number.isFinite(K.objectiveScore),he=Mn(K),Pe=Dn(K);return e.jsxs(Tr,{value:K.sliceId,className:"group hover-lift relative overflow-hidden rounded-2xl border border-white/[0.08] bg-white/[0.02] px-3 py-2.5 transition-colors hover:border-white/[0.14]",children:[e.jsx("div",{className:`pointer-events-none absolute inset-x-3 top-0 h-px bg-gradient-to-r ${En(K.status)}`,"aria-hidden":!0}),e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("button",{type:"button",className:"mt-0.5 inline-flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-md border border-strong bg-white/[0.04] text-caption text-secondary","aria-label":"Drag to reorder",title:"Drag to reorder",children:"⋮⋮"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsxs("span",{className:"rounded-md border border-[#BFFF00]/22 bg-[#BFFF00]/[0.08] px-1.5 py-0.5 text-micro font-semibold text-[#DFFFB5]",children:["#",pe]}),e.jsx("div",{className:"min-w-0 flex-1",children:e.jsxs("div",{className:"flex min-w-0 items-start gap-1.5",children:[e.jsx(Ge,{type:K.level,size:11,className:"mt-0.5 flex-shrink-0 opacity-80"}),e.jsx("p",{className:"min-w-0 flex-1 line-clamp-2 text-caption font-semibold leading-snug text-primary",children:An(K)})]})}),e.jsxs("div",{className:"ml-auto flex flex-shrink-0 items-center gap-1.5",children:[e.jsx("span",{className:Vt("rounded-full border px-2 py-0.5 text-micro uppercase tracking-[0.08em]",In(K.status)),children:K.status.replace(/_/g," ")}),K.initiativeId&&h?e.jsx("button",{type:"button",className:"control-pill h-6 px-2 text-micro font-semibold",onClick:()=>De(K),children:"Open"}):null]})]}),e.jsx("p",{className:"mt-1 inline-flex min-w-0 items-center gap-1 truncate text-micro text-secondary",title:Pe,children:e.jsx("span",{className:"truncate",children:Pe})}),e.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-1.5 text-micro text-secondary",children:[e.jsx("span",{className:"chip text-micro",children:Fn(K.level)}),e.jsx("span",{className:"chip text-micro",children:$n(K)}),e.jsxs("span",{className:"chip text-micro",children:["Agent ",he]}),Me?e.jsxs("span",{className:"chip text-micro",children:["ROI/token ",Kt(K.roiPerToken,3)]}):null,Be?e.jsxs("span",{className:"chip text-micro",children:["Obj ",Kt(K.objectiveScore,2)]}):null]}),Ie.length>0&&e.jsxs("details",{className:"mt-1.5",children:[e.jsx("summary",{className:"cursor-pointer text-micro text-secondary",children:"Why this slice"}),e.jsx("div",{className:"mt-1 space-y-1 text-micro text-secondary",children:Ie.slice(0,3).map((Ne,He)=>e.jsxs("p",{children:[(Ne.label??Ne.key??"factor").replace(/_/g," "),":"," ",Kt(Ne.value,2)]},`${K.sliceId}-factor-${He}`))})]})]})]})]},K.sliceId)})}):e.jsx("div",{className:"space-y-2",children:ue.map((p,ne)=>{var Pe;const K=p.finalRank??p.manualRank??p.algorithmRank??ne+1,Fe=(((Pe=p.iwmt)==null?void 0:Pe.factors)??[]).filter(Re=>typeof Re.value=="number"&&Number.isFinite(Re.value)),Ie=typeof p.roiPerToken=="number"&&Number.isFinite(p.roiPerToken),Me=typeof p.objectiveScore=="number"&&Number.isFinite(p.objectiveScore),Be=Mn(p),he=Dn(p);return e.jsxs(fe.article,{initial:{opacity:0,y:10,scale:.985},animate:{opacity:1,y:0,scale:1},transition:{duration:.22,delay:Math.min(ne,7)*.02,ease:[.22,1,.36,1]},className:"group hover-lift relative overflow-hidden rounded-2xl border border-white/[0.08] bg-white/[0.02] px-3 py-2.5 transition-colors hover:border-white/[0.14]",children:[e.jsx("div",{className:`pointer-events-none absolute inset-x-3 top-0 h-px bg-gradient-to-r ${En(p.status)}`,"aria-hidden":!0}),e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsxs("span",{className:"rounded-md border border-[#BFFF00]/22 bg-[#BFFF00]/[0.08] px-1.5 py-0.5 text-micro font-semibold text-[#DFFFB5]",children:["#",K]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex min-w-0 items-start gap-1.5",children:[e.jsx(Ge,{type:p.level,size:11,className:"mt-0.5 flex-shrink-0 opacity-80"}),e.jsx("p",{className:"min-w-0 flex-1 line-clamp-2 text-caption font-semibold leading-snug text-primary",children:An(p)})]}),e.jsx("p",{className:"mt-1 inline-flex min-w-0 items-center gap-1 truncate text-micro text-secondary",title:he,children:e.jsx("span",{className:"truncate",children:he})}),e.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-1.5 text-micro text-secondary",children:[e.jsx("span",{className:"chip text-micro",children:Fn(p.level)}),e.jsx("span",{className:"chip text-micro",children:$n(p)}),e.jsxs("span",{className:"chip text-micro",children:["Agent ",Be]}),Ie?e.jsxs("span",{className:"chip text-micro",children:["ROI/token ",Kt(p.roiPerToken,3)]}):null,Me?e.jsxs("span",{className:"chip text-micro",children:["Obj ",Kt(p.objectiveScore,2)]}):null,e.jsx("span",{className:Vt("rounded-full border px-2 py-0.5 uppercase tracking-[0.08em]",In(p.status)),children:p.status.replace(/_/g," ")})]}),Fe.length>0&&e.jsxs("details",{className:"mt-1.5",children:[e.jsx("summary",{className:"cursor-pointer text-micro text-secondary",children:"Why this slice"}),e.jsx("div",{className:"mt-1 space-y-1 text-micro text-secondary",children:Fe.slice(0,3).map((Re,Ne)=>e.jsxs("p",{children:[(Re.label??Re.key??"factor").replace(/_/g," "),":"," ",Kt(Re.value,2)]},`${p.sliceId}-factor-static-${Ne}`))})]})]}),p.initiativeId&&h?e.jsx("button",{type:"button",className:"control-pill h-7 px-2 text-micro font-semibold",onClick:()=>De(p),children:"Open"}):null]})]},p.sliceId)})})}),e.jsxs("div",{className:"flex items-center gap-2 border-t border-strong px-3 py-2",children:[e.jsxs("p",{className:"text-micro text-secondary",children:[G,"-",B," of ",_]}),e.jsx("button",{type:"button",className:"control-pill ml-auto h-7 px-2 text-micro font-semibold disabled:opacity-40",disabled:R===0,onClick:()=>v(Math.max(0,R-l)),children:"Prev"}),e.jsx("button",{type:"button",className:"control-pill h-7 px-2 text-micro font-semibold disabled:opacity-40",disabled:!((P==null?void 0:P.hasMore)??!1),onClick:()=>v(R+l),children:"Next"})]}),b&&e.jsx("div",{className:"border-t border-strong px-3 py-2",children:e.jsx(zn,{open:!0,tone:b.tone==="error"?"error":"success",title:b.tone==="error"?"Slice explorer error":"Slice explorer updated",message:b.message,onDismiss:()=>x(null),autoDismissMs:4200})})]})}function Os(t){return(t??"").trim().toLowerCase().replace(/[\s-]+/g,"_")}function Ws(t){return new Date(t.getFullYear(),t.getMonth(),t.getDate()).getTime()}function Ln(t){if(!t)return null;const s=Date.parse(`${t}T00:00:00`);return Number.isFinite(s)?s:null}function ei(t,s){return s==="target"?t.targetDate??null:s==="created"?t.createdAt??null:t.updatedAt??t.createdAt??null}function Bn(t){const s=(t??"").trim().toLowerCase();return s?s==="critical"||s==="p0"||s==="urgent"?0:s==="high"||s==="p1"?1:s==="medium"||s==="normal"||s==="p2"?2:s==="low"||s==="p3"?3:4:4}function Pn(t){return t==="active"?0:t==="blocked"?1:t==="paused"?2:3}function Rn(t,s){if(s==="status"){const a=new Map,n=["active","blocked","paused","completed"];for(const d of t){const o=d.status??"active",c=a.get(o)??[];c.push(d),a.set(o,c)}return n.filter(d=>a.has(d)).concat(Array.from(a.keys()).filter(d=>!n.includes(d))).map(d=>{var o;return{key:d,label:d.charAt(0).toUpperCase()+d.slice(1),count:((o=a.get(d))==null?void 0:o.length)??0,initiatives:a.get(d)??[]}})}if(s==="category"){const a=new Map;for(const n of t){const d=n.category??"Uncategorized",o=a.get(d)??[];o.push(n),a.set(d,o)}return Array.from(a.entries()).sort((n,d)=>n[0].localeCompare(d[0])).map(([n,d])=>({key:n,label:n,count:d.length,initiatives:d}))}if(s==="date"){const n=Ws(new Date),d=n+7*864e5,o=n+30*864e5,c={overdue:[],this_week:[],this_month:[],later:[],no_date:[]};for(const f of t){const y=f.targetDate?Date.parse(f.targetDate):null;y===null||!Number.isFinite(y)?c.no_date.push(f):y<n?c.overdue.push(f):y<d?c.this_week.push(f):y<o?c.this_month.push(f):c.later.push(f)}const h={overdue:"Overdue",this_week:"This Week",this_month:"This Month",later:"Later",no_date:"No Date"};return["overdue","this_week","this_month","later","no_date"].filter(f=>c[f].length>0).map(f=>({key:f,label:h[f],count:c[f].length,initiatives:c[f]}))}return[]}function Pt(t,s){return`${t}:${s}`}function ti(t){return`mc-group-${t}`.toLowerCase().replace(/[^a-z0-9_-]+/g,"-")}function qn(t,s){if(t.size!==s.size)return!1;for(const a of t)if(!s.has(a))return!1;return!0}function si(t){return t==="running"?"Running":t==="blocked"?"Blocked":t==="queued"?"Queued":t==="startable"?"Startable":t==="completed"?"Complete":t==="active_no_queue"?"Idle":"No target"}function ni(t){return t==="running"?"border-teal-300/24 bg-teal-400/[0.08] text-teal-100/90":t==="blocked"?"border-red-400/24 bg-red-500/[0.08] text-red-100/90":t==="queued"||t==="startable"?"border-[#BFFF00]/18 bg-[#BFFF00]/[0.06] text-[#E8FFD0]/95":t==="completed"?"border-strong bg-white/[0.05] text-secondary":"border-strong bg-white/[0.04] text-white/68"}function ri(t){const s=t.trim().toLowerCase();if(s.includes("timed out")||s.includes("timeout")||s.includes("request cancelled")||s.includes("signal is aborted"))return"Live sync is taking longer than expected. Initiatives and Next Up will repopulate as soon as sync completes.";if(s.includes("unauthorized")||s.includes("forbidden")||s.includes("api key")||s.includes("auth"))return"OrgX authentication needs attention. Reconnect your API key in Settings.";if(s.includes("unknown api endpoint")||s.includes("missing required live routes"))return"This runtime is missing required live routes. Restart and update the plugin build.";const a=t.split("|").map(n=>n.trim()).filter(Boolean).map(n=>n.replace(/^[^:]+:\s*/,"").trim()).filter(Boolean).slice(0,2).join(" ");return dt(a||t)||"Live data is temporarily unavailable."}function Gt(t,s){return!t||t.trim().length===0?s:dt(t.trim())||s}const ai=[12,24,36,48,72];function gi({initiatives:t,activities:s,agents:a,runtimeInstances:n=[],workspaceInitiativeId:d=null,isLoading:o,authToken:c,embedMode:h,initialInitiativeId:f,connection:y,lastSnapshotAt:u,error:F,hasApiKey:T,onOpenSettings:v,onRefresh:l,onCreateInitiative:b,onPlayNextUp:x,onStartAutopilot:j,nextUpQueueModel:S,nextUpActionsModel:g,snapshotVersion:I=null}){const q=Lr({activities:s,agents:a,initiatives:t});return e.jsx(Gr,{agentEntityMap:q,authToken:c,embedMode:h,children:e.jsx(li,{initiatives:t,runtimeInstances:n,workspaceInitiativeId:d,isLoading:o,initialInitiativeId:f,connection:y,lastSnapshotAt:u,error:F,hasApiKey:T,onOpenSettings:v,onRefresh:l,onCreateInitiative:b,onPlayNextUp:x,onStartAutopilot:j,nextUpQueueModel:S,nextUpActionsModel:g,snapshotVersion:I})})}function ii(t){if(!t)return"unknown";const s=Date.parse(t);if(!Number.isFinite(s))return"unknown";try{return new Date(s).toLocaleString()}catch{return"unknown"}}function oi(t,s){var a,n;return{...s,...t,rawStatus:t.rawStatus??s.rawStatus??null,priority:t.priority??s.priority??null,targetDate:t.targetDate??s.targetDate??null,createdAt:t.createdAt??s.createdAt??null,updatedAt:t.updatedAt??s.updatedAt??null,description:t.description??s.description,activeAgents:Math.max(t.activeAgents,s.activeAgents),totalAgents:Math.max(t.totalAgents,s.totalAgents),avatars:(a=t.avatars)!=null&&a.length?t.avatars:s.avatars,workstreams:(n=t.workstreams)!=null&&n.length?t.workstreams:s.workstreams,health:t.health>0?t.health:s.health}}function li({initiatives:t,runtimeInstances:s,workspaceInitiativeId:a=null,isLoading:n,initialInitiativeId:d,connection:o,lastSnapshotAt:c,error:h,hasApiKey:f,onOpenSettings:y,onRefresh:u,onCreateInitiative:F,onPlayNextUp:T,onStartAutopilot:v,nextUpQueueModel:l,nextUpActionsModel:b,snapshotVersion:x=null}){var an,on,ln,cn,dn;const{searchQuery:j,setSearchQuery:S,statusFilters:g,setStatusFilters:I,dateField:q,setDateField:H,datePreset:O,setDatePreset:ee,dateStart:te,setDateStart:J,dateEnd:Q,setDateEnd:D,clearFilters:w,hasActiveFilters:P,groupBy:$,sortBy:R,expandedInitiatives:_,expandAll:G,collapseAll:B,modalTarget:X,closeModal:ie,expandInitiative:ue,authToken:E,embedMode:V,mutations:ae}=Dt(),De=r.useRef(!1),Ve=r.useRef(null),ze=r.useRef(0),[p,ne]=r.useState(0),[K,pe]=r.useState(new Set),[Fe,Ie]=r.useState(!1),[Me,Be]=r.useState(!1),[he,Pe]=r.useState(!1),[Re,Ne]=r.useState(!1),[He,ft]=r.useState("next-up"),[St,je]=r.useState(null),[Je,Te]=r.useState(null),[st,gt]=r.useState(new Set),[jt,Ye]=r.useState(!1),[Qe,Ue]=r.useState(null),[ut,nt]=r.useState(0),[rt,Ot]=r.useState(24),kt=j.trim(),mt=Hr(kt,kt.length>=2,a),Ct=r.useMemo(()=>{var M;if(kt.length<2||!((M=mt.data)!=null&&M.length))return t;const m=new Map;for(const L of t)m.set(L.id,L);for(const L of mt.data){const Y=m.get(L.id);m.set(L.id,Y?oi(Y,L):L)}return Array.from(m.values())},[mt.data,t,kt.length]),at=r.useMemo(()=>new Set((mt.data??[]).map(m=>m.id)),[mt.data]);r.useEffect(()=>{if(!Qe)return;const m=Qe.tone==="success"?6500:9e3,M=window.setTimeout(()=>Ue(null),m);return()=>window.clearTimeout(M)},[Qe==null?void 0:Qe.message,Qe==null?void 0:Qe.tone]);const Mt=r.useMemo(()=>{const M=Ws(new Date),L=j.toLowerCase().trim().split(/\s+/).filter(Boolean);return Ct.filter(Y=>{if(g.length>0&&![Os(Y.status),Os(Y.rawStatus)].filter(Boolean).some(ct=>g.includes(ct)))return!1;const xe=ei(Y,q),_e=xe?Date.parse(xe):Number.NaN,qe=Number.isFinite(_e)?Ws(new Date(_e)):null,le=qe===null?null:Math.round((qe-M)/864e5);if(O==="missing"&&qe!==null||O==="overdue"&&!(le!==null&&le<0)||O==="today"&&le!==0||O==="next_7_days"&&!(le!==null&&le>=0&&le<=7)||O==="next_30_days"&&!(le!==null&&le>=0&&le<=30)||O==="past_7_days"&&!(le!==null&&le<=0&&le>=-7)||O==="past_30_days"&&!(le!==null&&le<=0&&le>=-30))return!1;if(O==="custom_range"){const it=Ln(te),ct=Ln(Q);if(qe===null||it!==null&&qe<it||ct!==null&&qe>ct)return!1}if(L.length===0||at.has(Y.id))return!0;const xt=[Y.name,Y.description??"",Y.status,Y.rawStatus??"",Y.category??""].join(" ").toLowerCase();return L.every(it=>xt.includes(it))})},[Ct,j,at,g,q,O,te,Q]),ye=r.useMemo(()=>{const m=(M,L,Y)=>{const xe=M.targetDate?Date.parse(M.targetDate):Number.NaN,_e=L.targetDate?Date.parse(L.targetDate):Number.NaN,qe=Number.isFinite(xe),le=Number.isFinite(_e);return!qe&&!le?0:qe?le?Y==="asc"?xe-_e:_e-xe:-1:1};return[...Mt].sort((M,L)=>{if(R==="date_asc")return m(M,L,"asc");if(R==="date_desc")return m(M,L,"desc");const Y=Bn(M.priority),xe=Bn(L.priority);if(R==="priority_high"&&Y!==xe)return Y-xe;if(R==="priority_low"&&Y!==xe)return xe-Y;if(R==="default"){const le=typeof M.sequenceIndex=="number"?M.sequenceIndex:Number.POSITIVE_INFINITY,xt=typeof L.sequenceIndex=="number"?L.sequenceIndex:Number.POSITIVE_INFINITY;if(le!==xt)return le-xt;const it=Pn(M.status)-Pn(L.status);if(it!==0)return it;if(Y!==xe)return Y-xe}const _e=M.updatedAt?Date.parse(M.updatedAt):0,qe=L.updatedAt?Date.parse(L.updatedAt):0;return _e!==qe?qe-_e:M.name.localeCompare(L.name)})},[Mt,R]),Xe=ye.length,Ze=Math.max(1,Math.ceil(Xe/rt)),ot=Xe===0?0:Math.min(ut,Ze-1),bt=ot*rt,i=Math.min(Xe,bt+rt),C=Xe===0?0:bt+1,A=Xe===0?0:i,z=r.useMemo(()=>ye.slice(bt,i),[i,bt,ye]),se=r.useMemo(()=>new Set(ye.map(m=>m.id)),[ye]),me=r.useMemo(()=>ye.filter(m=>st.has(m.id)),[st,ye]),ke=r.useMemo(()=>z.filter(m=>st.has(m.id)),[z,st]),$e=me.length,Ce=ke.length,Le=z.length>0&&Ce===z.length,ge=ae.bulkEntityMutation.isPending,et=r.useMemo(()=>{var L;const m=new Map;for(const Y of s){const xe=(L=Y.initiativeId)==null?void 0:L.trim();if(!xe)continue;const _e=m.get(xe)??{activeCount:0,totalCount:0,lastHeartbeatAt:null,lastHeartbeatMs:0};_e.totalCount+=1,Y.state==="active"&&(_e.activeCount+=1);const qe=Y.lastHeartbeatAt??Y.lastEventAt??null,le=qe?Date.parse(qe):Number.NaN;Number.isFinite(le)&&le>_e.lastHeartbeatMs&&(_e.lastHeartbeatMs=le,_e.lastHeartbeatAt=new Date(le).toISOString()),m.set(xe,_e)}const M=new Map;for(const[Y,xe]of m.entries())M.set(Y,{activeCount:xe.activeCount,totalCount:xe.totalCount,lastHeartbeatAt:xe.lastHeartbeatAt});return M},[s]),we=r.useMemo(()=>$!=="none"?Rn(z,$):null,[$,z]),yt=r.useMemo(()=>(we==null?void 0:we.map(m=>Pt($,m.key)))??[],[$,we]),k=r.useMemo(()=>{if(!we)return z.map(M=>M.id);const m=[];for(const M of we){const L=Pt($,M.key);if(K.has(L))for(const Y of M.initiatives)m.push(Y.id)}return m},[K,$,we,z]),{handleSelect:N}=Kn(k),oe=r.useCallback(m=>{pe(M=>{const L=new Set(M);return L.has(m)?L.delete(m):L.add(m),L})},[]);r.useEffect(()=>{if(!we||we.length===0){pe(M=>M.size===0?M:new Set);return}const m=new Set(we.map(M=>Pt($,M.key)));pe(M=>{const L=new Set(Array.from(M).filter(Y=>m.has(Y)));return L.size===0&&L.add(Pt($,we[0].key)),qn(L,M)?M:L})},[$,we]),r.useEffect(()=>{gt(m=>{if(m.size===0)return m;const M=new Set(Array.from(m).filter(L=>se.has(L)));return qn(M,m)?m:M})},[se]),r.useEffect(()=>{if(d&&!De.current&&!n&&t.length>0){const m=ye.findIndex(M=>M.id===d);if(m>=0&&nt(Math.floor(m/rt)),ue(d),we){const M=we.find(L=>L.initiatives.some(Y=>Y.id===d));if(M){const L=Pt($,M.key);pe(Y=>{if(Y.has(L))return Y;const xe=new Set(Y);return xe.add(L),xe})}}De.current=!0,requestAnimationFrame(()=>{const M=document.getElementById(`initiative-${d}`);M==null||M.scrollIntoView({behavior:"smooth",block:"start"})})}},[d,n,t.length,ue,rt,$,we,ye]),r.useEffect(()=>{$e===0&&jt&&Ye(!1)},[jt,$e]),r.useEffect(()=>{nt(m=>Math.min(m,Math.max(Ze-1,0)))},[Ze]),r.useEffect(()=>{nt(0)},[j,g,q,O,te,Q,$,R,rt]);const be=z.length>0&&z.every(m=>_.has(m.id)),We=r.useMemo(()=>ye.find(m=>m.status!=="completed")??ye[0]??null,[ye]),Nt=Ar({projectId:a,authToken:E,embedMode:V,enabled:l?!1:t.length>0,snapshotVersion:x}),Ee=l??Nt,ks=ns({authToken:E,embedMode:V}),pt=b??ks,ce=Ee.items[0]??null,U=r.useMemo(()=>Ee.items.find(m=>m.playbackState==="running"||m.playbackState==="blocked")??Ee.items.find(m=>m.queueState==="running"||m.queueState==="blocked")??null,[Ee.items]),Se=r.useMemo(()=>Ee.items.find(m=>U&&m.initiativeId===U.initiativeId&&m.workstreamId===U.workstreamId?!1:m.playbackState==="queued"||m.playbackState==="idle"||m.queueState==="queued"||m.queueState==="idle")??null,[Ee.items,U]),Z=r.useMemo(()=>ce?t.find(m=>m.id===ce.initiativeId)??We:We,[We,t,ce]),$t=U??Se??ce??null,Ft=($t==null?void 0:$t.initiativeId)??(Z==null?void 0:Z.id)??null,Vs=r.useCallback((m,M,L)=>{Ue(null),Ye(!1),N(m,M,L,gt)},[N]),Yn=r.useCallback(()=>{Ue(null),Ye(!1),gt(m=>{if(z.length===0)return m;const M=new Set(m);if(Le)for(const L of z)M.delete(L.id);else for(const L of z)M.add(L.id);return M})},[Le,z]),Xn=r.useCallback(()=>{Ye(!1),gt(new Set)},[]),Ks=ot>0,Gs=ot<Ze-1,It=r.useCallback(m=>{nt(Math.max(0,Math.min(m,Ze-1)))},[Ze]),Zn=r.useCallback(()=>{It(0)},[It]),er=r.useCallback(()=>{It(ot-1)},[ot,It]),tr=r.useCallback(()=>{It(ot+1)},[ot,It]),sr=r.useCallback(()=>{It(Ze-1)},[It,Ze]),rs=r.useCallback(async m=>{if(me.length!==0){Ye(!1),Ue(null);try{const M=await ae.bulkEntityMutation.mutateAsync({items:me.map(L=>({type:"initiative",id:L.id})),mode:"update",updates:{status:m}});M.failed>0?Ue({tone:"error",message:`Updated ${M.updated}, failed ${M.failed}.`}):Ue({tone:"success",message:`Updated ${M.updated} initiative${M.updated===1?"":"s"} to ${m}.`})}catch(M){Ue({tone:"error",message:Gt(M instanceof Error?M.message:"","Bulk initiative update failed.")})}}},[ae.bulkEntityMutation,me]),nr=r.useCallback(async()=>{if(me.length!==0){Ue(null);try{const m=await ae.bulkEntityMutation.mutateAsync({items:me.map(M=>({type:"initiative",id:M.id})),mode:"delete"});m.failed>0?Ue({tone:"error",message:`Deleted ${m.updated}, failed ${m.failed}.`}):(Ue({tone:"success",message:`Deleted ${m.updated} initiative${m.updated===1?"":"s"}.`}),gt(new Set),Ye(!1))}catch(m){Ue({tone:"error",message:Gt(m instanceof Error?m.message:"","Bulk initiative delete failed.")})}}},[ae.bulkEntityMutation,me]),Ns=r.useCallback(()=>{ze.current+=1,Ie(!1)},[]),rr=r.useCallback(m=>{if(m.length===0){Ns();return}const M=1,L=ze.current+1;ze.current=L,Ie(!0);const Y=xe=>{if(ze.current===L){if(G(m.slice(0,xe)),xe>=m.length){Ie(!1);return}requestAnimationFrame(()=>Y(Math.min(m.length,xe+M)))}};Y(Math.min(M,m.length))},[Ns,G]),Ae=wr({initiativeId:Ft,authToken:E,embedMode:V,enabled:!!Ft}),[Tt,zt]=r.useState(null),as=Ae.run,Ss=((an=Ae.error)==null?void 0:an.toLowerCase())??"",Cs=!Ft||Ss.includes("404")||Ss.includes("400")||Ss.includes("not found"),lt=Ft?et.get(Ft)??null:null,Fs=((lt==null?void 0:lt.activeCount)??0)>0,ar=((lt==null?void 0:lt.totalCount)??0)>0,Js=Tt?`Upgrade required · ${xn(Tt.currentPlan)} → ${xn(Tt.requiredPlan)}`:Ft?Ae.isRunning?Fs?`Running · ${(lt==null?void 0:lt.activeCount)??0} live`:ar?`Enabled · ${(lt==null?void 0:lt.totalCount)??0} idle`:"Enabled · waiting":as!=null&&as.stopReason?`Idle · ${as.stopReason.replace(/_/g," ")}`:"Idle":"No target",Ut=!!Tt&&!Ae.isRunning,ir=Ut?"amber":"teal",or=r.useMemo(()=>{const m=new URL("https://www.useorgx.com/integrations/openclaw");return m.searchParams.set("utm_source",V?"live_share":"orgx_openclaw_plugin"),m.searchParams.set("utm_medium","mission_control"),m.searchParams.set("utm_campaign","live_link_dashboard"),m.searchParams.set("utm_content","install_cta"),m.toString()},[V]);r.useEffect(()=>{zt(null)},[Ft]),r.useEffect(()=>{const m=Ve.current;if(!m)return;const M=()=>{ne(Math.max(64,m.offsetHeight))};if(M(),typeof ResizeObserver>"u")return;const L=new ResizeObserver(()=>M());return L.observe(m),()=>L.disconnect()},[Js,o,h,n,ye.length]);const Is=!!(!n&&f&&(o==="disconnected"||h)),lr=o==="disconnected"||h?"critical":"info",cr=o==="disconnected"?"Offline":h?"Live degraded":"Connected",Ys=h?ri(h):o==="disconnected"?"Live updates are offline. Data may be stale until reconnect.":`Last snapshot ${ii(c)}`;r.useEffect(()=>{Is||Be(!1)},[Is]);const Et=r.useCallback((m,M)=>{if(!t.find(le=>le.id===m)){const le=(M??"").trim(),xt=le?Hs(le)?`Initiative ${Vn(le)}`:Jt(le):"This initiative";return je({tone:"error",message:`${xt} is not in this workspace view. Switch workspace or clear filters to find it.`}),!1}je(null);const Y=ye.findIndex(le=>le.id===m),xe=Y<0;if(Y>=0&&nt(Math.floor(Y/rt)),xe&&(S(""),I([]),H("target"),ee("any"),J(""),D("")),ue(m),$!=="none"){const le=Y>=0?ye:t,it=Rn(le,$).find(ct=>ct.initiatives.some(Qt=>Qt.id===m));if(it){const ct=Pt($,it.key);pe(Qt=>{if(Qt.has(ct))return Qt;const un=new Set(Qt);return un.add(ct),un})}}const _e=(le=0)=>{const xt=document.getElementById(`initiative-${m}`);if(xt){xt.scrollIntoView({behavior:le===0?"smooth":"auto",block:"start"});const it=Math.max(72,p)+8,ct=xt.getBoundingClientRect();!(ct.top>=it&&ct.top<=window.innerHeight-72)&&le<18&&window.setTimeout(()=>_e(le+1),90);return}le>=60||requestAnimationFrame(()=>_e(le+1))},qe=()=>requestAnimationFrame(()=>_e());return xe?window.setTimeout(qe,90):qe(),!0},[t,rt,je,nt,S,I,H,ee,J,D,ue,$,ye,p]),dr=r.useCallback(()=>{Z&&(je(null),ae.updateEntity.mutateAsync({type:"initiative",id:Z.id,status:"active"}).then(()=>{je({tone:"success",message:`Started ${Z.name}.`}),Et(Z.id,Z.name)}).catch(m=>{je({tone:"error",message:Gt(m instanceof Error?m.message:"","Failed to start initiative.")})}))},[ae.updateEntity,Z,Et]),_t=r.useCallback(async(m,M,L)=>{Te(m),je(null);try{await M(),je({tone:"success",message:L})}catch(Y){je({tone:"error",message:Gt(Y instanceof Error?Y.message:"","Action failed.")})}finally{Te(null)}},[]),ur=r.useCallback(()=>U?_t("pause",()=>pt.stopTriage({initiativeId:U.initiativeId,workstreamId:U.workstreamId,placement:"bottom",resetToTodo:!1}),`Paused ${U.workstreamTitle} and moved it to bottom of queue.`):Promise.resolve(),[pt,U,_t]),mr=r.useCallback(()=>{if(!U)return Promise.resolve();const m=U.playbackState==="running"||U.playbackState==="blocked"||U.queueState==="running"||U.queueState==="blocked";return _t("defer",()=>m?pt.stopTriage({initiativeId:U.initiativeId,workstreamId:U.workstreamId,placement:"bottom",resetToTodo:!1}):pt.move({initiativeId:U.initiativeId,workstreamId:U.workstreamId,placement:"bottom"}),`Deferred ${U.workstreamTitle} to bottom of queue.`)},[pt,U,_t]),pr=r.useCallback(()=>{const m=U??Se??ce;if(!m)return Promise.resolve();const M=m.autoIntentEnabled===!0&&(m.autoRuntimeState==="running"||m.autoRuntimeState==="stopping");return _t("auto",()=>M?Ee.stopInitiativeAutoContinue({initiativeId:m.initiativeId}):(async()=>(await pt.move({initiativeId:m.initiativeId,workstreamId:m.workstreamId,placement:"top"}),Ee.startWorkstreamAutoContinue({initiativeId:m.initiativeId,workstreamId:m.workstreamId,agentId:m.runnerAgentId,scope:"initiative"})))(),M?`Stopped auto-continue for ${m.initiativeTitle}.`:`Auto-continue enabled for ${m.initiativeTitle}; starting with ${m.workstreamTitle}.`)},[Ee,ce,Se,pt,U,_t]),Xs=r.useCallback(()=>{Z&&(Et(Z.id,Z.name),typeof window<"u"&&window.innerWidth>=1280&&Pe(!0))},[Z,Et]),Es=r.useCallback(()=>{if(typeof window>"u")return;if(window.innerWidth>=1280){const M=!he;Ne(!1),Pe(M),je({tone:"success",message:M?"Opened queue rail.":"Closed queue rail."});return}const m=!Re;Pe(!1),Ne(m),je({tone:"success",message:m?"Opened queue panel.":"Closed queue panel."})},[Re,he]),Wt=Os((Z==null?void 0:Z.rawStatus)??(Z==null?void 0:Z.status)??null),Zs=r.useMemo(()=>new Set(["paused","draft","planned","todo","backlog","queued"]),[]),Ke=r.useMemo(()=>Z?(U==null?void 0:U.queueState)==="running"||(U==null?void 0:U.playbackState)==="running"||(ce==null?void 0:ce.autoIntentEnabled)===!0&&(ce.autoRuntimeState==="running"||ce.autoRuntimeState==="stopping")?"running":(ce==null?void 0:ce.queueState)==="blocked"||Z.status==="blocked"?"blocked":ce?"queued":Zs.has(Wt)?"startable":Wt==="completed"||Wt==="done"?"completed":"active_no_queue":"none",[Z,ce,Zs,Wt,U]),As=r.useMemo(()=>Z?Ke==="running"&&ce?{headline:`${ce.workstreamTitle} is running`,detail:`Runner: ${ce.runnerAgentName}. Follow live updates in Activity.`}:Ke==="queued"&&ce?{headline:ce.workstreamTitle,detail:`Ready to dispatch${ce.nextTaskTitle?` · ${ce.nextTaskTitle}`:""}.`}:Ke==="startable"?{headline:Wt==="paused"?`${Z.name} is paused`:`${Z.name} is ready to start`,detail:"Start initiative to queue and dispatch the next workstream."}:Ke==="blocked"?{headline:(ce==null?void 0:ce.queueState)==="blocked"?`${ce.workstreamTitle} is blocked`:`${Z.name} is blocked`,detail:(ce==null?void 0:ce.blockReason)??"Resolve blockers or approvals before dispatching more work."}:Ke==="completed"?{headline:`${Z.name} is complete`,detail:"Choose another active initiative or queue new workstreams."}:{headline:Z.name,detail:"No queued workstream detected yet. Use Next Up to choose what runs next."}:{headline:"No initiative selected",detail:"Create or select an initiative to queue work."},[Z,Ke,ce,Wt]),is=Ee.isPlaying||Ee.isStartingAutoContinue||Ee.isStoppingAutoContinue||ae.updateEntity.isPending,xr=r.useMemo(()=>Ke==="blocked"?"Review blockers":Ke==="active_no_queue"?"Open and queue work":Ke==="completed"?"Review initiative":"Open initiative",[Ke]),en=r.useMemo(()=>(U==null?void 0:U.playbackState)==="running"||(U==null?void 0:U.queueState)==="running"?"running":(U==null?void 0:U.playbackState)==="blocked"||(U==null?void 0:U.queueState)==="blocked"?"blocked":Se?"queued":Ke==="startable"?"startable":Ke==="completed"?"completed":Z?"active_no_queue":"none",[Z,Ke,Se,U]),tn=(U==null?void 0:U.workstreamTitle)??"No active workstream",hr=(U==null?void 0:U.initiativeTitle)??(Z==null?void 0:Z.name)??"No initiative selected",Ds=U?[U.nextTaskTitle?`Next: ${U.nextTaskTitle}`:null,U.blockReason?`Blocked: ${U.blockReason}`:null].filter(Boolean).join(" · "):Se?`Next up: ${Se.workstreamTitle}`:As.detail,sn=(Se==null?void 0:Se.workstreamTitle)??"Queue is empty",nn=Se!=null&&Se.nextTaskTitle?`Next task: ${Se.nextTaskTitle}`:"Add or reorder workstreams in queue.",fr=si(en),gr=ni(en),Ht=U??Se??ce,Ms=(Ht==null?void 0:Ht.autoIntentEnabled)===!0&&(Ht.autoRuntimeState==="running"||Ht.autoRuntimeState==="stopping"),$s="next-up-surface",Ts=r.useMemo(()=>({type:"spring",stiffness:340,damping:38,mass:.72}),[]),br=r.useMemo(()=>({backgroundColor:"rgba(10, 14, 21, 0.66)",borderColor:"rgba(255, 255, 255, 0.10)"}),[]),rn=r.useMemo(()=>({backgroundColor:"rgba(10, 14, 21, 0.95)",borderColor:"rgba(255, 255, 255, 0.11)"}),[]),yr=r.useMemo(()=>{if(!X)return null;const m=L=>t.find(Y=>Y.id===L)??null;if(X.type==="initiative"){const L=m(X.entity.id);return L?{...X,entity:L}:X}const M=m(X.initiative.id);return M?{...X,initiative:M}:X},[t,X]);return r.useEffect(()=>{je(null)},[Z==null?void 0:Z.id,ce==null?void 0:ce.initiativeId,ce==null?void 0:ce.workstreamId,U==null?void 0:U.initiativeId,U==null?void 0:U.workstreamId,Se==null?void 0:Se.initiativeId,Se==null?void 0:Se.workstreamId]),r.useEffect(()=>{if(!X)return;const m=X.type==="initiative"?X.entity.id:X.initiative.id;t.some(L=>L.id===m)||ie()},[ie,t,X]),r.useEffect(()=>{if(typeof window>"u")return;const m=()=>{window.innerWidth>=1280?Ne(!1):Pe(!1)};return m(),window.addEventListener("resize",m),()=>window.removeEventListener("resize",m)},[]),e.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden",children:[e.jsxs("div",{className:"relative flex-1 min-h-0",children:[e.jsx("div",{className:"pointer-events-none absolute top-0 left-0 right-0 h-6 bg-gradient-to-b from-[#02040A] to-transparent z-10"}),e.jsx("div",{className:"pointer-events-none absolute bottom-0 left-0 right-0 h-12 bg-gradient-to-t from-[#02040A] to-transparent z-10"}),e.jsx("div",{"data-mc-scroll-host":"true",className:"h-full overflow-y-auto overflow-x-hidden",children:e.jsxs("div",{className:"mx-auto max-w-6xl px-4 sm:px-6",style:{"--mc-toolbar-offset":`${p}px`},children:[e.jsxs(_r,{id:"next-up-morph",children:[e.jsxs("div",{ref:Ve,className:"sticky top-0 z-40 relative -mx-4 border-b border-subtle bg-[#02040A]/78 px-4 pb-2.5 pt-3.5 backdrop-blur-xl sm:-mx-6 sm:px-6",children:[e.jsx("div",{className:"pointer-events-none absolute right-4 top-2.5 z-50 sm:right-6",children:e.jsx(zn,{open:Is&&!Me,tone:lr==="critical"?"error":"warning",title:cr,message:Ys,onDismiss:()=>Be(!0),primaryAction:u?{label:"Refresh",onClick:u}:null,secondaryAction:y?{label:"Settings",onClick:y}:null})}),e.jsxs("div",{className:"toolbar-shell flex flex-col gap-2.5 md:flex-row md:items-center",children:[e.jsx("div",{className:"min-w-0 flex-1",children:e.jsx(Qs,{value:j,onChange:S,placeholder:"Search initiatives..."})}),e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-2.5 md:ml-auto md:flex-nowrap",children:[e.jsx(Ha,{initiatives:t,visibleCount:Mt.length}),e.jsxs("div",{className:"hidden min-w-[220px] max-w-[320px] items-center gap-2 rounded-lg border border-strong bg-white/[0.03] px-2.5 py-1.5 xl:flex",title:(Z==null?void 0:Z.name)??void 0,children:[e.jsx("span",{className:"text-micro font-semibold uppercase tracking-[0.08em] text-white/44",children:"Autopilot"}),e.jsxs("div",{className:"min-w-0 flex-1 text-right",children:[e.jsx("div",{className:"truncate text-micro text-white/72",children:Js}),Z&&e.jsx("div",{className:"truncate text-micro text-white/44",children:Z.name})]})]}),e.jsxs("button",{type:"button",onClick:()=>{if(Cs||!Ft)return;if(Ut&&Tt){vr({actions:Tt.actions,requiredPlan:Tt.requiredPlan}).catch(L=>{je({tone:"error",message:Gt(L instanceof Error?L.message:"","Unable to open checkout right now.")})});return}const m=Ae.isRunning;(m?Ae.stop:Ae.start)().then(()=>{zt(null);const L=(Z==null?void 0:Z.name)??"selected initiative";je({tone:"success",message:m?`Stopped Autopilot for ${L}.`:`Started Autopilot for ${L}.`})}).catch(L=>{L instanceof Dr?zt(L):(zt(null),je({tone:"error",message:Gt(L instanceof Error?L.message:"","Autopilot action failed.")}))})},disabled:Cs||Ae.isStarting||Ae.isStopping,title:Cs?"Select an initiative to run Autopilot":Ut?"Upgrade to enable auto-continue for BYOK agents":Ae.isRunning?"Stop Autopilot":`Start Autopilot${Z?` for ${Z.name}`:""}`,"data-state":Ae.isRunning||Ut?"active":"idle","data-tone":ir,className:"control-pill flex items-center gap-1.5 px-3 text-caption font-semibold disabled:opacity-40",children:[Ut?e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M12 5v14"}),e.jsx("path",{d:"M18 11l-6-6-6 6"})]}):Ae.isRunning?Fs?e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"currentColor",className:"status-breathe",children:e.jsx("rect",{x:"7",y:"7",width:"10",height:"10",rx:"2"})}):e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("circle",{cx:"12",cy:"12",r:"8"}),e.jsx("path",{d:"M12 8v4l3 2"})]}):e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("path",{d:"M8 5v14l11-7z"})}),e.jsx("span",{children:Ut?"Upgrade Autopilot":`${Ae.isRunning?"Stop":"Start"} Autopilot`}),Ae.isRunning&&Fs&&e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-[#0AD4C4] status-breathe"})]}),Ae.isRunning&&e.jsxs("div",{className:"autopilot-rail autopilot-rail-pulse flex items-center gap-2 rounded-lg px-3 py-1.5 mt-1.5","data-state":(on=Ae.run)!=null&&on.lastError?"error":((ln=Ae.run)==null?void 0:ln.stopReason)==="blocked"?"blocked":"running",children:[e.jsxs("span",{className:"relative flex h-2 w-2 flex-shrink-0",children:[e.jsx("span",{className:"absolute inline-flex h-full w-full animate-ping rounded-full bg-[#0AD4C4] opacity-75"}),e.jsx("span",{className:"relative inline-flex h-2 w-2 rounded-full bg-[#0AD4C4]"})]}),e.jsx("span",{className:"text-micro font-semibold text-[#7AEDE5]",children:"Autopilot Active"}),((cn=Ae.run)==null?void 0:cn.tokensUsed)!=null&&((dn=Ae.run)==null?void 0:dn.tokenBudget)!=null&&Ae.run.tokenBudget>0&&e.jsxs("span",{className:"text-micro text-[#7AEDE5]/60 tabular-nums",children:[Math.round(Ae.run.tokensUsed/Ae.run.tokenBudget*100),"% budget"]})]}),V&&e.jsxs("a",{href:or,target:"_blank",rel:"noreferrer noopener",onClick:()=>{try{Mr("live_install_cta_click",{surface:"mission_control",embedMode:!0,initiativeId:(Z==null?void 0:Z.id)??null})}catch{}},className:"control-pill flex items-center gap-1.5 px-3 text-caption font-semibold","data-tone":"amber",title:"Install OrgX for OpenClaw",children:[e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("path",{d:"M12 3v12"}),e.jsx("path",{d:"M8 11l4 4 4-4"}),e.jsx("path",{d:"M5 21h14"})]}),e.jsx("span",{children:"Install OrgX"})]}),z.length>0&&e.jsx("button",{type:"button",onClick:()=>{be?(Ns(),B(),we&&yt.length>0&&pe(new Set)):(rr(z.map(m=>m.id)),we&&yt.length>0&&pe(new Set(yt)))},title:be?"Collapse all":"Expand all","aria-busy":Fe&&!be,className:"control-pill flex h-8 w-8 flex-shrink-0 items-center justify-center text-secondary",children:e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:be?e.jsxs(e.Fragment,{children:[e.jsx("path",{d:"M4 14h16"}),e.jsx("path",{d:"M4 10h16"})]}):e.jsxs(e.Fragment,{children:[e.jsx("path",{d:"M4 12h16"}),e.jsx("path",{d:"M12 4v16"})]})})})]})]})]}),ye.length>0&&e.jsxs("div",{"data-mc-selection-bar":"true",className:`mt-3 relative grid overflow-hidden rounded-xl border xl:grid-cols-[minmax(0,1fr)_560px] xl:gap-0 xl:items-center ${$e>0?"border-[#BFFF00]/14 bg-[#0A0E15]/72":"border-white/[0.10] bg-[#0A0E15]/66"}`,children:[$e>0&&e.jsx("div",{"aria-hidden":!0,className:"pointer-events-none absolute inset-x-0 top-0 h-px",style:{background:"linear-gradient(90deg, rgba(191,255,0,0.22), rgba(10,212,196,0.16), transparent 72%)"}}),e.jsx("div",{className:`min-w-0 px-3 py-2 transition-[padding,min-height] duration-200 ease-out xl:flex ${$e>0?"xl:min-h-[92px] xl:items-start":"xl:min-h-[70px] xl:items-center"}`,children:e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("label",{className:"inline-flex flex-shrink-0 items-center gap-2 text-caption text-primary",children:[e.jsx("input",{type:"checkbox",checked:Le,onChange:Yn,className:"h-3.5 w-3.5 rounded border-white/20 bg-black/40 text-[#BFFF00] focus:ring-[#BFFF00]/35"}),"Select page"]}),e.jsx("span",{className:"flex-shrink-0 text-caption text-white/58",children:$e>0?`${$e} selected`:Xe===0?"0 visible":`${C}-${A} of ${Xe}`}),$e>0&&e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("button",{type:"button",onClick:()=>{rs("active")},disabled:ge,className:"control-pill h-8 flex-shrink-0 px-3 text-caption font-semibold disabled:opacity-45","data-state":"active",children:"Mark active"}),e.jsx("button",{type:"button",onClick:()=>{rs("paused")},disabled:ge,className:"control-pill h-8 flex-shrink-0 px-3 text-caption font-semibold disabled:opacity-45",children:"Pause"}),e.jsx("button",{type:"button",onClick:()=>{rs("blocked")},disabled:ge,className:"control-pill h-8 flex-shrink-0 px-3 text-caption font-semibold disabled:opacity-45",children:"Block"}),e.jsx("button",{type:"button",onClick:()=>{rs("completed")},disabled:ge,className:"control-pill h-8 flex-shrink-0 px-3 text-caption font-semibold disabled:opacity-45",children:"Complete"}),jt?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-micro text-white/58",children:"Delete selected?"}),e.jsx("button",{type:"button",onClick:()=>{nr()},disabled:ge,className:"control-pill h-8 flex-shrink-0 border-red-400/35 bg-red-500/14 px-3 text-caption font-semibold text-red-100 disabled:opacity-45",children:"Delete"}),e.jsx("button",{type:"button",onClick:()=>Ye(!1),disabled:ge,className:"control-pill h-8 flex-shrink-0 px-2.5 text-caption disabled:opacity-45",children:"Keep"})]}):e.jsx("button",{type:"button",onClick:()=>Ye(!0),disabled:ge,className:"control-pill h-8 flex-shrink-0 border-red-400/24 bg-red-500/[0.08] px-3 text-caption font-semibold text-red-100/85 disabled:opacity-45",children:"Delete"}),e.jsx("button",{type:"button",onClick:Xn,disabled:ge,className:"text-caption text-secondary transition-colors hover:text-primary disabled:opacity-45",children:"Clear"})]})]})}),e.jsx(ht,{initial:!1,mode:"popLayout",children:!he&&!Re&&e.jsxs(fe.div,{layout:"position",layoutId:$s,initial:{opacity:0,y:4},animate:{opacity:1,y:0,...br},exit:{opacity:0,y:-4},transition:{layout:Ts,duration:.2,ease:[.22,1,.36,1]},className:"flex w-full min-w-0 flex-col gap-2 overflow-hidden rounded-xl border border-strong px-2.5 py-2 shadow-[0_10px_24px_rgba(0,0,0,0.22)] backdrop-blur-[10px] sm:flex-row sm:items-center xl:h-full xl:rounded-none xl:border-b-0 xl:border-l xl:border-r-0 xl:border-t-0 xl:border-white/[0.10] xl:bg-transparent xl:px-3 xl:py-2 xl:shadow-none xl:backdrop-blur-none",children:[e.jsxs("div",{className:"flex min-w-0 w-full flex-1 items-center gap-2.5",children:[Ee.isLoading?e.jsx(vt,{className:"h-6 w-6 rounded-full"}):$t?e.jsx(Un,{name:$t.runnerAgentName,hint:`${$t.runnerAgentId} ${$t.runnerSource}`,size:"xs"}):e.jsx("div",{className:"h-6 w-6 rounded-full border border-strong bg-white/[0.05]"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-micro font-semibold uppercase tracking-[0.08em] text-white/76",children:"Now Working"}),Ee.isLoading?e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full border border-strong bg-white/[0.04] px-1.5 py-[1px] text-micro uppercase tracking-[0.07em] text-secondary",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-[#BFFF00]/70 status-breathe"}),"Syncing"]}):e.jsx("span",{className:`rounded-full border px-1.5 py-[1px] text-micro uppercase tracking-[0.07em] ${gr}`,children:fr})]}),Ee.isLoading?e.jsxs("div",{className:"mt-1.5 space-y-1",children:[e.jsx(vt,{className:"h-3 w-56 rounded"}),e.jsx(vt,{className:"h-3 w-44 rounded"})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"truncate text-body font-semibold leading-snug text-bright",title:tn,children:tn}),e.jsxs("p",{className:"truncate text-caption leading-snug text-secondary",title:Ds,children:[hr,Ds?` · ${Ds}`:""]}),e.jsxs("p",{className:"hidden truncate text-micro leading-snug text-secondary/85 sm:block",title:sn,children:["Up next: ",sn,nn?` · ${nn}`:""]})]})]})]}),e.jsxs("div",{className:"ml-auto flex w-full flex-wrap items-center justify-end gap-2 sm:w-auto",children:[e.jsx("button",{type:"button",onClick:()=>{const m=Se??ce;if(U){ur();return}if(m){_t("start",()=>Ee.playWorkstream({initiativeId:m.initiativeId,workstreamId:m.workstreamId,agentId:m.runnerAgentId}),`Started ${m.workstreamTitle}.`);return}Xs()},disabled:is||Je==="start"||Je==="pause",className:"control-pill h-8 flex-shrink-0 px-3 text-caption font-semibold disabled:opacity-45",title:U?`Pause ${U.workstreamTitle}`:"Start next workstream",children:U?"Pause":"Start"}),e.jsx("button",{type:"button",onClick:()=>void mr(),disabled:!U||Je==="defer"||is,className:"control-pill hidden h-8 flex-shrink-0 px-3 text-caption font-semibold disabled:opacity-45 sm:inline-flex",title:"Send current workstream to the bottom of queue",children:"Defer"}),e.jsx("button",{type:"button",onClick:()=>void pr(),disabled:!Ht||Je==="auto"||is,className:"control-pill h-8 flex-shrink-0 px-3 text-caption font-semibold disabled:opacity-45","data-state":Ms?"active":"idle","data-tone":"teal",title:Ms?"Stop automatic continuation":"Continue automatically for this initiative",children:Ms?"Auto on":"Auto"}),e.jsx("button",{type:"button",onClick:Es,className:"control-pill h-8 flex-shrink-0 px-3 text-caption font-semibold",title:"Open queue",children:"Open queue"})]})]},"next-up-inline-card")})]}),Qe&&e.jsxs("div",{role:"status","aria-live":"polite",className:"mt-2 flex items-start justify-between gap-3 rounded-lg border border-white/[0.08] bg-white/[0.02] px-3 py-2 text-caption text-white/72",children:[e.jsxs("div",{className:"flex min-w-0 items-start gap-2",children:[e.jsx("span",{"aria-hidden":!0,className:`mt-[3px] h-1.5 w-1.5 flex-shrink-0 rounded-full ${Qe.tone==="success"?"bg-emerald-300/90":"bg-amber-300/90"}`}),e.jsx("span",{className:"min-w-0 leading-snug",children:Qe.message})]}),e.jsx("button",{type:"button",onClick:()=>Ue(null),className:"inline-flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-md text-secondary transition-colors hover:bg-white/[0.06] hover:text-primary","aria-label":"Dismiss notice",title:"Dismiss",children:e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("path",{d:"M18 6 6 18"}),e.jsx("path",{d:"m6 6 12 12"})]})})]}),e.jsxs(fe.div,{layout:!0,transition:{type:"spring",stiffness:260,damping:30},className:`mt-3 grid gap-4 pb-8 ${he?"xl:grid-cols-[minmax(0,1fr)_320px] xl:gap-0":"grid-cols-1"}`,children:[e.jsxs(fe.div,{layout:!0,className:`min-w-0 ${he?"xl:pr-4":""}`,children:[!n&&Z&&e.jsxs(fe.div,{initial:{opacity:0,y:6,scale:.995},animate:{opacity:1,y:0,scale:1},transition:{type:"spring",stiffness:280,damping:30},className:"surface-tier-2 relative mb-3.5 overflow-hidden rounded-2xl p-4",children:[e.jsx("div",{"aria-hidden":!0,className:"absolute inset-x-0 top-0 h-px",style:{background:"linear-gradient(90deg, rgba(191,255,0,0.14), rgba(10,212,196,0.12), transparent 72%)"}}),e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-[240px]",children:[e.jsx("p",{className:"section-kicker",children:"Current context"}),e.jsx("p",{className:"mt-1 text-heading font-semibold leading-snug tracking-tight text-bright",children:As.headline}),e.jsx("p",{className:"mt-1 text-body leading-relaxed text-secondary",children:As.detail}),St&&e.jsx("div",{className:`mt-2 inline-flex max-w-[520px] items-center gap-1 rounded-full border px-2.5 py-1 text-micro ${St.tone==="success"?"border-emerald-400/24 bg-emerald-500/[0.1] text-emerald-100":"border-amber-400/24 bg-amber-500/[0.1] text-amber-100"}`,children:St.message})]}),e.jsxs("div",{className:"ml-auto flex flex-wrap items-center gap-2.5 xl:self-end",children:[Ke==="startable"?e.jsx("button",{type:"button",onClick:dr,disabled:is,className:"control-pill h-9 px-4 text-body font-semibold disabled:opacity-45","data-state":"active",children:"Start initiative"}):e.jsx("button",{type:"button",onClick:Xs,className:"control-pill h-9 px-4 text-body font-semibold","data-state":Ke==="blocked"?"active":"idle",children:xr}),e.jsx("button",{type:"button",onClick:Es,className:"control-pill h-9 px-4 text-body font-semibold",children:he?"Hide Queue":"Open Queue"})]})]})]}),n?e.jsx("div",{className:"space-y-3 pb-8",children:Array.from({length:4}).map((m,M)=>e.jsxs("div",{className:"bg-[--orgx-surface] border border-[--orgx-border] soft-shadow rounded-2xl p-4",children:[e.jsx(vt,{className:"h-4 w-2/5 rounded"}),e.jsx(vt,{className:"h-1 w-full rounded mt-3"})]},`mc-skeleton-${M}`))}):t.length===0?f?o==="disconnected"||h?e.jsx("div",{className:"pb-8",children:e.jsx(Ps,{mode:"degraded",detail:Ys,onCreateInitiative:F,onPlayNextUp:T,onStartAutopilot:v,onRefresh:u,onOpenSettings:y})}):e.jsx("div",{className:"pb-8",children:e.jsx(Ps,{mode:"empty",onCreateInitiative:F,onPlayNextUp:T,onStartAutopilot:v,onRefresh:u})}):e.jsx("div",{className:"pb-8",children:e.jsxs("div",{className:"rounded-2xl border border-white/[0.08] bg-white/[0.02] px-6 py-8 text-center",children:[e.jsx("div",{className:"text-heading font-semibold text-bright",children:"Connect OrgX to get started"}),e.jsx("div",{className:"mt-1 text-body text-secondary",children:"Mission Control shows your initiative hierarchy once a user-scoped API key is configured."}),y&&e.jsx("div",{className:"mt-4 flex items-center justify-center",children:e.jsx("button",{type:"button",onClick:y,className:"h-10 rounded-full border border-[#BFFF00]/30 bg-[#BFFF00]/15 px-4 text-body font-semibold text-[#D8FFA1] transition-colors hover:bg-[#BFFF00]/20",children:"Open settings"})})]})}):ye.length===0?e.jsx("div",{className:"pb-8",children:e.jsx(Ps,{mode:"filtered",hasActiveFilters:P,onClearFilters:P?w:void 0,onCreateInitiative:F,onPlayNextUp:T,onStartAutopilot:v,onRefresh:u})}):we?e.jsx("div",{className:"space-y-4 pb-8",children:we.map(m=>{const M=Pt($,m.key),L=ti(M),Y=K.has(M);return e.jsxs(fe.div,{layout:!0,transition:{type:"spring",stiffness:260,damping:30},children:[e.jsxs("button",{type:"button","aria-expanded":Y,"aria-controls":L,onClick:()=>oe(M),className:"mb-2 flex w-full items-center gap-2 rounded-xl border border-white/[0.075] bg-white/[0.016] px-3 py-2.5 text-left transition-colors hover:border-strong hover:bg-white/[0.04]",children:[e.jsx("span",{"aria-hidden":!0,className:`inline-flex h-5 w-5 items-center justify-center rounded-md border border-strong bg-white/[0.04] text-caption text-secondary transition-transform ${Y?"rotate-90":""}`,children:"▶"}),e.jsx("span",{className:"text-body font-semibold text-primary",children:m.label}),e.jsx("span",{className:"rounded-full border border-white/[0.1] bg-white/[0.04] px-2 py-0.5 text-micro text-secondary",children:m.count}),e.jsx("span",{className:"ml-auto text-micro uppercase tracking-[0.08em] text-secondary",children:Y?"Hide":"Show"})]}),e.jsx(ht,{initial:!1,children:Y&&e.jsx(fe.div,{id:L,initial:{opacity:0,y:-4},animate:{opacity:1,y:0},exit:{opacity:0,y:-4},transition:{duration:.2,ease:[.22,1,.36,1]},children:e.jsx("div",{className:"pt-0.5",children:e.jsx(yn,{initiatives:m.initiatives,selectedInitiativeIds:st,onToggleInitiativeSelection:Vs,isSquished:he,runtimeActivityByInitiativeId:et})})})})]},m.key)})}):e.jsx("div",{className:"pb-8",children:e.jsx(yn,{initiatives:z,selectedInitiativeIds:st,onToggleInitiativeSelection:Vs,isSquished:he,runtimeActivityByInitiativeId:et})}),ye.length>0&&e.jsxs("div",{className:"mt-2.5 flex flex-wrap items-center justify-between gap-2 rounded-xl border border-white/[0.08] bg-white/[0.02] px-3 py-2",children:[e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-2 text-caption text-white/70",children:[e.jsxs("span",{className:"font-medium text-white/80",children:["Showing ",C,"-",A]}),e.jsx("span",{className:"text-white/50",children:"of"}),e.jsx("span",{className:"font-medium text-white/80",children:Xe}),e.jsx("span",{className:"text-white/50",children:"initiatives"})]}),e.jsxs("div",{className:"ml-auto flex flex-wrap items-center justify-end gap-2",children:[e.jsxs("label",{className:"inline-flex items-center gap-1.5 rounded-lg border border-white/[0.08] bg-black/25 px-2 py-1 text-micro text-white/68",children:[e.jsx("span",{children:"Per page"}),e.jsx("select",{value:rt,onChange:m=>{const M=Number.parseInt(m.target.value,10);Number.isFinite(M)&&Ot(M)},className:"h-6 rounded-md border border-transparent bg-transparent px-1 text-caption text-white/90 outline-none",children:ai.map(m=>e.jsx("option",{value:m,children:m},m))})]}),e.jsxs("div",{className:"inline-flex items-center gap-1 rounded-lg border border-white/[0.08] bg-black/25 p-1",children:[e.jsx("button",{type:"button",onClick:Zn,disabled:!Ks,className:"control-pill h-7 px-2 text-micro font-semibold disabled:opacity-40",title:"First page",children:"«"}),e.jsx("button",{type:"button",onClick:er,disabled:!Ks,className:"control-pill h-7 px-2 text-micro font-semibold disabled:opacity-40",title:"Previous page",children:"‹"}),e.jsxs("span",{className:"px-1.5 text-micro text-white/64",children:["Page ",ot+1," / ",Ze]}),e.jsx("button",{type:"button",onClick:tr,disabled:!Gs,className:"control-pill h-7 px-2 text-micro font-semibold disabled:opacity-40",title:"Next page",children:"›"}),e.jsx("button",{type:"button",onClick:sr,disabled:!Gs,className:"control-pill h-7 px-2 text-micro font-semibold disabled:opacity-40",title:"Last page",children:"»"})]})]})]})]}),e.jsx(ht,{initial:!1,children:he&&e.jsx(fe.aside,{layout:!0,initial:{opacity:0,x:14},animate:{opacity:1,x:0},exit:{opacity:0,x:14},transition:{duration:.2,ease:[.22,1,.36,1]},className:"hidden xl:block",children:e.jsx("div",{className:"sticky",style:{top:"calc(var(--mc-toolbar-offset) + 12px)"},children:e.jsx(fe.div,{layout:"position",layoutId:$s,initial:{borderRadius:12},animate:{borderRadius:16,...rn},transition:{layout:Ts,type:"spring",stiffness:340,damping:38,mass:.72},className:"origin-top-right flex h-[calc(100vh-var(--mc-toolbar-offset)-24px)] min-h-0 flex-col overflow-hidden rounded-2xl border shadow-[0_18px_40px_rgba(0,0,0,0.42)] backdrop-blur-[12px] xl:rounded-l-none",children:e.jsxs("div",{className:"relative flex h-full min-h-0 flex-col",children:[e.jsxs("div",{className:"flex items-center gap-1 border-b border-strong px-3 py-2",children:[e.jsx("button",{type:"button",onClick:()=>ft("next-up"),className:`control-pill h-7 px-2 text-micro font-semibold ${He==="next-up"?"border-[#BFFF00]/34 bg-[#BFFF00]/[0.12] text-[#E8FFD0]":"text-secondary"}`,children:"Next Up"}),e.jsx("button",{type:"button",onClick:()=>ft("slices"),className:`control-pill h-7 px-2 text-micro font-semibold ${He==="slices"?"border-teal-300/34 bg-teal-400/[0.12] text-teal-100":"text-secondary"}`,children:"Slices"})]}),e.jsx("div",{className:"min-h-0 flex-1",children:He==="next-up"?e.jsx(mn,{title:"Next Up",panelStyle:"flat",className:"!bg-transparent !shadow-none !border-transparent",disableEnterAnimation:!0,projectId:a,authToken:E,embedMode:V,queueModel:Ee,queueActions:pt,snapshotVersion:x,onOpenInitiative:Et,onOpenSettings:y,onUpgradeGate:zt}):e.jsx(_n,{title:"Slice Explorer",className:"h-full !rounded-none !border-0 !bg-transparent",workspaceId:a,authToken:E,embedMode:V,compact:!0,onOpenInitiative:(m,M)=>{Et(m,M)}})}),e.jsx("button",{type:"button",onClick:Es,className:"control-pill absolute right-3 top-3 z-20 h-7 px-2 text-micro font-semibold",title:"Collapse Next Up rail",children:"Hide"})]})})})})})]})]}),e.jsx(ht,{children:Re&&e.jsxs(e.Fragment,{children:[e.jsx(fe.button,{type:"button","aria-label":"Close next up panel",onClick:()=>Ne(!1),initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"fixed bottom-0 left-0 right-0 top-[64px] z-[240] bg-black/45 xl:hidden"},"next-up-backdrop"),e.jsx(fe.aside,{initial:{x:"100%",opacity:.85},animate:{x:0,opacity:1},exit:{x:"100%",opacity:.9},transition:{type:"spring",stiffness:320,damping:34},className:"fixed inset-x-0 bottom-0 top-[60vh] z-[250] p-2 sm:top-[64px] sm:left-auto sm:right-0 sm:w-[min(84vw,360px)] sm:p-3 lg:w-[360px] lg:max-w-[94vw] xl:hidden",children:e.jsxs("div",{className:"relative flex h-full flex-col",children:[e.jsx("button",{type:"button",onClick:()=>Ne(!1),className:"absolute right-2 top-3 z-20 inline-flex h-8 w-8 items-center justify-center rounded-full border border-strong bg-[#080d14]/85 text-white/72 transition-colors hover:text-white","aria-label":"Close next up drawer",children:"✕"}),e.jsx(fe.div,{layout:"position",layoutId:$s,initial:{borderRadius:12},animate:{borderRadius:16,...rn},transition:{layout:Ts,type:"spring",stiffness:340,damping:38,mass:.72},className:"h-full overflow-hidden rounded-2xl border shadow-[0_18px_40px_rgba(0,0,0,0.42)] backdrop-blur-[12px]",children:e.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[e.jsxs("div",{className:"flex items-center gap-1 border-b border-strong px-3 py-2",children:[e.jsx("button",{type:"button",onClick:()=>ft("next-up"),className:`control-pill h-7 px-2 text-micro font-semibold ${He==="next-up"?"border-[#BFFF00]/34 bg-[#BFFF00]/[0.12] text-[#E8FFD0]":"text-secondary"}`,children:"Next Up"}),e.jsx("button",{type:"button",onClick:()=>ft("slices"),className:`control-pill h-7 px-2 text-micro font-semibold ${He==="slices"?"border-teal-300/34 bg-teal-400/[0.12] text-teal-100":"text-secondary"}`,children:"Slices"})]}),e.jsx("div",{className:"min-h-0 flex-1",children:He==="next-up"?e.jsx(mn,{title:"Next Up",panelStyle:"flat",className:"!bg-transparent !shadow-none !border-transparent",disableEnterAnimation:!0,projectId:a,authToken:E,embedMode:V,queueModel:Ee,queueActions:pt,snapshotVersion:x,onOpenInitiative:(m,M)=>{Et(m,M),Ne(!1)},onOpenSettings:y,onUpgradeGate:zt}):e.jsx(_n,{title:"Slice Explorer",className:"h-full !rounded-none !border-0 !bg-transparent",workspaceId:a,authToken:E,embedMode:V,compact:!0,onOpenInitiative:(m,M)=>{Et(m,M),Ne(!1)}})})]})})]})},"next-up-drawer")]})})]})})]}),e.jsx(qa,{target:yr,onClose:ie})]})}export{gi as MissionControlView};
|