@useorgx/openclaw-plugin 0.7.15 → 0.7.16

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.
Files changed (126) hide show
  1. package/dashboard/dist/assets/8pbG6uLK.js +1 -0
  2. package/dashboard/dist/assets/8pbG6uLK.js.br +0 -0
  3. package/dashboard/dist/assets/8pbG6uLK.js.gz +0 -0
  4. package/dashboard/dist/assets/B1LENRC8.js +212 -0
  5. package/dashboard/dist/assets/B1LENRC8.js.br +0 -0
  6. package/dashboard/dist/assets/B1LENRC8.js.gz +0 -0
  7. package/dashboard/dist/assets/{gZr_xKlA.js → BM75sh1f.js} +1 -1
  8. package/dashboard/dist/assets/BM75sh1f.js.br +0 -0
  9. package/dashboard/dist/assets/BM75sh1f.js.gz +0 -0
  10. package/dashboard/dist/assets/{CJjEAGFN.js → BYVYH9CH.js} +1 -1
  11. package/dashboard/dist/assets/BYVYH9CH.js.br +0 -0
  12. package/dashboard/dist/assets/BYVYH9CH.js.gz +0 -0
  13. package/dashboard/dist/assets/BkMrrjAv.js +1 -0
  14. package/dashboard/dist/assets/BkMrrjAv.js.br +0 -0
  15. package/dashboard/dist/assets/BkMrrjAv.js.gz +0 -0
  16. package/dashboard/dist/assets/BpF7v1Dk.js +1 -0
  17. package/dashboard/dist/assets/BpF7v1Dk.js.br +0 -0
  18. package/dashboard/dist/assets/BpF7v1Dk.js.gz +0 -0
  19. package/dashboard/dist/assets/{C9fvfXmS.js → Bv_86bUY.js} +1 -1
  20. package/dashboard/dist/assets/Bv_86bUY.js.br +0 -0
  21. package/dashboard/dist/assets/Bv_86bUY.js.gz +0 -0
  22. package/dashboard/dist/assets/{CFZ4Swr5.js → C3PrI8L7.js} +1 -1
  23. package/dashboard/dist/assets/C3PrI8L7.js.br +0 -0
  24. package/dashboard/dist/assets/C3PrI8L7.js.gz +0 -0
  25. package/dashboard/dist/assets/{C91KLKit.js → C6AqbA9J.js} +1 -1
  26. package/dashboard/dist/assets/C6AqbA9J.js.br +0 -0
  27. package/dashboard/dist/assets/C6AqbA9J.js.gz +0 -0
  28. package/dashboard/dist/assets/{7DhYqBrM.js → CUXb_4F3.js} +1 -1
  29. package/dashboard/dist/assets/CUXb_4F3.js.br +0 -0
  30. package/dashboard/dist/assets/CUXb_4F3.js.gz +0 -0
  31. package/dashboard/dist/assets/{3TtV4moZ.js → Cn8sRTkO.js} +1 -1
  32. package/dashboard/dist/assets/Cn8sRTkO.js.br +0 -0
  33. package/dashboard/dist/assets/Cn8sRTkO.js.gz +0 -0
  34. package/dashboard/dist/assets/{CnPC783_.js → D5IgXoTj.js} +1 -1
  35. package/dashboard/dist/assets/D5IgXoTj.js.br +0 -0
  36. package/dashboard/dist/assets/D5IgXoTj.js.gz +0 -0
  37. package/dashboard/dist/assets/DMKyYAtD.js +1 -0
  38. package/dashboard/dist/assets/DMKyYAtD.js.br +0 -0
  39. package/dashboard/dist/assets/DMKyYAtD.js.gz +0 -0
  40. package/dashboard/dist/assets/{CGj8kRhg.js → DXzpQUC0.js} +1 -1
  41. package/dashboard/dist/assets/DXzpQUC0.js.br +0 -0
  42. package/dashboard/dist/assets/DXzpQUC0.js.gz +0 -0
  43. package/dashboard/dist/assets/JDPvhd68.js +1 -0
  44. package/dashboard/dist/assets/JDPvhd68.js.br +0 -0
  45. package/dashboard/dist/assets/JDPvhd68.js.gz +0 -0
  46. package/dashboard/dist/assets/{3VwNyxUf.js → R6N_VVqm.js} +1 -1
  47. package/dashboard/dist/assets/R6N_VVqm.js.br +0 -0
  48. package/dashboard/dist/assets/R6N_VVqm.js.gz +0 -0
  49. package/dashboard/dist/assets/{CKrH5fYO.js → cEP7N1dn.js} +1 -1
  50. package/dashboard/dist/assets/cEP7N1dn.js.br +0 -0
  51. package/dashboard/dist/assets/cEP7N1dn.js.gz +0 -0
  52. package/dashboard/dist/assets/iLnvdWmW.css +1 -0
  53. package/dashboard/dist/assets/iLnvdWmW.css.br +0 -0
  54. package/dashboard/dist/assets/iLnvdWmW.css.gz +0 -0
  55. package/dashboard/dist/assets/{Ctw95IkC.js → konqMbVI.js} +1 -1
  56. package/dashboard/dist/assets/konqMbVI.js.br +0 -0
  57. package/dashboard/dist/assets/konqMbVI.js.gz +0 -0
  58. package/dashboard/dist/assets/{T2NFtzAv.js → wc6cgXzV.js} +1 -1
  59. package/dashboard/dist/assets/wc6cgXzV.js.br +0 -0
  60. package/dashboard/dist/assets/wc6cgXzV.js.gz +0 -0
  61. package/dashboard/dist/index.html +3 -3
  62. package/dashboard/dist/index.html.br +0 -0
  63. package/dashboard/dist/index.html.gz +0 -0
  64. package/dist/http/helpers/auto-continue-engine.d.ts +15 -0
  65. package/dist/http/helpers/auto-continue-engine.js +165 -0
  66. package/dist/http/helpers/mission-control.d.ts +3 -0
  67. package/dist/http/helpers/mission-control.js +38 -7
  68. package/dist/http/helpers/value-utils.d.ts +1 -1
  69. package/dist/http/helpers/value-utils.js +5 -2
  70. package/dist/http/index.js +3 -1
  71. package/dist/http/routes/chat.d.ts +1 -1
  72. package/dist/http/routes/chat.js +2 -2
  73. package/dist/http/routes/entities.js +60 -2
  74. package/dist/http/routes/entity-dynamic.js +49 -9
  75. package/dist/http/routes/live-snapshot.d.ts +10 -1
  76. package/dist/http/routes/live-snapshot.js +11 -3
  77. package/dist/http/routes/mission-control-actions.d.ts +6 -0
  78. package/dist/http/routes/mission-control-actions.js +33 -0
  79. package/package.json +1 -1
  80. package/dashboard/dist/assets/0RUEVzJa.js +0 -1
  81. package/dashboard/dist/assets/0RUEVzJa.js.br +0 -0
  82. package/dashboard/dist/assets/0RUEVzJa.js.gz +0 -0
  83. package/dashboard/dist/assets/3TtV4moZ.js.br +0 -0
  84. package/dashboard/dist/assets/3TtV4moZ.js.gz +0 -0
  85. package/dashboard/dist/assets/3VwNyxUf.js.br +0 -0
  86. package/dashboard/dist/assets/3VwNyxUf.js.gz +0 -0
  87. package/dashboard/dist/assets/7DhYqBrM.js.br +0 -0
  88. package/dashboard/dist/assets/7DhYqBrM.js.gz +0 -0
  89. package/dashboard/dist/assets/BVvffj0x.js +0 -1
  90. package/dashboard/dist/assets/BVvffj0x.js.br +0 -0
  91. package/dashboard/dist/assets/BVvffj0x.js.gz +0 -0
  92. package/dashboard/dist/assets/BiOgVMED.js +0 -1
  93. package/dashboard/dist/assets/BiOgVMED.js.br +0 -0
  94. package/dashboard/dist/assets/BiOgVMED.js.gz +0 -0
  95. package/dashboard/dist/assets/C91KLKit.js.br +0 -0
  96. package/dashboard/dist/assets/C91KLKit.js.gz +0 -0
  97. package/dashboard/dist/assets/C9fvfXmS.js.br +0 -0
  98. package/dashboard/dist/assets/C9fvfXmS.js.gz +0 -0
  99. package/dashboard/dist/assets/CFZ4Swr5.js.br +0 -0
  100. package/dashboard/dist/assets/CFZ4Swr5.js.gz +0 -0
  101. package/dashboard/dist/assets/CGj8kRhg.js.br +0 -0
  102. package/dashboard/dist/assets/CGj8kRhg.js.gz +0 -0
  103. package/dashboard/dist/assets/CJjEAGFN.js.br +0 -0
  104. package/dashboard/dist/assets/CJjEAGFN.js.gz +0 -0
  105. package/dashboard/dist/assets/CKrH5fYO.js.br +0 -0
  106. package/dashboard/dist/assets/CKrH5fYO.js.gz +0 -0
  107. package/dashboard/dist/assets/CMTTPXch.js +0 -1
  108. package/dashboard/dist/assets/CMTTPXch.js.br +0 -0
  109. package/dashboard/dist/assets/CMTTPXch.js.gz +0 -0
  110. package/dashboard/dist/assets/CnPC783_.js.br +0 -0
  111. package/dashboard/dist/assets/CnPC783_.js.gz +0 -0
  112. package/dashboard/dist/assets/Ctw95IkC.js.br +0 -0
  113. package/dashboard/dist/assets/Ctw95IkC.js.gz +0 -0
  114. package/dashboard/dist/assets/DHz-aQPw.js +0 -1
  115. package/dashboard/dist/assets/DHz-aQPw.js.br +0 -0
  116. package/dashboard/dist/assets/DHz-aQPw.js.gz +0 -0
  117. package/dashboard/dist/assets/DNX2foSJ.css +0 -1
  118. package/dashboard/dist/assets/DNX2foSJ.css.br +0 -0
  119. package/dashboard/dist/assets/DNX2foSJ.css.gz +0 -0
  120. package/dashboard/dist/assets/DxUw4FMR.js +0 -212
  121. package/dashboard/dist/assets/DxUw4FMR.js.br +0 -0
  122. package/dashboard/dist/assets/DxUw4FMR.js.gz +0 -0
  123. package/dashboard/dist/assets/T2NFtzAv.js.br +0 -0
  124. package/dashboard/dist/assets/T2NFtzAv.js.gz +0 -0
  125. package/dashboard/dist/assets/gZr_xKlA.js.br +0 -0
  126. package/dashboard/dist/assets/gZr_xKlA.js.gz +0 -0
