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