@@ -0,0 +1 @@
1
+ import{r,j as e}from"./Dj2k1r16.js";import{u as mn,c as Xt,b as It}from"./DMKyYAtD.js";import{i as fs,q as Jt,b as ft,p as Gs,a as Ln,c as Gr,t as Jr,h as jt,d as Yr,e as O,n as Xr,E as Es,u as gs,f as qe,A as an,s as _n,g as bs,j as ks,k as As,P as Zr,m as ea,l as ta,W as sa,I as pn,o as gr,r as Ms,v as na,w as on,M as ra,x as Ns,y as aa,z as Bn,B as ls,C as ds,D as xn,F as br,G as ia,H as Pn,J as Rn,K as Dt,U as oa,L as la}from"./B1LENRC8.js";import{I as yr,o as ca,N as qn}from"./BpF7v1Dk.js";import{S as Ft}from"./DXzpQUC0.js";import{A as lt,m as de,R as da,a as ua,u as ma,L as pa}from"./eeHXe_OQ.js";import{M as xa}from"./BCudUvwg.js";import{E as Ds}from"./C6AqbA9J.js";import{u as ha}from"./cEP7N1dn.js";import"./cX2e-TLi.js";import"./BjK42gtU.js";import"./BV0BcV1u.js";import"./R6N_VVqm.js";function fa({activities:t,agents:s,initiatives:a}){return r.useMemo(()=>{const n=new Map,o=(l,c,h,f)=>{const v=n.get(l)??[];v.some(m=>m.id===c)||(v.push({id:c,name:h,confidence:f}),n.set(l,v))};return t.forEach(l=>{const c="metadata"in l&&l.metadata&&typeof l.metadata=="object"?l.metadata:null,h=c&&typeof c=="object"?c:{},f=("initiativeId"in l&&typeof l.initiativeId=="string"?l.initiativeId:void 0)??h.initiativeId??void 0,v=l.agentId??void 0,m=("agentName"in l&&typeof l.agentName=="string"?l.agentName:"agent"in l&&typeof l.agent=="string"?l.agent:void 0)??v??"Unknown";f&&v&&o(f,v,m,"high")}),a.forEach(l=>{var c;(c=l.avatars)!=null&&c.length&&l.avatars.forEach(h=>{const f=s.find(v=>v.name.toLowerCase()===h.toLowerCase());f?o(l.id,f.id,f.name,"medium"):o(l.id,`avatar:${h}`,h,"medium")})}),s.forEach(l=>{if(!l.task)return;const c=l.task.toLowerCase();a.forEach(h=>{h.name.toLowerCase().split(/\s+/).filter(I=>I.length>3).some(I=>c.includes(I))&&o(h.id,l.id,l.name,"low")})}),n},[t,s,a])}function ga({initiativeId:t=null,authToken:s=null,embedMode:a=!1,enabled:n=!0}){var b,N,M;const o=mn(),l=fs(),c=r.useMemo(()=>Jt.autoContinueStatus({initiativeId:t??null,authToken:s,embedMode:a}),[t,s,a]),h=Xt({queryKey:c,enabled:n&&(!!t||t===null),queryFn:async()=>{if(l)return{ok:!0,initiativeId:t,run:null,defaults:{tokenBudget:null,tickMs:0}};const F=new URLSearchParams;t&&F.set("initiative_id",t);const p=await fetch(`/orgx/api/mission-control/auto-continue/status?${F.toString()}`,{headers:ft({authToken:s,embedMode:a})}),j=await p.json().catch(()=>null);if(!p.ok){const C=typeof(j==null?void 0:j.error)=="string"&&j.error||typeof(j==null?void 0:j.message)=="string"&&j.message||`Failed to load auto-continue status (${p.status})`;return{ok:!1,initiativeId:t,run:null,defaults:{tokenBudget:null,tickMs:0},error:C}}return j},refetchInterval:F=>{var z,ne;const p=F.state.data;if((p==null?void 0:p.ok)===!1)return!1;const j=((z=p==null?void 0:p.error)==null?void 0:z.toLowerCase())??"";if(j.includes("404")||j.includes("400")||j.includes("not found")||j.includes("bad request"))return!1;const L=((ne=p==null?void 0:p.run)==null?void 0:ne.status)??null;return L==="running"||L==="stopping"?2500:12e3}}),f=async()=>{await o.invalidateQueries({queryKey:c}),await o.invalidateQueries({queryKey:Jt.missionControlGraph({initiativeId:t,authToken:s,embedMode:a})}),await o.invalidateQueries({queryKey:Jt.liveData({authToken:s,embedMode:a})})},v=It({mutationFn:async F=>{if(l){const L=h.data??null;return{ok:!0,initiativeId:t,run:(L==null?void 0:L.run)??null,defaults:(L==null?void 0:L.defaults)??{tokenBudget:null,tickMs:0}}}const p={};t&&(p.initiativeId=t),p.ignoreSpawnGuardRateLimit=!0,F&&typeof F=="object"&&(typeof F.tokenBudgetTokens=="number"&&(p.tokenBudgetTokens=F.tokenBudgetTokens),typeof F.agentId=="string"&&F.agentId.trim().length>0&&(p.agentId=F.agentId.trim()),typeof F.maxParallelSlices=="number"&&Number.isFinite(F.maxParallelSlices)&&(p.maxParallelSlices=F.maxParallelSlices),F.parallelMode==="iwmt"&&(p.parallelMode=F.parallelMode));const j=await fetch("/orgx/api/mission-control/auto-continue/start",{method:"POST",headers:ft({authToken:s,embedMode:a,contentTypeJson:!0}),body:JSON.stringify(p)}),C=await j.json().catch(()=>null);if(!j.ok){const L=Ln(C);throw L||Gs(j,C,"Failed to start auto-continue")}if(C&&typeof C=="object"&&"run"in C){const L=h.data??null;return{ok:!0,initiativeId:t,run:C.run??null,defaults:(L==null?void 0:L.defaults)??{tokenBudget:null,tickMs:0}}}return C},onSuccess:F=>{o.setQueryData(c,F),f()}}),m=It({mutationFn:async()=>{if(l){const C=h.data??null;return{ok:!0,initiativeId:t,run:null,defaults:(C==null?void 0:C.defaults)??{tokenBudget:null,tickMs:0}}}const F={};t&&(F.initiativeId=t);const p=await fetch("/orgx/api/mission-control/auto-continue/stop",{method:"POST",headers:ft({authToken:s,embedMode:a,contentTypeJson:!0}),body:JSON.stringify(F)}),j=await p.json().catch(()=>null);if(!p.ok)throw Gs(p,j,"Failed to stop auto-continue");if(j&&typeof j=="object"&&"run"in j){const C=h.data??null;return{ok:!0,initiativeId:t,run:j.run??null,defaults:(C==null?void 0:C.defaults)??{tokenBudget:null,tickMs:0}}}return j},onSuccess:F=>{o.setQueryData(c,F),f()}}),I=It({mutationFn:async F=>{var L;if(l)return{ok:!0,dispatched:((L=F.workstreamIds)==null?void 0:L.length)??1};const p={initiativeId:F.initiativeId};F.workstreamIds&&F.workstreamIds.length>0&&(p.workstreamIds=F.workstreamIds),F.agentId&&(p.agentId=F.agentId),F.scope&&(p.scope=F.scope),p.ignoreSpawnGuardRateLimit=!0;const j=await fetch("/orgx/api/mission-control/next-up/launch",{method:"POST",headers:ft({authToken:s,embedMode:a,contentTypeJson:!0}),body:JSON.stringify(p)}),C=await j.json().catch(()=>null);if(!j.ok){const z=Ln(C);throw z||Gs(j,C,"Failed to launch")}return C??{ok:!0,dispatched:0}},onSuccess:()=>{f()}}),$=((b=h.data)==null?void 0:b.run)??null,g=($==null?void 0:$.status)??null,d=g==="running"||g==="stopping",w=g==="stopping"||m.isPending;return{status:h.data??null,run:$,isRunning:d,isGracefullyStopping:w,isLoading:h.isLoading,error:((N=h.data)==null?void 0:N.error)??((M=h.error)==null?void 0:M.message)??null,start:v.mutateAsync,stop:m.mutateAsync,launchSingle:I.mutateAsync,isStarting:v.isPending,isStopping:m.isPending,isLaunching:I.isPending,refetch:h.refetch}}function wr(t){const s=r.useRef(null),a=r.useCallback((n,o,l,c)=>{if(l&&s.current!==null){const h=t.indexOf(s.current),f=t.indexOf(n);if(h!==-1&&f!==-1){const v=Math.min(h,f),m=Math.max(h,f),I=t.slice(v,m+1);c($=>{const g=new Set($);for(const d of I)o?g.add(d):g.delete(d);return g});return}}c(h=>{const f=new Set(h);return o?f.add(n):f.delete(n),f}),s.current=n},[t]);return{lastClickedId:s,handleSelect:a}}const ba=100,ya=5,wa=75,va=3,ja=["workstream","milestone","task"],ka=60;function Ss(t){const s=Date.parse(t??"");return Number.isFinite(s)?s:0}function Na(t){return t.toLowerCase().trim().split(/\s+/).filter(Boolean)}function Sa(t,s){const a=[];for(let n=0;n<t.length;n+=s)a.push(t.slice(n,n+s));return a}async function On(t,s,a){var l;const n=[];let o=0;for(let c=0;c<a;c+=1){const h=new URLSearchParams(t);h.set("limit",String(s)),h.set("offset",String(o));const f=await fetch(`/orgx/api/entities?${h.toString()}`);if(!f.ok)break;const v=await f.json(),m=v.data??[];if(n.push(...m),!!!((l=v.pagination)!=null&&l.has_more)||m.length===0)break;o+=s}return n}function zn(t,s,a,n){const o=t.name.toLowerCase(),l=(t.description??"").toLowerCase();let c=0;n&&(c+=65),o===s&&(c+=140),o.startsWith(s)&&(c+=100),o.includes(s)&&(c+=80),l.includes(s)&&(c+=40);for(const h of a)o.includes(h)&&(c+=22),l.includes(h)&&(c+=8);return c}function Ca(t,s,a=null){const n=t.trim().toLowerCase(),o=(a==null?void 0:a.trim())??"";return Xt({queryKey:Jt.initiativeSearch({query:n,projectId:o||null}),enabled:s&&n.length>=2,queryFn:async()=>{var g;if(n.length<2||fs())return[];const l=d=>{const w=new URLSearchParams(d);return o.length>0&&w.set("workspace_id",o),w},c=await On(l({type:"initiative",search:n}),ba,ya),h=await Promise.all(ja.map(d=>On(l({type:d,search:n}),wa,va))),f=new Set;for(const d of h)for(const w of d){const b=(g=w.initiative_id)==null?void 0:g.trim();b&&f.add(b)}const v=[];for(const d of Sa(Array.from(f),ka)){if(d.length===0)continue;const w=l({type:"initiative",ids:d.join(","),limit:String(d.length),offset:"0"}),b=await fetch(`/orgx/api/entities?${w.toString()}`);if(!b.ok)continue;const N=await b.json();v.push(...N.data??[])}const m=[...c,...v],I=new Map;for(const d of m){const w=I.get(d.id);if(!w){I.set(d.id,d);continue}Ss(d.updated_at??d.created_at)>Ss(w.updated_at??w.created_at)&&I.set(d.id,d)}const $=Na(n);return Array.from(I.values()).filter(d=>Gr(d.status)).map(Jr).filter(d=>{if(f.has(d.id))return!0;const w=[d.name,d.description??"",d.rawStatus??"",d.status].join(" ").toLowerCase();return $.every(b=>w.includes(b))}).sort((d,w)=>{const b=zn(w,n,$,f.has(w.id))-zn(d,n,$,f.has(d.id));return b!==0?b:Ss(w.updatedAt??w.createdAt)-Ss(d.updatedAt??d.createdAt)})},staleTime:15e3})}function hn({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 Vt(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(jt(a))}return t}function Ia(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 Js(t){const s=t.trim().toLowerCase();return s==="deleted"||s==="archived"||s==="cancelled"}function Fa(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 Ea(t){const s=mn(),a=ft({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"]})},o=(g,d)=>{s.setQueryData(["initiative-tombstones"],w=>{const b=Array.isArray(w)?w.filter(M=>typeof M=="string"):[],N=b.includes(g);return d?N?b:[...b,g]:N?b.filter(M=>M!==g):b})},l=(g,d)=>{const w=Ia(d),b=new Date().toISOString(),N=Js(d);o(g,N);const M=F=>{if(!Array.isArray(F))return F;if(N){const C=F.filter(L=>{if(!L||typeof L!="object")return!0;const z=L;return!(typeof z.id=="string"&&z.id===g)});return C.length===F.length?F:C}let p=!1;const j=F.map(C=>{if(!C||typeof C!="object")return C;const L=C;return typeof L.id!="string"||L.id!==g?C:(p=!0,{...L,status:w,rawStatus:d,updatedAt:b})});return p?j:F};s.setQueriesData({queryKey:["entities"]},M),s.setQueriesData({queryKey:["live-initiatives"]},M)},c=(g,d,w="status")=>{const b=Fa(d);s.setQueriesData({queryKey:["live-data"]},N=>{if(!N||typeof N!="object")return N;const M=N,F=M.sessions;if(!F||typeof F!="object")return N;const p=F,j=p.nodes;if(!Array.isArray(j))return N;let C=!1;const L=w==="delete"?j.filter(P=>{if(!P||typeof P!="object")return!0;const y=P,E=(typeof y.initiativeId=="string"?y.initiativeId:null)===g;return E&&(C=!0),!E}):j.map(P=>{if(!P||typeof P!="object")return P;const y=P;return(typeof y.initiativeId=="string"?y.initiativeId:null)!==g||y.status===b?P:(C=!0,{...y,status:b})});if(!C)return N;const z=new Set,ne=new Set;for(const P of L){if(!P||typeof P!="object")continue;const y=P;typeof y.id=="string"&&z.add(y.id),typeof y.groupId=="string"&&ne.add(y.groupId)}const ae=Array.isArray(p.edges)?p.edges.filter(P=>{if(!P||typeof P!="object")return!1;const y=P,W=typeof y.parentId=="string"?y.parentId:null,E=typeof y.childId=="string"?y.childId:null;return W!==null&&E!==null&&z.has(W)&&z.has(E)}):p.edges,X=Array.isArray(p.groups)?p.groups.filter(P=>{if(!P||typeof P!="object")return!1;const y=P;return typeof y.id=="string"&&ne.has(y.id)}):p.groups;return{...M,sessions:{...p,nodes:L,edges:ae,groups:X}}})},h={start:"active",complete:"completed",block:"blocked",unblock:"active",pause:"paused",resume:"active"},f=It({mutationFn:async g=>{const{type:d,...w}=g,b=await fetch("/orgx/api/entities",{method:"POST",headers:a,body:JSON.stringify({type:d,...w})});return await Vt(b),b.json()},onSuccess:n}),v=It({mutationFn:async g=>{const{type:d,id:w,...b}=g,N=await fetch("/orgx/api/entities",{method:"PATCH",headers:a,body:JSON.stringify({type:d,id:w,...b})});return await Vt(N),N.json()},onSuccess:(g,d)=>{d.type.trim().toLowerCase()==="initiative"&&typeof d.status=="string"&&d.status.trim().length>0&&(l(d.id,d.status),c(d.id,d.status,Js(d.status)?"delete":"status")),n()}}),m=It({mutationFn:async g=>{const d=await fetch(`/orgx/api/entities/${encodeURIComponent(g.type)}/${encodeURIComponent(g.id)}/delete`,{method:"POST",headers:a,body:"{}"});return await Vt(d),d.json()},onSuccess:(g,d)=>{d.type.trim().toLowerCase()==="initiative"&&(l(d.id,"archived"),c(d.id,"archived","delete")),n()}}),I=It({mutationFn:async g=>{const d=await fetch(`/orgx/api/entities/${encodeURIComponent(g.type)}/${encodeURIComponent(g.id)}/${encodeURIComponent(g.action)}`,{method:"POST",headers:a,body:JSON.stringify({force:g.force??!1})});return await Vt(d),d.json()},onSuccess:(g,d)=>{if(d.type.trim().toLowerCase()==="initiative"){const w=h[d.action.trim().toLowerCase()];w&&(l(d.id,w),c(d.id,w,"status"))}n()}}),$=It({mutationFn:async g=>{const d=Array.from(new Map((g.items??[]).filter(p=>typeof(p==null?void 0:p.type)=="string"&&p.type.trim().length>0&&typeof(p==null?void 0:p.id)=="string"&&p.id.trim().length>0).map(p=>[`${p.type}:${p.id}`,p])).values());if(d.length===0)return{updated:0,failed:0,errors:[]};if(g.mode==="action"&&!g.action)throw new Error("bulk action requires an action name");const w=async p=>{try{if(g.mode==="delete"){const C=await fetch(`/orgx/api/entities/${encodeURIComponent(p.type)}/${encodeURIComponent(p.id)}/delete`,{method:"POST",headers:a,body:"{}"});return await Vt(C),{ok:!0}}if(g.mode==="update"){const C=await fetch("/orgx/api/entities",{method:"PATCH",headers:a,body:JSON.stringify({type:p.type,id:p.id,...g.updates??{}})});return await Vt(C),{ok:!0}}const j=await fetch(`/orgx/api/entities/${encodeURIComponent(p.type)}/${encodeURIComponent(p.id)}/${encodeURIComponent(g.action)}`,{method:"POST",headers:a,body:JSON.stringify({force:g.force??!1})});return await Vt(j),{ok:!0}}catch(j){return{ok:!1,error:j instanceof Error?j.message:"Unknown bulk mutation failure"}}},b=await Promise.all(d.map(p=>w(p)));let N=0,M=0;const F=[];for(const p of b)p.ok?N+=1:(M+=1,F.push(p.error));return{updated:N,failed:M,errors:F}},onSuccess:(g,d)=>{var b;const w=(d.items??[]).filter(N=>N.type.trim().toLowerCase()==="initiative");if(w.length>0){if(d.mode==="update"&&typeof((b=d.updates)==null?void 0:b.status)=="string"&&d.updates.status.trim().length>0)for(const N of w)l(N.id,d.updates.status),c(N.id,d.updates.status,Js(d.updates.status)?"delete":"status");else if(d.mode==="delete")for(const N of w)l(N.id,"archived"),c(N.id,"archived","delete");else if(d.mode==="action"&&d.action){const N=h[d.action.trim().toLowerCase()];if(N)for(const M of w)l(M.id,N),c(M.id,N,"status")}}n()}});return{createEntity:f,updateEntity:v,deleteEntity:m,entityAction:I,bulkEntityMutation:$}}const vr=r.createContext(null);function zt(){const t=r.useContext(vr);if(!t)throw new Error("useMissionControl must be used within MissionControlProvider");return t}function Aa({children:t,agentEntityMap:s,authToken:a,embedMode:n}){const[o,l]=r.useState(new Set),[c,h]=r.useState(null),[f,v]=r.useState(""),[m,I]=r.useState([]),[$,g]=r.useState("target"),[d,w]=r.useState("any"),[b,N]=r.useState(""),[M,F]=r.useState(""),[p,j]=r.useState("status"),[C,L]=r.useState("default"),z=Ea({authToken:a,embedMode:n}),ne=r.useCallback(H=>{l(pe=>{const re=new Set(pe);return re.has(H)?re.delete(H):re.add(H),re})},[]),ae=r.useCallback(H=>{l(pe=>{if(pe.has(H))return pe;const re=new Set(pe);return re.add(H),re})},[]),X=r.useCallback(H=>{l(new Set(H))},[]),P=r.useCallback(()=>{l(new Set)},[]),y=r.useCallback(H=>{h(H)},[]),W=r.useCallback(()=>{h(null)},[]),E=r.useCallback(H=>{const pe=Array.from(new Set((H??[]).map(re=>re.trim().toLowerCase()).filter(Boolean)));I(pe)},[]),Q=r.useCallback(H=>{I(pe=>{const re=H.trim().toLowerCase();return re?pe.includes(re)?pe.filter(Se=>Se!==re):[...pe,re]:pe})},[]),K=r.useCallback(()=>{v(""),I([]),g("target"),w("any"),N(""),F("")},[]),ue=b.trim().length>0||M.trim().length>0,R=d!=="any"&&(d!=="custom_range"||ue),_=m.length+(R?1:0),q=f.trim().length>0||_>0,U=r.useMemo(()=>({agentEntityMap:s,expandedInitiatives:o,modalTarget:c,searchQuery:f,statusFilters:m,dateField:$,datePreset:d,dateStart:b,dateEnd:M,activeFilterCount:_,hasActiveFilters:q,groupBy:p,sortBy:C,authToken:a,embedMode:n,mutations:z,toggleExpanded:ne,expandInitiative:ae,expandAll:X,collapseAll:P,openModal:y,closeModal:W,setSearchQuery:v,setStatusFilters:E,toggleStatusFilter:Q,setDateField:g,setDatePreset:w,setDateStart:N,setDateEnd:F,setGroupBy:j,setSortBy:L,clearFilters:K}),[s,o,c,f,m,$,d,b,M,_,q,p,C,a,n,z,ne,ae,X,P,y,W,E,Q,g,w,N,F,j,L,K]);return e.jsx(vr.Provider,{value:U,children:t})}function Ma(t){if(typeof t!="number"||!Number.isFinite(t))return;const s=Math.max(0,Math.trunc(t));return s>0?s-1:s}function Da(t){return t==="workstream"?"W":t==="milestone"?"M":t==="task"?"T":"I"}function Ys(t){return{initiative:{id:t,title:"Initiative",status:"active",summary:null,assignedAgents:[]},nodes:[],edges:[],recentTodos:[]}}function Ta(t){const s=new Date().toISOString(),a=t==="init-2"?"Black Friday Email":"Q4 Feature Ship",n=`${t}:ws:design`,o=`${t}:ms:polish`,l=`${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:o,type:"milestone",title:"Polish pass",status:"active",parentId:n,initiativeId:t,workstreamId:n,milestoneId:o,priorityNum:1,priorityLabel:"P1",dependencyIds:[n],dueDate:null,etaEndAt:null,expectedDurationHours:4,expectedBudgetUsd:900,assignedAgents:[{id:"dana",name:"Dana",domain:"design"}],updatedAt:s},{id:l,type:"task",title:"Refine queue action ergonomics",status:"todo",parentId:o,initiativeId:t,workstreamId:n,milestoneId:o,priorityNum:1,priorityLabel:"P1",dependencyIds:[o],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:o,initiativeId:t,workstreamId:n,milestoneId:o,priorityNum:2,priorityLabel:"P2",dependencyIds:[l],dueDate:null,etaEndAt:null,expectedDurationHours:2,expectedBudgetUsd:420,assignedAgents:[{id:"mark",name:"Mark",domain:"engineering"}],updatedAt:s}],edges:[{from:n,to:o,kind:"depends_on"},{from:o,to:l,kind:"depends_on"},{from:l,to:c,kind:"depends_on"}],recentTodos:[l,c]}}function $a({initiativeId:t,authToken:s=null,embedMode:a=!1,enabled:n=!0}){var v,m;const o=fs(),l=Yr(t),c=r.useMemo(()=>Jt.missionControlGraph({initiativeId:t,authToken:s,embedMode:a}),[t,s,a]),h=Xt({queryKey:c,enabled:n&&!!t&&l,queryFn:async()=>{if(!t)throw new Error("initiativeId is required");if(o)return Ta(t);if(!l)return Ys(t);const I=new URLSearchParams({initiative_id:t}),$={};a&&($["X-Orgx-Embed"]="true"),s&&($.Authorization=`Bearer ${s}`);const g=Object.keys($).length>0?$:void 0,d=await fetch(`/orgx/api/mission-control/graph?${I.toString()}`,{headers:g});if(!d.ok){const N=await d.json().catch(()=>null),M=typeof(N==null?void 0:N.error)=="string"&&N.error||typeof(N==null?void 0:N.message)=="string"&&N.message||`Failed to fetch Mission Control graph (${d.status})`;return{...Ys(t),degraded:[M]}}const w=await d.json(),b=Array.isArray(w.nodes)?w.nodes.map(N=>{const M=N,F=Ma(M.sequenceIndex??M.sequence);if(typeof F!="number")return N;const p=typeof M.hierarchyLabel=="string"&&M.hierarchyLabel.trim().length>0;return{...M,sequenceIndex:F,hierarchyLabel:p?M.hierarchyLabel:`${Da(String(M.type??"initiative"))}${F+1}`}}):[];return{...w,nodes:b.length>0?b:w.nodes}}});return{graph:h.data??(t?Ys(t):null),isLoading:l?h.isLoading:!1,error:l?((v=h.error)==null?void 0:v.message)??null:null,degraded:l?((m=h.data)==null?void 0:m.degraded)??[]:[],refetch:h.refetch}}const La=["initiative","workstream","milestone","task"],_a={initiative:"Initiatives",workstream:"Workstreams",milestone:"Milestones",task:"Tasks"},Ba=8,Xs=30;function Pa(t){const s=t.trim().toLowerCase();return s==="blocked"?O.red:s==="done"||s==="completed"?O.teal:["in_progress","active","running","queued"].includes(s)?O.lime:"rgba(255,255,255,0.35)"}function Ra({nodes:t,edges:s,selectedNodeId:a,focusedWorkstreamId:n,onSelectNode:o}){r.useMemo(()=>new Map(t.map(p=>[p.id,p])),[t]);const l=r.useRef(null),c=r.useRef(new Map),[h,f]=r.useState([]),[v,m]=r.useState(new Set),I=r.useMemo(()=>{if(!n)return new Set(t.map(C=>C.id));const p=new Set;for(const C of t)(C.type==="initiative"||C.id===n||C.workstreamId===n)&&p.add(C.id);let j=!0;for(;j;){j=!1;for(const C of s)(p.has(C.from)||p.has(C.to))&&(!p.has(C.from)||!p.has(C.to))&&(p.add(C.from),p.add(C.to),j=!0)}return p},[n,t,s]),$=r.useMemo(()=>{var L;const j=t.filter(z=>I.has(z.id)).slice(0,Xs),C={initiative:[],workstream:[],milestone:[],task:[]};for(const z of j)(L=C[z.type])==null||L.push(z);return C},[t,I]),g=Object.values($).reduce((p,j)=>p+j.length,0),d=t.filter(p=>I.has(p.id)).length>Xs,w=r.useMemo(()=>{const p=new Set(Object.values($).flat().map(j=>j.id));return s.filter(j=>p.has(j.from)&&p.has(j.to))},[s,$]),b=r.useMemo(()=>{if(!a)return new Set;const p=new Set([a]);let j=!0;for(;j;){j=!1;for(const C of w)p.has(C.from)&&!p.has(C.to)&&(p.add(C.to),j=!0),p.has(C.to)&&!p.has(C.from)&&(p.add(C.from),j=!0)}return p},[a,w]),N=r.useCallback(()=>{const p=l.current;if(!p)return;const j=p.getBoundingClientRect(),C=[];for(const L of w){const z=c.current.get(L.from),ne=c.current.get(L.to);if(!z||!ne)continue;const ae=z.getBoundingClientRect(),X=ne.getBoundingClientRect(),P=ae.right-j.left,y=ae.top+ae.height/2-j.top,W=X.left-j.left,E=X.top+X.height/2-j.top,Q=Math.min(Math.abs(W-P)*.4,60),K=`M ${P} ${y} C ${P+Q} ${y}, ${W-Q} ${E}, ${W} ${E}`,ue=a!==null&&b.has(L.from)&&b.has(L.to);C.push({key:`${L.from}-${L.to}`,d:K,highlighted:ue})}f(C)},[w,a,b]);r.useLayoutEffect(()=>{N()},[N,$,v]),r.useEffect(()=>{const p=l.current;if(!p||typeof ResizeObserver>"u")return;const j=new ResizeObserver(()=>N());return j.observe(p),()=>j.disconnect()},[N]);const M=La.filter(p=>{var j;return(((j=$[p])==null?void 0:j.length)??0)>0});if(g===0)return 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 dependencies mapped"});const F=(p,j)=>{j?c.current.set(p,j):c.current.delete(p)};return 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:[g," nodes · ",w.length," links"]}),n&&e.jsx("span",{className:"status-pill","data-tone":"active",children:"Focused workstream"})]}),e.jsxs("div",{ref:l,className:"relative overflow-x-auto rounded-xl border border-white/[0.07] bg-black/[0.14] p-3",children:[e.jsx("svg",{className:"pointer-events-none absolute inset-0 h-full w-full",style:{zIndex:1},children:h.map(({key:p,d:j,highlighted:C})=>e.jsx("path",{d:j,fill:"none",stroke:C?O.lime:"rgba(255,255,255,0.12)",strokeWidth:C?1.5:1,strokeDasharray:C?void 0:"4 3",opacity:C?.85:.5},p))}),e.jsx("div",{className:"relative z-[2] flex gap-3",style:{minWidth:M.length*160},children:M.map(p=>{const j=$[p]??[],C=v.has(p),L=C?j:j.slice(0,Ba),z=j.length-L.length;return e.jsxs("div",{className:"flex-1 min-w-[140px]",children:[e.jsxs("div",{className:"mb-2 text-micro uppercase tracking-[0.09em] text-secondary",children:[_a[p]," (",j.length,")"]}),e.jsxs("div",{className:"space-y-1",children:[L.map(ne=>{const ae=a===ne.id,X=!ae&&b.has(ne.id);return e.jsxs("button",{ref:P=>F(ne.id,P),type:"button",onClick:()=>o(ne.id),title:ne.title,className:`flex w-full items-center gap-1.5 rounded-md border px-2 py-1 text-left transition-colors ${ae?"border-[#BFFF00]/35 bg-[#BFFF00]/12":X?"border-[#BFFF00]/20 bg-[#BFFF00]/[0.06]":"border-white/[0.06] bg-white/[0.03] hover:bg-white/[0.08]"}`,children:[e.jsx("span",{className:"h-1.5 w-1.5 flex-shrink-0 rounded-full",style:{backgroundColor:Pa(ne.status)}}),e.jsx("span",{className:"max-w-[140px] truncate text-micro text-primary",children:ne.title})]},ne.id)}),z>0&&!C&&e.jsxs("button",{type:"button",onClick:()=>m(ne=>new Set([...ne,p])),className:"w-full rounded-md px-2 py-1 text-center text-micro text-muted transition-colors hover:bg-white/[0.04] hover:text-secondary",children:["Show all (",j.length,")"]})]})]},p)})})]}),d&&e.jsxs("div",{className:"text-micro text-muted",children:["Showing ",Xs," of ",t.filter(p=>I.has(p.id)).length," nodes. Focus a workstream to narrow scope."]})]})}const qa=new Set(["completed","complete","done","resolved","success","succeeded","archived","cancelled","canceled","stopped","deleted"]);function Oa(t){return qa.has(Xr(t))}function Ke(t){return Oa(t)}function Ts(t){return Number.isFinite(t)?Math.max(0,Math.min(100,Math.round(t))):0}function Yt(t,s){return s<=0?0:Ts(t/s*100)}function ln({type:t,className:s=""}){return e.jsx(Es,{type:t,className:s,size:14})}function za({dependencies:t,allNodes:s,disabled:a=!1,onSave:n}){const[o,l]=r.useState(!1),[c,h]=r.useState(""),[f,v]=r.useState(t),m=r.useMemo(()=>new Map(s.map(d=>[d.id,d])),[s]),I=r.useMemo(()=>{const d=c.trim().toLowerCase(),w=[...s].sort((b,N)=>b.title.localeCompare(N.title));return d?w.filter(b=>b.title.toLowerCase().includes(d)||b.id.toLowerCase().includes(d)).slice(0,16):w.slice(0,16)},[s,c]),$=()=>{n(Array.from(new Set(f))),l(!1)},g=d=>{v(w=>w.includes(d)?w.filter(b=>b!==d):[...w,d])};return e.jsxs("div",{className:"relative",children:[e.jsx("button",{type:"button",disabled:a,onClick:()=>{h(""),v(t),l(d=>!d)},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"}),o&&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:d=>h(d.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(d=>{var b;const w=((b=m.get(d))==null?void 0:b.title)??d;return e.jsxs("button",{type:"button",onClick:()=>g(d),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:w,children:[e.jsx("span",{className:"max-w-[180px] truncate",children:w}),e.jsx("span",{className:"text-secondary",children:"×"})]},d)})}),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:I.length===0?e.jsx("div",{className:"px-1 text-micro text-muted",children:"No matching nodes"}):I.map(d=>{const w=f.includes(d.id);return e.jsxs("button",{type:"button",onClick:()=>g(d.id),className:`flex w-full items-center justify-between rounded-md border px-2 py-1 text-left text-micro transition-colors ${w?"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:d.title}),e.jsxs("span",{className:"block truncate text-muted",children:[d.id.slice(0,8),"…"]})]}),e.jsx("span",{className:"font-semibold",children:w?"Linked":"Link"})]},d.id)})}),e.jsxs("div",{className:"mt-2 flex items-center justify-end gap-1.5",children:[e.jsx("button",{type:"button",onClick:()=>l(!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:$,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 Ua={bottom:"Add to queue"},Wa=[{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 Qa({scope:t,size:s=12}){const a=s,n=Math.round(a*.14),o=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+o,r:n}),e.jsx("circle",{cx:c,cy:a/2,r:n}),e.jsx("circle",{cx:c,cy:a-n-o,r:n})]})}const l=n+o+1;return e.jsxs("svg",{width:a,height:a,viewBox:`0 0 ${a} ${a}`,fill:"currentColor","aria-hidden":!0,children:[e.jsx("circle",{cx:l,cy:l,r:n}),e.jsx("circle",{cx:a-l,cy:l,r:n}),e.jsx("circle",{cx:l,cy:a-l,r:n}),e.jsx("circle",{cx:a-l,cy:a-l,r:n})]})}function $s({label:t="Queue",defaultPlacement:s="bottom",size:a="sm",align:n="right",menuDirection:o="up",disabled:l=!1,busy:c=!1,className:h="",menuClassName:f="",title:v,stopPropagation:m=!1,onSelectPlacement:I}){const[$,g]=r.useState(!1),d=r.useRef(null),w=r.useRef(`queue-placement-${Math.random().toString(36).slice(2,10)}`),b=l||c,N=a==="md"?"h-8 text-caption":"h-7 text-micro",M=a==="md"?"px-3":"px-2.5",F=a==="md"?"h-8 w-8":"h-7 w-7",p=n==="left"?"left-0":"right-0",j=o==="up"?"bottom-[calc(100%+6px)]":"top-[calc(100%+6px)]";r.useEffect(()=>{if(!$)return;const L=ne=>{var X;const ae=ne.target;ae&&((X=d.current)!=null&&X.contains(ae)||g(!1))},z=ne=>{ne.key==="Escape"&&g(!1)};return document.addEventListener("mousedown",L),document.addEventListener("touchstart",L),document.addEventListener("keydown",z),()=>{document.removeEventListener("mousedown",L),document.removeEventListener("touchstart",L),document.removeEventListener("keydown",z)}},[$]);const C=(L,z,ne)=>{m&&L.stopPropagation(),g(!1),I(z,ne)};return e.jsxs("div",{ref:d,className:`relative inline-flex items-center ${h}`,children:[e.jsxs("button",{type:"button",title:v??`Queue ${s==="top"?"to top":"to end"}`,onClick:L=>C(L,s),disabled:b,className:`control-pill ${N} ${M} 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":$,"aria-controls":w.current,onClick:L=>{m&&L.stopPropagation(),!b&&g(z=>!z)},disabled:b,className:`control-pill ${F} 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 ${$?"rotate-180":""}`,"aria-hidden":!0,children:e.jsx("path",{d:"m6 9 6 6 6-6"})})}),$&&e.jsxs("div",{id:w.current,role:"menu",className:`absolute ${p} ${j} 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:[Wa.map(L=>e.jsxs("button",{type:"button",role:"menuitem",onClick:z=>C(z,"top",L.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(Qa,{scope:L.scope,size:12}),e.jsx("span",{className:"text-caption font-medium text-primary",children:L.label}),e.jsx("span",{className:"ml-auto text-micro text-tertiary",children:L.description})]},L.scope)),e.jsx("div",{className:"my-1 border-t border-strong"}),e.jsx("button",{type:"button",role:"menuitem",onClick:L=>C(L,"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:Ua.bottom})})]})]})}function Un(t){if(!t)return{label:"—",tone:"none"};const s=new Date(t);if(Number.isNaN(s.getTime()))return{label:"—",tone:"none"};const a=new Date,n=s.getTime()-a.getTime(),o=Math.round(n/(1e3*60*60*24));if(o<-1)return{label:`${Math.abs(o)}d overdue`,tone:"overdue"};if(o===-1)return{label:"Yesterday",tone:"overdue"};if(o===0)return{label:"Today",tone:"soon"};if(o===1)return{label:"Tomorrow",tone:"soon"};if(o<=7)return{label:`In ${o} days`,tone:"soon"};const l=s.toLocaleString("en-US",{month:"short"}),c=s.getDate();return{label:`${l} ${c}`,tone:"normal"}}function Wn(t){return t==="overdue"?"text-red-300/90":t==="soon"?"text-amber-200/85":""}function Ha(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"),o=String(s.getDate()).padStart(2,"0"),l=String(s.getHours()).padStart(2,"0"),c=String(s.getMinutes()).padStart(2,"0");return`${a}-${n}-${o}T${l}:${c}`}const Qn=["not_started","planned","todo","in_progress","active","blocked","done"];function Hn(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 Va(t,s){return s==="all"?!0:s==="blocked"?t==="blocked":s==="done"?t==="done":t!=="blocked"&&t!=="done"}function Ka(t){const s=Number.isFinite(t)?Math.max(1,Math.min(100,Math.round(t))):50;return s<=12?{label:"Urgent",toneClass:"font-bold text-red-200/90"}:s<=30?{label:"High",toneClass:"font-semibold text-amber-100/80"}:s<=60?{label:"Medium",toneClass:"font-medium text-secondary"}:{label:"Low",toneClass:"font-normal text-muted"}}function Ga(t,s){const a=new Map(s.map(l=>[l.id,l])),n=new Set,o=[t];for(;o.length>0;){const l=o.shift(),c=a.get(l);c&&(c.parentId&&!n.has(c.parentId)&&(n.add(c.parentId),o.push(c.parentId)),c.workstreamId&&!n.has(c.workstreamId)&&(n.add(c.workstreamId),o.push(c.workstreamId)),c.milestoneId&&!n.has(c.milestoneId)&&(n.add(c.milestoneId),o.push(c.milestoneId)))}return n}function Ja(t,s,a,n){let o=0;if(a==="title")o=t.title.localeCompare(s.title);else if(a==="status")o=_n(t.status)-_n(s.status);else if(a==="priority")o=t.priorityNum-s.priorityNum;else if(a==="eta"){const l=t.etaEndAt?Date.parse(t.etaEndAt):1/0,c=s.etaEndAt?Date.parse(s.etaEndAt):1/0;o=l-c}return n==="desc"?-o:o}function ms(t,s){return!t||t.trim().length===0?s:jt(t.trim())||s}function Ya({nodes:t,edges:s,selectedNodeId:a,highlightedNodeIds:n,editMode:o,onToggleEditMode:l,onSelectNode:c,onFocusWorkstream:h,onOpenNode:f,onUpdateNode:v,mutations:m}){const{authToken:I,embedMode:$}=zt(),g=gs({authToken:I,embedMode:$}),[d,w]=r.useState(""),[b,N]=r.useState(new Set),[M,F]=r.useState("all"),[p,j]=r.useState(!1),[C,L]=r.useState(null),[z,ne]=r.useState("asc"),[ae,X]=r.useState(new Set),[P,y]=r.useState(!1),[W,E]=r.useState(null),Q=r.useRef(null),K=r.useRef(null),ue=r.useRef(null),R=r.useRef(null),_=r.useRef(null),q=r.useRef(null),[U,H]=r.useState(!1);r.useEffect(()=>{if(!W)return;const i=W.tone==="success"?6500:9e3,k=window.setTimeout(()=>E(null),i);return()=>window.clearTimeout(k)},[W==null?void 0:W.message,W==null?void 0:W.tone]),r.useEffect(()=>{if(!W)return;const i=W.tone==="success"?6500:9e3,k=window.setTimeout(()=>E(null),i);return()=>window.clearTimeout(k)},[W==null?void 0:W.message,W==null?void 0:W.tone]);const pe=r.useMemo(()=>new Map(t.map(i=>[i.id,i])),[t]),re=r.useMemo(()=>t.map(i=>({id:i.id,title:i.title})),[t]),Se=r.useMemo(()=>{const i=new Map;for(const k of t){const D=Cs(k.status);i.set(D,(i.get(D)??0)+1)}return i},[t]),Oe=r.useMemo(()=>{let i=0,k=0,D=0;for(const ee of t){const ie=Cs(ee.status);ie==="blocked"?k+=1:ie==="done"?D+=1:i+=1}return{all:t.length,open:i,blocked:k,done:D}},[t]),He=r.useMemo(()=>{const i=d.trim().toLowerCase(),k=i.length>0,D=b.size>0;if(!k&&!D&&!(M!=="all"))return null;const ie=new Set;for(const Me of t){const pt=Cs(Me.status),me=!k||Me.title.toLowerCase().includes(i)||Me.assignedAgents.some(yt=>yt.name.toLowerCase().includes(i)),Ve=!D||b.has(pt),Fe=Va(pt,M);me&&Ve&&Fe&&ie.add(Me.id)}const Ne=new Set(ie);for(const Me of ie)for(const pt of Ga(Me,t))Ne.add(pt);return Ne},[b,t,d,M]),x=r.useMemo(()=>t.filter(i=>i.type==="workstream").sort((i,k)=>i.priorityNum-k.priorityNum||i.title.localeCompare(k.title)),[t]),Y=r.useMemo(()=>{const i=new Map;for(const k of t.filter(D=>D.type==="milestone")){const D=k.workstreamId??"unscoped",ee=i.get(D)??[];ee.push(k),i.set(D,ee)}for(const k of i.values())k.sort((D,ee)=>D.priorityNum-ee.priorityNum||D.title.localeCompare(ee.title));return i},[t]),Z=r.useMemo(()=>{const i=new Map;for(const k of t.filter(D=>D.type==="task"&&D.milestoneId)){const D=k.milestoneId??"unscoped",ee=i.get(D)??[];ee.push(k),i.set(D,ee)}for(const k of i.values())k.sort((D,ee)=>D.priorityNum-ee.priorityNum||D.title.localeCompare(ee.title));return i},[t]),ge=r.useMemo(()=>{const i=new Map;for(const k of t.filter(D=>D.type==="task"&&!D.milestoneId)){const D=k.workstreamId??"unscoped",ee=i.get(D)??[];ee.push(k),i.set(D,ee)}for(const k of i.values())k.sort((D,ee)=>D.priorityNum-ee.priorityNum||D.title.localeCompare(ee.title));return i},[t]),De=r.useMemo(()=>{const i=new Set;for(const k of x)i.add(k.id);for(const k of t.filter(D=>D.type==="milestone"))i.add(k.id);return i},[t,x]),[ze,Be]=r.useState(De);r.useEffect(()=>{Be(De)},[De]);const T=i=>C?[...i].sort((k,D)=>Ja(k,D,C,z)):i,G=r.useMemo(()=>{const i=[],k=ie=>He===null||He.has(ie);for(const ie of T(x)){if(!k(ie.id))continue;const Ne=T(Y.get(ie.id)??[]),Me=T(ge.get(ie.id)??[]),pt=Ne.length>0||Me.length>0;if(i.push({node:ie,depth:0,canCollapse:pt}),!!ze.has(ie.id)){for(const me of Ne){if(!k(me.id))continue;const Ve=T(Z.get(me.id)??[]);if(i.push({node:me,depth:1,canCollapse:Ve.length>0}),ze.has(me.id))for(const Fe of Ve)k(Fe.id)&&i.push({node:Fe,depth:2,canCollapse:!1})}for(const me of Me)k(me.id)&&i.push({node:me,depth:1,canCollapse:!1})}}const D=T(Y.get("unscoped")??[]),ee=T(ge.get("unscoped")??[]);for(const ie of D)if(k(ie.id)&&(i.push({node:ie,depth:0,canCollapse:(Z.get(ie.id)??[]).length>0}),ze.has(ie.id)))for(const Ne of T(Z.get(ie.id)??[]))k(Ne.id)&&i.push({node:Ne,depth:1,canCollapse:!1});for(const ie of ee)k(ie.id)&&i.push({node:ie,depth:0,canCollapse:!1});return i},[ge,ze,He,Y,C,z,Z,x]),oe=r.useMemo(()=>G.map(({node:i})=>i.id),[G]),{handleSelect:Ce}=wr(oe),Ie=r.useMemo(()=>new Set(oe),[oe]),Le=r.useMemo(()=>G.filter(({node:i})=>ae.has(i.id)),[G,ae]),Pe=(M!=="all"?1:0)+b.size,kt=d.trim().length>0||M!=="all"||b.size>0,Ae=Le.length,xe=G.length>0&&Ae===G.length,ye=(m==null?void 0:m.bulkEntityMutation.isPending)??!1;r.useEffect(()=>{X(i=>{if(i.size===0)return i;const k=new Set(Array.from(i).filter(D=>Ie.has(D)));return k.size===i.size?i:k})},[Ie]),r.useEffect(()=>{Q.current&&(Q.current.indeterminate=Ae>0&&!xe)},[xe,Ae]),r.useEffect(()=>{Ae===0&&P&&y(!1)},[P,Ae]),r.useEffect(()=>{if(!p)return;const i=D=>{var ie;const ee=D.target;ee&&((ie=K.current)!=null&&ie.contains(ee)||j(!1))},k=D=>{D.key==="Escape"&&j(!1)};return document.addEventListener("mousedown",i),document.addEventListener("touchstart",i),document.addEventListener("keydown",k),()=>{document.removeEventListener("mousedown",i),document.removeEventListener("touchstart",i),document.removeEventListener("keydown",k)}},[p]);const rt=i=>i.dependencyIds.length,xt=g.isPinning||g.isMoving,Ut=async i=>{await g.pin({initiativeId:i.initiativeId,workstreamId:i.workstreamId,taskId:i.taskId??null,milestoneId:i.milestoneId??null}),await g.move({initiativeId:i.initiativeId,workstreamId:i.workstreamId,placement:i.placement})},Ge=async(i,k="bottom")=>{if(i.type==="initiative"){const Me=x.filter(yt=>yt.initiativeId===i.id);if(Me.length===0){E({tone:"error",message:"Cannot queue initiative: no workstreams found."});return}const pt=k==="top"?[...Me].reverse():Me;let me=0,Ve=0,Fe=null;for(const yt of pt)try{await Ut({initiativeId:i.id,workstreamId:yt.id,placement:k}),me+=1}catch(Je){Ve+=1,Fe||(Fe=ms(Je instanceof Error?Je.message:"","Failed to add initiative workstream to queue."))}Ve>0?E({tone:me>0?"success":"error",message:me>0?`Queued ${me}/${Me.length} workstreams (${Ve} failed). ${Fe??""}`.trim():Fe??"Failed to queue initiative workstreams."}):E({tone:"success",message:`Queued ${me} workstream${me===1?"":"s"} to ${k==="top"?"top":"end"}.`}),window.setTimeout(()=>E(null),Ve>0?4200:2400);return}const D=i.initiativeId??"",ee=i.type==="workstream"?i.id:i.workstreamId??"",ie=i.type==="task"?i.id:null,Ne=i.type==="milestone"?i.id:null;if(!D||!ee){E({tone:"error",message:"Cannot add to queue: missing initiative/workstream id."});return}try{await Ut({initiativeId:D,workstreamId:ee,taskId:ie,milestoneId:Ne,placement:k}),E({tone:"success",message:i.type==="task"?`Queued task workstream to ${k==="top"?"top":"end"}.`:i.type==="milestone"?`Queued milestone workstream to ${k==="top"?"top":"end"}.`:`Queued workstream to ${k==="top"?"top":"end"}.`}),window.setTimeout(()=>E(null),2e3)}catch(Me){E({tone:"error",message:ms(Me instanceof Error?Me.message:"","Failed to add workstream to queue.")}),window.setTimeout(()=>E(null),2400)}},Ze=i=>{if(i.type==="workstream")return i.id;if(i.type==="milestone"||i.type==="task")return i.workstreamId??null;if(i.type==="initiative"){const k=x.filter(ee=>ee.initiativeId===i.id);if(k.length===0)return null;const D=k.find(ee=>!Ke(ee.status))??k[0];return(D==null?void 0:D.id)??null}return null},Tt=async(i,k)=>{const D=i.type==="initiative"?i.id:i.initiativeId??"",ee=k??(i.type==="workstream"?i.id:i.workstreamId??"");if(!D||!ee){E({tone:"error",message:"Cannot start now: missing initiative/workstream id."});return}try{const ie=await fetch("/orgx/api/mission-control/next-up/play",{method:"POST",headers:ft({authToken:I,embedMode:$,contentTypeJson:!0}),body:JSON.stringify({initiativeId:D,workstreamId:ee,fastAck:!0,ignoreSpawnGuardRateLimit:!0})}),Ne=await ie.json().catch(()=>null);if(!ie.ok)throw new Error((Ne==null?void 0:Ne.error)??(Ne==null?void 0:Ne.message)??`Failed to start workstream (${ie.status})`);E({tone:"success",message:`Started ${i.title}.`}),window.setTimeout(()=>E(null),1800)}catch(ie){E({tone:"error",message:ms(ie instanceof Error?ie.message:"","Failed to start workstream now.")}),window.setTimeout(()=>E(null),2400)}},$t=r.useMemo(()=>{const i=new Map,k=(D,ee)=>{if(D.length>0){const ie=D.filter(Ne=>Ke(Ne.status)).length;return Yt(ie,D.length)}return Ke(ee)?100:0};for(const D of t.filter(ee=>ee.type==="milestone")){const ee=Z.get(D.id)??[];i.set(D.id,k(ee,D.status))}for(const D of x){const ie=(Y.get(D.id)??[]).flatMap(Me=>Z.get(Me.id)??[]),Ne=ge.get(D.id)??[];i.set(D.id,k([...Ne,...ie],D.status))}return i},[ge,Y,t,Z,x]),dt=r.useMemo(()=>{if(G.length===0)return null;const i=G.filter(({node:ee})=>ee.assignedAgents.length>0);if(i.length===0)return null;const k=i[0].node.assignedAgents.map(ee=>ee.id).sort().join(",");return!i.every(({node:ee})=>ee.assignedAgents.map(ie=>ie.id).sort().join(",")===k)||i.length<G.length*.7?null:i[0].node.assignedAgents},[G]),ht=dt!==null&&!o,ut=i=>{C===i?ne(k=>k==="asc"?"desc":"asc"):(L(i),ne("asc"))},mt=i=>{N(k=>{const D=new Set(k);return D.has(i)?D.delete(i):D.add(i),D})},Ue=()=>{w(""),F("all"),N(new Set)},et=(i,k,D)=>{E(null),y(!1),Ce(i,k,D,X)},gt=()=>{E(null),y(!1),X(()=>G.length===0||xe?new Set:new Set(oe))},bt=()=>{y(!1),X(new Set)},We=async i=>{if(!(!m||Le.length===0)){y(!1),E(null);try{const k=await m.bulkEntityMutation.mutateAsync({items:Le.map(({node:D})=>({type:D.type,id:D.id})),mode:"update",updates:{status:i}});k.failed>0?E({tone:"error",message:`Updated ${k.updated}, failed ${k.failed}.`}):E({tone:"success",message:`Updated ${k.updated} item${k.updated===1?"":"s"} to ${qe(i)}.`})}catch(k){E({tone:"error",message:ms(k instanceof Error?k.message:"","Bulk status update failed.")})}}},Zt=async()=>{if(!(!m||Le.length===0)){E(null);try{const i=await m.bulkEntityMutation.mutateAsync({items:Le.map(({node:k})=>({type:k.type,id:k.id})),mode:"delete"});i.failed>0?E({tone:"error",message:`Deleted ${i.updated}, failed ${i.failed}.`}):(E({tone:"success",message:`Deleted ${i.updated} item${i.updated===1?"":"s"}.`}),X(new Set),y(!1))}catch(i){E({tone:"error",message:ms(i instanceof Error?i.message:"","Bulk delete failed.")})}}},at=({field:i})=>C!==i?e.jsx("span",{className:"text-faint ml-0.5",children:"↕"}):e.jsx("span",{className:"text-[#BFFF00] ml-0.5",children:z==="asc"?"↑":"↓"}),Et=U?"0px":"calc(var(--mc-toolbar-offset, 0px) + 12px)",Wt=i=>{if(q.current==="body"){q.current=null;return}const k=i.currentTarget.scrollLeft,D=R.current;!D||D.scrollLeft===k||(q.current="header",D.scrollLeft=k)},Nt=i=>{if(q.current==="header"){q.current=null;return}const k=i.currentTarget.scrollLeft,D=ue.current;!D||D.scrollLeft===k||(q.current="body",D.scrollLeft=k)};r.useEffect(()=>{const i=R.current,k=ue.current;!i||!k||k.scrollLeft!==i.scrollLeft&&(k.scrollLeft=i.scrollLeft)},[G.length]),r.useEffect(()=>{if(typeof window>"u")return;const i=_.current;if(!i)return;const k=()=>{const ee=Math.min(window.innerHeight*.62,560),ie=i.scrollHeight;H(ie>ee+1)};k();const D=typeof ResizeObserver<"u"?new ResizeObserver(()=>k()):null;return D==null||D.observe(i),window.addEventListener("resize",k),()=>{D==null||D.disconnect(),window.removeEventListener("resize",k)}},[G.length]);const Lt=()=>o?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}})]}):e.jsxs("colgroup",{children:[e.jsx("col",{style:{width:40}}),e.jsx("col",{})," ",!ht&&e.jsx("col",{style:{width:72}}),e.jsx("col",{style:{width:160}})," ",e.jsx("col",{style:{width:80}})," ",e.jsx("col",{style:{width:120}})," "]});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(hn,{value:d,onChange:w,placeholder:"Search items or agents..."})}),e.jsxs("div",{className:"flex min-h-[40px] min-w-0 flex-wrap items-center gap-2.5",children:[l&&e.jsxs("button",{type:"button",onClick:l,"data-state":o?"active":"idle",className:`control-pill inline-flex h-8 items-center gap-1.5 px-3.5 text-caption font-semibold ${o?"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"})}),o?"Editing":"Edit"]}),e.jsxs("div",{ref:K,className:"relative",children:[e.jsxs("button",{type:"button",onClick:()=>j(i=>!i),"data-state":p||Pe>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"}),Pe>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:Pe})]}),e.jsx(lt,{children:p&&e.jsxs(de.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:Oe.all},{id:"open",label:"Open",count:Oe.open},{id:"blocked",label:"Blocked",count:Oe.blocked},{id:"done",label:"Done",count:Oe.done}].map(i=>{const k=M===i.id;return e.jsxs("button",{type:"button",onClick:()=>F(i.id),className:`inline-flex h-7 items-center gap-1.5 rounded-full border px-2.5 text-micro font-semibold transition-colors ${k?"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:Qn.map(i=>{const k=b.has(i),D=Se.get(i)??0;return e.jsxs("button",{type:"button",onClick:()=>mt(i),className:`inline-flex h-7 items-center gap-1 rounded-full border px-2.5 text-micro transition-colors ${k?"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:qe(i)}),e.jsx("span",{className:"text-micro text-current/75",children:D})]},i)})})]}),(M!=="all"||b.size>0)&&e.jsx("button",{type:"button",onClick:()=>{F("all"),N(new Set)},className:"text-micro text-secondary transition-colors hover:text-primary",children:"Reset filters"})]})})]}),e.jsx(lt,{initial:!1,children:kt&&e.jsx(de.button,{type:"button",onClick:Ue,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:gt,"data-state":xe?"active":"idle",className:"control-pill inline-flex h-8 items-center gap-1.5 px-3.5 text-caption font-semibold",children:xe?"Clear all":"Select all"})]})]}),e.jsx("div",{className:"mb-1.5",children:e.jsx("div",{className:`rounded-xl border px-3 ${Ae>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:Q,type:"checkbox",checked:xe,onChange:gt,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:Ae>0?`${Ae} selected`:`${G.length} visible`}),Ae>0&&e.jsxs("div",{className:"flex flex-shrink-0 items-center gap-2 whitespace-nowrap",children:[e.jsx("button",{type:"button",onClick:()=>{We("planned")},disabled:ye,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:()=>{We("in_progress")},disabled:ye,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:()=>{We("blocked")},disabled:ye,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:()=>{We("done")},disabled:ye,className:"control-pill h-8 flex-shrink-0 px-3 text-caption font-semibold disabled:opacity-45",children:"Complete"}),P?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:()=>{Zt()},disabled:ye,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:()=>y(!1),disabled:ye,className:"control-pill h-8 flex-shrink-0 px-2.5 text-caption disabled:opacity-45",children:"Keep"})]}):e.jsx("button",{type:"button",onClick:()=>y(!0),disabled:ye,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:bt,disabled:ye,className:"text-caption text-secondary transition-colors hover:text-primary disabled:opacity-45",children:"Clear"})]})]})})}),W&&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 ${W.tone==="success"?"bg-emerald-300/90":"bg-amber-300/90"}`}),e.jsx("span",{className:"min-w-0 leading-snug",children:W.message})]}),e.jsx("button",{type:"button",onClick:()=>E(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"})]})})]})}),o&&e.jsx("div",{className:"mb-2 text-micro text-secondary",children:"Edit mode: select a row to edit its fields inline."}),dt&&!o&&e.jsxs("div",{className:"mb-2 flex items-center gap-2 rounded-lg border border-white/[0.06] bg-white/[0.02] px-3 py-1.5",children:[e.jsx("div",{className:"flex items-center -space-x-1.5",children:dt.slice(0,2).map(i=>e.jsx("div",{className:"rounded-full ring-1 ring-[#02040A]",children:e.jsx(an,{name:i.name,hint:i.id,size:"xs"})},i.id))}),e.jsxs("span",{className:"text-caption text-secondary",children:["Assigned to ",dt.map(i=>i.name).join(", ")]})]}),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:_,"data-hierarchy-table-viewport":!0,className:`${U?"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:Et},children:e.jsx("div",{ref:ue,onScroll:Wt,className:"overflow-x-auto overflow-y-hidden [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",children:e.jsxs("table",{className:`w-full table-fixed border-separate border-spacing-y-0 ${o?"min-w-[1464px]":""}`,children:[Lt(),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:()=>ut("title"),children:["Item ",e.jsx(at,{field:"title"})]}),o?e.jsxs(e.Fragment,{children:[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:()=>ut("status"),children:["Status ",e.jsx(at,{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:()=>ut("priority"),children:["Priority ",e.jsx(at,{field:"priority"})]}),e.jsxs("th",{className:"px-2 py-1.5 cursor-pointer select-none",onClick:()=>ut("eta"),children:["ETA ",e.jsx(at,{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.jsxs(e.Fragment,{children:[!ht&&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:()=>ut("status"),children:["Status ",e.jsx(at,{field:"status"})]}),e.jsxs("th",{className:"px-2 py-1.5 cursor-pointer select-none",onClick:()=>ut("priority"),children:["Priority ",e.jsx(at,{field:"priority"})]}),e.jsxs("th",{className:"px-2 py-1.5 cursor-pointer select-none",onClick:()=>ut("eta"),children:["ETA ",e.jsx(at,{field:"eta"})]})]})]})})]})})}),e.jsx("div",{ref:R,onScroll:Nt,className:"overflow-x-auto",children:e.jsxs("table",{className:`w-full table-fixed border-separate border-spacing-y-1.5 ${o?"min-w-[1464px]":""}`,children:[Lt(),e.jsx("tbody",{children:G.map(({node:i,depth:k,canCollapse:D})=>{const ee=a===i.id,ie=n.has(i.id),Ne=ae.has(i.id),Me=i.assignedAgents.map(J=>J.name).join(", "),pt=i.dependencyIds.map(J=>{var je;return((je=pe.get(J))==null?void 0:je.title)??J}).slice(0,3).join(", "),me=$t.get(i.id),Ve=Ka(i.priorityNum),Fe=o&&ee,yt=i.type==="initiative"||i.type==="workstream"||i.type==="milestone"||i.type==="task",Je=Ze(i),_t=!!Je;return e.jsxs("tr",{onClick:()=>{c(i.id),i.type==="workstream"&&h(i.id)},className:`group/row cursor-pointer rounded-lg border transition-colors ${ee?"border-[#BFFF00]/[0.22] bg-[#BFFF00]/[0.08]":ie?"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:Ne,onChange:J=>{J.stopPropagation();const je=J.nativeEvent.shiftKey??!1;et(i.id,J.currentTarget.checked,je)},onClick:J=>J.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:k*14}}),D?e.jsx("button",{type:"button",onClick:J=>{J.stopPropagation(),Be(je=>{const it=new Set(je);return it.has(i.id)?it.delete(i.id):it.add(i.id),it})},"aria-label":`${ze.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:ze.has(i.id)?"▾":"▸"}):e.jsx("span",{className:"w-2.5"}),e.jsx(ln,{type:i.type}),e.jsx("button",{type:"button",onClick:J=>{J.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})]}),!o&&!Ke(i.status)&&e.jsxs("div",{className:"ml-1 grid w-[168px] min-w-[168px] grid-cols-[124px_34px] items-center justify-end gap-2 opacity-0 translate-x-1 transition-all duration-150 group-hover/row:opacity-100 group-hover/row:translate-x-0 group-focus-within/row:opacity-100 group-focus-within/row:translate-x-0 touch-device:opacity-60 touch-device:translate-x-0",children:[yt?e.jsx($s,{label:"Queue",size:"sm",busy:xt,stopPropagation:!0,title:`Queue ${i.type}: ${i.title}`,onSelectPlacement:J=>Ge(i,J)}):e.jsx("span",{className:"h-7 w-[124px]"}),e.jsx("button",{type:"button",disabled:!_t,title:_t?"Start":"No runnable workstream",onClick:J=>{J.stopPropagation(),Je&&Tt(i,Je)},"aria-label":_t?`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"})})})]})]})}),!ht&&e.jsx("td",{className:"px-2 py-1.5 text-caption text-primary whitespace-nowrap",children:Fe?e.jsx("input",{type:"text",defaultValue:Me,placeholder:"Agent A, Agent B",onClick:J=>J.stopPropagation(),onBlur:J=>{const je=J.currentTarget.value.split(",").map(it=>it.trim()).filter(Boolean);v(i,{assigned_agent_names:je,assigned_agent_ids:je.map(it=>`name:${it}`),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.jsx("div",{className:"flex items-center -space-x-1.5",title:Me,children:i.assignedAgents.slice(0,3).map(J=>e.jsx("div",{title:J.name,className:"rounded-full ring-1 ring-[#02040A]",children:e.jsx(an,{name:J.name,hint:`${J.id} ${i.title}`,size:"xs"})},`${i.id}:${J.id}`))}):e.jsx("span",{className:"text-muted",children:"—"})})}),o?e.jsxs(e.Fragment,{children:[e.jsx("td",{className:"px-2 py-1.5 text-caption text-primary",children:Fe?e.jsx("select",{defaultValue:Cs(i.status),onClick:J=>J.stopPropagation(),onChange:J=>{v(i,{status:J.target.value})},className:"rounded border border-strong bg-white/[0.06] px-2 py-1 text-micro text-white/82",children:Qn.map(J=>e.jsx("option",{value:J,children:qe(J)},J))}):e.jsx("span",{className:"status-pill whitespace-nowrap","data-tone":Hn(i.status),children:qe(i.status)})}),e.jsx("td",{className:"px-2 py-1.5 text-caption text-primary",children:me!==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:`${me}%`,backgroundColor:i.type==="milestone"?O.teal:O.lime}})}),e.jsxs("span",{className:"text-micro text-secondary",style:{fontVariantNumeric:"tabular-nums"},children:[me,"%"]})]}):e.jsx("span",{className:"text-muted",children:"—"})}),e.jsx("td",{className:"px-2 py-1.5 text-caption text-primary",children:Fe?e.jsx("input",{type:"number",min:1,max:100,defaultValue:i.priorityNum,onClick:J=>J.stopPropagation(),onBlur:J=>{const je=Number(J.currentTarget.value);Number.isFinite(je)&&v(i,{priority_num:je})},className:"w-[72px] rounded border border-strong bg-white/[0.06] px-2 py-1 text-micro text-white/82"}):e.jsx("span",{className:`text-micro tracking-[0.02em] ${Ve.toneClass}`,children:Ve.label})}),e.jsx("td",{className:"px-2 py-1.5 text-caption text-primary",children:Fe?e.jsx("input",{type:"datetime-local",defaultValue:Ha(i.etaEndAt),onClick:J=>J.stopPropagation(),onBlur:J=>{const je=J.currentTarget.value;v(i,{eta_end_at:je?new Date(je).toISOString():null})},className:"w-[176px] rounded border border-strong bg-white/[0.06] px-2 py-1 text-micro text-white/82"}):(()=>{const J=Un(i.etaEndAt);return e.jsx("span",{className:Wn(J.tone),title:i.etaEndAt?new Date(i.etaEndAt).toLocaleString():void 0,children:J.label})})()}),e.jsx("td",{className:"px-2 py-1.5 text-caption text-primary",children:Fe&&i.type!=="task"?e.jsx("input",{type:"number",min:0,step:.5,defaultValue:i.expectedDurationHours,onClick:J=>J.stopPropagation(),onBlur:J=>{const je=Number(J.currentTarget.value);Number.isFinite(je)&&v(i,{expected_duration_hours:je})},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:Fe&&i.type!=="task"?e.jsx("input",{type:"number",min:0,step:1,defaultValue:i.expectedBudgetUsd,onClick:J=>J.stopPropagation(),onBlur:J=>{const je=Number(J.currentTarget.value);Number.isFinite(je)&&v(i,{expected_budget_usd:je})},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()]})}),e.jsx("td",{className:"rounded-r-lg px-2 py-1.5 text-caption text-primary",children:Fe?e.jsx("div",{onClick:J=>J.stopPropagation(),children:e.jsx(za,{dependencies:i.dependencyIds,allNodes:re,onSave:J=>void v(i,{depends_on:J})})}):e.jsx("div",{className:"max-w-[250px] truncate",children:rt(i)>0?`${rt(i)} · ${pt}`:"—"})})]}):e.jsxs(e.Fragment,{children:[e.jsx("td",{className:"px-2 py-1.5 text-caption text-primary",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"status-pill whitespace-nowrap","data-tone":Hn(i.status),children:qe(i.status)}),me!==void 0&&(i.type==="workstream"||i.type==="milestone")&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:"h-1 w-[40px] rounded-full bg-white/[0.06] overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${me}%`,backgroundColor:i.type==="milestone"?O.teal:O.lime}})}),e.jsxs("span",{className:"text-micro text-secondary",style:{fontVariantNumeric:"tabular-nums"},children:[me,"%"]})]})]})}),e.jsx("td",{className:"px-2 py-1.5 text-caption text-primary",children:e.jsx("span",{className:`text-micro tracking-[0.02em] ${Ve.toneClass}`,children:Ve.label})}),e.jsx("td",{className:"rounded-r-lg px-2 py-1.5 text-caption text-primary",children:(()=>{const J=Un(i.etaEndAt);return e.jsx("span",{className:Wn(J.tone),title:i.etaEndAt?new Date(i.etaEndAt).toLocaleString():void 0,children:J.label})})()})]})]},i.id)})})]})})]})}),G.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:d||b.size>0||M!=="all"?"No items match the current filters":"No work items yet"}),e.jsx("div",{className:"mt-1 text-caption text-muted",children:d||b.size>0||M!=="all"?"Try adjusting your search or filter criteria.":"Workstreams, milestones, and tasks will appear here."})]})]})}function Xa(t){if(!t)return{label:"—",tone:"none"};const s=new Date(t);if(Number.isNaN(s.getTime()))return{label:"—",tone:"none"};const a=new Date,n=s.getTime()-a.getTime(),o=Math.round(n/(1e3*60*60*24));if(o<-1)return{label:`${Math.abs(o)}d overdue`,tone:"overdue"};if(o===-1)return{label:"Yesterday",tone:"overdue"};if(o===0)return{label:"Today",tone:"soon"};if(o===1)return{label:"Tomorrow",tone:"soon"};if(o<=7)return{label:`In ${o} days`,tone:"soon"};const l=s.toLocaleString("en-US",{month:"short"}),c=s.getDate();return{label:`${l} ${c}`,tone:"normal"}}function Vn(t){if(!t)return{label:"No target date",tone:"none"};const s=Xa(t);return s.tone==="none"?{label:"No target date",tone:"none"}:s}function Is(t){if(!t)return!1;const s=new Date(t);return Number.isNaN(s.getTime())?!1:s.getTime()<Date.now()}function Kn(t){return t==="milestone"?"Milestone":t==="workstream"?"Workstream":"Task"}const Za=5;function ei({recentTodoIds:t,nodesById:s,selectedNodeId:a,onSelectNode:n}){const[o,l]=r.useState(!1),c=t.map(g=>s.get(g)).filter(g=>!!g).sort((g,d)=>{const w=Is(g.dueDate),b=Is(d.dueDate);if(w!==b)return w?-1:1;if(g.priorityNum!==d.priorityNum)return g.priorityNum-d.priorityNum;const N=g.dueDate?Date.parse(g.dueDate):Number.POSITIVE_INFINITY,M=d.dueDate?Date.parse(d.dueDate):Number.POSITIVE_INFINITY;return N-M}).slice(0,14);if(c.length===0)return null;const h=c[0],f=Vn(h.dueDate),v=Is(h.dueDate),m=c.slice(1),I=o?m:m.slice(0,Za-1),$=m.length-I.length;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:[c.length," in queue"]})]}),e.jsx("button",{type:"button",onClick:()=>n(h.id),className:`surface-hero group w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${v?"border-l-2 border-l-red-400/60 ":""}${a===h.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(ln,{type:h.type}),e.jsx("span",{children:Kn(h.type)})]}),e.jsx("p",{className:"mt-1 line-clamp-2 text-body font-semibold leading-snug text-white",children:h.title}),e.jsx("p",{className:`mt-1 text-caption ${f.tone==="overdue"?"text-red-300/90":f.tone==="soon"?"text-amber-200/85":"text-secondary"}`,children:f.label})]}),h.priorityNum<=30&&e.jsx("span",{className:`inline-flex flex-shrink-0 text-micro tracking-[0.02em] ${h.priorityNum<=12?"font-bold text-red-200/90":"font-semibold text-amber-100/80"}`,children:h.priorityNum<=12?"Urgent":"High"})]})}),I.length>0&&e.jsxs("div",{className:"space-y-1.5",children:[I.map(g=>{const d=Vn(g.dueDate),w=Is(g.dueDate);return e.jsxs("button",{type:"button",onClick:()=>n(g.id),className:`flex min-h-[54px] min-w-0 items-start justify-between gap-2 rounded-lg border px-2.5 py-2 text-left transition-colors ${w?"border-l-2 border-l-red-400/60 ":""}${a===g.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(ln,{type:g.type}),e.jsx("span",{children:Kn(g.type)})]}),e.jsx("p",{className:"mt-1 line-clamp-1 break-words text-caption leading-snug text-bright",title:g.title,children:g.title}),e.jsx("p",{className:`mt-1 text-micro ${d.tone==="overdue"?"text-red-300/90":d.tone==="soon"?"text-amber-200/85":"text-secondary"}`,children:d.label})]}),g.priorityNum<=30&&e.jsx("span",{className:`inline-flex flex-shrink-0 text-micro tracking-[0.02em] ${g.priorityNum<=12?"font-bold text-red-200/90":"font-semibold text-amber-100/80"}`,children:g.priorityNum<=12?"Urgent":"High"})]},g.id)}),$>0&&!o&&e.jsxs("button",{type:"button",onClick:()=>l(!0),className:"w-full rounded-lg px-2.5 py-1.5 text-center text-micro text-secondary transition-colors hover:bg-white/[0.04] hover:text-primary",children:["View all (",m.length+1,")"]})]})]})}function ti(t,s){try{const a=localStorage.getItem(`orgx.section.${t}`);if(a==="0")return!1;if(a==="1")return!0}catch{}return s}function si(t,s){try{localStorage.setItem(`orgx.section.${t}`,s?"1":"0")}catch{}}function Zs({title:t,defaultOpen:s=!0,storageKey:a,sticky:n=!1,stickyOffsetClass:o="top-0",stickyTop:l,contentOverflowVisible:c=!1,badge:h,children:f}){const[v,m]=r.useState(()=>a?ti(a,s):s),[I,$]=r.useState(!1),g=r.useRef(null),[d,w]=r.useState(40),b=()=>{const N=!v;m(N),a&&si(a,N)};return r.useEffect(()=>{if(!n)return;const N=g.current;if(!N)return;const M=()=>{const p=Math.max(34,N.offsetHeight);w(j=>j===p?j:p)};if(M(),typeof ResizeObserver>"u")return;const F=new ResizeObserver(()=>M());return F.observe(N),()=>F.disconnect()},[n,l,t]),e.jsxs("div",{style:n?{"--mc-collapsible-header-offset":`${d}px`}:void 0,children:[e.jsxs("button",{ref:n?g: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 ${o} 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&&l?{top:l}: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 ${v?"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}),h&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-micro text-white/45",children:"·"}),e.jsx("span",{className:`text-micro ${h.tone==="error"?"text-red-200/80":h.tone==="warning"?"text-amber-200/80":"text-secondary"}`,children:h.label}),h.action&&e.jsx("span",{role:"button",tabIndex:0,onClick:N=>{N.stopPropagation(),h.action.onClick()},onKeyDown:N=>{(N.key==="Enter"||N.key===" ")&&(N.stopPropagation(),N.preventDefault(),h.action.onClick())},className:`text-micro font-semibold text-[#D8FFA1] transition-colors hover:text-white ${h.action.busy?"pointer-events-none opacity-45":"cursor-pointer"}`,children:h.action.busy?"Fixing…":h.action.label})]})]}),e.jsx(lt,{initial:!1,children:v&&e.jsx(de.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{type:"spring",stiffness:400,damping:35},onAnimationStart:()=>$(!0),onAnimationComplete:()=>$(!1),className:c&&!I?"overflow-visible":"overflow-hidden",children:f})})]})}function ni(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 ri(t){const s=t.toLowerCase();return["todo","not_started","planned","pending","backlog"].includes(s)}function ai(t){const s=t.toLowerCase();return["in_progress","active","running","queued"].includes(s)}function ii(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},o=(s.workstreams.length>0?s.workstreams:(t.workstreams??[]).map(m=>({id:m.id,name:m.name,summary:null,status:m.status,progress:null,initiativeId:t.id,createdAt:null}))).map(m=>({id:m.id,type:"workstream",title:m.name,status:m.status,parentId:t.id,initiativeId:t.id,workstreamId:m.id,milestoneId:null,priorityNum:50,priorityLabel:"medium",dependencyIds:[],dueDate:null,etaEndAt:null,expectedDurationHours:16,expectedBudgetUsd:300,assignedAgents:[],updatedAt:m.createdAt,sequenceIndex:typeof m.sequenceIndex=="number"?m.sequenceIndex??void 0:void 0,hierarchyLabel:typeof m.hierarchyLabel=="string"?m.hierarchyLabel??void 0:void 0})),l=new Set(o.map(m=>m.id)),c=s.milestones.map(m=>({id:m.id,type:"milestone",title:m.title,status:m.status,parentId:m.workstreamId&&l.has(m.workstreamId)?m.workstreamId:t.id,initiativeId:t.id,workstreamId:m.workstreamId&&l.has(m.workstreamId)?m.workstreamId:null,milestoneId:m.id,priorityNum:50,priorityLabel:"medium",dependencyIds:[],dueDate:m.dueDate,etaEndAt:m.dueDate,expectedDurationHours:6,expectedBudgetUsd:120,assignedAgents:[],updatedAt:m.createdAt,sequenceIndex:m.sequenceIndex,hierarchyLabel:m.hierarchyLabel})),h=new Set(c.map(m=>m.id)),f=s.tasks.map(m=>{const I=ni(m.priority),$=m.milestoneId&&h.has(m.milestoneId),g=m.workstreamId&&l.has(m.workstreamId);return{id:m.id,type:"task",title:m.title,status:m.status,parentId:$?m.milestoneId:g?m.workstreamId:t.id,initiativeId:t.id,workstreamId:g?m.workstreamId:null,milestoneId:$?m.milestoneId:null,priorityNum:I.priorityNum,priorityLabel:I.priorityLabel,dependencyIds:[],dueDate:m.dueDate,etaEndAt:m.dueDate,expectedDurationHours:2,expectedBudgetUsd:40,assignedAgents:[],updatedAt:m.createdAt,sequenceIndex:m.sequenceIndex,hierarchyLabel:m.hierarchyLabel}}),v=f.filter(m=>["todo","not_started","planned","pending","backlog"].includes(m.status.toLowerCase())).sort((m,I)=>{const $=m.priorityNum-I.priorityNum;if($!==0)return $;const g=m.etaEndAt?Date.parse(m.etaEndAt):1/0,d=I.etaEndAt?Date.parse(I.etaEndAt):1/0;if(g!==d)return g-d;const w=m.updatedAt?Date.parse(m.updatedAt):0;return(I.updatedAt?Date.parse(I.updatedAt):0)-w}).map(m=>m.id);return{nodes:[a,...o,...c,...f],edges:[],recentTodos:v}}function oi(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 o=new Set,l=[t];for(;l.length>0;){const c=l.shift();if(o.has(c))continue;o.add(c);const h=a.get(c);if(h){for(const f of h.dependencyIds)o.has(f)||l.push(f);for(const f of n.get(c)??[])o.has(f)||l.push(f)}}return o}function li(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 ci(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 di(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 Fs={hidden:{opacity:0},show:{opacity:1}};function ui({initiative:t,selected:s=!1,onSelectionChange:a,isSquished:n=!1,runtimeActivity:o=null}){var es;const{expandedInitiatives:l,toggleExpanded:c,openModal:h,agentEntityMap:f,authToken:v,embedMode:m,mutations:I}=zt(),[$,g]=r.useState(!1),[d,w]=r.useState(null),[b,N]=r.useState(null),[M,F]=r.useState(!1),[p,j]=r.useState(!1),[C,L]=r.useState(null),[z,ne]=r.useState(!1),ae=r.useRef(null),[X,P]=r.useState(52),[y,W]=r.useState(0),E=l.has(t.id),{graph:Q,isLoading:K,degraded:ue,error:R,refetch:_}=$a({initiativeId:t.id,authToken:v,embedMode:m}),{details:q,isLoading:U,error:H}=bs({initiativeId:t.id,authToken:v,embedMode:m}),pe=gs({authToken:v,embedMode:m}),re=r.useMemo(()=>ii(t,q),[t,q]),Se=!!(Q&&Q.nodes.length>0),Oe=re.nodes.length>0,He=!Se&&Oe,x=He?re.nodes:Se?(Q==null?void 0:Q.nodes)??[]:re.nodes,Y=He?re.edges:Se?(Q==null?void 0:Q.edges)??[]:re.edges,Z=He?re.recentTodos:Se?(Q==null?void 0:Q.recentTodos)??[]:re.recentTodos,ge=ue.some(S=>/401|unauthorized/i.test(S))||!!(R&&/401|unauthorized/i.test(R))||!!(H&&/401|unauthorized/i.test(H)),De=R&&/unknown api endpoint/i.test(R)?"Graph API unavailable. Showing session-derived data.":R,ze=H,Be=[...ue,...De?[De]:[],...ze?[`Entity data partially unavailable: ${ze}`]:[],...ge?["OrgX auth is missing or expired in this local plugin instance. Reconnect in onboarding to load full workstreams/milestones/tasks."]:[]],T=Be.filter(S=>/cyclic dependency edge/i.test(S)),G=T.reduce((S,te)=>{const _e=/detected\s+(\d+)\s+cyclic dependency edge/i.exec(te);return S+(_e&&Number(_e[1])||0)},0),oe=T.length>0,Ce=async()=>{if(!z){ne(!0);try{const S=await fetch("/orgx/api/mission-control/graph/cycles/auto-fix",{method:"POST",headers:ft({authToken:v,embedMode:m,contentTypeJson:!0}),body:JSON.stringify({initiativeId:t.id})}),te=await S.json().catch(()=>null);if(!S.ok)throw new Error((te==null?void 0:te.error)??(te==null?void 0:te.message)??`Failed to auto-fix dependency cycles (${S.status})`);const _e=typeof(te==null?void 0:te.cycleEdgesDetected)=="number"?te.cycleEdgesDetected:G,Qe=typeof(te==null?void 0:te.nodesUpdated)=="number"?te.nodesUpdated:0,Ye=typeof(te==null?void 0:te.nodesFailed)=="number"?te.nodesFailed:0;L({tone:Ye>0?"error":"success",message:Ye>0?`Auto-fix removed ${_e} cyclic edge${_e===1?"":"s"} and updated ${Qe} nodes (${Ye} failed).`:`Auto-fix removed ${_e} cyclic edge${_e===1?"":"s"} and updated ${Qe} nodes.`}),_()}catch(S){L({tone:"error",message:S instanceof Error?S.message:"Failed to auto-fix dependency cycles."})}finally{ne(!1)}}},Ie=r.useMemo(()=>new Map(x.map(S=>[S.id,S])),[x]),Le=r.useMemo(()=>oi(d,x),[d,x]),Pe=r.useMemo(()=>Z.some(S=>Ie.has(S)),[Ie,Z]);r.useEffect(()=>{const S=ae.current;if(!S||!E)return;const te=()=>{const Qe=Math.max(48,S.offsetHeight);P(Ye=>Ye===Qe?Ye:Qe)};if(te(),typeof ResizeObserver>"u")return;const _e=new ResizeObserver(()=>te());return _e.observe(S),()=>_e.disconnect()},[E,t.status,t.targetDate,t.name]),r.useEffect(()=>{const S=ae.current;if(!S||!E){W(0);return}const te=S.closest('[data-mc-scroll-host="true"]')??S.closest(".h-full.overflow-y-auto.overflow-x-hidden"),_e=te??window;let Qe=0;const Ye=()=>{Qe=0;const ke=Number.parseFloat(getComputedStyle(S).top||"0"),_s=S.getBoundingClientRect(),us=(te==null?void 0:te.getBoundingClientRect().top)??0,Bs=1-(_s.top-us-ke)/56,St=Math.pow(Math.max(0,Math.min(1,Bs)),1.2);W(be=>Math.abs(be-St)<.015?be:St)},At=()=>{Qe||(Qe=window.requestAnimationFrame(Ye))};return Ye(),_e.addEventListener("scroll",At,{passive:!0}),window.addEventListener("resize",At),()=>{Qe&&window.cancelAnimationFrame(Qe),_e.removeEventListener("scroll",At),window.removeEventListener("resize",At)}},[E,t.id]),r.useEffect(()=>{var S;E&&!d&&x.length>0&&w(((S=x[0])==null?void 0:S.id)??null)},[E,x,d]),r.useEffect(()=>{if(!C)return;const S=window.setTimeout(()=>L(null),C.tone==="success"?2800:4200);return()=>window.clearTimeout(S)},[C]);const kt=((Q==null?void 0:Q.initiative.assignedAgents)??[]).map(S=>({id:S.id,name:S.name,confidence:"high"})),Ae=f.get(t.id)??[];kt.length>0;const xe=x.filter(S=>S.type==="task"),ye=xe.filter(S=>ai(S.status)).length,rt=xe.filter(S=>ri(S.status)).length,xt=xe.filter(S=>Ke(S.status)).length,Ut=(o==null?void 0:o.activeCount)??0;o==null||o.totalCount;const Ge=ye>0||Ut>0,Ze=t.status==="active"&&Ge?"in_progress":t.status,Tt=Ze==="in_progress"?As.active:As[Ze],$t=Ze==="in_progress"?"In Progress":qe(Ze),dt=xe.length>0?xe:x.some(S=>S.type==="milestone")?x.filter(S=>S.type==="milestone"):x.filter(S=>S.type==="workstream"),ht=Math.round(dt.reduce((S,te)=>S+(te.expectedDurationHours||0),0)*10)/10,ut=Math.round(dt.reduce((S,te)=>S+(te.expectedBudgetUsd||0),0)*100)/100,mt=x.filter(S=>S.type==="milestone"),Ue=x.filter(S=>S.type==="workstream"),et=pe.isPinning||pe.isMoving,gt=(t.rawStatus??t.status??"").trim().toLowerCase().replace(/[\s-]+/g,"_"),bt=new Set(["active","in_progress","running"]).has(gt),We=new Set(["paused","draft","planned","todo","backlog","queued"]).has(gt)||bt,Zt=bt?"Play next":gt==="paused"?"Resume":"Start",at=r.useMemo(()=>We?null:Be.length>0?"Live sync is degraded. Refresh sync or reconnect OrgX, then retry.":(["blocked"].includes(gt)||["completed","done","archived","cancelled","deleted"].includes(gt),null),[We,gt,Be.length]),Et=!n,Wt=n,Nt=r.useMemo(()=>Ue.filter(S=>S.initiativeId===t.id).sort((S,te)=>S.priorityNum-te.priorityNum||S.title.localeCompare(te.title)),[t.id,Ue]),Lt=Se||q.workstreams.length>0||q.milestones.length>0||q.tasks.length>0,i=xe.length>0?Yt(xt,xe.length):mt.length>0?Yt(mt.filter(S=>Ke(S.status)).length,mt.length):Lt&&Ue.length>0?Yt(Ue.filter(S=>Ke(S.status)).length,Ue.length):null,k=Ts(i===null?t.health:i),D=k===0?2:k,ee=(t.workstreams??[]).some(S=>S.status.toLowerCase()==="blocked")||Ue.some(S=>S.status.toLowerCase()==="blocked"),ie=t.status==="blocked"||ee,Ne=Ke(t.status),Me=k>0&&k<100&&!ie&&!Ne,me=ie?"border-l-2 border-l-red-400/60":Ne?"border-l-2 border-l-teal-400/60":Me?"border-l-2 border-l-lime-400/60":k===0&&!ie&&!Ne&&!Ge?"border-l-2 border-l-white/10":"",Ve=k===0&&t.status==="active"&&!Ge,Fe=Math.pow(y,.82),yt=Math.max(0,Number((16*(1-Fe)).toFixed(2))),Je=`0 10px 26px rgba(0,0,0,${(.18+Fe*.24).toFixed(3)}), 0 1px 0 rgba(191,255,0,${(Fe*.09).toFixed(3)})`,_t=async S=>{if(Nt.length===0){L({tone:"error",message:"No workstreams available to queue for this initiative."});return}const te=S==="top"?[...Nt].reverse():Nt;let _e=0,Qe=0,Ye=null;for(const At of te)try{await pe.pin({initiativeId:t.id,workstreamId:At.id}),await pe.move({initiativeId:t.id,workstreamId:At.id,placement:S}),_e+=1}catch(ke){Qe+=1,Ye||(Ye=ke instanceof Error?ke.message:"Failed to queue this initiative.")}if(Qe>0){L({tone:_e>0?"success":"error",message:_e>0?`Queued ${_e}/${Nt.length} workstreams (${Qe} failed).`:Ye??"Failed to queue initiative workstreams."});return}L({tone:"success",message:`Queued ${_e} workstream${_e===1?"":"s"} to ${S==="top"?"top":"end"}.`})},J=S=>{if(S.type==="initiative"){h({type:"initiative",entity:t});return}if(S.type==="workstream"){h({type:"workstream",entity:li(S,t),initiative:t});return}if(S.type==="milestone"){h({type:"milestone",entity:ci(S,t),initiative:t});return}h({type:"task",entity:di(S,t),initiative:t})},je=async(S,te)=>{await I.updateEntity.mutateAsync({type:S.type,id:S.id,...te})},it=S=>te=>{te.stopPropagation(),I.entityAction.mutate({type:"initiative",id:t.id,action:S})},Re=S=>{if(S.stopPropagation(),bt){_t("bottom");return}I.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,opacity] duration-200 ${E?"bg-[--orgx-surface-elevated]":"bg-[--orgx-surface]"} ${s?"ring-1 ring-[#BFFF00]/30 shadow-[0_0_0_1px_rgba(191,255,0,0.12)]":""} ${me} ${Ve?"opacity-60":""}`,style:{"--mc-initiative-header-offset":`${X}px`},children:[e.jsxs("div",{ref:ae,role:"button",tabIndex:0,"aria-expanded":E,onClick:()=>c(t.id),onKeyDown:S=>{(S.key==="Enter"||S.key===" ")&&(S.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 ${E?"sticky z-30 border-b border-subtle bg-[#0C0E14]/95 shadow-[0_8px_20px_rgba(0,0,0,0.3)] backdrop-blur-xl":""}`,style:E?{top:"var(--mc-toolbar-offset, 88px)",borderTopLeftRadius:`${yt}px`,borderTopRightRadius:`${yt}px`,boxShadow:Je}:void 0,children:[e.jsx(de.div,{animate:{rotate:E?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:S=>{const te=S.nativeEvent.shiftKey??!1;a(t.id,S.currentTarget.checked,te)},onClick:S=>S.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 ${Ge?"status-breathe":""}`,style:{backgroundColor:ks(Ze)}}),e.jsx("div",{className:"min-w-[80px] flex-[1_1_auto] overflow-hidden pr-1.5 sm:min-w-0 sm:pr-2",children:e.jsx("button",{type:"button",onClick:S=>{S.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.jsxs("div",{className:`ml-1 flex flex-shrink-0 justify-start ${n?"w-[80px] min-w-[80px]":"w-[80px] min-w-[80px] sm:w-[90px] sm:min-w-[90px] md:w-[102px] md: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"} ${Tt}`,children:$t}),ue.length>0&&e.jsx("span",{className:"ml-1 h-2 w-2 flex-shrink-0 rounded-full bg-amber-400/70 animate-pulse",title:`Sync degraded: ${ue.length} issue${ue.length!==1?"s":""}`})]}),e.jsx("div",{className:`ml-1.5 flex-shrink-0 ${Wt?"flex":"lg:hidden"}`,title:`${k}% complete`,children:e.jsxs("svg",{viewBox:"0 0 36 36",className:"h-9 w-9","aria-label":`${k}% complete`,children:[e.jsx("circle",{cx:"18",cy:"18",r:"15",fill:"none",stroke:"rgba(255,255,255,0.06)",strokeWidth:"3"}),e.jsx(de.circle,{cx:"18",cy:"18",r:"15",fill:"none",stroke:ks(Ze),strokeWidth:"3",strokeLinecap:"round",initial:!1,animate:{strokeDasharray:`${D/100*94.25} 94.25`,opacity:k===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:[k,"%"]})]})}),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] ${Wt?"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(de.div,{className:"h-full rounded-full transition-all",initial:!1,animate:{width:`${D}%`,opacity:k===0?.45:1},transition:{type:"spring",stiffness:260,damping:34,mass:.75},style:{backgroundColor:ks(Ze)}})})}),e.jsxs("span",{className:"w-[42px] text-right text-micro text-muted xl:w-[48px] xl:text-caption",style:{fontVariantNumeric:"tabular-nums"},children:[k,"%"]})]}),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:[Et&&e.jsx($s,{label:"Queue",size:"sm",busy:et,disabled:Nt.length===0,stopPropagation:!0,title:`Queue initiative: ${t.name}`,onSelectPlacement:_t}),e.jsxs("button",{type:"button",onClick:S=>{We&&Re(S)},disabled:!We||I.updateEntity.isPending,title:We?`${Zt} initiative`:`Cannot start while status is ${qe(gt)}`,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:Zt})]})]}),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:it("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:it("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:S=>{S.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"})]})})]})]}),C&&e.jsx("div",{role:"status","aria-live":"polite",className:`mx-3 mb-2 rounded-lg border px-2.5 py-1.5 text-micro ${C.tone==="success"?"border-[#BFFF00]/24 bg-[#BFFF00]/[0.1] text-[#D8FFA1]":"border-red-400/24 bg-red-500/[0.1] text-red-100"}`,children:C.message}),at&&Be.length>0&&e.jsx("div",{role:"note",className:"mx-3 mb-2 rounded-lg border border-amber-300/20 bg-amber-500/[0.08] px-2.5 py-1.5 text-micro text-amber-100/90",children:at}),e.jsx(lt,{children:E&&e.jsx(de.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:()=>j(!0),onAnimationComplete:()=>j(!1),className:p?"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"}),K||!Se&&U?e.jsx("div",{className:"space-y-2",children:Array.from({length:3}).map((S,te)=>e.jsx(Ft,{className:"h-24 w-full rounded-xl"},`mc-loading-${te}`))}):e.jsxs(de.div,{initial:"hidden",animate:"show",variants:{hidden:{},show:{transition:{staggerChildren:.08}}},className:"space-y-3.5",children:[(rt>0||ye>0||xt>0||ht>0)&&e.jsx(de.div,{variants:Fs,children:e.jsxs("div",{className:"flex items-center gap-4 py-1",children:[e.jsxs("svg",{viewBox:"0 0 68 68",className:"h-16 w-16 flex-shrink-0","aria-label":`${k}% complete`,children:[e.jsx("circle",{cx:"34",cy:"34",r:"28",fill:"none",stroke:"rgba(255,255,255,0.06)",strokeWidth:"5"}),e.jsx(de.circle,{cx:"34",cy:"34",r:"28",fill:"none",stroke:ks(Ze),strokeWidth:"5",strokeLinecap:"round",initial:!1,animate:{strokeDasharray:`${(k===0?2:k)/100*175.93} 175.93`,opacity:k===0?.45:1},transition:{type:"spring",stiffness:260,damping:34,mass:.75},transform:"rotate(-90 34 34)"}),e.jsxs("text",{x:"34",y:"32",textAnchor:"middle",dominantBaseline:"central",fill:"currentColor",fontSize:"14",fontWeight:"700",className:"text-bright",children:[k,"%"]}),e.jsxs("text",{x:"34",y:"46",textAnchor:"middle",dominantBaseline:"central",fill:"currentColor",fontSize:"8",className:"text-muted",children:[xt,"/",xe.length," done"]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-1 text-caption text-secondary",children:[e.jsxs("span",{children:[e.jsx("span",{className:"text-bright font-medium",children:"Queue:"})," ",rt,ye>0?` (${ye} active)`:""]}),ht>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-white/20",children:"·"}),e.jsxs("span",{children:[e.jsx("span",{className:"text-bright font-medium",children:"Duration:"})," ",ht,"h"]})]}),ut>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-white/20",children:"·"}),e.jsxs("span",{children:[e.jsx("span",{className:"text-bright font-medium",children:"Budget:"})," $",ut.toLocaleString()]})]})]})]})}),b&&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 ",((es=Ie.get(b))==null?void 0:es.title)??b]}),e.jsx("button",{type:"button",onClick:()=>N(null),className:"text-micro underline underline-offset-2",children:"Clear focus"})]}),e.jsx(de.div,{variants:Fs,children:e.jsxs(Zs,{title:"Dependency Map",storageKey:`depmap.${t.id}`,defaultOpen:!0,badge:oe?{label:`${G||T.length} cycle${(G||T.length)===1?"":"s"}`,tone:"warning",action:{label:"Fix",onClick:Ce,busy:z}}:null,children:[e.jsx(Ra,{nodes:x,edges:Y,selectedNodeId:d,focusedWorkstreamId:b,onSelectNode:S=>{w(S);const te=Ie.get(S);(te==null?void 0:te.type)==="workstream"&&N(te.id)}}),Be.filter(S=>!/cyclic dependency edge/i.test(S)).length>0&&e.jsxs("div",{className:"mt-2",children:[e.jsxs("button",{type:"button",onClick:()=>F(S=>!S),className:"flex items-center gap-1.5 text-micro text-amber-200/65 transition-colors hover:text-amber-100/85",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-amber-300/60"}),Be.filter(S=>!/cyclic dependency edge/i.test(S)).length," warning",Be.filter(S=>!/cyclic dependency edge/i.test(S)).length!==1?"s":"",e.jsx("svg",{width:"8",height:"8",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",className:`transition-transform ${M?"rotate-180":""}`,children:e.jsx("path",{d:"m6 9 6 6 6-6"})})]}),e.jsx(lt,{children:M&&e.jsx(de.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 pt-1.5",children:Be.filter(S=>!/cyclic dependency edge/i.test(S)).map((S,te)=>e.jsx("div",{className:"text-micro text-amber-100/60",children:jt(S)},te))})})})]})]})}),Pe&&e.jsx(de.div,{variants:Fs,children:e.jsx(Zs,{title:"Next Up",storageKey:`nextup.${t.id}`,defaultOpen:!0,children:e.jsx(ei,{recentTodoIds:Z,nodesById:Ie,selectedNodeId:d,onSelectNode:S=>{w(S);const te=Ie.get(S);(te==null?void 0:te.type)==="workstream"&&N(te.id)}})})}),e.jsx(de.div,{variants:Fs,children:e.jsx(Zs,{title:"Hierarchy",storageKey:`hierarchy.${t.id}`,defaultOpen:!0,contentOverflowVisible:!0,children:e.jsx(Ya,{nodes:x,edges:Y,selectedNodeId:d,highlightedNodeIds:Le,editMode:$,onSelectNode:w,onFocusWorkstream:N,onOpenNode:J,onUpdateNode:je,onToggleEditMode:()=>g(S=>!S),mutations:I})})})]}),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 mi={hidden:{opacity:0},show:{opacity:1,transition:{staggerChildren:.045,delayChildren:.02}}},pi={hidden:{opacity:0,y:10,scale:.995},show:{opacity:1,y:0,scale:1,transition:{type:"spring",stiffness:320,damping:28,mass:.7}}};function Gn({initiatives:t,selectedInitiativeIds:s,onToggleInitiativeSelection:a,isSquished:n=!1,runtimeActivityByInitiativeId:o}){return e.jsx(de.div,{variants:mi,initial:"hidden",animate:"show",className:"space-y-2",children:t.map(l=>e.jsx(de.div,{variants:pi,layout:!0,transition:{type:"spring",stiffness:280,damping:32,mass:.75},children:e.jsx(ui,{initiative:l,selected:(s==null?void 0:s.has(l.id))??!1,onSelectionChange:a,isSquished:n,runtimeActivity:(o==null?void 0:o.get(l.id))??null})},l.id))})}function en({mode:t="empty",hasActiveFilters:s=!1,detail:a=null,onClearFilters:n,onCreateInitiative:o,onPlayNextUp:l,onStartAutopilot:c,onRefresh:h,onOpenSettings:f}){const[v,m]=r.useState(null),[I,$]=r.useState(null),g=r.useCallback(async(b,N)=>{if(N){$(null),m(b);try{await N()}catch(M){const F=M instanceof Error?M.message:"";$(F?jt(F):"Action failed")}finally{m(M=>M===b?null:M)}}},[]),d=t==="filtered"?"No initiatives match this view":t==="degraded"?"Initiatives are temporarily unavailable":"No initiatives yet",w=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(Zr,{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:`${O.iris}1a`,border:`1px solid ${O.iris}33`},children:e.jsxs("svg",{width:"22",height:"22",viewBox:"0 0 24 24",fill:"none",stroke:O.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:d}),e.jsx("p",{className:"mt-1 text-body leading-relaxed text-secondary",children:w})]})]}),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"}),o&&e.jsx("button",{type:"button",onClick:o,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"}),l&&e.jsx("button",{type:"button",onClick:()=>void g("play",l),disabled:v!==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:v==="play"?"Dispatching...":"Play Next Up"}),c&&e.jsx("button",{type:"button",onClick:()=>void g("autopilot",c),disabled:v!==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:v==="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:jt(a)}),I&&e.jsx("p",{className:"text-caption text-amber-200/80",children:I})]})})})}function jr({percent:t,size:s=56,strokeWidth:a=4,className:n}){const o=Math.max(0,Math.min(100,t)),l=(s-a)/2,c=2*Math.PI*l,h=c-o/100*c,f=o>66?"#BFFF00":o>33?"#F5B700":"rgba(255,255,255,0.38)";return e.jsxs("div",{className:n,style:{width:s,height:s,position:"relative"},children:[e.jsxs("svg",{width:s,height:s,viewBox:`0 0 ${s} ${s}`,children:[e.jsx("circle",{cx:s/2,cy:s/2,r:l,fill:"none",stroke:"rgba(255,255,255,0.06)",strokeWidth:a}),e.jsx(de.circle,{cx:s/2,cy:s/2,r:l,fill:"none",stroke:f,strokeWidth:a,strokeLinecap:"round",strokeDasharray:c,initial:{strokeDashoffset:c},animate:{strokeDashoffset:h},transition:{duration:ea.durationEntrance/1e3,ease:[.22,1,.36,1]},transform:`rotate(-90 ${s/2} ${s/2})`})]}),e.jsx("span",{className:"absolute inset-0 flex items-center justify-center text-[18px] font-light",style:{fontVariantNumeric:"tabular-nums",color:f},children:Math.round(o)})]})}function ve({label:t,icon:s,color:a="#BFFF00",variant:n="secondary",size:o="md",className:l="",type:c="button",...h}){const f=o==="sm"?"px-2.5 py-1 text-micro":"px-3 py-1.5 text-caption",v=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} ${l}`,style:v,...h,children:[s,t&&e.jsx("span",{children:t})]})}const Jn={draft:O.textMuted,in_review:O.amber,approved:O.lime,changes_requested:O.red,superseded:O.textMuted,archived:O.textMuted};function xi(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 hi(){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 Yn(t,s,a){if(fs())return xi(t,s);try{const n=ft(a),o=new URLSearchParams({entity_type:t,entity_id:s,limit:"20"}),l=await fetch(`/orgx/api/work-artifacts/by-entity?${o.toString()}`,{headers:n});if(!l.ok)return[];const c=await l.json();return(c==null?void 0:c.artifacts)??[]}catch{return[]}}function Ls({entityType:t,entityId:s,title:a="Artifacts",authToken:n=null,embedMode:o=!1,finalOnly:l=!1,milestoneIds:c}){const{open:h}=ta(),[f,v]=r.useState(!l),m=!!(c!=null&&c.length),I=Xt({queryKey:Jt.artifactsByEntity({entityType:t,entityId:s,authToken:n,embedMode:o}),enabled:!m&&!!s,queryFn:()=>Yn(t,s,{authToken:n,embedMode:o})}),$=Xt({queryKey:["artifacts-by-milestones",c,n,o],enabled:m,queryFn:async()=>{if(!(c!=null&&c.length))return[];const b=await Promise.all(c.map(M=>Yn("milestone",M,{authToken:n,embedMode:o}))),N=new Map;for(const M of b)for(const F of M)N.has(F.id)||N.set(F.id,F);return[...N.values()].sort((M,F)=>Date.parse(F.updated_at)-Date.parse(M.updated_at))}}),g=m?$:I,d=g.data??[],w=f?d:d.filter(b=>b.status==="approved");return g.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"})]}):d.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," (",w.length,")"]}),l&&e.jsx("button",{type:"button",onClick:()=>v(b=>!b),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:[w.slice(0,10).map(b=>e.jsxs("button",{type:"button",onClick:()=>h(b.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(hi,{}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-body text-primary",children:b.name}),e.jsx("span",{className:"text-micro text-faint",children:b.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:Jn[b.status]??O.textMuted,backgroundColor:`${Jn[b.status]??O.textMuted}15`},children:b.status})]},b.id)),w.length>10&&e.jsxs("p",{className:"text-micro text-faint pl-2",children:["+",w.length-10," more"]})]})]})}function ct({level:t,size:s=12,className:a=""}){return t==="initiative"?e.jsxs("svg",{width:s,height:s,viewBox:"0 0 24 24",className:a,fill:"none",stroke:O.iris,strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[e.jsx("circle",{cx:"12",cy:"12",r:"9",fill:"rgba(124,124,255,0.14)"}),e.jsx("circle",{cx:"12",cy:"12",r:"4.5"}),e.jsx("circle",{cx:"12",cy:"12",r:"1.6",fill:O.iris,stroke:"none"})]}):t==="workstream"?e.jsx(sa,{size:s,className:a,stroke:O.lime,strokeWidth:1.9,withBackground:!0,backgroundColor:"rgba(191,255,0,0.12)"}):t==="milestone"?e.jsxs("svg",{width:s,height:s,viewBox:"0 0 24 24",className:a,fill:"none",stroke:O.teal,strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[e.jsx("path",{d:"M7 5v14"}),e.jsx("path",{d:"m7 6 10 1.1-1.8 3.5L17 14 7 12.9z",fill:"rgba(20,184,166,0.12)"}),e.jsx("circle",{cx:"7",cy:"5",r:"1.2",fill:O.teal,stroke:"none"})]}):e.jsxs("svg",{width:s,height:s,viewBox:"0 0 24 24",className:a,fill:"none",stroke:"rgba(255,255,255,0.72)",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[e.jsx("rect",{x:"4.5",y:"4.5",width:"15",height:"15",rx:"4",fill:"rgba(255,255,255,0.1)"}),e.jsx("path",{d:"M9 12.2 11.1 14.3 15.2 10.1"})]})}function nt(t){return t==="initiative"?"I":t==="workstream"?"W":t==="milestone"?"M":"T"}function fi({initiative:t}){const{agentEntityMap:s,openModal:a,closeModal:n,authToken:o,embedMode:l,mutations:c}=zt(),h=s.get(t.id)??[],[f,v]=r.useState(!1),[m,I]=r.useState(""),[$,g]=r.useState(!1),[d,w]=r.useState(!1),[b,N]=r.useState(!1),M=r.useRef(null),[F,p]=r.useState(null),[j,C]=r.useState(t.name),[L,z]=r.useState(t.description??""),[ne,ae]=r.useState(ps(t.priority)),[X,P]=r.useState(tn(t.targetDate)),[y,W]=r.useState(null),{details:E,isLoading:Q}=bs({initiativeId:t.id,authToken:o,embedMode:l}),K=gs({authToken:o,embedMode:l}),ue=E.tasks.filter(T=>["active","in_progress"].includes(T.status.toLowerCase())).length,R=E.tasks.filter(T=>T.status.toLowerCase()==="blocked").length,_=E.tasks.filter(T=>Ke(T.status)).length,q=y??t.status,U=gi(y??t.rawStatus??t.status),H=["active","in_progress","running","queued"].includes(U),pe=["paused","draft","planned","todo","backlog","pending","not_started"].includes(U),re=c.entityAction.isPending||c.createEntity.isPending||c.updateEntity.isPending||c.deleteEntity.isPending,Se=K.isPinning||K.isMoving,Oe=r.useMemo(()=>E.workstreams.length>0?E.workstreams.map(T=>({id:T.id,name:T.name})):(t.workstreams??[]).map(T=>({id:T.id,name:T.name})),[E.workstreams,t.workstreams]),He=r.useMemo(()=>{const T=new Map,G=[];for(const oe of E.milestones){if(!oe.workstreamId){G.push(oe);continue}const Ce=T.get(oe.workstreamId);Ce?Ce.push(oe):T.set(oe.workstreamId,[oe])}return{grouped:T,unscoped:G}},[E.milestones]),x=r.useMemo(()=>{const T=new Map;for(const G of E.tasks){if(!G.workstreamId)continue;const oe=T.get(G.workstreamId);oe?oe.push(G):T.set(G.workstreamId,[G])}return T},[E.tasks]),Y=r.useMemo(()=>{const T=new Map;for(const G of E.tasks){if(!G.milestoneId)continue;const oe=T.get(G.milestoneId);oe?oe.push(G):T.set(G.milestoneId,[G])}return T},[E.tasks]),Z=r.useMemo(()=>E.tasks.filter(T=>!T.workstreamId&&!T.milestoneId),[E.tasks]),ge=(T,G)=>T&&T.trim().length>0?jt(T.trim()):G;r.useEffect(()=>{$||(C(t.name),z(t.description??""),P(tn(t.targetDate)),ae(ps(t.priority)))},[$,t.description,t.name,t.priority,t.targetDate]),r.useEffect(()=>{W(null),w(!1)},[t.id,t.status,t.rawStatus]),r.useEffect(()=>{if(!b)return;const T=oe=>{M.current&&!M.current.contains(oe.target)&&N(!1)},G=oe=>{oe.key==="Escape"&&N(!1)};return document.addEventListener("mousedown",T),document.addEventListener("keydown",G),()=>{document.removeEventListener("mousedown",T),document.removeEventListener("keydown",G)}},[b]);const De=(T,G,oe)=>{p(null),c.entityAction.mutate({type:"initiative",id:t.id,action:T},{onSuccess:()=>{W(G),p(oe)},onError:Ce=>{p(ge(Ce instanceof Error?Ce.message:"",`Failed to ${T} initiative.`))}})},ze=()=>{const T=j.trim();if(!T){p("Initiative title is required.");return}p(null),c.updateEntity.mutate({type:"initiative",id:t.id,title:T,summary:L.trim()||null,priority:ne,target_date:X||null},{onSuccess:()=>{g(!1),p("Initiative updated.")},onError:G=>{p(ge(G instanceof Error?G.message:"","Failed to update initiative."))}})},Be=async T=>{if(Oe.length===0){p("No workstreams available to queue.");return}const G=T==="top"?[...Oe].reverse():Oe;let oe=0,Ce=0,Ie=null;for(const Le of G)try{await K.pin({initiativeId:t.id,workstreamId:Le.id}),await K.move({initiativeId:t.id,workstreamId:Le.id,placement:T}),oe+=1}catch(Pe){Ce+=1,Ie||(Ie=ge(Pe instanceof Error?Pe.message:"","Failed to queue initiative workstream."))}if(Ce>0){p(oe>0?`Queued ${oe}/${Oe.length} workstreams (${Ce} failed).`:Ie??"Failed to queue initiative workstreams.");return}p(`Queued ${oe} workstream${oe===1?"":"s"} to ${T==="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-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ct,{level:"initiative",size:16}),e.jsx("h2",{className:"text-[28px] font-medium leading-none text-white truncate",children:t.name})]}),e.jsxs("div",{className:"mt-2 flex items-center gap-2",children:[e.jsx("span",{className:`rounded-full px-2 py-0.5 text-[10px] font-semibold uppercase tracking-widest ${As[q]??As.active}`,children:qe(q)}),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:bi(t.priority)})]})]}),(()=>{const T=E.tasks.length||0,G=T>0?Math.round(_/T*100):0;return T>0?e.jsx(jr,{percent:G,size:56}):null})()]}),$?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:T=>C(T.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:L,onChange:T=>z(T.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:X,onChange:T=>P(T.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:ne,onChange:T=>ae(ps(T.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(pn,{agents:h,max:6})]}),F&&e.jsx("div",{className:"text-caption text-secondary",children:F})]}),e.jsx(xa,{metrics:[{label:"Done",value:_,color:O.teal},{label:"Active",value:ue,color:O.lime},{label:"Blocked",value:R,color:O.red},...t.targetDate?[{label:"ETA",value:yi(t.targetDate)}]:[]],className:"pt-2 pb-4 border-b border-white/[0.04]"}),E.tasks.length>0&&(()=>{const T=E.tasks.length,G=Math.round(_/T*100);return 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(G,2)}%`,background:`linear-gradient(90deg, ${O.teal}, ${O.lime})`}})}),e.jsxs("span",{className:"text-micro text-secondary tabular-nums",children:[G,"%"]})]})})(),Q?e.jsx("div",{className:"space-y-2",children:Array.from({length:3}).map((T,G)=>e.jsx(Ft,{className:"h-14 w-full rounded-lg"},`init-detail-${G}`))}):e.jsxs(e.Fragment,{children:[(E.workstreams.length>0||E.milestones.length>0||Z.length>0)&&e.jsxs("section",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("h3",{className:"text-[11px] font-semibold uppercase tracking-[0.12em] text-white/55",children:"IWMT Composition"}),e.jsxs("p",{className:"text-micro text-muted",children:[E.workstreams.length," workstreams · ",E.milestones.length," milestones ·"," ",E.tasks.length," tasks"]})]}),e.jsxs("div",{className:"space-y-2.5",children:[E.workstreams.map(T=>{const G=He.grouped.get(T.id)??[],oe=x.get(T.id)??[],Ce=oe.filter(Ae=>Ke(Ae.status)).length,Ie=oe.length>0?Yt(Ce,oe.length):typeof T.progress=="number"?Ts(T.progress<=1?T.progress*100:T.progress):Ke(T.status)?100:0,Le=T.status.toLowerCase(),Pe=!["done","completed","archived"].includes(Le),kt=T.hierarchyLabel??nt("workstream");return e.jsxs("article",{className:"rounded-xl border border-white/[0.08] bg-white/[0.02] px-3 py-2.5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("button",{onClick:()=>a({type:"workstream",entity:T,initiative:t}),className:"group min-w-0 flex-1 text-left",children:e.jsxs("div",{className:"flex min-w-0 items-start gap-2.5",children:[e.jsx("span",{className:"mt-0.5 inline-flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-md border border-white/[0.12] bg-white/[0.04]",children:e.jsx(ct,{level:"workstream",size:12})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("span",{className:"text-micro font-semibold uppercase tracking-[0.08em] text-white/58",children:kt}),e.jsx("span",{className:"truncate text-body text-bright",children:T.name})]}),e.jsxs("p",{className:"mt-0.5 text-caption text-muted",children:[G.length," milestone",G.length===1?"":"s"," ·"," ",oe.length," task",oe.length===1?"":"s"," · ",Ie,"% done"]})]})]})}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[Pe&&e.jsx("button",{type:"button",className:"inline-flex items-center gap-1 rounded-md border border-white/[0.12] bg-white/[0.05] px-1.5 py-0.5 text-micro text-white/70 transition-colors hover:bg-white/[0.1] hover:text-white",onClick:async Ae=>{Ae.stopPropagation(),p(null);try{await K.pin({initiativeId:t.id,workstreamId:T.id}),await K.move({initiativeId:t.id,workstreamId:T.id,placement:"bottom"}),p(`Queued "${T.name}" to end.`)}catch(xe){p(ge(xe instanceof Error?xe.message:"","Failed to queue workstream."))}},children:"Queue"}),e.jsx("span",{className:`text-micro px-1.5 py-0.5 rounded-full border uppercase tracking-[0.08em] ${gr(T.status)}`,children:qe(T.status)})]})]}),G.length>0?e.jsx("div",{className:"ml-7 mt-2.5 space-y-1.5 border-l border-white/[0.08] pl-3",children:G.map(Ae=>{const xe=Y.get(Ae.id)??[],ye=xe.filter(xt=>Ke(xt.status)).length,rt=Ae.hierarchyLabel??nt("milestone");return e.jsxs("button",{onClick:()=>a({type:"milestone",entity:Ae,initiative:t}),className:"flex w-full items-center justify-between gap-2 rounded-lg bg-white/[0.015] px-2 py-1.5 text-left transition-colors hover:bg-white/[0.06]",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx(ct,{level:"milestone",size:11,className:"flex-shrink-0"}),e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-white/52",children:rt}),e.jsx("span",{className:"truncate text-caption text-bright",children:Ae.title})]}),e.jsxs("p",{className:"mt-0.5 text-micro text-muted",children:[ye,"/",xe.length," tasks done"]})]}),e.jsx("span",{className:`text-micro px-1.5 py-0.5 rounded-full border uppercase tracking-[0.08em] ${Ms(Ae.status)}`,children:qe(Ae.status)})]},Ae.id)})}):e.jsx("div",{className:"ml-7 mt-2 rounded-lg border border-dashed border-white/[0.1] bg-white/[0.01] px-3 py-2 text-micro text-muted",children:"No milestones yet."})]},T.id)}),He.unscoped.length>0&&e.jsxs("article",{className:"rounded-xl border border-white/[0.08] bg-white/[0.015] px-3 py-2.5",children:[e.jsx("p",{className:"text-micro uppercase tracking-[0.1em] text-white/50",children:"Unscoped milestones"}),e.jsx("div",{className:"mt-2 space-y-1.5",children:He.unscoped.map(T=>e.jsxs("button",{onClick:()=>a({type:"milestone",entity:T,initiative:t}),className:"flex w-full items-center justify-between gap-2 rounded-lg bg-white/[0.015] px-2 py-1.5 text-left transition-colors hover:bg-white/[0.06]",children:[e.jsx("div",{className:"min-w-0",children:e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx(ct,{level:"milestone",size:11,className:"flex-shrink-0"}),e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-white/52",children:T.hierarchyLabel??nt("milestone")}),e.jsx("span",{className:"truncate text-caption text-bright",children:T.title})]})}),e.jsx("span",{className:`text-micro px-1.5 py-0.5 rounded-full border uppercase tracking-[0.08em] ${Ms(T.status)}`,children:qe(T.status)})]},T.id))})]}),Z.length>0&&e.jsxs("article",{className:"rounded-xl border border-white/[0.08] bg-white/[0.015] px-3 py-2.5",children:[e.jsx("p",{className:"text-micro uppercase tracking-[0.1em] text-white/50",children:"Unscoped tasks"}),e.jsxs("p",{className:"mt-1 text-caption text-muted",children:[Z.length," task",Z.length===1?"":"s"," without a workstream or milestone."]})]})]})]}),e.jsx("div",{className:"h-px bg-gradient-to-r from-transparent via-white/[0.06] to-transparent"}),e.jsx(Ls,{entityType:"initiative",entityId:t.id,authToken:o,embedMode:l}),e.jsx("div",{className:"space-y-2",children:e.jsx(Ds,{entityType:"initiative",entityId:t.id,authToken:o,embedMode:l})})]})]}),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:[H&&e.jsx(ve,{label:"Pause",color:O.amber,onClick:()=>De("pause","paused","Initiative paused."),disabled:re}),pe&&e.jsx(ve,{label:U==="paused"?"Resume":"Start",color:O.lime,variant:"primary",onClick:()=>De("resume","active",U==="paused"?"Initiative resumed.":"Initiative started."),disabled:re}),e.jsx($s,{label:"Queue",size:"md",busy:Se,disabled:re||Oe.length===0,title:`Queue initiative: ${t.name}`,onSelectPlacement:Be}),$?e.jsxs(e.Fragment,{children:[e.jsx(ve,{label:"Save",color:O.teal,variant:"primary",onClick:ze,disabled:re||!j.trim()}),e.jsx(ve,{label:"Cancel",variant:"ghost",onClick:()=>{g(!1),C(t.name),z(t.description??""),ae(ps(t.priority)),P(tn(t.targetDate)),p(null)},disabled:re})]}):e.jsx(ve,{label:"Edit",variant:"ghost",onClick:()=>{g(!0),p(null)},disabled:re}),e.jsx("div",{className:"flex-1"}),e.jsxs("div",{className:"relative",ref:M,children:[e.jsx("button",{type:"button",className:"rounded-lg border border-white/10 bg-white/5 px-2 py-1.5 text-secondary hover:bg-white/10 hover:text-primary transition-colors text-sm leading-none",onClick:()=>{N(T=>!T),w(!1)},"aria-label":"More actions",disabled:re,children:"⋯"}),b&&e.jsx("div",{className:"absolute bottom-full right-0 mb-1 min-w-[160px] rounded-lg border border-white/10 bg-[#0c1322] shadow-xl z-50",children:d?e.jsxs("div",{className:"flex flex-col gap-1 p-2",children:[e.jsx("span",{className:"text-caption text-secondary px-2",children:"Delete initiative?"}),e.jsx("button",{type:"button",className:"w-full text-left rounded-md px-3 py-1.5 text-sm hover:bg-white/5 transition-colors",style:{color:O.red},onClick:()=>c.deleteEntity.mutate({type:"initiative",id:t.id},{onSuccess:()=>n(),onError:T=>p(T instanceof Error?T.message:"Failed to delete initiative.")}),disabled:re,children:"Confirm Delete"}),e.jsx("button",{type:"button",className:"w-full text-left rounded-md px-3 py-1.5 text-sm text-secondary hover:bg-white/5 transition-colors",onClick:()=>w(!1),disabled:re,children:"Cancel"})]}):e.jsx("div",{className:"p-1",children:e.jsx("button",{type:"button",className:"w-full text-left rounded-md px-3 py-1.5 text-sm hover:bg-white/5 transition-colors",style:{color:O.red},onClick:()=>w(!0),disabled:re,children:"Delete"})})})]}),f?e.jsxs("form",{className:"flex flex-wrap items-center gap-2",onSubmit:T=>{T.preventDefault(),m.trim()&&c.createEntity.mutate({type:"workstream",title:m.trim(),initiative_id:t.id,status:"not_started"},{onSuccess:()=>{I(""),v(!1)}})},children:[e.jsx("input",{type:"text",value:m,onChange:T=>I(T.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(ve,{type:"submit",label:"Add",color:O.lime,disabled:!m.trim()||c.createEntity.isPending,size:"sm"}),e.jsx(ve,{label:"Cancel",variant:"ghost",onClick:()=>{v(!1),I("")},size:"sm"})]}):e.jsx(ve,{label:"+ Workstream",variant:"ghost",onClick:()=>v(!0),disabled:re})]})})]})}function tn(t){if(!t)return"";const s=Date.parse(t);return Number.isFinite(s)?new Date(s).toISOString().slice(0,10):""}function gi(t){return(t??"").trim().toLowerCase().replace(/[\s-]+/g,"_")}function ps(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 bi(t){const s=ps(t);return s==="critical"?"Priority: Critical":s==="high"?"Priority: High":s==="low"?"Priority: Low":"Priority: Medium"}function yi(t){return t?na(t):"—"}function wi({workstream:t,initiative:s}){const{agentEntityMap:a,openModal:n,closeModal:o,authToken:l,embedMode:c,mutations:h}=zt(),f=a.get(t.id)??a.get(s.id)??[],[v,m]=r.useState(!1),[I,$]=r.useState(""),[g,d]=r.useState(!1),[w,b]=r.useState(!1),[N,M]=r.useState(!1),F=r.useRef(null),[p,j]=r.useState(null),[C,L]=r.useState(t.name),[z,ne]=r.useState(t.summary??""),[ae,X]=r.useState(t.status);r.useEffect(()=>{if(!N)return;const x=Z=>{F.current&&!F.current.contains(Z.target)&&M(!1)},Y=Z=>{Z.key==="Escape"&&M(!1)};return document.addEventListener("mousedown",x),document.addEventListener("keydown",Y),()=>{document.removeEventListener("mousedown",x),document.removeEventListener("keydown",Y)}},[N]);const{details:P,isLoading:y}=bs({initiativeId:s.id,authToken:l,embedMode:c}),W=gs({authToken:l,embedMode:c}),E=r.useMemo(()=>P.milestones.filter(x=>x.workstreamId===t.id),[P.milestones,t.id]),Q=r.useMemo(()=>new Set(E.map(x=>x.id)),[E]),K=r.useMemo(()=>P.tasks.filter(x=>x.workstreamId===t.id||x.milestoneId!==null&&Q.has(x.milestoneId)).sort((x,Y)=>{const Z=typeof x.sequenceIndex=="number"?x.sequenceIndex:Number.POSITIVE_INFINITY,ge=typeof Y.sequenceIndex=="number"?Y.sequenceIndex:Number.POSITIVE_INFINITY;if(Z!==ge)return Z-ge;const De=x.createdAt?Date.parse(x.createdAt):0,ze=Y.createdAt?Date.parse(Y.createdAt):0;return De-ze}),[P.tasks,Q,t.id]),ue=r.useMemo(()=>{const x=new Map;for(const Y of K){if(!Y.milestoneId)continue;const Z=x.get(Y.milestoneId);Z?Z.push(Y):x.set(Y.milestoneId,[Y])}return x},[K]),R=r.useMemo(()=>K.filter(x=>!x.milestoneId),[K]),_=K.filter(x=>Ke(x.status)).length,q=K.length>0?Yt(_,K.length):typeof t.progress=="number"?Ts(t.progress<=1?t.progress*100:t.progress):Ke(t.status)?100:null,U=t.status.toLowerCase(),H=h.entityAction.isPending||h.createEntity.isPending||h.updateEntity.isPending||h.deleteEntity.isPending,pe=W.isPinning||W.isMoving,re=(x,Y)=>x&&x.trim().length>0?jt(x.trim()):Y,Se=(x,Y,Z)=>{j(null),h.entityAction.mutate({type:"workstream",id:t.id,action:x},{onSuccess:()=>j(Y),onError:ge=>{j(re(ge instanceof Error?ge.message:"",Z))}})},Oe=()=>{const x=C.trim();if(!x){j("Workstream name is required.");return}j(null),h.updateEntity.mutate({type:"workstream",id:t.id,title:x,summary:z.trim()||null,status:ae},{onSuccess:()=>{d(!1),j("Workstream updated.")},onError:Y=>{j(re(Y instanceof Error?Y.message:"","Failed to update workstream."))}})},He=async x=>{j(null);try{await W.pin({initiativeId:s.id,workstreamId:t.id}),await W.move({initiativeId:s.id,workstreamId:t.id,placement:x}),j(`Queued workstream to ${x==="top"?"top":"end"}.`)}catch(Y){j(re(Y instanceof Error?Y.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:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ct,{level:"workstream",size:16}),e.jsx("h2",{className:"text-title font-semibold text-white",children:t.name}),e.jsx("span",{className:"rounded-full border border-white/[0.12] bg-white/[0.04] px-1.5 py-0.5 text-micro font-semibold uppercase tracking-[0.08em] text-white/65",children:t.hierarchyLabel??nt("workstream")}),e.jsx("span",{className:`text-micro px-2.5 py-0.5 rounded-full border uppercase tracking-[0.08em] ${gr(t.status)}`,children:qe(t.status)})]}),g?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:C,onChange:x=>L(x.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:z,onChange:x=>ne(x.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:ae,onChange:x=>X(x.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(x=>e.jsx("option",{value:x,children:qe(x)},x))})]})]}):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(pn,{agents:f,max:6})]}),p&&e.jsx("div",{className:"text-caption text-secondary",children:p})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-caption text-secondary",children:[K.length," ",K.length===1?"task":"tasks"," · ",_,"/",K.length," done",E.length>0&&` · ${E.length} milestone${E.length===1?"":"s"}`]}),q!==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(q,2)}%`,backgroundColor:O.lime}})}),e.jsxs("span",{className:"text-micro text-secondary tabular-nums",children:[q,"%"]})]})]}),y?e.jsx("div",{className:"space-y-2",children:Array.from({length:3}).map((x,Y)=>e.jsx(Ft,{className:"h-12 w-full rounded-lg"},`ws-detail-${Y}`))}):e.jsxs(e.Fragment,{children:[(E.length>0||R.length>0)&&e.jsxs("section",{className:"space-y-3",children:[e.jsx("h3",{className:"text-[11px] font-semibold uppercase tracking-[0.12em] text-white/55",children:"IWMT Composition"}),e.jsxs("div",{className:"space-y-2.5",children:[E.map(x=>{const Y=ue.get(x.id)??[],Z=Y.filter(ge=>Ke(ge.status)).length;return e.jsxs("article",{className:"rounded-xl border border-white/[0.08] bg-white/[0.02] px-3 py-2.5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("button",{onClick:()=>n({type:"milestone",entity:x,initiative:s}),className:"group min-w-0 flex-1 text-left",children:e.jsxs("div",{className:"flex min-w-0 items-start gap-2.5",children:[e.jsx("span",{className:"mt-0.5 inline-flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-md border border-white/[0.12] bg-white/[0.04]",children:e.jsx(ct,{level:"milestone",size:12})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("span",{className:"text-micro font-semibold uppercase tracking-[0.08em] text-white/58",children:x.hierarchyLabel??nt("milestone")}),e.jsx("span",{className:"truncate text-body text-bright",children:x.title})]}),e.jsxs("p",{className:"mt-0.5 text-caption text-muted",children:[Z,"/",Y.length," tasks done"]})]})]})}),e.jsx("span",{className:`text-micro px-1.5 py-0.5 rounded-full border uppercase tracking-[0.08em] ${Ms(x.status)}`,children:qe(x.status)})]}),e.jsx("div",{className:"ml-7 mt-2.5 border-l border-white/[0.08] pl-3",children:Y.length>0?e.jsx("div",{className:"space-y-1.5",children:Y.map(ge=>e.jsxs("button",{onClick:()=>n({type:"task",entity:ge,initiative:s}),className:"flex w-full items-center justify-between gap-2 rounded-lg bg-white/[0.015] px-2 py-1.5 text-left transition-colors hover:bg-white/[0.06]",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx(ct,{level:"task",size:11,className:"flex-shrink-0"}),e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-white/50",children:ge.hierarchyLabel??nt("task")}),e.jsx("span",{className:"truncate text-caption text-bright",children:ge.title})]}),ge.priority&&e.jsx("p",{className:"mt-0.5 text-micro uppercase tracking-[0.08em] text-muted",children:ge.priority})]}),e.jsx("span",{className:`text-micro px-1.5 py-0.5 rounded-full border uppercase tracking-[0.08em] ${on(ge.status)}`,children:qe(ge.status)})]},ge.id))}):e.jsx("p",{className:"rounded-lg border border-dashed border-white/[0.1] bg-white/[0.01] px-3 py-2 text-micro text-muted",children:"No tasks yet."})})]},x.id)}),R.length>0&&e.jsxs("article",{className:"rounded-xl border border-white/[0.08] bg-white/[0.015] px-3 py-2.5",children:[e.jsx("p",{className:"text-micro uppercase tracking-[0.1em] text-white/50",children:"Unscoped tasks"}),e.jsx("div",{className:"mt-2 space-y-1.5",children:R.map(x=>e.jsxs("button",{onClick:()=>n({type:"task",entity:x,initiative:s}),className:"flex w-full items-center justify-between gap-2 rounded-lg bg-white/[0.015] px-2 py-1.5 text-left transition-colors hover:bg-white/[0.06]",children:[e.jsx("div",{className:"min-w-0",children:e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx(ct,{level:"task",size:11,className:"flex-shrink-0"}),e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-white/50",children:x.hierarchyLabel??nt("task")}),e.jsx("span",{className:"truncate text-caption text-bright",children:x.title})]})}),e.jsx("span",{className:`text-micro px-1.5 py-0.5 rounded-full border uppercase tracking-[0.08em] ${on(x.status)}`,children:qe(x.status)})]},x.id))})]})]})]}),e.jsx("div",{className:"h-px bg-gradient-to-r from-transparent via-white/[0.06] to-transparent"}),e.jsx(Ls,{entityType:"workstream",entityId:t.id,title:"Artifacts (from milestones)",authToken:l,embedMode:c,finalOnly:!0,milestoneIds:E.map(x=>x.id)}),e.jsx("div",{className:"space-y-2",children:e.jsx(Ds,{entityType:"workstream",entityId:t.id,authToken:l,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(U)&&e.jsx(ve,{label:"Start",color:O.lime,variant:"primary",onClick:()=>Se("start","Workstream started.","Failed to start workstream."),disabled:H}),["active","in_progress"].includes(U)&&e.jsxs(e.Fragment,{children:[e.jsx(ve,{label:"Complete",color:O.teal,variant:"primary",onClick:()=>Se("complete","Workstream marked complete.","Failed to complete workstream."),disabled:H}),e.jsx(ve,{label:"Pause",color:O.amber,onClick:()=>Se("pause","Workstream paused.","Failed to pause workstream."),disabled:H}),e.jsx(ve,{label:"Block",color:O.red,variant:"destructive",onClick:()=>Se("block","Workstream blocked.","Failed to block workstream."),disabled:H})]}),["paused","blocked"].includes(U)&&e.jsx(ve,{label:"Resume",color:O.lime,variant:"primary",onClick:()=>Se("resume","Workstream resumed.","Failed to resume workstream."),disabled:H}),e.jsx($s,{label:"Queue",size:"md",busy:pe,disabled:H,title:`Queue workstream: ${t.name}`,onSelectPlacement:He}),g?e.jsxs(e.Fragment,{children:[e.jsx(ve,{label:"Save",color:O.teal,variant:"primary",onClick:Oe,disabled:H||!C.trim()}),e.jsx(ve,{label:"Cancel",variant:"ghost",onClick:()=>{d(!1),L(t.name),ne(t.summary??""),X(t.status),j(null)},disabled:H})]}):e.jsx(ve,{label:"Edit",variant:"ghost",onClick:()=>{d(!0),j(null)},disabled:H}),e.jsx("div",{className:"flex-1"}),e.jsxs("div",{className:"relative",ref:F,children:[e.jsx("button",{type:"button",className:"rounded-lg border border-white/10 bg-white/5 px-2 py-1.5 text-secondary hover:bg-white/10 hover:text-primary transition-colors text-sm leading-none",onClick:()=>{M(x=>!x),b(!1)},"aria-label":"More actions",disabled:H,children:"⋯"}),N&&e.jsx("div",{className:"absolute bottom-full right-0 mb-1 min-w-[160px] rounded-lg border border-white/10 bg-[#0c1322] shadow-xl z-50",children:w?e.jsxs("div",{className:"flex flex-col gap-1 p-2",children:[e.jsx("span",{className:"text-caption text-secondary px-2",children:"Delete workstream?"}),e.jsx("button",{type:"button",className:"w-full text-left rounded-md px-3 py-1.5 text-sm hover:bg-white/5 transition-colors",style:{color:O.red},onClick:()=>h.deleteEntity.mutate({type:"workstream",id:t.id},{onSuccess:()=>o(),onError:x=>j(re(x instanceof Error?x.message:"","Failed to delete workstream."))}),disabled:H,children:"Confirm Delete"}),e.jsx("button",{type:"button",className:"w-full text-left rounded-md px-3 py-1.5 text-sm text-secondary hover:bg-white/5 transition-colors",onClick:()=>b(!1),disabled:H,children:"Cancel"})]}):e.jsx("div",{className:"p-1",children:e.jsx("button",{type:"button",className:"w-full text-left rounded-md px-3 py-1.5 text-sm hover:bg-white/5 transition-colors",style:{color:O.red},onClick:()=>b(!0),disabled:H,children:"Delete"})})})]}),v?e.jsxs("form",{className:"flex flex-wrap items-center gap-2",onSubmit:x=>{x.preventDefault(),I.trim()&&h.createEntity.mutate({type:"task",title:I.trim(),workstream_id:t.id,initiative_id:s.id,status:"todo"},{onSuccess:()=>{$(""),m(!1)},onError:Y=>{j(re(Y instanceof Error?Y.message:"","Failed to create task."))}})},children:[e.jsx("input",{type:"text",value:I,onChange:x=>$(x.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(ve,{label:"Add",color:O.lime,type:"submit",size:"sm",disabled:!I.trim()||h.createEntity.isPending}),e.jsx(ve,{label:"Cancel",variant:"ghost",size:"sm",onClick:()=>{m(!1),$("")}})]}):e.jsx(ve,{label:"+ Task",variant:"ghost",onClick:()=>m(!0),disabled:H})]})})]})}function vi({milestone:t,initiative:s}){const{openModal:a,closeModal:n,authToken:o,embedMode:l,mutations:c}=zt(),[h,f]=r.useState(!1),[v,m]=r.useState(!1),[I,$]=r.useState(!1),g=r.useRef(null),[d,w]=r.useState(!1),[b,N]=r.useState(""),[M,F]=r.useState(null),[p,j]=r.useState(t.title),[C,L]=r.useState(t.description??""),[z,ne]=r.useState(Xn(t.dueDate)),[ae,X]=r.useState(t.status);r.useEffect(()=>{if(!I)return;const _=U=>{g.current&&!g.current.contains(U.target)&&$(!1)},q=U=>{U.key==="Escape"&&$(!1)};return document.addEventListener("mousedown",_),document.addEventListener("keydown",q),()=>{document.removeEventListener("mousedown",_),document.removeEventListener("keydown",q)}},[I]);const{details:P}=bs({initiativeId:s.id,authToken:o,embedMode:l}),y=P.tasks.filter(_=>_.milestoneId===t.id);P.workstreams.find(_=>_.id===t.workstreamId);const W=t.status.toLowerCase()==="done"||t.status.toLowerCase()==="completed",E=y.filter(_=>Ke(_.status)).length,Q=y.length>0?Yt(E,y.length):W?100:0,K=c.entityAction.isPending||c.createEntity.isPending||c.updateEntity.isPending||c.deleteEntity.isPending,ue=(_,q)=>_&&_.trim().length>0?jt(_.trim()):q,R=()=>{const _=p.trim();if(!_){F("Milestone title is required.");return}F(null),c.updateEntity.mutate({type:"milestone",id:t.id,title:_,description:C.trim()||null,due_date:z||null,status:ae},{onSuccess:()=>{f(!1),F("Milestone updated.")},onError:q=>{F(ue(q instanceof Error?q.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:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ct,{level:"milestone",size:16}),e.jsx("h2",{className:"text-title font-semibold text-white",children:t.title}),e.jsx("span",{className:"rounded-full border border-white/[0.12] bg-white/[0.04] px-1.5 py-0.5 text-micro font-semibold uppercase tracking-[0.08em] text-white/65",children:t.hierarchyLabel??nt("milestone")}),e.jsx("span",{className:`text-micro px-2.5 py-0.5 rounded-full border uppercase tracking-[0.08em] ${Ms(t.status)}`,children:qe(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:p,onChange:_=>j(_.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:C,onChange:_=>L(_.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:z,onChange:_=>ne(_.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:ae,onChange:_=>X(_.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:qe(_)},_))})]})]})]}):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."}),M&&e.jsx("div",{className:"text-caption text-secondary",children:M})]}),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:[y.length," ",y.length===1?"task":"tasks"]}),e.jsx("span",{className:"text-faint",children:"·"}),e.jsxs("span",{style:{fontVariantNumeric:"tabular-nums"},children:[E,"/",y.length," done"]}),t.dueDate&&(()=>{const _=Date.parse(t.dueDate);if(!Number.isFinite(_))return null;const q=Math.ceil((_-Date.now())/864e5),U=q<0?O.red:q<=3?O.red:q<=7?O.amber:"rgba(255,255,255,0.5)",H=q<0?`${Math.abs(q)}d overdue`:`Due in ${q}d`;return e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-faint",children:"·"}),e.jsx("span",{style:{color:U},children:H})]})})()]}),y.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(Q,2)}%`,backgroundColor:O.teal}})}),e.jsxs("span",{className:"text-micro text-secondary tabular-nums",children:[Q,"%"]})]})]}),e.jsxs("section",{className:"space-y-3",children:[e.jsx("h3",{className:"text-[11px] font-semibold uppercase tracking-[0.12em] text-white/55",children:"IWMT Composition"}),y.length>0?e.jsx("div",{className:"rounded-xl border border-white/[0.08] bg-white/[0.02] px-3 py-2.5",children:e.jsx("div",{className:"space-y-1.5",children:y.map(_=>e.jsxs("button",{onClick:()=>a({type:"task",entity:_,initiative:s}),className:"flex w-full items-center justify-between gap-2 rounded-lg bg-white/[0.015] px-2 py-1.5 text-left transition-colors hover:bg-white/[0.06]",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx(ct,{level:"task",size:11,className:"flex-shrink-0"}),e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-white/50",children:_.hierarchyLabel??nt("task")}),e.jsx("span",{className:"truncate text-caption text-bright",children:_.title})]}),_.priority&&e.jsx("p",{className:"mt-0.5 text-micro uppercase tracking-[0.08em] text-muted",children:_.priority})]}),e.jsx("span",{className:`text-micro px-1.5 py-0.5 rounded-full border uppercase tracking-[0.08em] ${on(_.status)}`,children:qe(_.status)})]},_.id))})}):e.jsx("div",{className:"rounded-xl border border-dashed border-white/[0.1] bg-white/[0.01] px-3 py-2 text-micro text-muted",children:"No tasks linked to this milestone yet."})]}),e.jsx("div",{className:"h-px bg-gradient-to-r from-transparent via-white/[0.06] to-transparent"}),e.jsx(Ls,{entityType:"milestone",entityId:t.id,authToken:o,embedMode:l}),e.jsx("div",{className:"space-y-2",children:e.jsx(Ds,{entityType:"milestone",entityId:t.id,authToken:o,embedMode:l})})]}),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:[!W&&t.status.toLowerCase()==="planned"&&e.jsx(ve,{label:"Start",color:O.lime,variant:"primary",onClick:()=>c.entityAction.mutate({type:"milestone",id:t.id,action:"start"}),disabled:K}),!W&&(t.status.toLowerCase()==="in_progress"||t.status.toLowerCase()==="at_risk")&&e.jsx(ve,{label:y.length>0&&!y.every(_=>Ke(_.status))?"Complete (force)":"Complete",color:O.teal,variant:"primary",onClick:()=>{const _=y.length===0||y.every(q=>Ke(q.status));c.entityAction.mutate({type:"milestone",id:t.id,action:"complete",force:!_})},disabled:K}),h?e.jsxs(e.Fragment,{children:[e.jsx(ve,{label:"Save",color:O.teal,variant:"primary",onClick:R,disabled:K||!p.trim()}),e.jsx(ve,{label:"Cancel",variant:"ghost",onClick:()=>{f(!1),j(t.title),L(t.description??""),ne(Xn(t.dueDate)),X(t.status),F(null)},disabled:K})]}):e.jsx(ve,{label:"Edit",variant:"ghost",onClick:()=>{f(!0),F(null)},disabled:K}),e.jsx("div",{className:"flex-1"}),e.jsxs("div",{className:"relative",ref:g,children:[e.jsx("button",{type:"button",className:"rounded-lg border border-white/10 bg-white/5 px-2 py-1.5 text-secondary hover:bg-white/10 hover:text-primary transition-colors text-sm leading-none",onClick:()=>{$(_=>!_),m(!1)},"aria-label":"More actions",disabled:K,children:"⋯"}),I&&e.jsx("div",{className:"absolute bottom-full right-0 mb-1 min-w-[160px] rounded-lg border border-white/10 bg-[#0c1322] shadow-xl z-50",children:v?e.jsxs("div",{className:"flex flex-col gap-1 p-2",children:[e.jsx("span",{className:"text-caption text-secondary px-2",children:"Delete milestone?"}),e.jsx("button",{type:"button",className:"w-full text-left rounded-md px-3 py-1.5 text-sm hover:bg-white/5 transition-colors",style:{color:O.red},onClick:()=>c.deleteEntity.mutate({type:"milestone",id:t.id},{onSuccess:()=>n(),onError:_=>F(ue(_ instanceof Error?_.message:"","Failed to delete milestone."))}),disabled:K,children:"Confirm Delete"}),e.jsx("button",{type:"button",className:"w-full text-left rounded-md px-3 py-1.5 text-sm text-secondary hover:bg-white/5 transition-colors",onClick:()=>m(!1),disabled:K,children:"Cancel"})]}):e.jsx("div",{className:"p-1",children:e.jsx("button",{type:"button",className:"w-full text-left rounded-md px-3 py-1.5 text-sm hover:bg-white/5 transition-colors",style:{color:O.red},onClick:()=>m(!0),disabled:K,children:"Delete"})})})]}),d?e.jsxs("form",{className:"flex flex-wrap items-center gap-2",onSubmit:_=>{_.preventDefault(),b.trim()&&c.createEntity.mutate({type:"task",title:b.trim(),milestone_id:t.id,workstream_id:t.workstreamId??void 0,initiative_id:s.id,status:"todo"},{onSuccess:()=>{N(""),w(!1)},onError:q=>{F(ue(q instanceof Error?q.message:"","Failed to create task."))}})},children:[e.jsx("input",{type:"text",value:b,onChange:_=>N(_.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(ve,{label:"Add",color:O.lime,type:"submit",size:"sm",disabled:!b.trim()||c.createEntity.isPending}),e.jsx(ve,{label:"Cancel",variant:"ghost",size:"sm",onClick:()=>{w(!1),N("")}})]}):e.jsx(ve,{label:"+ Task",variant:"ghost",onClick:()=>w(!0),disabled:K})]})})]})}function Xn(t){if(!t)return"";const s=Date.parse(t);return Number.isFinite(s)?new Date(s).toISOString().slice(0,10):""}function ji(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:O.red}:n<=3?{text:`Due in ${n}d`,tone:O.red}:n<=7?{text:`Due in ${n}d`,tone:O.amber}:{text:`Due ${new Date(s).toLocaleDateString()}`,tone:"rgba(255,255,255,0.5)"}}function ki(t){const s=t.toLowerCase();return["active","in_progress","running"].includes(s)?Ns.active.text:["done","completed"].includes(s)?Ns.done.text:s==="blocked"?Ns.blocked.text:Ns.planned.text}function Ni({task:t,initiative:s}){const{agentEntityMap:a,openModal:n,mutations:o,closeModal:l,authToken:c,embedMode:h}=zt(),{details:f}=bs({initiativeId:s.id,authToken:c,embedMode:h}),v=a.get(t.id)??a.get(s.id)??[],[m,I]=r.useState(!1),[$,g]=r.useState(!1),d=r.useRef(null),[w,b]=r.useState(!1),[N,M]=r.useState(null),[F,p]=r.useState(t.title),[j,C]=r.useState(t.description??""),[L,z]=r.useState(t.priority??""),[ne,ae]=r.useState(Zn(t.dueDate)),[X,P]=r.useState(t.status),y=t.status.toLowerCase(),W=r.useMemo(()=>ji(t.dueDate),[t.dueDate]),E=r.useMemo(()=>f.milestones.find(U=>U.id===t.milestoneId),[f.milestones,t.milestoneId]),Q=r.useMemo(()=>{if(t.workstreamId)return f.workstreams.find(U=>U.id===t.workstreamId);if(E!=null&&E.workstreamId)return f.workstreams.find(U=>U.id===E.workstreamId)},[f.workstreams,E==null?void 0:E.workstreamId,t.workstreamId]),K=(U,H)=>U&&U.trim().length>0?jt(U.trim()):H,ue=o.entityAction.isPending||o.updateEntity.isPending||o.deleteEntity.isPending,R=U=>{M(null),o.entityAction.mutate({type:"task",id:t.id,action:U},{onError:H=>{M(K(H instanceof Error?H.message:"","Task action failed."))}})},_=()=>{const U=F.trim();if(!U){M("Task title is required.");return}M(null),o.updateEntity.mutate({type:"task",id:t.id,title:U,description:j.trim()||null,priority:L.trim()||null,due_date:ne||null,status:X},{onSuccess:()=>{b(!1),M("Task updated.")},onError:H=>{M(K(H instanceof Error?H.message:"","Failed to update task."))}})},q=()=>{M(null),o.deleteEntity.mutate({type:"task",id:t.id},{onSuccess:()=>l(),onError:U=>{M(K(U instanceof Error?U.message:"","Failed to delete task."))}})};return r.useEffect(()=>{if(!$)return;const U=pe=>{d.current&&!d.current.contains(pe.target)&&g(!1)},H=pe=>{pe.key==="Escape"&&g(!1)};return document.addEventListener("mousedown",U),document.addEventListener("keydown",H),()=>{document.removeEventListener("mousedown",U),document.removeEventListener("keydown",H)}},[$]),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 flex-wrap items-center gap-3",children:[e.jsx(ct,{level:"task",size:16}),e.jsx("h2",{className:"break-words text-title font-semibold text-white",children:t.title}),e.jsx("span",{className:"rounded-full border border-white/[0.12] bg-white/[0.04] px-1.5 py-0.5 text-micro font-semibold uppercase tracking-[0.08em] text-white/65",children:t.hierarchyLabel??nt("task")})]}),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:ki(t.status)}}),qe(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})]}),W&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-faint",children:"·"}),e.jsx("span",{style:{color:W.tone},children:W.text})]})]}),(Q||E)&&e.jsxs("div",{className:"rounded-xl border border-white/[0.08] bg-white/[0.02] px-3 py-2.5",children:[e.jsx("p",{className:"text-micro uppercase tracking-[0.1em] text-white/50",children:"IWMT scope"}),e.jsxs("div",{className:"mt-2 space-y-1.5",children:[Q&&e.jsxs("button",{type:"button",onClick:()=>n({type:"workstream",entity:Q,initiative:s}),className:"flex w-full items-center gap-2 rounded-lg bg-white/[0.015] px-2 py-1.5 text-left transition-colors hover:bg-white/[0.06]",children:[e.jsx(ct,{level:"workstream",size:11,className:"flex-shrink-0"}),e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-white/50",children:Q.hierarchyLabel??nt("workstream")}),e.jsx("span",{className:"truncate text-caption text-bright",children:Q.name})]}),E&&e.jsxs("button",{type:"button",onClick:()=>n({type:"milestone",entity:E,initiative:s}),className:"ml-4 flex w-[calc(100%-1rem)] items-center gap-2 rounded-lg bg-white/[0.015] px-2 py-1.5 text-left transition-colors hover:bg-white/[0.06]",children:[e.jsx(ct,{level:"milestone",size:11,className:"flex-shrink-0"}),e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-white/50",children:E.hierarchyLabel??nt("milestone")}),e.jsx("span",{className:"truncate text-caption text-bright",children:E.title})]})]})]}),w?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:F,onChange:U=>p(U.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:U=>C(U.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:L,onChange:U=>z(U.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:ne,onChange:U=>ae(U.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:X,onChange:U=>P(U.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(U=>e.jsx("option",{value:U,children:qe(U)},U))})]})]})]}):t.description?e.jsx(ra,{text:t.description,mode:"block",className:"text-body text-secondary leading-relaxed"}):e.jsx("p",{className:"text-body text-muted",children:"No description yet."}),v.length>0&&e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(pn,{agents:v,max:4})})]}),N&&e.jsx("div",{className:"text-caption px-1",style:{color:`${O.red}b3`},children:N}),e.jsx("div",{className:"h-px bg-gradient-to-r from-transparent via-white/[0.06] to-transparent"}),e.jsx(Ls,{entityType:"task",entityId:t.id,authToken:c,embedMode:h}),e.jsx("div",{className:"space-y-2",children:e.jsx(Ds,{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:[y==="todo"&&e.jsx(ve,{label:"Start",color:O.lime,variant:"primary",onClick:()=>R("start"),disabled:ue}),(y==="in_progress"||y==="active")&&e.jsx(ve,{label:"Complete",color:O.teal,variant:"primary",onClick:()=>R("complete"),disabled:ue}),(y==="todo"||y==="in_progress"||y==="active")&&e.jsx(ve,{label:"Block",color:O.red,variant:"destructive",onClick:()=>R("block"),disabled:ue}),y==="blocked"&&e.jsx(ve,{label:"Unblock",color:O.amber,onClick:()=>R("unblock"),disabled:ue}),w?e.jsxs(e.Fragment,{children:[e.jsx(ve,{label:"Save",color:O.teal,variant:"primary",onClick:_,disabled:ue||!F.trim()}),e.jsx(ve,{label:"Cancel",variant:"ghost",onClick:()=>{b(!1),M(null),p(t.title),C(t.description??""),z(t.priority??""),ae(Zn(t.dueDate)),P(t.status)},disabled:ue})]}):e.jsx(ve,{label:"Edit",variant:"ghost",onClick:()=>{b(!0),M(null)},disabled:ue}),e.jsx("div",{className:"flex-1"}),e.jsxs("div",{className:"relative",ref:d,children:[e.jsx("button",{type:"button",className:"rounded-lg border border-white/10 bg-white/5 px-2 py-1.5 text-secondary hover:bg-white/10 hover:text-primary transition-colors text-sm leading-none",onClick:()=>{g(U=>!U),I(!1)},"aria-label":"More actions",disabled:ue,children:"⋯"}),$&&e.jsx("div",{className:"absolute bottom-full right-0 mb-1 min-w-[160px] rounded-lg border border-white/10 bg-[#0c1322] shadow-xl z-50",children:m?e.jsxs("div",{className:"flex flex-col gap-1 p-2",children:[e.jsx("span",{className:"text-caption",style:{color:`${O.red}b3`},children:"Delete task?"}),e.jsx("button",{type:"button",className:"w-full text-left rounded-md px-3 py-1.5 text-sm hover:bg-white/5 transition-colors",style:{color:O.red},onClick:q,disabled:ue,children:"Confirm Delete"}),e.jsx("button",{type:"button",className:"w-full text-left rounded-md px-3 py-1.5 text-sm text-secondary hover:bg-white/5 transition-colors",onClick:()=>I(!1),disabled:ue,children:"Cancel"})]}):e.jsx("div",{className:"p-1",children:e.jsx("button",{type:"button",className:"w-full text-left rounded-md px-3 py-1.5 text-sm hover:bg-white/5 transition-colors",style:{color:O.red},onClick:()=>I(!0),disabled:ue,children:"Delete"})})})]})]})})]})}function Zn(t){if(!t)return"";const s=Date.parse(t);return Number.isFinite(s)?new Date(s).toISOString().slice(0,10):""}function Si(t){var a,n;if(t.type==="initiative")return null;if(t.type==="workstream")return t.entity.name;const s=t.entity.workstreamId;return s?((n=(a=t.initiative.workstreams)==null?void 0:a.find(o=>o.id===s))==null?void 0:n.name)??null:null}function Ci(t){if(t.type==="initiative")return[{id:t.entity.id,label:t.entity.name,level:"initiative"}];const s=[{id:t.initiative.id,label:t.initiative.name,level:"initiative"}],a=Si(t),n=t.type==="workstream"?t.entity.id:t.entity.workstreamId;return a&&n&&s.push({id:n,label:a,level:"workstream"}),t.type==="milestone"?s.push({id:t.entity.id,label:t.entity.title,level:"milestone"}):t.type==="task"&&s.push({id:t.entity.id,label:t.entity.title,level:"task"}),s}function Ii(t){return t.type==="initiative"?t.entity.hierarchyLabel??nt("initiative"):t.type==="workstream"?t.entity.hierarchyLabel??nt("workstream"):t.type==="milestone"?t.entity.hierarchyLabel??nt("milestone"):t.entity.hierarchyLabel??nt("task")}function Fi({target:t,onClose:s}){return e.jsx(aa,{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.jsx("div",{className:"border-b border-subtle bg-[linear-gradient(180deg,rgba(255,255,255,0.03),rgba(255,255,255,0))] px-5 py-3 sm:px-6",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsx("div",{className:"min-w-0 flex-1",children:e.jsx("div",{className:"-mx-0.5 overflow-x-auto pb-0.5",children:e.jsx("ol",{className:"flex min-w-max items-center gap-1 px-0.5 text-body text-secondary",children:Ci(t).map((a,n,o)=>{const l=n===o.length-1;return e.jsxs("li",{className:"flex min-w-0 items-center gap-1",children:[n>0&&e.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"flex-shrink-0 text-faint","aria-hidden":!0,children:e.jsx("path",{d:"m9 18 6-6-6-6"})}),e.jsx(ct,{level:a.level,size:11,className:`flex-shrink-0 ${l?"opacity-95":"opacity-75"}`}),e.jsx("span",{className:`max-w-[320px] truncate sm:max-w-[420px] ${l?"font-medium text-primary":"text-secondary"}`,children:a.label})]},a.id)})})})}),e.jsxs("span",{className:"inline-flex flex-shrink-0 items-center gap-1.5 rounded-full border border-white/[0.12] bg-white/[0.04] px-2.5 py-1 text-micro uppercase tracking-[0.08em] text-white/72",children:[e.jsx(ct,{level:t.type,size:11,className:"opacity-90"}),e.jsx("span",{className:"font-semibold text-white/82",children:Ii(t)}),e.jsx("span",{children: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(fi,{initiative:t.entity}),t.type==="workstream"&&e.jsx(wi,{workstream:t.entity,initiative:t.initiative}),t.type==="milestone"&&e.jsx(vi,{milestone:t.entity,initiative:t.initiative}),t.type==="task"&&e.jsx(Ni,{task:t.entity,initiative:t.initiative})]})]})})}function er(t){return(t??"").trim().toLowerCase().replace(/[\s-]+/g,"_")}function Ei(t){return t.split("_").map(s=>s.slice(0,1).toUpperCase()+s.slice(1)).join(" ")}const sn=["active","in_progress","not_started","planned","blocked","at_risk","paused","completed","done","backlog","todo","pending","draft"],Ai=[{value:"target",label:"Target date"},{value:"created",label:"Created at"},{value:"updated",label:"Updated at"}],Mi=[{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"}],Di=[{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 Ti({initiatives:t,visibleCount:s}){const{statusFilters:a,dateField:n,datePreset:o,dateStart:l,dateEnd:c,activeFilterCount:h,groupBy:f,setGroupBy:v,sortBy:m,setSortBy:I,setStatusFilters:$,toggleStatusFilter:g,setDateField:d,setDatePreset:w,setDateStart:b,setDateEnd:N,clearFilters:M}=zt(),[F,p]=r.useState(!1),[j,C]=r.useState(!1),L=r.useRef(null);r.useEffect(()=>{if(!F)return;const R=q=>{var H;const U=q.target;U&&((H=L.current)!=null&&H.contains(U)||p(!1))},_=q=>{q.key==="Escape"&&p(!1)};return document.addEventListener("mousedown",R),document.addEventListener("keydown",_),()=>{document.removeEventListener("mousedown",R),document.removeEventListener("keydown",_)}},[F]);const z=r.useMemo(()=>{const R=new Map;for(const q of t){const U=new Set([er(q.status),er(q.rawStatus)]);for(const H of U)H&&R.set(H,(R.get(H)??0)+1)}for(const q of sn)R.has(q)||R.set(q,0);return Array.from(R.entries()).sort((q,U)=>{const H=sn.indexOf(q[0]),pe=sn.indexOf(U[0]);return H>=0&&pe>=0?H-pe:H>=0?-1:pe>=0?1:q[0].localeCompare(U[0])}).map(([q,U])=>({key:q,count:U}))},[t]),ne=a.length,ae=r.useMemo(()=>z.filter(R=>j||R.count>0||a.includes(R.key)),[j,a,z]),X=z.length-ae.length,P=r.useMemo(()=>n==="target"?Mi:Di,[n]);r.useEffect(()=>{P.some(R=>R.value===o)||w("any")},[o,P,w]);const y=[{value:"none",label:"None"},{value:"status",label:"Status"},{value:"date",label:"Date"},{value:"category",label:"Category"}],W=[{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)"}],E=f!=="status"||m!=="default",Q=h>0,K=h,ue=Q||E;return e.jsxs("div",{ref:L,className:"relative flex items-center gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>{p(R=>{const _=!R;return _||C(!1),_})},"data-state":F||K>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"}),K>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:K})]}),s<t.length&&e.jsxs("span",{className:"text-micro text-muted whitespace-nowrap",children:[s,"/",t.length]}),e.jsx(lt,{initial:!1,children:Q&&e.jsx(de.button,{type:"button",onClick:M,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(lt,{children:F&&e.jsxs(de.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"})]}),Q?e.jsxs("span",{className:"rounded-full border border-strong bg-white/[0.04] px-2 py-0.5 text-micro text-primary",children:[K," active"]}):E?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:R=>v(R.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:y.map(R=>e.jsx("option",{value:R.value,children:R.label},R.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:m,onChange:R=>I(R.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(R=>e.jsx("option",{value:R.value,children:R.label},R.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"}),X>0&&e.jsx("button",{type:"button",onClick:()=>C(R=>!R),className:"text-micro text-muted transition-colors hover:text-white/72",children:j?"Hide empty":`Show empty (${X})`})]}),e.jsx("div",{className:"max-h-40 space-y-1 overflow-auto pr-1",children:ae.map(R=>{const _=a.includes(R.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 ${_?"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:_,onChange:()=>g(R.key),className:"h-3.5 w-3.5 accent-[#BFFF00]"}),e.jsx("span",{children:Ei(R.key)})]}),e.jsx("span",{className:"text-micro text-secondary",children:R.count})]},R.key)})}),e.jsxs("div",{className:"mt-2 flex items-center justify-between",children:[e.jsx("button",{type:"button",onClick:()=>$([]),className:`text-micro uppercase tracking-[0.08em] ${ne>0?"text-primary hover:text-white":"text-muted"}`,disabled:ne===0,children:"Clear status"}),e.jsxs("div",{className:"text-micro text-secondary",children:[ne," 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:R=>d(R.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:Ai.map(R=>e.jsx("option",{value:R.value,children:R.label},R.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:o,onChange:R=>w(R.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:P.map(R=>e.jsx("option",{value:R.value,children:R.label},R.value))})]})]}),o==="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:l,onChange:R=>b(R.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:R=>N(R.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"})]})]})]}),ue&&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&&e.jsx("button",{type:"button",onClick:()=>{v("status"),I("default")},className:"text-micro uppercase tracking-[0.09em] text-secondary transition-colors hover:text-bright",children:"Reset layout"}),Q&&e.jsx("button",{type:"button",onClick:M,className:"text-micro uppercase tracking-[0.09em] text-secondary transition-colors hover:text-bright",children:"Clear filters"})]})]})]})})]})}function Ct(t){return!t||typeof t!="object"||Array.isArray(t)?null:t}function fe(t){if(typeof t!="string")return null;const s=t.trim();return s.length>0?s:null}function Ee(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 $i(t){const s=(fe(t)??"").toLowerCase();return s==="assigned"||s==="inferred"||s==="fallback"?s:null}function hs(t){const s=fe(t);if(!s)return null;const a=s.toLowerCase();return a==="undefined"||a==="null"||a==="main"||a==="unassigned"?null:s}function kr(t){return hs(t)}function Li(t,s,a){if(!Array.isArray(t)){if(s||a){const l=s??a??"",c=a??s??"";if(l.trim().length>0&&c.trim().length>0)return[{id:l,name:c}]}return[]}const n=[],o=new Set;for(const l of t){const c=Ct(l);if(!c)continue;const h=kr(c.id)??hs(c.name),f=hs(c.name)??h;if(!h||!f)continue;const v=h.toLowerCase();o.has(v)||(o.add(v),n.push({id:h,name:f}))}if(n.length===0&&(s||a)){const l=s??a??"",c=a??s??"";if(l.trim().length>0&&c.trim().length>0)return[{id:l,name:c}]}return n}function cn(t,s){const a=(fe(t)??"").toLowerCase();return a==="initiative"?"initiative":a==="milestone"?"milestone":a==="task"?"task":a==="workstream"?"workstream":s}function _i(t){return(fe(t)??"").toLowerCase()==="algorithmic"?"algorithmic":"manual"}function Kt(t){return Array.isArray(t)?t.map(s=>fe(s)).filter(s=>!!s):[]}function Bi(t,s,a){const n=Ct(t);if(!n)return null;const o=fe(n.sliceId)??fe(n.id);if(!o)return null;const l=cn(n.level??n.scope,s),c=fe(n.title)??fe(n.workstreamTitle)??fe(n.milestoneTitle)??fe(n.taskTitle)??fe(n.initiativeTitle)??o,h=Ct(n.order),f=Ct(n.dispatch),v=Ct(n.objectiveSnapshot??n.objective??n.ranking),m=Ct(n.factors),I=Ct(n.iwmt),$=Ct(n.lineage),g=kr(n.runnerAgentId??n.agentId),d=hs(n.runnerAgentName??n.agentName)??hs(n.runner),w=Li(n.runnerAgents,g,d??g),b=w[0]??null;return{sliceId:o,level:l,title:c,initiativeId:fe(n.initiativeId),initiativeTitle:fe(n.initiativeTitle),workstreamId:fe(n.workstreamId),workstreamTitle:fe(n.workstreamTitle),milestoneId:fe(n.milestoneId),milestoneTitle:fe(n.milestoneTitle),taskId:fe(n.taskId),taskTitle:fe(n.taskTitle),status:fe(n.status)??fe(n.queueState)??(f&&f.runnable===!1?"blocked":"queued"),priorityNum:Ee(n.priorityNum??n.nextTaskPriority),dueAt:fe(n.dueAt??n.nextTaskDueAt),dependencyState:fe(n.dependencyState),objectiveScore:Ee(n.objectiveScore)??Ee(v==null?void 0:v.objectiveScore)??Ee(n.mixScore),roiPerToken:Ee(n.roiPerToken)??Ee(v==null?void 0:v.roiPerToken),expectedTokens:Ee(n.expectedTokens)??Ee(v==null?void 0:v.expectedTokens),expectedValueUsd:Ee(n.expectedValueUsd)??Ee(v==null?void 0:v.expectedValueUsd),goalAlignment:Ee(n.goalAlignment)??Ee(m==null?void 0:m.goalAlignment),riskPenalty:Ee(n.riskPenalty)??Ee(m==null?void 0:m.riskPenalty),runnable:typeof(f==null?void 0:f.runnable)=="boolean"?f.runnable:void 0,blockReason:fe((f==null?void 0:f.blockReason)??n.blockReason),suggestedScope:f&&f.suggestedScope?cn(f.suggestedScope,l):null,manualRank:Ee(n.manualRank)??Ee(h==null?void 0:h.manualRank),algorithmRank:Ee(n.algorithmRank)??Ee(h==null?void 0:h.algorithmRank)??a,finalRank:Ee(n.finalRank)??Ee(h==null?void 0:h.finalRank)??a,iwmt:I?{laneId:fe(I.laneId),mixScore:Ee(I.mixScore),factors:Array.isArray(I.factors)?I.factors.map(N=>{const M=Ct(N);return M?{key:fe(M.key)??void 0,label:fe(M.label)??fe(M.key)??void 0,value:Ee(M.value)??void 0,weight:Ee(M.weight)??void 0}:null}).filter(N=>!!N):void 0}:null,lineage:$?{initiativeIds:Kt($.initiativeIds),workstreamIds:Kt($.workstreamIds),milestoneIds:Kt($.milestoneIds),taskIds:Kt($.taskIds),iwmtIds:Kt($.iwmtIds)}:null,sourceWorkstreamIds:Kt(n.sourceWorkstreamIds),queueState:fe(n.queueState),sliceTaskIds:Kt(n.sliceTaskIds),sliceTaskCount:Ee(n.sliceTaskCount),sliceMilestoneId:fe(n.sliceMilestoneId),runnerAgentId:(b==null?void 0:b.id)??g,runnerAgentName:(b==null?void 0:b.name)??d,runnerAgents:w,runnerSource:$i(n.runnerSource)??((b==null?void 0:b.id)??g?"inferred":"fallback"),updatedAt:fe(n.updatedAt)}}function Pi(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 Ri(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 qi({workspaceId:t=null,initiativeId:s=null,level:a,orderMode:n=null,includeCompleted:o=!1,search:l="",offset:c=0,limit:h=24,authToken:f=null,embedMode:v=!1,enabled:m=!0}){var M,F,p,j,C,L,z,ne,ae;const I=fs(),$=Math.max(0,c),g=Math.max(1,Math.min(300,h)),d=l.trim(),w=r.useMemo(()=>Jt.missionControlSlices({workspaceId:t,initiativeId:s,level:a,orderMode:n,includeCompleted:o,search:d,offset:$,limit:g,authToken:f,embedMode:v}),[f,v,o,s,a,g,$,d,n,t]),b=Xt({queryKey:w,enabled:m,queryFn:async()=>{if(I)return Pi(a,n??"manual",$,g);const X=new URLSearchParams;Bn(X,t,{allTokenWhenMissing:!0}),s&&X.set("initiative_id",s),X.set("level",a),X.set("include_completed",o?"1":"0"),X.set("offset",String($)),X.set("limit",String(g)),X.set("mix_policy","iwmt_v1"),n&&X.set("order_mode",n),d.length>0&&X.set("q",d);const P=await fetch(`/orgx/api/mission-control/slices?${X.toString()}`,{headers:ft({authToken:f,embedMode:v})}),y=await P.json().catch(()=>null);if(!P.ok){const _=y&&typeof y.error=="string"&&y.error||y&&typeof y.message=="string"&&y.message||`Failed to fetch mission-control slices (${P.status})`;throw new Error(_)}const W=Array.isArray(y==null?void 0:y.items)?y.items:[],E=cn((y==null?void 0:y.level)??(y==null?void 0:y.scope),a),Q=W.map((_,q)=>Bi(_,E,q+1)).filter(_=>!!_),K=Ct(y==null?void 0:y.pagination),ue=Ee(y==null?void 0:y.total)??Ee(K==null?void 0:K.total)??Q.length,R=K?{offset:Ee(K.offset)??$,limit:Ee(K.limit)??g,total:ue,nextCursor:fe(K.nextCursor),hasMore:typeof K.hasMore=="boolean"?K.hasMore:!1}:Ri({offset:$,limit:g,total:ue});return{ok:!0,generatedAt:fe(y==null?void 0:y.generatedAt)??new Date().toISOString(),workspaceId:fe((y==null?void 0:y.workspaceId)??(y==null?void 0:y.workspace_id)),initiativeId:fe((y==null?void 0:y.initiativeId)??(y==null?void 0:y.initiative_id)??s),level:E,mixPolicy:fe((y==null?void 0:y.mixPolicy)??(y==null?void 0:y.mix_policy))??"iwmt_v1",orderMode:_i((y==null?void 0:y.orderMode)??(y==null?void 0:y.order_mode)??(y==null?void 0:y.order)),total:ue,items:Q,degraded:Array.isArray(y==null?void 0:y.degraded)?y.degraded.map(_=>fe(_)).filter(_=>!!_):void 0,source:fe(y==null?void 0:y.source)==="canonical"?"canonical":fe(y==null?void 0:y.source)==="local_fallback"?"local_fallback":"local",pagination:R}}}),N=r.useRef(null);return r.useEffect(()=>{var W;const X=(W=b.data)==null?void 0:W.pagination;if(!m||!(X!=null&&X.hasMore)||!X.nextCursor||N.current===X.nextCursor)return;const P=Number.parseInt(X.nextCursor,10);if(!Number.isFinite(P))return;N.current=X.nextCursor;const y=new URLSearchParams;Bn(y,t,{allTokenWhenMissing:!0}),s&&y.set("initiative_id",s),y.set("level",a),y.set("include_completed",o?"1":"0"),y.set("offset",String(P)),y.set("limit",String(g)),y.set("mix_policy","iwmt_v1"),n&&y.set("order_mode",n),d.length>0&&y.set("q",d),fetch(`/orgx/api/mission-control/slices?${y.toString()}`,{headers:ft({authToken:f,embedMode:v})}).catch(()=>{})},[m,(F=(M=b.data)==null?void 0:M.pagination)==null?void 0:F.hasMore,(j=(p=b.data)==null?void 0:p.pagination)==null?void 0:j.nextCursor,t,s,a,n,o,d,g,f,v]),{...b,slices:((C=b.data)==null?void 0:C.items)??[],orderMode:((L=b.data)==null?void 0:L.orderMode)??n??"manual",degraded:((z=b.data)==null?void 0:z.degraded)??[],source:((ne=b.data)==null?void 0:ne.source)??null,pagination:((ae=b.data)==null?void 0:ae.pagination)??null}}function tr(t,s){if(!s||s.trim().length===0)return;const a=s.trim();t.workspace_id=a}async function sr(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 Oi({workspaceId:t=null,initiativeId:s=null,level:a,authToken:n=null,embedMode:o=!1}){const l=mn(),c=It({mutationFn:async f=>{const v={level:a,order:f.map(I=>({sliceId:I}))};tr(v,t),s&&(v.initiative_id=s);const m=await fetch("/orgx/api/mission-control/slices/reorder",{method:"POST",headers:ft({authToken:n,embedMode:o,contentTypeJson:!0,workspaceId:t}),body:JSON.stringify(v)});return sr(m)},onMutate:async f=>{const v=l.getQueriesData({queryKey:["mission-control-slices"]});for(const[m,I]of v){if(!I||I.level!==a||s&&I.initiativeId&&I.initiativeId!==s)continue;const $=new Map(I.items.map(w=>[w.sliceId,w])),g=f.map(w=>$.get(w)??null).filter(w=>!!w);if(g.length===0)continue;const d=new Set(g.map(w=>w.sliceId));for(const w of I.items)d.has(w.sliceId)||g.push(w);l.setQueryData(m,{...I,items:g.map((w,b)=>({...w,manualRank:b+1,finalRank:b+1})),orderMode:"manual"})}return{snapshots:v}},onError:(f,v,m)=>{for(const[I,$]of(m==null?void 0:m.snapshots)??[])l.setQueryData(I,$)},onSettled:()=>{l.invalidateQueries({queryKey:["mission-control-slices"]})}}),h=It({mutationFn:async f=>{const v={level:a,order_mode:f};tr(v,t),s&&(v.initiative_id=s);const m=await fetch("/orgx/api/mission-control/slices/order-mode",{method:"POST",headers:ft({authToken:n,embedMode:o,contentTypeJson:!0,workspaceId:t}),body:JSON.stringify(v)});return sr(m)},onMutate:async f=>{const v=l.getQueriesData({queryKey:["mission-control-slices"]});for(const[m,I]of v)!I||I.level!==a||s&&I.initiativeId&&I.initiativeId!==s||l.setQueryData(m,{...I,orderMode:f});return{snapshots:v}},onError:(f,v,m)=>{for(const[I,$]of(m==null?void 0:m.snapshots)??[])l.setQueryData(I,$)},onSettled:()=>{l.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 dn=[{value:"initiative",label:"Initiative"},{value:"workstream",label:"Workstream"},{value:"milestone",label:"Milestone"},{value:"task",label:"Task"}];function nr(t){var s;return((s=dn.find(a=>a.value===t))==null?void 0:s.label)??"Workstream"}function rr(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 ar(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 cs(t,s=2){return typeof t!="number"||!Number.isFinite(t)?"—":t.toFixed(s)}function xs(t,s){if(!t)return s;const a=t.trim();return a?xn(a)?`${s} ${br(a)}`:a:s}function ir(t){var a,n,o,l;const s=t.title.trim()||((a=t.taskTitle)==null?void 0:a.trim())||((n=t.milestoneTitle)==null?void 0:n.trim())||((o=t.workstreamTitle)==null?void 0:o.trim())||((l=t.initiativeTitle)==null?void 0:l.trim())||"";return s&&!xn(s)?ds(s):t.level==="task"?xs(t.taskId??t.sliceId,"Task"):t.level==="milestone"?xs(t.milestoneId??t.sliceId,"Milestone"):t.level==="initiative"?xs(t.initiativeId??t.sliceId,"Initiative"):xs(t.workstreamId??t.sliceId,"Workstream")}function or(t){const s=[t.initiativeTitle,t.workstreamTitle,t.milestoneTitle,t.taskTitle].filter(n=>!!(n&&n.trim().length>0));return s.length===0?ds(xs(t.sliceId,"Slice")):s.map(n=>ds(n)).filter(n=>n.length>0).join(" / ")}function lr(t){var o,l;const s=((o=t.runnerAgentName)==null?void 0:o.trim())??"",a=((l=t.runnerAgentId)==null?void 0:l.trim().toLowerCase())??"";if(!s)return a&&a!=="main"?ds(a):"Unassigned";const n=s.toLowerCase();return n==="undefined"||n==="null"||n==="main"&&(a==="main"||t.runnerSource==="fallback")?"Unassigned":ds(s)}function cr(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 dr(t,s){return!t||t.trim().length===0?s:jt(t.trim())||s}function ur({workspaceId:t=null,initiativeId:s=null,authToken:a=null,embedMode:n=!1,className:o="",title:l="Slice Explorer",compact:c=!1,onOpenInitiative:h}){var Oe,He;const[f,v]=r.useState("workstream"),[m,I]=r.useState(""),[$,g]=r.useState(0),[d]=r.useState(c?18:28),[w,b]=r.useState(null),[N,M]=r.useState([]),[F,p]=r.useState(!1),[j,C]=r.useState(null),[L,z]=r.useState(!1),ne=r.useRef(null),ae=qi({workspaceId:t,initiativeId:s,level:f,orderMode:j,includeCompleted:!1,search:m,offset:$,limit:d,authToken:a,embedMode:n,enabled:!!(t||s)}),X=Oi({workspaceId:t,initiativeId:s,level:f,authToken:a,embedMode:n}),P=ae.slices,y=ae.source,W=ae.pagination,E=ae.orderMode??"manual",Q=(W==null?void 0:W.offset)??$,K=(W==null?void 0:W.total)??((Oe=ae.data)==null?void 0:Oe.total)??P.length,ue=P.length===0?0:Q+1,R=P.length===0?0:Q+P.length;r.useEffect(()=>{if(!w)return;const x=window.setTimeout(()=>b(null),5e3);return()=>window.clearTimeout(x)},[w]),r.useEffect(()=>{if(!L)return;const x=Z=>{var De;const ge=Z.target;ge&&((De=ne.current)!=null&&De.contains(ge)||z(!1))},Y=Z=>{Z.key==="Escape"&&z(!1)};return document.addEventListener("mousedown",x),document.addEventListener("touchstart",x),document.addEventListener("keydown",Y),()=>{document.removeEventListener("mousedown",x),document.removeEventListener("touchstart",x),document.removeEventListener("keydown",Y)}},[L]),r.useEffect(()=>{g(0)},[f,m]);const _=r.useMemo(()=>P.map(x=>x.sliceId).join("|"),[P]);r.useEffect(()=>{M(P.map(x=>x.sliceId)),p(!1)},[_,E]);const q=r.useMemo(()=>new Map(P.map(x=>[x.sliceId,x])),[P]),U=r.useMemo(()=>{if(!F||N.length!==P.length)return P;const x=N.map(Y=>q.get(Y)??null).filter(Y=>!!Y);return x.length!==P.length?P:x},[F,N,P,q]),H=E==="manual"&&P.length>1&&!X.isReordering&&Q===0&&!((W==null?void 0:W.hasMore)??!1),pe=async()=>{if(!(!H||!F))try{await X.reorder(N),p(!1),b({tone:"success",message:`Saved ${N.length} slice positions.`})}catch(x){b({tone:"error",message:dr(x instanceof Error?x.message:"","Failed to save slice order.")})}},re=async x=>{if(!(x===E&&j===null)){C(x);try{await X.setOrderMode(x),b({tone:"success",message:`Slice ordering set to ${x}.`})}catch(Y){b({tone:"error",message:dr(Y instanceof Error?Y.message:"",`Failed to set ${x} ordering.`)})}finally{C(null)}}},Se=x=>{!h||!x.initiativeId||h(x.initiativeId,x.initiativeTitle??void 0)};return e.jsxs("section",{className:ls("flex min-h-0 flex-col rounded-2xl border border-strong bg-[#070b12]/88",o),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:l}),e.jsx("span",{className:"rounded-full border border-strong bg-white/[0.04] px-2 py-0.5 text-micro text-secondary",children:K}),e.jsxs("div",{className:"ml-auto flex items-center gap-1.5",children:[e.jsxs("div",{ref:ne,className:"relative",children:[e.jsxs("button",{type:"button",onClick:()=>z(x=>!x),className:"control-pill h-8 px-2.5 text-micro font-semibold","aria-haspopup":"menu","aria-expanded":L,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"})]}),L?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:dn.map(x=>e.jsxs("button",{type:"button",onClick:()=>{v(x.value),z(!1)},className:ls("control-pill flex h-8 items-center gap-1.5 px-2 text-micro font-semibold",f===x.value?"border-[#BFFF00]/34 bg-[#BFFF00]/[0.12] text-[#E8FFD0]":"text-secondary"),children:[e.jsx(Es,{type:x.value,size:10,className:"opacity-80"}),e.jsx("span",{children:x.label})]},x.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:ls("control-pill h-8 px-2.5 text-micro font-semibold",E==="manual"?"border-[#BFFF00]/34 bg-[#BFFF00]/[0.12] text-[#E8FFD0]":"text-secondary"),disabled:X.isSettingOrderMode,onClick:()=>void re("manual"),children:"Manual"}),e.jsx("button",{type:"button",className:ls("control-pill h-8 px-2.5 text-micro font-semibold",E==="algorithmic"?"border-teal-300/34 bg-teal-400/[0.13] text-teal-100":"text-secondary"),disabled:X.isSettingOrderMode,onClick:()=>void re("algorithmic"),children:"Algorithmic"})]})]})]})}):null]}),E==="manual"&&e.jsx("button",{type:"button",className:"control-pill h-8 px-2.5 text-micro font-semibold disabled:opacity-45",disabled:!F||!H,onClick:()=>void pe(),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(hn,{value:m,onChange:I,placeholder:"Search slices, entities, or IDs..."})}),e.jsx("span",{className:"chip whitespace-nowrap text-micro",children:((He=dn.find(x=>x.value===f))==null?void 0:He.label)??"Workstream"})]}),(y==="local_fallback"||ae.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:y==="local_fallback"?"Canonical slices unavailable; showing local fallback.":ae.degraded[0]})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto overscroll-y-contain scroll-smooth px-2 pb-2 pt-2",children:ae.isLoading?e.jsx("div",{className:"space-y-2 px-1",children:Array.from({length:c?4:7}).map((x,Y)=>e.jsxs("div",{className:"rounded-xl border border-strong bg-white/[0.02] px-3 py-2",children:[e.jsx(Ft,{className:"h-3.5 w-1/2 rounded-full"}),e.jsx(Ft,{className:"mt-2 h-3 w-4/5 rounded-full"})]},`slice-loading-${Y}`))}):U.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."}):H?e.jsx(da,{axis:"y",values:N,onReorder:x=>{M(x),p(!0)},className:"space-y-2",children:N.map((x,Y)=>{var Ce;const Z=q.get(x);if(!Z)return null;const ge=Z.finalRank??Z.manualRank??Z.algorithmRank??Y+1,ze=(((Ce=Z.iwmt)==null?void 0:Ce.factors)??[]).filter(Ie=>typeof Ie.value=="number"&&Number.isFinite(Ie.value)),Be=typeof Z.roiPerToken=="number"&&Number.isFinite(Z.roiPerToken),T=typeof Z.objectiveScore=="number"&&Number.isFinite(Z.objectiveScore),G=lr(Z),oe=or(Z);return e.jsxs(ua,{value:Z.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 ${ar(Z.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:["#",ge]}),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(Es,{type:Z.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:ir(Z)})]})}),e.jsxs("div",{className:"ml-auto flex flex-shrink-0 items-center gap-1.5",children:[e.jsx("span",{className:ls("rounded-full border px-2 py-0.5 text-micro uppercase tracking-[0.08em]",rr(Z.status)),children:Z.status.replace(/_/g," ")}),Z.initiativeId&&h?e.jsx("button",{type:"button",className:"control-pill h-6 px-2 text-micro font-semibold",onClick:()=>Se(Z),children:"Open"}):null]})]}),e.jsx("p",{className:"mt-1 inline-flex min-w-0 items-center gap-1 truncate text-micro text-secondary",title:oe,children:e.jsx("span",{className:"truncate",children:oe})}),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:nr(Z.level)}),e.jsx("span",{className:"chip text-micro",children:cr(Z)}),e.jsxs("span",{className:"chip text-micro",children:["Agent ",G]}),Be?e.jsxs("span",{className:"chip text-micro",children:["ROI/token ",cs(Z.roiPerToken,3)]}):null,T?e.jsxs("span",{className:"chip text-micro",children:["Obj ",cs(Z.objectiveScore,2)]}):null]}),ze.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:ze.slice(0,3).map((Ie,Le)=>e.jsxs("p",{children:[(Ie.label??Ie.key??"factor").replace(/_/g," "),":"," ",cs(Ie.value,2)]},`${Z.sliceId}-factor-${Le}`))})]})]})]})]},Z.sliceId)})}):e.jsx("div",{className:"space-y-2",children:U.map((x,Y)=>{var oe;const Z=x.finalRank??x.manualRank??x.algorithmRank??Y+1,De=(((oe=x.iwmt)==null?void 0:oe.factors)??[]).filter(Ce=>typeof Ce.value=="number"&&Number.isFinite(Ce.value)),ze=typeof x.roiPerToken=="number"&&Number.isFinite(x.roiPerToken),Be=typeof x.objectiveScore=="number"&&Number.isFinite(x.objectiveScore),T=lr(x),G=or(x);return e.jsxs(de.article,{initial:{opacity:0,y:10,scale:.985},animate:{opacity:1,y:0,scale:1},transition:{duration:.22,delay:Math.min(Y,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 ${ar(x.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:["#",Z]}),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(Es,{type:x.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:ir(x)})]}),e.jsx("p",{className:"mt-1 inline-flex min-w-0 items-center gap-1 truncate text-micro text-secondary",title:G,children:e.jsx("span",{className:"truncate",children:G})}),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:nr(x.level)}),e.jsx("span",{className:"chip text-micro",children:cr(x)}),e.jsxs("span",{className:"chip text-micro",children:["Agent ",T]}),ze?e.jsxs("span",{className:"chip text-micro",children:["ROI/token ",cs(x.roiPerToken,3)]}):null,Be?e.jsxs("span",{className:"chip text-micro",children:["Obj ",cs(x.objectiveScore,2)]}):null,e.jsx("span",{className:ls("rounded-full border px-2 py-0.5 uppercase tracking-[0.08em]",rr(x.status)),children:x.status.replace(/_/g," ")})]}),De.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:De.slice(0,3).map((Ce,Ie)=>e.jsxs("p",{children:[(Ce.label??Ce.key??"factor").replace(/_/g," "),":"," ",cs(Ce.value,2)]},`${x.sliceId}-factor-static-${Ie}`))})]})]}),x.initiativeId&&h?e.jsx("button",{type:"button",className:"control-pill h-7 px-2 text-micro font-semibold",onClick:()=>Se(x),children:"Open"}):null]})]},x.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:[ue,"-",R," of ",K]}),e.jsx("button",{type:"button",className:"control-pill ml-auto h-7 px-2 text-micro font-semibold disabled:opacity-40",disabled:Q===0,onClick:()=>g(Math.max(0,Q-d)),children:"Prev"}),e.jsx("button",{type:"button",className:"control-pill h-7 px-2 text-micro font-semibold disabled:opacity-40",disabled:!((W==null?void 0:W.hasMore)??!1),onClick:()=>g(Q+d),children:"Next"})]}),w&&e.jsx("div",{className:"border-t border-strong px-3 py-2",children:e.jsx(yr,{open:!0,tone:w.tone==="error"?"error":"success",title:w.tone==="error"?"Slice explorer error":"Slice explorer updated",message:w.message,onDismiss:()=>b(null),autoDismissMs:4200})})]})}function zi({completionPercent:t,totalTasks:s,doneTasks:a,blockedCount:n,activeAgents:o,className:l}){const c=t*.6,h=Math.min(n*10,30),f=Math.min(o*5,10),v=Math.max(0,Math.min(100,c+f-h+40)),m=Math.round(v/10),I=m>=7;return e.jsx("div",{className:`${I?"surface-hero":"surface-tier-2"} rounded-2xl px-5 py-4 ${l??""}`,children:e.jsxs("div",{className:"flex items-center gap-5",children:[e.jsx(jr,{percent:v,size:56}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"text-[28px] font-light",style:{color:m>=7?O.lime:m>=5?O.amber:O.red,fontVariantNumeric:"tabular-nums"},children:[m,e.jsx("span",{className:"text-sm font-normal text-muted",children:"/10"})]}),e.jsx("p",{className:"text-caption text-secondary mt-0.5",children:"Health Score"})]}),e.jsxs("div",{className:"flex items-center gap-6 flex-shrink-0",children:[e.jsxs("div",{className:"text-center",children:[e.jsxs("p",{className:"text-body font-light tabular-nums",style:{color:O.teal},children:[a,"/",s]}),e.jsx("p",{className:"text-micro text-muted",children:"tasks"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-body font-light tabular-nums",style:{color:n>0?O.red:"rgba(255,255,255,0.2)"},children:n}),e.jsx("p",{className:"text-micro text-muted",children:"blocked"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-body font-light tabular-nums",style:{color:o>0?O.lime:"rgba(255,255,255,0.2)"},children:o}),e.jsx("p",{className:"text-micro text-muted",children:"agents"})]})]})]})})}function nn(t){return t>=1e4?`$${(t/100).toFixed(0)}`:`$${(t/100).toFixed(2)}`}function Ui({usage:t,className:s}){if(!t)return null;const a=t.actual.costCents,n=t.plan.includedBudgetCents,o=t.headroom.budgetRemainingCents,l=t.utilization.budgetPct??0,c=t.velocity.dailyAvgCostCents,h=l>85?O.red:l>60?O.amber:O.lime,f=l>85?O.red:l>60?O.amber:O.lime;return e.jsxs("div",{className:`subsection-shell rounded-2xl px-5 py-4 ${s??""}`,children:[e.jsx("p",{className:"section-kicker font-semibold mb-3",children:"Budget & Spend"}),e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-widest text-muted",children:"Spent"}),e.jsx("p",{className:"mt-1 text-[20px] font-light tabular-nums text-primary",children:nn(a)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-widest text-muted",children:"Remaining"}),e.jsx("p",{className:"mt-1 text-[20px] font-light tabular-nums",style:{color:f},children:nn(o)})]})]}),n>0&&e.jsxs("div",{className:"mt-3",children:[e.jsx("div",{className:"h-1.5 rounded-full bg-white/[0.06] overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full transition-all duration-500",style:{width:`${Math.min(l,100)}%`,background:`linear-gradient(90deg, ${h}, ${h}cc)`}})}),e.jsxs("div",{className:"mt-1.5 flex items-center justify-between text-micro text-muted",children:[e.jsxs("span",{className:"tabular-nums",children:[Math.round(l),"% utilized"]}),c>0&&e.jsxs("span",{className:"tabular-nums",children:["~",nn(c),"/day"]})]})]})]})}function Wi({enabled:t=!0,projectId:s=null}={}){return Xt({queryKey:["live-initiatives-summary",{projectId:s??null}],queryFn:async()=>{const a=new URLSearchParams;s&&s.trim().length>0&&a.set("workspace_id",s);const n=`/orgx/api/live/initiatives/summary${a.toString()?`?${a}`:""}`,o=await fetch(n,{headers:ft({workspaceId:s})});if(!o.ok)throw new Error(`Failed to load initiative summary (${o.status})`);return await o.json()},enabled:t,refetchInterval:6e4})}function rn(t){return(t??"").trim().toLowerCase().replace(/[\s-]+/g,"_")}function un(t){return new Date(t.getFullYear(),t.getMonth(),t.getDate()).getTime()}function mr(t){if(!t)return null;const s=Date.parse(`${t}T00:00:00`);return Number.isFinite(s)?s:null}function Qi(t,s){return s==="target"?t.targetDate??null:s==="created"?t.createdAt??null:t.updatedAt??t.createdAt??null}function pr(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 xr(t){return t==="active"?0:t==="blocked"?1:t==="paused"?2:3}function hr(t,s){if(s==="status"){const a=new Map,n=["active","blocked","paused","completed"];for(const o of t){const l=o.status??"active",c=a.get(l)??[];c.push(o),a.set(l,c)}return n.filter(o=>a.has(o)).concat(Array.from(a.keys()).filter(o=>!n.includes(o))).map(o=>{var l;return{key:o,label:o.charAt(0).toUpperCase()+o.slice(1),count:((l=a.get(o))==null?void 0:l.length)??0,initiatives:a.get(o)??[]}})}if(s==="category"){const a=new Map;for(const n of t){const o=n.category??"Uncategorized",l=a.get(o)??[];l.push(n),a.set(o,l)}return Array.from(a.entries()).sort((n,o)=>n[0].localeCompare(o[0])).map(([n,o])=>({key:n,label:n,count:o.length,initiatives:o}))}if(s==="date"){const n=un(new Date),o=n+7*864e5,l=n+30*864e5,c={overdue:[],this_week:[],this_month:[],later:[],no_date:[]};for(const f of t){const v=f.targetDate?Date.parse(f.targetDate):null;v===null||!Number.isFinite(v)?c.no_date.push(f):v<n?c.overdue.push(f):v<o?c.this_week.push(f):v<l?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 Gt(t,s){return`${t}:${s}`}function Hi(t){return`mc-group-${t}`.toLowerCase().replace(/[^a-z0-9_-]+/g,"-")}function fr(t,s){if(t.size!==s.size)return!1;for(const a of t)if(!s.has(a))return!1;return!0}function Vi(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 Ki(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 Gi(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 jt(a||t)||"Live data is temporarily unavailable."}function Ot(t,s){return!t||t.trim().length===0?s:jt(t.trim())||s}const Ji=[12,24,36,48,72];function xo({initiatives:t,activities:s,agents:a,runtimeInstances:n=[],workspaceInitiativeId:o=null,isLoading:l,authToken:c,embedMode:h,initialInitiativeId:f,connection:v,lastSnapshotAt:m,error:I,hasApiKey:$,onOpenSettings:g,onRefresh:d,onCreateInitiative:w,onPlayNextUp:b,onStartAutopilot:N,nextUpQueueModel:M,nextUpActionsModel:F,snapshotVersion:p=null,devMode:j=!1}){const C=fa({activities:s,agents:a,initiatives:t});return e.jsx(Aa,{agentEntityMap:C,authToken:c,embedMode:h,children:e.jsx(Zi,{initiatives:t,runtimeInstances:n,workspaceInitiativeId:o,isLoading:l,initialInitiativeId:f,connection:v,lastSnapshotAt:m,error:I,hasApiKey:$,onOpenSettings:g,onRefresh:d,onCreateInitiative:w,onPlayNextUp:b,onStartAutopilot:N,nextUpQueueModel:M,nextUpActionsModel:F,snapshotVersion:p,devMode:j})})}function Yi(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 Xi(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 Zi({initiatives:t,runtimeInstances:s,workspaceInitiativeId:a=null,isLoading:n,initialInitiativeId:o,connection:l,lastSnapshotAt:c,error:h,hasApiKey:f,onOpenSettings:v,onRefresh:m,onCreateInitiative:I,onPlayNextUp:$,onStartAutopilot:g,nextUpQueueModel:d,nextUpActionsModel:w,snapshotVersion:b=null,devMode:N=!1}){var En,An,Mn,Dn,Tn;const{searchQuery:M,setSearchQuery:F,statusFilters:p,setStatusFilters:j,dateField:C,setDateField:L,datePreset:z,setDatePreset:ne,dateStart:ae,setDateStart:X,dateEnd:P,setDateEnd:y,clearFilters:W,hasActiveFilters:E,groupBy:Q,sortBy:K,expandedInitiatives:ue,expandAll:R,collapseAll:_,modalTarget:q,closeModal:U,expandInitiative:H,authToken:pe,embedMode:re,mutations:Se}=zt(),Oe=r.useRef(!1),He=r.useRef(null),x=r.useRef(0),[Y,Z]=r.useState(0),[ge,De]=r.useState(new Set),[ze,Be]=r.useState(!1),[T,G]=r.useState(!1),[oe,Ce]=r.useState(!1),[Ie,Le]=r.useState(!1),[Pe,kt]=r.useState("next-up"),[Ae,xe]=r.useState(null),[ye,rt]=r.useState(null),[xt,Ut]=r.useState(!1),[Ge,Ze]=r.useState(null),[Tt,$t]=r.useState(null),[dt,ht]=r.useState(new Set),[ut,mt]=r.useState(!1),[Ue,et]=r.useState(null),[gt,bt]=r.useState(0),[We,Zt]=r.useState(24),at=M.trim(),Et=Ca(at,at.length>=2,a),Wt=r.useMemo(()=>{var A;if(at.length<2||!((A=Et.data)!=null&&A.length))return t;const u=new Map;for(const B of t)u.set(B.id,B);for(const B of Et.data){const V=u.get(B.id);u.set(B.id,V?Xi(V,B):B)}return Array.from(u.values())},[Et.data,t,at.length]),Nt=r.useMemo(()=>new Set((Et.data??[]).map(u=>u.id)),[Et.data]);r.useEffect(()=>{if(!Ue)return;const u=Ue.tone==="success"?6500:9e3,A=window.setTimeout(()=>et(null),u);return()=>window.clearTimeout(A)},[Ue==null?void 0:Ue.message,Ue==null?void 0:Ue.tone]);const Lt=r.useMemo(()=>{const A=un(new Date),B=M.toLowerCase().trim().split(/\s+/).filter(Boolean);return Wt.filter(V=>{if(p.length>0&&![rn(V.status),rn(V.rawStatus)].filter(Boolean).some(vt=>p.includes(vt)))return!1;const he=Qi(V,C),Te=he?Date.parse(he):Number.NaN,we=Number.isFinite(Te)?un(new Date(Te)):null,le=we===null?null:Math.round((we-A)/864e5);if(z==="missing"&&we!==null||z==="overdue"&&!(le!==null&&le<0)||z==="today"&&le!==0||z==="next_7_days"&&!(le!==null&&le>=0&&le<=7)||z==="next_30_days"&&!(le!==null&&le>=0&&le<=30)||z==="past_7_days"&&!(le!==null&&le<=0&&le>=-7)||z==="past_30_days"&&!(le!==null&&le<=0&&le>=-30))return!1;if(z==="custom_range"){const st=mr(ae),vt=mr(P);if(we===null||st!==null&&we<st||vt!==null&&we>vt)return!1}if(B.length===0||Nt.has(V.id))return!0;const Xe=[V.name,V.description??"",V.status,V.rawStatus??"",V.category??""].join(" ").toLowerCase();return B.every(st=>Xe.includes(st))})},[Wt,M,Nt,p,C,z,ae,P]),i=r.useMemo(()=>{const u=(A,B,V)=>{const he=A.targetDate?Date.parse(A.targetDate):Number.NaN,Te=B.targetDate?Date.parse(B.targetDate):Number.NaN,we=Number.isFinite(he),le=Number.isFinite(Te);return!we&&!le?0:we?le?V==="asc"?he-Te:Te-he:-1:1};return[...Lt].sort((A,B)=>{if(K==="date_asc")return u(A,B,"asc");if(K==="date_desc")return u(A,B,"desc");const V=pr(A.priority),he=pr(B.priority);if(K==="priority_high"&&V!==he)return V-he;if(K==="priority_low"&&V!==he)return he-V;if(K==="default"){const le=typeof A.sequenceIndex=="number"?A.sequenceIndex:Number.POSITIVE_INFINITY,Xe=typeof B.sequenceIndex=="number"?B.sequenceIndex:Number.POSITIVE_INFINITY;if(le!==Xe)return le-Xe;const st=xr(A.status)-xr(B.status);if(st!==0)return st;if(V!==he)return V-he}const Te=A.updatedAt?Date.parse(A.updatedAt):0,we=B.updatedAt?Date.parse(B.updatedAt):0;return Te!==we?we-Te:A.name.localeCompare(B.name)})},[Lt,K]),k=i.length,D=Math.max(1,Math.ceil(k/We)),ee=k===0?0:Math.min(gt,D-1),ie=ee*We,Ne=Math.min(k,ie+We),Me=k===0?0:ie+1,pt=k===0?0:Ne,me=r.useMemo(()=>i.slice(ie,Ne),[Ne,ie,i]),Ve=r.useMemo(()=>new Set(i.map(u=>u.id)),[i]),Fe=r.useMemo(()=>i.filter(u=>dt.has(u.id)),[dt,i]),yt=r.useMemo(()=>me.filter(u=>dt.has(u.id)),[me,dt]),Je=Fe.length,_t=yt.length,J=me.length>0&&_t===me.length,je=Se.bulkEntityMutation.isPending,it=r.useMemo(()=>{var B;const u=new Map;for(const V of s){const he=(B=V.initiativeId)==null?void 0:B.trim();if(!he)continue;const Te=u.get(he)??{activeCount:0,totalCount:0,lastHeartbeatAt:null,lastHeartbeatMs:0};Te.totalCount+=1,V.state==="active"&&(Te.activeCount+=1);const we=V.lastHeartbeatAt??V.lastEventAt??null,le=we?Date.parse(we):Number.NaN;Number.isFinite(le)&&le>Te.lastHeartbeatMs&&(Te.lastHeartbeatMs=le,Te.lastHeartbeatAt=new Date(le).toISOString()),u.set(he,Te)}const A=new Map;for(const[V,he]of u.entries())A.set(V,{activeCount:he.activeCount,totalCount:he.totalCount,lastHeartbeatAt:he.lastHeartbeatAt});return A},[s]),Re=r.useMemo(()=>Q!=="none"?hr(me,Q):null,[Q,me]),es=r.useMemo(()=>(Re==null?void 0:Re.map(u=>Gt(Q,u.key)))??[],[Q,Re]),S=r.useMemo(()=>{if(!Re)return me.map(A=>A.id);const u=[];for(const A of Re){const B=Gt(Q,A.key);if(ge.has(B))for(const V of A.initiatives)u.push(V.id)}return u},[ge,Q,Re,me]),{handleSelect:te}=wr(S),_e=r.useCallback(u=>{De(A=>{const B=new Set(A);return B.has(u)?B.delete(u):B.add(u),B})},[]);r.useEffect(()=>{if(!Re||Re.length===0){De(A=>A.size===0?A:new Set);return}const u=new Set(Re.map(A=>Gt(Q,A.key)));De(A=>{const B=new Set(Array.from(A).filter(V=>u.has(V)));return B.size===0&&B.add(Gt(Q,Re[0].key)),fr(B,A)?A:B})},[Q,Re]),r.useEffect(()=>{ht(u=>{if(u.size===0)return u;const A=new Set(Array.from(u).filter(B=>Ve.has(B)));return fr(A,u)?u:A})},[Ve]),r.useEffect(()=>{if(o&&!Oe.current&&!n&&t.length>0){const u=i.findIndex(A=>A.id===o);if(u>=0&&bt(Math.floor(u/We)),H(o),Re){const A=Re.find(B=>B.initiatives.some(V=>V.id===o));if(A){const B=Gt(Q,A.key);De(V=>{if(V.has(B))return V;const he=new Set(V);return he.add(B),he})}}Oe.current=!0,requestAnimationFrame(()=>{const A=document.getElementById(`initiative-${o}`);A==null||A.scrollIntoView({behavior:"smooth",block:"start"})})}},[o,n,t.length,H,We,Q,Re,i]),r.useEffect(()=>{Je===0&&ut&&mt(!1)},[ut,Je]),r.useEffect(()=>{bt(u=>Math.min(u,Math.max(D-1,0)))},[D]),r.useEffect(()=>{bt(0)},[M,p,C,z,ae,P,Q,K,We]);const Qe=me.length>0&&me.every(u=>ue.has(u.id)),Ye=r.useMemo(()=>i.find(u=>u.status!=="completed")??i[0]??null,[i]),At=ia({projectId:a,limit:40,authToken:pe,embedMode:re,enabled:d?!1:t.length>0,snapshotVersion:b}),ke=d??At,_s=ha({authToken:pe,embedMode:re,enabled:t.length>0}),us=Wi({enabled:t.length>0,projectId:a}),ts=r.useMemo(()=>{var Te;if((Te=us.data)!=null&&Te.aggregate){const we=us.data.aggregate;return{completionPercent:we.completionPercent,totalTasks:we.totalTasks,doneTasks:we.doneTasks,blockedCount:we.blockedCount,activeAgents:we.activeAgents}}const u=t.reduce((we,le)=>{var Xe;return we+(((Xe=le.workstreams)==null?void 0:Xe.length)??0)},0),A=t.reduce((we,le)=>{var Xe;return we+(((Xe=le.workstreams)==null?void 0:Xe.filter(st=>st.status==="completed"||st.status==="done").length)??0)},0),B=u>0?A/u*100:0,V=t.filter(we=>we.status==="blocked").length,he=t.reduce((we,le)=>we+le.activeAgents,0);return{completionPercent:B,totalTasks:u,doneTasks:A,blockedCount:V,activeAgents:he}},[t,us.data]),Bs=gs({authToken:pe,embedMode:re}),St=w??Bs,be=ke.items[0]??null,se=r.useMemo(()=>ke.items.find(u=>u.playbackState==="running"||u.playbackState==="blocked")??ke.items.find(u=>u.queueState==="running"||u.queueState==="blocked")??null,[ke.items]),tt=r.useMemo(()=>ke.items.find(u=>se&&u.initiativeId===se.initiativeId&&u.workstreamId===se.workstreamId?!1:u.playbackState==="queued"||u.playbackState==="idle"||u.queueState==="queued"||u.queueState==="idle")??null,[ke.items,se]),ce=r.useMemo(()=>be?t.find(u=>u.id===be.initiativeId)??Ye:Ye,[Ye,t,be]),Qt=se??tt??be??null,Bt=(Qt==null?void 0:Qt.initiativeId)??(ce==null?void 0:ce.id)??null,fn=r.useCallback((u,A,B)=>{et(null),mt(!1),te(u,A,B,ht)},[te]),Nr=r.useCallback(()=>{et(null),mt(!1),ht(u=>{if(me.length===0)return u;const A=new Set(u);if(J)for(const B of me)A.delete(B.id);else for(const B of me)A.add(B.id);return A})},[J,me]),Sr=r.useCallback(()=>{mt(!1),ht(new Set)},[]),gn=ee>0,bn=ee<D-1,Pt=r.useCallback(u=>{bt(Math.max(0,Math.min(u,D-1)))},[D]),Cr=r.useCallback(()=>{Pt(0)},[Pt]),Ir=r.useCallback(()=>{Pt(ee-1)},[ee,Pt]),Fr=r.useCallback(()=>{Pt(ee+1)},[ee,Pt]),Er=r.useCallback(()=>{Pt(D-1)},[Pt,D]),ys=r.useCallback(async u=>{if(Fe.length!==0){mt(!1),et(null);try{const A=await Se.bulkEntityMutation.mutateAsync({items:Fe.map(B=>({type:"initiative",id:B.id})),mode:"update",updates:{status:u}});A.failed>0?et({tone:"error",message:`Updated ${A.updated}, failed ${A.failed}.`}):et({tone:"success",message:`Updated ${A.updated} initiative${A.updated===1?"":"s"} to ${u}.`})}catch(A){et({tone:"error",message:Ot(A instanceof Error?A.message:"","Bulk initiative update failed.")})}}},[Se.bulkEntityMutation,Fe]),Ar=r.useCallback(async()=>{if(Fe.length!==0){et(null);try{const u=await Se.bulkEntityMutation.mutateAsync({items:Fe.map(A=>({type:"initiative",id:A.id})),mode:"delete"});u.failed>0?et({tone:"error",message:`Deleted ${u.updated}, failed ${u.failed}.`}):(et({tone:"success",message:`Deleted ${u.updated} initiative${u.updated===1?"":"s"}.`}),ht(new Set),mt(!1))}catch(u){et({tone:"error",message:Ot(u instanceof Error?u.message:"","Bulk initiative delete failed.")})}}},[Se.bulkEntityMutation,Fe]),Ps=r.useCallback(()=>{x.current+=1,Be(!1)},[]),Mr=r.useCallback(u=>{if(u.length===0){Ps();return}const A=1,B=x.current+1;x.current=B,Be(!0);const V=he=>{if(x.current===B){if(R(u.slice(0,he)),he>=u.length){Be(!1);return}requestAnimationFrame(()=>V(Math.min(u.length,he+A)))}};V(Math.min(A,u.length))},[Ps,R]),$e=ga({initiativeId:Bt,authToken:pe,embedMode:re,enabled:!!Bt}),[Ht,ss]=r.useState(null),ws=$e.run,Rs=((En=$e.error)==null?void 0:En.toLowerCase())??"",qs=!Bt||Rs.includes("404")||Rs.includes("400")||Rs.includes("not found"),wt=Bt?it.get(Bt)??null:null,Os=((wt==null?void 0:wt.activeCount)??0)>0,Dr=((wt==null?void 0:wt.totalCount)??0)>0,yn=Ht?`Upgrade required · ${Pn(Ht.currentPlan)} → ${Pn(Ht.requiredPlan)}`:Bt?$e.isRunning?Os?`Running · ${(wt==null?void 0:wt.activeCount)??0} live`:Dr?`Enabled · ${(wt==null?void 0:wt.totalCount)??0} idle`:"Enabled · waiting":ws!=null&&ws.stopReason?`Idle · ${ws.stopReason.replace(/_/g," ")}`:"Idle":"No target",ns=!!Ht&&!$e.isRunning,Tr=ns?"amber":"teal",$r=r.useMemo(()=>{const u=new URL("https://www.useorgx.com/integrations/openclaw");return u.searchParams.set("utm_source",re?"live_share":"orgx_openclaw_plugin"),u.searchParams.set("utm_medium","mission_control"),u.searchParams.set("utm_campaign","live_link_dashboard"),u.searchParams.set("utm_content","install_cta"),u.toString()},[re]);r.useEffect(()=>{ss(null)},[Bt]),r.useEffect(()=>{const u=He.current;if(!u)return;const A=()=>{Z(Math.max(64,u.offsetHeight))};if(A(),typeof ResizeObserver>"u")return;const B=new ResizeObserver(()=>A());return B.observe(u),()=>B.disconnect()},[yn,l,h,n,i.length]);const zs=!!(!n&&f&&(l==="disconnected"||h)),Lr=l==="disconnected"||h?"critical":"info",_r=l==="disconnected"?"Offline":h?"Live degraded":"Connected",wn=h?Gi(h):l==="disconnected"?"Live updates are offline. Data may be stale until reconnect.":`Last snapshot ${Yi(c)}`;r.useEffect(()=>{zs||G(!1)},[zs]);const Mt=r.useCallback((u,A)=>{if(!t.find(le=>le.id===u)){const le=(A??"").trim(),Xe=le?xn(le)?`Initiative ${br(le)}`:ds(le):"This initiative";return xe({tone:"error",message:`${Xe} is not in this workspace view. Switch workspace or clear filters to find it.`}),!1}xe(null);const V=i.findIndex(le=>le.id===u),he=V<0;if(V>=0&&bt(Math.floor(V/We)),he&&(F(""),j([]),L("target"),ne("any"),X(""),y("")),H(u),Q!=="none"){const le=V>=0?i:t,st=hr(le,Q).find(vt=>vt.initiatives.some(os=>os.id===u));if(st){const vt=Gt(Q,st.key);De(os=>{if(os.has(vt))return os;const $n=new Set(os);return $n.add(vt),$n})}}const Te=(le=0)=>{const Xe=document.getElementById(`initiative-${u}`);if(Xe){Xe.scrollIntoView({behavior:le===0?"smooth":"auto",block:"start"});const st=Math.max(72,Y)+8,vt=Xe.getBoundingClientRect();!(vt.top>=st&&vt.top<=window.innerHeight-72)&&le<18&&window.setTimeout(()=>Te(le+1),90);return}le>=60||requestAnimationFrame(()=>Te(le+1))},we=()=>requestAnimationFrame(()=>Te());return he?window.setTimeout(we,90):we(),!0},[t,We,xe,bt,F,j,L,ne,X,y,H,Q,i,Y]),Br=r.useCallback(()=>{ce&&(xe(null),Se.updateEntity.mutateAsync({type:"initiative",id:ce.id,status:"active"}).then(()=>{xe({tone:"success",message:`Started ${ce.name}.`}),Mt(ce.id,ce.name)}).catch(u=>{xe({tone:"error",message:Ot(u instanceof Error?u.message:"","Failed to start initiative.")})}))},[Se.updateEntity,ce,Mt]),Rt=r.useCallback(async(u,A,B)=>{$t(u),xe(null);try{await A(),xe({tone:"success",message:B})}catch(V){xe({tone:"error",message:Ot(V instanceof Error?V.message:"","Action failed.")})}finally{$t(null)}},[]),Us=r.useCallback(async(u,A)=>{const B=(A==null?void 0:A.surface)!=="card";B&&($t("start"),xe(null)),rt(null);try{const V=await ke.playWorkstream({initiativeId:u.initiativeId,workstreamId:u.workstreamId,agentId:u.runnerAgentId});return B&&xe({tone:"success",message:`Started ${u.workstreamTitle}.`}),V}catch(V){if(Rn(V)&&V.code==="auto_continue_already_running"){const he=V.details,Te=he&&typeof he.activeWorkstreamTitle=="string"?he.activeWorkstreamTitle:null,we=he&&typeof he.activeWorkstreamId=="string"?he.activeWorkstreamId:null;if(rt({target:u,message:V.message||"A workstream is already running. Stop it before starting another.",activeWorkstreamTitle:Te,activeWorkstreamId:we}),!B)throw V;return null}if(B)return xe({tone:"error",message:Ot(V instanceof Error?V.message:"","Unable to start workstream.")}),null;throw V}finally{B&&$t(null)}},[ke]),Pr=r.useCallback(()=>se?Rt("pause",()=>St.stopTriage({initiativeId:se.initiativeId,workstreamId:se.workstreamId,placement:"bottom",resetToTodo:!1}),`Paused ${se.workstreamTitle} and moved it to bottom of queue.`):Promise.resolve(),[St,se,Rt]),Rr=r.useCallback(()=>{if(!se)return Promise.resolve();const u=se.playbackState==="running"||se.playbackState==="blocked"||se.queueState==="running"||se.queueState==="blocked";return Rt("defer",()=>u?St.stopTriage({initiativeId:se.initiativeId,workstreamId:se.workstreamId,placement:"bottom",resetToTodo:!1}):St.move({initiativeId:se.initiativeId,workstreamId:se.workstreamId,placement:"bottom"}),`Deferred ${se.workstreamTitle} to bottom of queue.`)},[St,se,Rt]),qr=r.useCallback(()=>{const u=se??tt??be;return u?u.autoIntentEnabled===!0&&(u.autoRuntimeState==="running"||u.autoRuntimeState==="stopping")?Rt("auto",()=>ke.stopInitiativeAutoContinue({initiativeId:u.initiativeId}),`Stopped auto-continue for ${u.initiativeTitle}.`):(Ze(u),Promise.resolve()):Promise.resolve()},[ke,be,tt,se,Rt]),Or=r.useCallback(()=>{if(!Ge)return;const u=Ge;Ze(null),Rt("auto",()=>ke.startWorkstreamAutoContinue({initiativeId:u.initiativeId,workstreamId:u.workstreamId,agentId:u.runnerAgentId,scope:"initiative"}),`Auto-continue enabled for ${u.initiativeTitle}; starting with ${u.workstreamTitle}.`)},[Ge,ke,Rt]),zr=r.useCallback(async()=>{if(!(!ye||xt)){Ut(!0),xe(null);try{try{await ke.stopInitiativeAutoContinue({initiativeId:ye.target.initiativeId})}catch(u){if(!Rn(u)||u.status!==404)throw u}await ke.playWorkstream({initiativeId:ye.target.initiativeId,workstreamId:ye.target.workstreamId,agentId:ye.target.runnerAgentId}),rt(null),xe({tone:"success",message:`Switched run to ${ye.target.workstreamTitle}.`})}catch(u){xe({tone:"error",message:Ot(u instanceof Error?u.message:"","Unable to switch run.")})}finally{Ut(!1)}}},[xt,ke,ye]),vn=r.useCallback(()=>{ce&&(Mt(ce.id,ce.name),typeof window<"u"&&window.innerWidth>=1280&&Ce(!0))},[ce,Mt]),Ws=r.useCallback(()=>{if(typeof window>"u")return;if(window.innerWidth>=1280){const A=!oe;Le(!1),Ce(A),xe({tone:"success",message:A?"Opened queue rail.":"Closed queue rail."});return}const u=!Ie;Ce(!1),Le(u),xe({tone:"success",message:u?"Opened queue panel.":"Closed queue panel."})},[Ie,oe]),rs=rn((ce==null?void 0:ce.rawStatus)??(ce==null?void 0:ce.status)??null),jn=r.useMemo(()=>new Set(["paused","draft","planned","todo","backlog","queued"]),[]),ot=r.useMemo(()=>ce?(se==null?void 0:se.queueState)==="running"||(se==null?void 0:se.playbackState)==="running"||(be==null?void 0:be.autoIntentEnabled)===!0&&(be.autoRuntimeState==="running"||be.autoRuntimeState==="stopping")?"running":(be==null?void 0:be.queueState)==="blocked"||ce.status==="blocked"?"blocked":be?"queued":jn.has(rs)?"startable":rs==="completed"||rs==="done"?"completed":"active_no_queue":"none",[ce,be,jn,rs,se]),Qs=r.useMemo(()=>ce?ot==="running"&&be?{headline:`${be.workstreamTitle} is running`,detail:`Runner: ${be.runnerAgentName}. Follow live updates in Activity.`}:ot==="queued"&&be?{headline:be.workstreamTitle,detail:`Ready to dispatch${be.nextTaskTitle?` · ${be.nextTaskTitle}`:""}.`}:ot==="startable"?{headline:rs==="paused"?`${ce.name} is paused`:`${ce.name} is ready to start`,detail:"Start initiative to queue and dispatch the next workstream."}:ot==="blocked"?{headline:(be==null?void 0:be.queueState)==="blocked"?`${be.workstreamTitle} is blocked`:`${ce.name} is blocked`,detail:(be==null?void 0:be.blockReason)??"Resolve blockers or approvals before dispatching more work."}:ot==="completed"?{headline:`${ce.name} is complete`,detail:"Choose another active initiative or queue new workstreams."}:{headline:ce.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."},[ce,ot,be,rs]),vs=ke.isPlaying||ke.isStartingAutoContinue||ke.isStoppingAutoContinue||xt||Se.updateEntity.isPending,Ur=r.useMemo(()=>ot==="blocked"?"Review blockers":ot==="active_no_queue"?"Open and queue work":ot==="completed"?"Review initiative":"Open initiative",[ot]),kn=r.useMemo(()=>(se==null?void 0:se.playbackState)==="running"||(se==null?void 0:se.queueState)==="running"?"running":(se==null?void 0:se.playbackState)==="blocked"||(se==null?void 0:se.queueState)==="blocked"?"blocked":tt?"queued":ot==="startable"?"startable":ot==="completed"?"completed":ce?"active_no_queue":"none",[ce,ot,tt,se]),Nn=(se==null?void 0:se.workstreamTitle)??"No active workstream",Wr=(se==null?void 0:se.initiativeTitle)??(ce==null?void 0:ce.name)??"No initiative selected",Hs=se?[se.nextTaskTitle?`Next: ${se.nextTaskTitle}`:null,se.blockReason?`Blocked: ${se.blockReason}`:null].filter(Boolean).join(" · "):tt?`Next up: ${tt.workstreamTitle}`:Qs.detail,Sn=(tt==null?void 0:tt.workstreamTitle)??"Queue is empty",Cn=tt!=null&&tt.nextTaskTitle?`Next task: ${tt.nextTaskTitle}`:"Add or reorder workstreams in queue.",Qr=Vi(kn),Hr=Ki(kn),as=se??tt??be,Vs=(as==null?void 0:as.autoIntentEnabled)===!0&&(as.autoRuntimeState==="running"||as.autoRuntimeState==="stopping"),is=ma(),Ks="next-up-surface",qt=r.useMemo(()=>is?{duration:.01}:Dt.railMorphSpring,[is]),In=r.useMemo(()=>is?{duration:.01}:Dt.surfaceSwitch,[is]),js=r.useMemo(()=>is?{initial:{opacity:1,y:0},animate:{opacity:1,y:0},exit:{opacity:1,y:0},transition:{duration:.01}}:Dt.contentCrossFade,[is]),Vr=r.useMemo(()=>({backgroundColor:"rgba(10, 14, 21, 0.66)",borderColor:"rgba(255, 255, 255, 0.10)"}),[]),Fn=r.useMemo(()=>({backgroundColor:"rgba(10, 14, 21, 0.95)",borderColor:"rgba(255, 255, 255, 0.11)"}),[]),Kr=r.useMemo(()=>{if(!q)return null;const u=B=>t.find(V=>V.id===B)??null;if(q.type==="initiative"){const B=u(q.entity.id);return B?{...q,entity:B}:q}const A=u(q.initiative.id);return A?{...q,initiative:A}:q},[t,q]);return r.useEffect(()=>{if(!ye)return;ke.items.some(A=>A.initiativeId===ye.target.initiativeId&&A.workstreamId===ye.target.workstreamId)||rt(null)},[ke.items,ye]),r.useEffect(()=>{if(!Ge)return;ke.items.some(A=>A.initiativeId===Ge.initiativeId&&A.workstreamId===Ge.workstreamId)||Ze(null)},[Ge,ke.items]),r.useEffect(()=>{if(!q)return;const u=q.type==="initiative"?q.entity.id:q.initiative.id;t.some(B=>B.id===u)||U()},[U,t,q]),r.useEffect(()=>{if(typeof window>"u")return;const u=()=>{window.innerWidth>=1280?Le(!1):Ce(!1)};return u(),window.addEventListener("resize",u),()=>window.removeEventListener("resize",u)},[]),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":`${Y}px`},children:[e.jsxs(pa,{id:"next-up-morph",children:[e.jsxs("div",{ref:He,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(yr,{open:zs&&!T,tone:Lr==="critical"?"error":"warning",title:_r,message:wn,onDismiss:()=>G(!0),primaryAction:m?{label:"Refresh",onClick:m}:null,secondaryAction:v?{label:"Settings",onClick:v}: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(hn,{value:M,onChange:F,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(Ti,{initiatives:t,visibleCount:Lt.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:(ce==null?void 0:ce.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:yn}),ce&&e.jsx("div",{className:"truncate text-micro text-white/44",children:ce.name})]})]}),e.jsxs("button",{type:"button",onClick:()=>{if(qs||!Bt)return;if(ns&&Ht){ca({actions:Ht.actions,requiredPlan:Ht.requiredPlan}).catch(B=>{xe({tone:"error",message:Ot(B instanceof Error?B.message:"","Unable to open checkout right now.")})});return}const u=$e.isRunning;(u?$e.stop:$e.start)().then(()=>{ss(null);const B=(ce==null?void 0:ce.name)??"selected initiative";xe({tone:"success",message:u?`Stopped Autopilot for ${B}.`:`Started Autopilot for ${B}.`})}).catch(B=>{B instanceof oa?ss(B):(ss(null),xe({tone:"error",message:Ot(B instanceof Error?B.message:"","Autopilot action failed.")}))})},disabled:qs||$e.isStarting||$e.isGracefullyStopping,title:qs?"Select an initiative to run Autopilot":ns?"Upgrade to enable auto-continue for BYOK agents":$e.isRunning?"Stop Autopilot":`Start Autopilot${ce?` for ${ce.name}`:""}`,"data-state":$e.isRunning||ns?"active":"idle","data-tone":Tr,className:"control-pill flex items-center gap-1.5 px-3 text-caption font-semibold disabled:opacity-40",children:[ns?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"})]}):$e.isRunning?Os?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:ns?"Upgrade Autopilot":$e.isGracefullyStopping?"Stopping Autopilot…":`${$e.isRunning?"Stop":"Start"} Autopilot`}),$e.isRunning&&Os&&e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-[#0AD4C4] status-breathe"})]}),$e.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":(An=$e.run)!=null&&An.lastError?"error":((Mn=$e.run)==null?void 0:Mn.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"}),((Dn=$e.run)==null?void 0:Dn.tokensUsed)!=null&&((Tn=$e.run)==null?void 0:Tn.tokenBudget)!=null&&$e.run.tokenBudget>0&&e.jsxs("span",{className:"text-micro text-[#7AEDE5]/60 tabular-nums",children:[Math.round($e.run.tokensUsed/$e.run.tokenBudget*100),"% budget"]})]}),re&&e.jsxs("a",{href:$r,target:"_blank",rel:"noreferrer noopener",onClick:()=>{try{la("live_install_cta_click",{surface:"mission_control",embedMode:!0,initiativeId:(ce==null?void 0:ce.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"})]}),me.length>0&&e.jsx("button",{type:"button",onClick:()=>{Qe?(Ps(),_(),Re&&es.length>0&&De(new Set)):(Mr(me.map(u=>u.id)),Re&&es.length>0&&De(new Set(es)))},title:Qe?"Collapse all":"Expand all","aria-busy":ze&&!Qe,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:Qe?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"})]})})})]})]})]}),!1,i.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 ${Je>0?"border-[#BFFF00]/14 bg-[#0A0E15]/72":"border-white/[0.10] bg-[#0A0E15]/66"}`,children:[Je>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 ${Je>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:J,onChange:Nr,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:Je>0?`${Je} selected`:k===0?"0 visible":`${Me}-${pt} of ${k}`}),Je>0&&e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("button",{type:"button",onClick:()=>{ys("active")},disabled:je,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:()=>{ys("paused")},disabled:je,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:()=>{ys("blocked")},disabled:je,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:()=>{ys("completed")},disabled:je,className:"control-pill h-8 flex-shrink-0 px-3 text-caption font-semibold disabled:opacity-45",children:"Complete"}),ut?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:()=>{Ar()},disabled:je,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:()=>mt(!1),disabled:je,className:"control-pill h-8 flex-shrink-0 px-2.5 text-caption disabled:opacity-45",children:"Keep"})]}):e.jsx("button",{type:"button",onClick:()=>mt(!0),disabled:je,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:Sr,disabled:je,className:"text-caption text-secondary transition-colors hover:text-primary disabled:opacity-45",children:"Clear"})]})]})}),e.jsx(lt,{initial:!1,mode:"popLayout",children:!oe&&!Ie&&e.jsxs(de.div,{layout:"position",layoutId:Ks,initial:{opacity:0,y:4},animate:{opacity:1,y:0,...Vr},exit:{opacity:0,y:-4},transition:{layout:qt,...In},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:[ke.isLoading?e.jsx(Ft,{className:"h-6 w-6 rounded-full"}):Qt?e.jsx(an,{name:Qt.runnerAgentName,hint:`${Qt.runnerAgentId} ${Qt.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"}),ke.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] ${Hr}`,children:Qr})]}),ke.isLoading?e.jsxs("div",{className:"mt-1.5 space-y-1",children:[e.jsx(Ft,{className:"h-3 w-56 rounded"}),e.jsx(Ft,{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:Nn,children:Nn}),e.jsxs("p",{className:"truncate text-caption leading-snug text-secondary",title:Hs,children:[Wr,Hs?` · ${Hs}`:""]}),e.jsxs("p",{className:"hidden truncate text-micro leading-snug text-secondary/85 sm:block",title:Sn,children:["Up next: ",Sn,Cn?` · ${Cn}`:""]})]})]})]}),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 u=tt??be;if(se){Pr();return}if(u){Us(u);return}vn()},disabled:vs||Tt==="start"||Tt==="pause",className:"control-pill h-8 flex-shrink-0 px-3 text-caption font-semibold disabled:opacity-45",title:se?`Pause ${se.workstreamTitle}`:"Start next workstream",children:se?"Pause":"Start"}),e.jsx("button",{type:"button",onClick:()=>void Rr(),disabled:!se||Tt==="defer"||vs,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 qr(),disabled:!as||Tt==="auto"||vs,className:"control-pill h-8 flex-shrink-0 px-3 text-caption font-semibold disabled:opacity-45","data-state":Vs?"active":"idle","data-tone":"teal",title:Vs?"Stop automatic continuation":"Continue automatically for this initiative",children:Vs?"Auto on":"Auto"}),e.jsx("button",{type:"button",onClick:Ws,className:"control-pill h-8 flex-shrink-0 px-3 text-caption font-semibold",title:"Open queue",children:"Open queue"})]})]},"next-up-inline-card")})]}),Ue&&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 ${Ue.tone==="success"?"bg-emerald-300/90":"bg-amber-300/90"}`}),e.jsx("span",{className:"min-w-0 leading-snug",children:Ue.message})]}),e.jsx("button",{type:"button",onClick:()=>et(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(de.div,{layout:!0,transition:{type:"spring",stiffness:260,damping:30},className:`mt-3 grid gap-4 pb-8 ${oe?"xl:grid-cols-[minmax(0,1fr)_320px] xl:gap-0":"grid-cols-1"}`,children:[e.jsxs(de.div,{layout:!0,className:`min-w-0 ${oe?"xl:pr-4":""}`,children:[N&&!n&&ce&&e.jsxs(de.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:Qs.headline}),e.jsx("p",{className:"mt-1 text-body leading-relaxed text-secondary",children:Qs.detail}),Ae&&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 ${Ae.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:Ae.message})]}),e.jsxs("div",{className:"ml-auto flex flex-wrap items-center gap-2.5 xl:self-end",children:[ot==="startable"?e.jsx("button",{type:"button",onClick:Br,disabled:vs,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:vn,className:"control-pill h-9 px-4 text-body font-semibold","data-state":ot==="blocked"?"active":"idle",children:Ur}),e.jsx("button",{type:"button",onClick:Ws,className:"control-pill h-9 px-4 text-body font-semibold",children:oe?"Hide Queue":"Open Queue"})]})]})]}),N&&!n&&t.length>0&&e.jsxs("div",{className:"grid grid-cols-1 gap-4 xl:grid-cols-2",children:[e.jsx(zi,{completionPercent:ts.completionPercent,totalTasks:ts.totalTasks,doneTasks:ts.doneTasks,blockedCount:ts.blockedCount,activeAgents:ts.activeAgents}),e.jsx(Ui,{usage:_s.summary})]}),n?e.jsx("div",{className:"space-y-3 pb-8",children:Array.from({length:4}).map((u,A)=>e.jsxs("div",{className:"bg-[--orgx-surface] border border-[--orgx-border] soft-shadow rounded-2xl p-4",children:[e.jsx(Ft,{className:"h-4 w-2/5 rounded"}),e.jsx(Ft,{className:"h-1 w-full rounded mt-3"})]},`mc-skeleton-${A}`))}):t.length===0?f?l==="disconnected"||h?e.jsx("div",{className:"pb-8",children:e.jsx(en,{mode:"degraded",detail:wn,onCreateInitiative:I,onPlayNextUp:$,onStartAutopilot:g,onRefresh:m,onOpenSettings:v})}):e.jsx("div",{className:"pb-8",children:e.jsx(en,{mode:"empty",onCreateInitiative:I,onPlayNextUp:$,onStartAutopilot:g,onRefresh:m})}):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."}),v&&e.jsx("div",{className:"mt-4 flex items-center justify-center",children:e.jsx("button",{type:"button",onClick:v,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"})})]})}):i.length===0?e.jsx("div",{className:"pb-8",children:e.jsx(en,{mode:"filtered",hasActiveFilters:E,onClearFilters:E?W:void 0,onCreateInitiative:I,onPlayNextUp:$,onStartAutopilot:g,onRefresh:m})}):Re?e.jsx("div",{className:"space-y-4 pb-8",children:Re.map(u=>{const A=Gt(Q,u.key),B=Hi(A),V=ge.has(A);return e.jsxs(de.div,{layout:!0,transition:{type:"spring",stiffness:260,damping:30},children:[e.jsxs("button",{type:"button","aria-expanded":V,"aria-controls":B,onClick:()=>_e(A),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 ${V?"rotate-90":""}`,children:"▶"}),e.jsx("span",{className:"text-body font-semibold text-primary",children:u.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:u.count}),e.jsx("span",{className:"ml-auto text-micro uppercase tracking-[0.08em] text-secondary",children:V?"Hide":"Show"})]}),e.jsx(lt,{initial:!1,children:V&&e.jsx(de.div,{id:B,initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{height:{type:"spring",stiffness:320,damping:32},opacity:{duration:.14}},className:"overflow-hidden",children:e.jsx("div",{className:"pt-0.5",children:e.jsx(Gn,{initiatives:u.initiatives,selectedInitiativeIds:dt,onToggleInitiativeSelection:fn,isSquished:oe,runtimeActivityByInitiativeId:it})})})})]},u.key)})}):e.jsx("div",{className:"pb-8",children:e.jsx(Gn,{initiatives:me,selectedInitiativeIds:dt,onToggleInitiativeSelection:fn,isSquished:oe,runtimeActivityByInitiativeId:it})}),i.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 ",Me,"-",pt]}),e.jsx("span",{className:"text-white/50",children:"of"}),e.jsx("span",{className:"font-medium text-white/80",children:k}),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:We,onChange:u=>{const A=Number.parseInt(u.target.value,10);Number.isFinite(A)&&Zt(A)},className:"h-6 rounded-md border border-transparent bg-transparent px-1 text-caption text-white/90 outline-none",children:Ji.map(u=>e.jsx("option",{value:u,children:u},u))})]}),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:Cr,disabled:!gn,className:"control-pill h-7 px-2 text-micro font-semibold disabled:opacity-40",title:"First page",children:"«"}),e.jsx("button",{type:"button",onClick:Ir,disabled:!gn,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 ",ee+1," / ",D]}),e.jsx("button",{type:"button",onClick:Fr,disabled:!bn,className:"control-pill h-7 px-2 text-micro font-semibold disabled:opacity-40",title:"Next page",children:"›"}),e.jsx("button",{type:"button",onClick:Er,disabled:!bn,className:"control-pill h-7 px-2 text-micro font-semibold disabled:opacity-40",title:"Last page",children:"»"})]})]})]})]}),e.jsx(lt,{initial:!1,children:oe&&e.jsx(de.aside,{layout:!0,initial:{opacity:0,x:14},animate:{opacity:1,x:0},exit:{opacity:0,x:14},transition:In,className:"hidden xl:block",children:e.jsx("div",{className:"sticky",style:{top:"calc(var(--mc-toolbar-offset) + 12px)"},children:e.jsx(de.div,{layout:"position",layoutId:Ks,initial:{borderRadius:12},animate:{borderRadius:16,...Fn},transition:{layout:qt},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.jsxs(de.button,{type:"button",onClick:()=>kt("next-up"),...Dt.segmentedTap,className:`control-pill relative h-7 px-2 text-micro font-semibold ${Pe==="next-up"?"text-[#E8FFD0]":"text-secondary"}`,children:[Pe==="next-up"?e.jsx(de.span,{layoutId:"next-up-rail-surface-indicator",transition:qt,className:"pointer-events-none absolute inset-0 rounded-md border border-[#BFFF00]/34 bg-[#BFFF00]/[0.12]","aria-hidden":!0}):null,e.jsx("span",{className:"relative z-[1]",children:"Next Up"})]}),e.jsxs(de.button,{type:"button",onClick:()=>kt("slices"),...Dt.segmentedTap,className:`control-pill relative h-7 px-2 text-micro font-semibold ${Pe==="slices"?"text-teal-100":"text-secondary"}`,children:[Pe==="slices"?e.jsx(de.span,{layoutId:"next-up-rail-surface-indicator",transition:qt,className:"pointer-events-none absolute inset-0 rounded-md border border-teal-300/34 bg-teal-400/[0.12]","aria-hidden":!0}):null,e.jsx("span",{className:"relative z-[1]",children:"Slices"})]})]}),e.jsx("div",{className:"min-h-0 flex-1",children:e.jsx(lt,{initial:!1,mode:"wait",children:Pe==="next-up"?e.jsx(de.div,{...js,className:"h-full min-h-0",children:e.jsx(qn,{title:"Next Up",panelStyle:"flat",className:"!bg-transparent !shadow-none !border-transparent",disableEnterAnimation:!0,showHeader:!1,projectId:a,authToken:pe,embedMode:re,queueModel:ke,queueActions:St,snapshotVersion:b,onPlayWorkstream:u=>Us(u,{surface:"card"}),onOpenInitiative:Mt,onOpenSettings:v,onUpgradeGate:ss,excludeRunning:!0})},"next-up-rail"):e.jsx(de.div,{...js,className:"h-full min-h-0",children:e.jsx(ur,{title:"Slice Explorer",className:"h-full !rounded-none !border-0 !bg-transparent",workspaceId:a,authToken:pe,embedMode:re,compact:!0,onOpenInitiative:(u,A)=>{Mt(u,A)}})},"slices-rail")})}),e.jsx("button",{type:"button",onClick:Ws,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(lt,{children:Ie&&e.jsxs(e.Fragment,{children:[e.jsx(de.button,{type:"button","aria-label":"Close next up panel",onClick:()=>Le(!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(de.aside,{initial:{x:"100%",opacity:.85},animate:{x:0,opacity:1},exit:{x:"100%",opacity:.9},transition:qt,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:()=>Le(!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(de.div,{layout:"position",layoutId:Ks,initial:{borderRadius:12},animate:{borderRadius:16,...Fn},transition:{layout:qt},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.jsxs(de.button,{type:"button",onClick:()=>kt("next-up"),...Dt.segmentedTap,className:`control-pill relative h-7 px-2 text-micro font-semibold ${Pe==="next-up"?"text-[#E8FFD0]":"text-secondary"}`,children:[Pe==="next-up"?e.jsx(de.span,{layoutId:"next-up-rail-surface-indicator-mobile",transition:qt,className:"pointer-events-none absolute inset-0 rounded-md border border-[#BFFF00]/34 bg-[#BFFF00]/[0.12]","aria-hidden":!0}):null,e.jsx("span",{className:"relative z-[1]",children:"Next Up"})]}),e.jsxs(de.button,{type:"button",onClick:()=>kt("slices"),...Dt.segmentedTap,className:`control-pill relative h-7 px-2 text-micro font-semibold ${Pe==="slices"?"text-teal-100":"text-secondary"}`,children:[Pe==="slices"?e.jsx(de.span,{layoutId:"next-up-rail-surface-indicator-mobile",transition:qt,className:"pointer-events-none absolute inset-0 rounded-md border border-teal-300/34 bg-teal-400/[0.12]","aria-hidden":!0}):null,e.jsx("span",{className:"relative z-[1]",children:"Slices"})]})]}),e.jsx("div",{className:"min-h-0 flex-1",children:e.jsx(lt,{initial:!1,mode:"wait",children:Pe==="next-up"?e.jsx(de.div,{...js,className:"h-full min-h-0",children:e.jsx(qn,{title:"Next Up",panelStyle:"flat",className:"!bg-transparent !shadow-none !border-transparent",disableEnterAnimation:!0,showHeader:!1,projectId:a,authToken:pe,embedMode:re,queueModel:ke,queueActions:St,snapshotVersion:b,onPlayWorkstream:u=>Us(u,{surface:"card"}),onOpenInitiative:(u,A)=>{Mt(u,A),Le(!1)},onOpenSettings:v,onUpgradeGate:ss,excludeRunning:!0})},"next-up-drawer"):e.jsx(de.div,{...js,className:"h-full min-h-0",children:e.jsx(ur,{title:"Slice Explorer",className:"h-full !rounded-none !border-0 !bg-transparent",workspaceId:a,authToken:pe,embedMode:re,compact:!0,onOpenInitiative:(u,A)=>{Mt(u,A),Le(!1)}})},"slices-drawer")})})]})})]})},"next-up-drawer")]})}),e.jsx(lt,{children:Ge&&e.jsxs(e.Fragment,{children:[e.jsx(de.button,{type:"button","aria-label":"Close auto-enable dialog",onClick:()=>Ze(null),initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"fixed inset-0 z-[320] bg-black/50"},"auto-enable-backdrop"),e.jsxs(de.div,{initial:{opacity:0,y:12,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:10,scale:.98},transition:Dt.surfaceSwitch,className:"fixed inset-x-4 top-1/2 z-[330] -translate-y-1/2 rounded-2xl border border-white/[0.12] bg-[#080d14]/96 p-4 shadow-[0_24px_60px_rgba(0,0,0,0.5)] backdrop-blur-xl sm:left-1/2 sm:right-auto sm:w-[440px] sm:-translate-x-1/2",children:[e.jsx("p",{className:"text-caption uppercase tracking-[0.08em] text-secondary",children:"Enable Auto"}),e.jsx("h3",{className:"mt-1 text-heading font-semibold text-bright",children:"Auto-continue this initiative"}),e.jsxs("p",{className:"mt-2 text-caption text-secondary",children:["Initiative: ",e.jsx("span",{className:"text-primary",children:Ge.initiativeTitle})]}),e.jsxs("p",{className:"mt-1 text-caption text-secondary",children:["Starting workstream:"," ",e.jsx("span",{className:"text-primary",children:Ge.workstreamTitle})]}),e.jsx("p",{className:"mt-3 text-caption text-secondary",children:"OrgX will continue dispatching work in this initiative until blocked or stopped."}),e.jsxs("div",{className:"mt-4 flex items-center justify-end gap-2",children:[e.jsx("button",{type:"button",onClick:()=>Ze(null),className:"control-pill h-8 px-3 text-caption font-semibold",children:"Cancel"}),e.jsx("button",{type:"button",onClick:Or,className:"control-pill h-8 px-3 text-caption font-semibold","data-tone":"teal",children:"Enable Auto"})]})]},"auto-enable-dialog")]})}),e.jsx(lt,{children:ye&&e.jsxs(e.Fragment,{children:[e.jsx(de.button,{type:"button","aria-label":"Close switch-run dialog",onClick:()=>rt(null),initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"fixed inset-0 z-[320] bg-black/50"},"play-conflict-backdrop"),e.jsxs(de.div,{initial:{opacity:0,y:12,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:10,scale:.98},transition:Dt.surfaceSwitch,className:"fixed inset-x-4 top-1/2 z-[330] -translate-y-1/2 rounded-2xl border border-white/[0.12] bg-[#080d14]/96 p-4 shadow-[0_24px_60px_rgba(0,0,0,0.5)] backdrop-blur-xl sm:left-1/2 sm:right-auto sm:w-[460px] sm:-translate-x-1/2",children:[e.jsx("p",{className:"text-caption uppercase tracking-[0.08em] text-secondary",children:"Run conflict"}),e.jsx("h3",{className:"mt-1 text-heading font-semibold text-bright",children:"Another workstream is already running"}),e.jsx("p",{className:"mt-2 text-caption text-secondary",children:ye.activeWorkstreamTitle?`Running now: ${ye.activeWorkstreamTitle}`:ye.message}),e.jsxs("p",{className:"mt-1 text-caption text-secondary",children:["Requested: ",e.jsx("span",{className:"text-primary",children:ye.target.workstreamTitle})]}),e.jsxs("div",{className:"mt-4 flex flex-wrap items-center justify-end gap-2",children:[e.jsx("button",{type:"button",onClick:()=>rt(null),className:"control-pill h-8 px-3 text-caption font-semibold",children:"Keep current"}),e.jsx("button",{type:"button",onClick:()=>{Mt(ye.target.initiativeId,ye.target.initiativeTitle),rt(null)},className:"control-pill h-8 px-3 text-caption font-semibold",children:"Open running"}),e.jsx("button",{type:"button",disabled:xt,onClick:()=>void zr(),className:"control-pill h-8 px-3 text-caption font-semibold disabled:opacity-45","data-tone":"teal",children:xt?"Switching…":"Switch run"})]})]},"play-conflict-dialog")]})})]})})]}),e.jsx(Fi,{target:Kr,onClose:U})]})}export{xo as MissionControlView};