@useorgx/openclaw-plugin 0.7.26 → 0.7.27
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/BGqqzQfq.js +1 -0
- package/dashboard/dist/assets/BGqqzQfq.js.br +0 -0
- package/dashboard/dist/assets/BGqqzQfq.js.gz +0 -0
- package/dashboard/dist/assets/BIW2kmQr.js +1 -0
- package/dashboard/dist/assets/BIW2kmQr.js.br +0 -0
- package/dashboard/dist/assets/BIW2kmQr.js.gz +0 -0
- package/dashboard/dist/assets/{BZCkOZ20.js → BLCzNocO.js} +1 -1
- package/dashboard/dist/assets/BLCzNocO.js.br +0 -0
- package/dashboard/dist/assets/BLCzNocO.js.gz +0 -0
- package/dashboard/dist/assets/BYsvgOkA.js +1 -0
- package/dashboard/dist/assets/BYsvgOkA.js.br +0 -0
- package/dashboard/dist/assets/BYsvgOkA.js.gz +0 -0
- package/dashboard/dist/assets/BafISmbX.js +1 -0
- package/dashboard/dist/assets/BafISmbX.js.br +0 -0
- package/dashboard/dist/assets/BafISmbX.js.gz +0 -0
- package/dashboard/dist/assets/CDsk---g.js +1 -0
- package/dashboard/dist/assets/CDsk---g.js.br +0 -0
- package/dashboard/dist/assets/CDsk---g.js.gz +0 -0
- package/dashboard/dist/assets/{BvFcH_Iy.js → CJ0ozAqs.js} +1 -1
- package/dashboard/dist/assets/CJ0ozAqs.js.br +0 -0
- package/dashboard/dist/assets/CJ0ozAqs.js.gz +0 -0
- package/dashboard/dist/assets/{MrW1ixGx.js → CKUnb6Tt.js} +1 -1
- package/dashboard/dist/assets/CKUnb6Tt.js.br +0 -0
- package/dashboard/dist/assets/CKUnb6Tt.js.gz +0 -0
- package/dashboard/dist/assets/{B_LdOJUa.js → CPfdWIdE.js} +1 -1
- package/dashboard/dist/assets/CPfdWIdE.js.br +0 -0
- package/dashboard/dist/assets/CPfdWIdE.js.gz +0 -0
- package/dashboard/dist/assets/{B6VftyY6.js → CQceXoUm.js} +1 -1
- package/dashboard/dist/assets/CQceXoUm.js.br +0 -0
- package/dashboard/dist/assets/CQceXoUm.js.gz +0 -0
- package/dashboard/dist/assets/{BANQdlC4.js → CgCm4tUc.js} +1 -1
- package/dashboard/dist/assets/CgCm4tUc.js.br +0 -0
- package/dashboard/dist/assets/CgCm4tUc.js.gz +0 -0
- package/dashboard/dist/assets/{DJYl7gyA.js → Cgp0m1Ld.js} +1 -1
- package/dashboard/dist/assets/Cgp0m1Ld.js.br +0 -0
- package/dashboard/dist/assets/Cgp0m1Ld.js.gz +0 -0
- package/dashboard/dist/assets/{DZtNMX0t.js → CjGl4MOt.js} +1 -1
- package/dashboard/dist/assets/CjGl4MOt.js.br +0 -0
- package/dashboard/dist/assets/CjGl4MOt.js.gz +0 -0
- package/dashboard/dist/assets/DNCNDTzi.js +212 -0
- package/dashboard/dist/assets/DNCNDTzi.js.br +0 -0
- package/dashboard/dist/assets/DNCNDTzi.js.gz +0 -0
- package/dashboard/dist/assets/dgbgHLWm.js +1 -0
- package/dashboard/dist/assets/dgbgHLWm.js.br +0 -0
- package/dashboard/dist/assets/dgbgHLWm.js.gz +0 -0
- package/dashboard/dist/assets/h2T7lbDc.js +1 -0
- package/dashboard/dist/assets/h2T7lbDc.js.br +0 -0
- package/dashboard/dist/assets/h2T7lbDc.js.gz +0 -0
- package/dashboard/dist/assets/oWHKFgkC.js +1 -0
- package/dashboard/dist/assets/oWHKFgkC.js.br +0 -0
- package/dashboard/dist/assets/oWHKFgkC.js.gz +0 -0
- package/dashboard/dist/assets/{CqRNb2EL.js → qD5absr0.js} +1 -1
- package/dashboard/dist/assets/qD5absr0.js.br +0 -0
- package/dashboard/dist/assets/qD5absr0.js.gz +0 -0
- package/dashboard/dist/assets/wzn4QuPG.css +1 -0
- package/dashboard/dist/assets/wzn4QuPG.css.br +0 -0
- package/dashboard/dist/assets/wzn4QuPG.css.gz +0 -0
- package/dashboard/dist/index.html +2 -2
- package/dashboard/dist/index.html.br +0 -0
- package/dashboard/dist/index.html.gz +0 -0
- package/dist/openclaw.plugin.json +1 -1
- package/openclaw.plugin.json +1 -1
- package/package.json +1 -1
- package/dashboard/dist/assets/B6VftyY6.js.br +0 -0
- package/dashboard/dist/assets/B6VftyY6.js.gz +0 -0
- package/dashboard/dist/assets/BANQdlC4.js.br +0 -0
- package/dashboard/dist/assets/BANQdlC4.js.gz +0 -0
- package/dashboard/dist/assets/BPL4CL3c.js +0 -1
- package/dashboard/dist/assets/BPL4CL3c.js.br +0 -0
- package/dashboard/dist/assets/BPL4CL3c.js.gz +0 -0
- package/dashboard/dist/assets/BZCkOZ20.js.br +0 -0
- package/dashboard/dist/assets/BZCkOZ20.js.gz +0 -0
- package/dashboard/dist/assets/B_LdOJUa.js.br +0 -0
- package/dashboard/dist/assets/B_LdOJUa.js.gz +0 -0
- package/dashboard/dist/assets/Bfp-wdwb.css +0 -1
- package/dashboard/dist/assets/Bfp-wdwb.css.br +0 -0
- package/dashboard/dist/assets/Bfp-wdwb.css.gz +0 -0
- package/dashboard/dist/assets/BvFcH_Iy.js.br +0 -0
- package/dashboard/dist/assets/BvFcH_Iy.js.gz +0 -0
- package/dashboard/dist/assets/By0MIBj_.js +0 -1
- package/dashboard/dist/assets/By0MIBj_.js.br +0 -0
- package/dashboard/dist/assets/By0MIBj_.js.gz +0 -0
- package/dashboard/dist/assets/C0i7ABUU.js +0 -212
- package/dashboard/dist/assets/C0i7ABUU.js.br +0 -0
- package/dashboard/dist/assets/C0i7ABUU.js.gz +0 -0
- package/dashboard/dist/assets/CFB0MM7j.js +0 -1
- package/dashboard/dist/assets/CFB0MM7j.js.br +0 -0
- package/dashboard/dist/assets/CFB0MM7j.js.gz +0 -0
- package/dashboard/dist/assets/CQSRb1yu.js +0 -1
- package/dashboard/dist/assets/CQSRb1yu.js.br +0 -0
- package/dashboard/dist/assets/CQSRb1yu.js.gz +0 -0
- package/dashboard/dist/assets/CUoQoSm-.js +0 -1
- package/dashboard/dist/assets/CUoQoSm-.js.br +0 -0
- package/dashboard/dist/assets/CUoQoSm-.js.gz +0 -0
- package/dashboard/dist/assets/Ckd1R1iE.js +0 -1
- package/dashboard/dist/assets/Ckd1R1iE.js.br +0 -0
- package/dashboard/dist/assets/Ckd1R1iE.js.gz +0 -0
- package/dashboard/dist/assets/CqRNb2EL.js.br +0 -0
- package/dashboard/dist/assets/CqRNb2EL.js.gz +0 -0
- package/dashboard/dist/assets/DClUc9rw.js +0 -1
- package/dashboard/dist/assets/DClUc9rw.js.br +0 -0
- package/dashboard/dist/assets/DClUc9rw.js.gz +0 -0
- package/dashboard/dist/assets/DF2PMTwT.js +0 -1
- package/dashboard/dist/assets/DF2PMTwT.js.br +0 -0
- package/dashboard/dist/assets/DF2PMTwT.js.gz +0 -0
- package/dashboard/dist/assets/DJYl7gyA.js.br +0 -0
- package/dashboard/dist/assets/DJYl7gyA.js.gz +0 -0
- package/dashboard/dist/assets/DZtNMX0t.js.br +0 -0
- package/dashboard/dist/assets/DZtNMX0t.js.gz +0 -0
- package/dashboard/dist/assets/DlEa8PI0.js +0 -1
- package/dashboard/dist/assets/DlEa8PI0.js.br +0 -0
- package/dashboard/dist/assets/DlEa8PI0.js.gz +0 -0
- package/dashboard/dist/assets/M4QxcXjh.js +0 -1
- package/dashboard/dist/assets/M4QxcXjh.js.br +0 -0
- package/dashboard/dist/assets/M4QxcXjh.js.gz +0 -0
- package/dashboard/dist/assets/MrW1ixGx.js.br +0 -0
- package/dashboard/dist/assets/MrW1ixGx.js.gz +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{r,j as e}from"./Dj2k1r16.js";import{u as Nn,c as ss,b as Dt}from"./DMKyYAtD.js";import{i as ws,q as vs,b as yt,p as cn,a as Gn,c as Os,d as la,t as ca,h as Nt,e as da,f as z,g as ua,E as Rs,u as js,j as ze,A as bn,s as Jn,k as ks,l as Ds,m as qs,P as ma,n as pa,o as xa,W as ha,I as Sn,r as Tr,v as zs,w as fa,x as yn,M as ga,y as $s,z as ba,B as Yn,C as ps,D as hs,F as Cn,G as Dr,H as ya,J as Xn,K as Zn,L as Ft,U as wa,N as va}from"./C0i7ABUU.js";import{I as $r,o as ja,N as er}from"./DF2PMTwT.js";import{S as $t}from"./BZCkOZ20.js";import{A as at,m as le,R as ka,a as Na,u as Sa,L as Ca}from"./eeHXe_OQ.js";import{M as Ia}from"./By0MIBj_.js";import{E as Us}from"./CqRNb2EL.js";import{u as Ea}from"./BvFcH_Iy.js";import"./cX2e-TLi.js";import"./BjK42gtU.js";import"./BV0BcV1u.js";import"./CUoQoSm-.js";function Aa({activities:t,agents:s,initiatives:a}){return r.useMemo(()=>{const n=new Map,o=(l,c,h,f)=>{const j=n.get(l)??[];j.some(p=>p.id===c)||(j.push({id:c,name:h,confidence:f}),n.set(l,j))};return t.forEach(l=>{const c="metadata"in l&&l.metadata&&typeof l.metadata=="object"?l.metadata:null,h=c&&typeof c=="object"?c:{},f=("initiativeId"in l&&typeof l.initiativeId=="string"?l.initiativeId:void 0)??h.initiativeId??void 0,j=l.agentId??void 0,p=("agentName"in l&&typeof l.agentName=="string"?l.agentName:"agent"in l&&typeof l.agent=="string"?l.agent:void 0)??j??"Unknown";f&&j&&o(f,j,p,"high")}),a.forEach(l=>{var c;(c=l.avatars)!=null&&c.length&&l.avatars.forEach(h=>{const f=s.find(j=>j.name.toLowerCase()===h.toLowerCase());f?o(l.id,f.id,f.name,"medium"):o(l.id,`avatar:${h}`,h,"medium")})}),s.forEach(l=>{if(!l.task)return;const c=l.task.toLowerCase();a.forEach(h=>{h.name.toLowerCase().split(/\s+/).filter(E=>E.length>3).some(E=>c.includes(E))&&o(h.id,l.id,l.name,"low")})}),n},[t,s,a])}function Ma({initiativeId:t=null,projectId:s=null,authToken:a=null,embedMode:n=!1,enabled:o=!0}){var S,M,R;const l=Nn(),c=ws(),h=r.useMemo(()=>vs.autoContinueStatus({initiativeId:t??null,authToken:a,embedMode:n}),[t,a,n]),f=ss({queryKey:h,enabled:o&&(!!t||t===null),queryFn:async()=>{if(c)return{ok:!0,initiativeId:t,run:null,defaults:{tokenBudget:null,tickMs:0}};const m=new URLSearchParams;t&&m.set("initiative_id",t);const b=await fetch(`/orgx/api/mission-control/auto-continue/status?${m.toString()}`,{headers:yt({authToken:a,embedMode:n})}),k=await b.json().catch(()=>null);if(!b.ok){const $=typeof(k==null?void 0:k.error)=="string"&&k.error||typeof(k==null?void 0:k.message)=="string"&&k.message||`Failed to load auto-continue status (${b.status})`;return{ok:!1,initiativeId:t,run:null,defaults:{tokenBudget:null,tickMs:0},error:$}}return k},refetchInterval:m=>{var te,re;const b=m.state.data;if((b==null?void 0:b.ok)===!1)return!1;const k=((te=b==null?void 0:b.error)==null?void 0:te.toLowerCase())??"";if(k.includes("404")||k.includes("400")||k.includes("not found")||k.includes("bad request"))return!1;const F=((re=b==null?void 0:b.run)==null?void 0:re.status)??null;return F==="running"||F==="stopping"?2500:12e3}}),j=async()=>{await Os(l,{initiativeId:t,projectId:s,authToken:a,embedMode:n,includeSlices:!1})},p=Dt({onMutate:async()=>{await l.cancelQueries({queryKey:h});const m=l.getQueryData(h);return l.setQueryData(h,b=>!b||!b.run?b:{...b,run:{...b.run,status:"running",startedAt:new Date().toISOString()}}),{previous:m}},onError:(m,b,k)=>{k!=null&&k.previous&&l.setQueryData(h,k.previous)},mutationFn:async m=>{if(c){const F=f.data??null;return{ok:!0,initiativeId:t,run:(F==null?void 0:F.run)??null,defaults:(F==null?void 0:F.defaults)??{tokenBudget:null,tickMs:0}}}const b={};t&&(b.initiativeId=t),s&&(b.workspaceId=s),b.ignoreSpawnGuardRateLimit=!0,m&&typeof m=="object"&&(typeof m.tokenBudgetTokens=="number"&&(b.tokenBudgetTokens=m.tokenBudgetTokens),typeof m.agentId=="string"&&m.agentId.trim().length>0&&(b.agentId=m.agentId.trim()),typeof m.maxParallelSlices=="number"&&Number.isFinite(m.maxParallelSlices)&&(b.maxParallelSlices=m.maxParallelSlices),m.parallelMode==="iwmt"&&(b.parallelMode=m.parallelMode));const k=await fetch("/orgx/api/mission-control/auto-continue/start",{method:"POST",headers:yt({authToken:a,embedMode:n,contentTypeJson:!0}),body:JSON.stringify(b)}),$=await k.json().catch(()=>null);if(!k.ok){const F=Gn($);throw F||cn(k,$,"Failed to start auto-continue")}if($&&typeof $=="object"&&"run"in $){const F=f.data??null;return{ok:!0,initiativeId:t,run:$.run??null,defaults:(F==null?void 0:F.defaults)??{tokenBudget:null,tickMs:0}}}return $},onSuccess:m=>{l.setQueryData(h,m),j()}}),E=Dt({onMutate:async()=>{await l.cancelQueries({queryKey:h});const m=l.getQueryData(h);return l.setQueryData(h,b=>!b||!b.run?b:{...b,run:{...b.run,status:"stopping"}}),{previous:m}},onError:(m,b,k)=>{k!=null&&k.previous&&l.setQueryData(h,k.previous)},mutationFn:async()=>{if(c){const $=f.data??null;return{ok:!0,initiativeId:t,run:null,defaults:($==null?void 0:$.defaults)??{tokenBudget:null,tickMs:0}}}const m={};t&&(m.initiativeId=t);const b=await fetch("/orgx/api/mission-control/auto-continue/stop",{method:"POST",headers:yt({authToken:a,embedMode:n,contentTypeJson:!0}),body:JSON.stringify(m)}),k=await b.json().catch(()=>null);if(!b.ok)throw cn(b,k,"Failed to stop auto-continue");if(k&&typeof k=="object"&&"run"in k){const $=f.data??null;return{ok:!0,initiativeId:t,run:k.run??null,defaults:($==null?void 0:$.defaults)??{tokenBudget:null,tickMs:0}}}return k},onSuccess:m=>{l.setQueryData(h,m),j()}}),L=Dt({mutationFn:async m=>{var F;if(c)return{ok:!0,dispatched:((F=m.workstreamIds)==null?void 0:F.length)??1};const b={initiativeId:m.initiativeId};m.workstreamIds&&m.workstreamIds.length>0&&(b.workstreamIds=m.workstreamIds),m.agentId&&(b.agentId=m.agentId),m.scope&&(b.scope=m.scope),b.ignoreSpawnGuardRateLimit=!0;const k=await fetch("/orgx/api/mission-control/next-up/launch",{method:"POST",headers:yt({authToken:a,embedMode:n,contentTypeJson:!0}),body:JSON.stringify(b)}),$=await k.json().catch(()=>null);if(!k.ok){const te=Gn($);throw te||cn(k,$,"Failed to launch")}return $??{ok:!0,dispatched:0}},onSuccess:()=>{j()}}),g=((S=f.data)==null?void 0:S.run)??null,d=(g==null?void 0:g.status)??null,v=d==="running"||d==="stopping",y=d==="stopping"||E.isPending;return{status:f.data??null,run:g,isRunning:v,isGracefullyStopping:y,isLoading:f.isLoading,error:((M=f.data)==null?void 0:M.error)??((R=f.error)==null?void 0:R.message)??null,start:p.mutateAsync,stop:E.mutateAsync,launchSingle:L.mutateAsync,isStarting:p.isPending,isStopping:E.isPending,isLaunching:L.isPending,refetch:f.refetch}}function Lr(t){const s=r.useRef(null),a=r.useCallback((n,o,l,c)=>{if(l&&s.current!==null){const h=t.indexOf(s.current),f=t.indexOf(n);if(h!==-1&&f!==-1){const j=Math.min(h,f),p=Math.max(h,f),E=t.slice(j,p+1);c(L=>{const g=new Set(L);for(const d of E)o?g.add(d):g.delete(d);return g});return}}c(h=>{const f=new Set(h);return o?f.add(n):f.delete(n),f}),s.current=n},[t]);return{lastClickedId:s,handleSelect:a}}const Ta=100,Da=5,$a=75,La=3,_a=["workstream","milestone","task"],Pa=60;function Ls(t){const s=Date.parse(t??"");return Number.isFinite(s)?s:0}function Fa(t){return t.toLowerCase().trim().split(/\s+/).filter(Boolean)}function Ra(t,s){const a=[];for(let n=0;n<t.length;n+=s)a.push(t.slice(n,n+s));return a}async function tr(t,s,a){var l;const n=[];let o=0;for(let c=0;c<a;c+=1){const h=new URLSearchParams(t);h.set("limit",String(s)),h.set("offset",String(o));const f=await fetch(`/orgx/api/entities?${h.toString()}`);if(!f.ok)break;const j=await f.json(),p=j.data??[];if(n.push(...p),!!!((l=j.pagination)!=null&&l.has_more)||p.length===0)break;o+=s}return n}function sr(t,s,a,n){const o=t.name.toLowerCase(),l=(t.description??"").toLowerCase();let c=0;n&&(c+=65),o===s&&(c+=140),o.startsWith(s)&&(c+=100),o.includes(s)&&(c+=80),l.includes(s)&&(c+=40);for(const h of a)o.includes(h)&&(c+=22),l.includes(h)&&(c+=8);return c}function Ba(t,s,a=null){const n=t.trim().toLowerCase(),o=(a==null?void 0:a.trim())??"";return ss({queryKey:vs.initiativeSearch({query:n,projectId:o||null}),enabled:s&&n.length>=2,queryFn:async()=>{var g;if(n.length<2||ws())return[];const l=d=>{const v=new URLSearchParams(d);return o.length>0&&v.set("workspace_id",o),v},c=await tr(l({type:"initiative",search:n}),Ta,Da),h=await Promise.all(_a.map(d=>tr(l({type:d,search:n}),$a,La))),f=new Set;for(const d of h)for(const v of d){const y=(g=v.initiative_id)==null?void 0:g.trim();y&&f.add(y)}const j=[];for(const d of Ra(Array.from(f),Pa)){if(d.length===0)continue;const v=l({type:"initiative",ids:d.join(","),limit:String(d.length),offset:"0"}),y=await fetch(`/orgx/api/entities?${v.toString()}`);if(!y.ok)continue;const S=await y.json();j.push(...S.data??[])}const p=[...c,...j],E=new Map;for(const d of p){const v=E.get(d.id);if(!v){E.set(d.id,d);continue}Ls(d.updated_at??d.created_at)>Ls(v.updated_at??v.created_at)&&E.set(d.id,d)}const L=Fa(n);return Array.from(E.values()).filter(d=>la(d.status)).map(ca).filter(d=>{if(f.has(d.id))return!0;const v=[d.name,d.description??"",d.rawStatus??"",d.status].join(" ").toLowerCase();return L.every(y=>v.includes(y))}).sort((d,v)=>{const y=sr(v,n,L,f.has(v.id))-sr(d,n,L,f.has(d.id));return y!==0?y:Ls(v.updatedAt??v.createdAt)-Ls(d.updatedAt??d.createdAt)})},staleTime:15e3})}function In({value:t,onChange:s,placeholder:a}){return e.jsxs("label",{className:"relative block",children:[e.jsx("span",{className:"sr-only",children:a}),e.jsxs("svg",{className:"pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-muted",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("circle",{cx:"11",cy:"11",r:"8"}),e.jsx("path",{d:"m21 21-4.3-4.3"})]}),e.jsx("input",{type:"text",value:t,onChange:n=>s(n.target.value),placeholder:a,className:"w-full rounded-xl border border-white/[0.08] bg-white/[0.03] py-2.5 pl-10 pr-8 text-body text-white placeholder:text-muted transition-all focus:border-lime/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 Xt(t){if(!t.ok){const s=await t.json().catch(()=>null),a=typeof(s==null?void 0:s.error)=="string"&&s.error||typeof(s==null?void 0:s.message)=="string"&&s.message||`Request failed (${t.status})`;throw new Error(Nt(a))}return t}function Oa(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 dn(t){const s=t.trim().toLowerCase();return s==="deleted"||s==="archived"||s==="cancelled"}function qa(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 za(t){const s=Nn(),a=yt({authToken:t.authToken,embedMode:t.embedMode,contentTypeJson:!0}),n=()=>{Os(s,{authToken:t.authToken,embedMode:t.embedMode}),s.invalidateQueries({queryKey:["live-initiatives"]}),s.invalidateQueries({queryKey:["initiative-details"]}),s.invalidateQueries({queryKey:["entities"]})},o=(g,d)=>{s.setQueryData(["initiative-tombstones"],v=>{const y=Array.isArray(v)?v.filter(M=>typeof M=="string"):[],S=y.includes(g);return d?S?y:[...y,g]:S?y.filter(M=>M!==g):y})},l=(g,d)=>{const v=Oa(d),y=new Date().toISOString(),S=dn(d);o(g,S);const M=R=>{if(!Array.isArray(R))return R;if(S){const k=R.filter($=>{if(!$||typeof $!="object")return!0;const F=$;return!(typeof F.id=="string"&&F.id===g)});return k.length===R.length?R:k}let m=!1;const b=R.map(k=>{if(!k||typeof k!="object")return k;const $=k;return typeof $.id!="string"||$.id!==g?k:(m=!0,{...$,status:v,rawStatus:d,updatedAt:y})});return m?b:R};s.setQueriesData({queryKey:["entities"]},M),s.setQueriesData({queryKey:["live-initiatives"]},M)},c=(g,d,v="status")=>{const y=qa(d);s.setQueriesData({queryKey:["live-data"]},S=>{if(!S||typeof S!="object")return S;const M=S,R=M.sessions;if(!R||typeof R!="object")return S;const m=R,b=m.nodes;if(!Array.isArray(b))return S;let k=!1;const $=v==="delete"?b.filter(O=>{if(!O||typeof O!="object")return!0;const w=O,A=(typeof w.initiativeId=="string"?w.initiativeId:null)===g;return A&&(k=!0),!A}):b.map(O=>{if(!O||typeof O!="object")return O;const w=O;return(typeof w.initiativeId=="string"?w.initiativeId:null)!==g||w.status===y?O:(k=!0,{...w,status:y})});if(!k)return S;const F=new Set,te=new Set;for(const O of $){if(!O||typeof O!="object")continue;const w=O;typeof w.id=="string"&&F.add(w.id),typeof w.groupId=="string"&&te.add(w.groupId)}const re=Array.isArray(m.edges)?m.edges.filter(O=>{if(!O||typeof O!="object")return!1;const w=O,Q=typeof w.parentId=="string"?w.parentId:null,A=typeof w.childId=="string"?w.childId:null;return Q!==null&&A!==null&&F.has(Q)&&F.has(A)}):m.edges,X=Array.isArray(m.groups)?m.groups.filter(O=>{if(!O||typeof O!="object")return!1;const w=O;return typeof w.id=="string"&&te.has(w.id)}):m.groups;return{...M,sessions:{...m,nodes:$,edges:re,groups:X}}})},h={start:"active",complete:"completed",block:"blocked",unblock:"active",pause:"paused",resume:"active"},f=Dt({mutationFn:async g=>{const{type:d,...v}=g,y=await fetch("/orgx/api/entities",{method:"POST",headers:a,body:JSON.stringify({type:d,...v})});return await Xt(y),y.json()},onSuccess:n}),j=Dt({mutationFn:async g=>{const{type:d,id:v,...y}=g,S=await fetch("/orgx/api/entities",{method:"PATCH",headers:a,body:JSON.stringify({type:d,id:v,...y})});return await Xt(S),S.json()},onSuccess:(g,d)=>{d.type.trim().toLowerCase()==="initiative"&&typeof d.status=="string"&&d.status.trim().length>0&&(l(d.id,d.status),c(d.id,d.status,dn(d.status)?"delete":"status")),n()}}),p=Dt({mutationFn:async g=>{const d=await fetch(`/orgx/api/entities/${encodeURIComponent(g.type)}/${encodeURIComponent(g.id)}/delete`,{method:"POST",headers:a,body:"{}"});return await Xt(d),d.json()},onSuccess:(g,d)=>{d.type.trim().toLowerCase()==="initiative"&&(l(d.id,"archived"),c(d.id,"archived","delete")),n()}}),E=Dt({mutationFn:async g=>{const d=await fetch(`/orgx/api/entities/${encodeURIComponent(g.type)}/${encodeURIComponent(g.id)}/${encodeURIComponent(g.action)}`,{method:"POST",headers:a,body:JSON.stringify({force:g.force??!1})});return await Xt(d),d.json()},onSuccess:(g,d)=>{if(d.type.trim().toLowerCase()==="initiative"){const v=h[d.action.trim().toLowerCase()];v&&(l(d.id,v),c(d.id,v,"status"))}n()}}),L=Dt({mutationFn:async g=>{const d=Array.from(new Map((g.items??[]).filter(m=>typeof(m==null?void 0:m.type)=="string"&&m.type.trim().length>0&&typeof(m==null?void 0:m.id)=="string"&&m.id.trim().length>0).map(m=>[`${m.type}:${m.id}`,m])).values());if(d.length===0)return{updated:0,failed:0,errors:[]};if(g.mode==="action"&&!g.action)throw new Error("bulk action requires an action name");const v=async m=>{try{if(g.mode==="delete"){const k=await fetch(`/orgx/api/entities/${encodeURIComponent(m.type)}/${encodeURIComponent(m.id)}/delete`,{method:"POST",headers:a,body:"{}"});return await Xt(k),{ok:!0}}if(g.mode==="update"){const k=await fetch("/orgx/api/entities",{method:"PATCH",headers:a,body:JSON.stringify({type:m.type,id:m.id,...g.updates??{}})});return await Xt(k),{ok:!0}}const b=await fetch(`/orgx/api/entities/${encodeURIComponent(m.type)}/${encodeURIComponent(m.id)}/${encodeURIComponent(g.action)}`,{method:"POST",headers:a,body:JSON.stringify({force:g.force??!1})});return await Xt(b),{ok:!0}}catch(b){return{ok:!1,error:b instanceof Error?b.message:"Unknown bulk mutation failure"}}},y=await Promise.all(d.map(m=>v(m)));let S=0,M=0;const R=[];for(const m of y)m.ok?S+=1:(M+=1,R.push(m.error));return{updated:S,failed:M,errors:R}},onSuccess:(g,d)=>{var y;const v=(d.items??[]).filter(S=>S.type.trim().toLowerCase()==="initiative");if(v.length>0){if(d.mode==="update"&&typeof((y=d.updates)==null?void 0:y.status)=="string"&&d.updates.status.trim().length>0)for(const S of v)l(S.id,d.updates.status),c(S.id,d.updates.status,dn(d.updates.status)?"delete":"status");else if(d.mode==="delete")for(const S of v)l(S.id,"archived"),c(S.id,"archived","delete");else if(d.mode==="action"&&d.action){const S=h[d.action.trim().toLowerCase()];if(S)for(const M of v)l(M.id,S),c(M.id,S,"status")}}n()}});return{createEntity:f,updateEntity:j,deleteEntity:p,entityAction:E,bulkEntityMutation:L}}const _r=r.createContext(null);function Ht(){const t=r.useContext(_r);if(!t)throw new Error("useMissionControl must be used within MissionControlProvider");return t}function Ua({children:t,agentEntityMap:s,authToken:a,embedMode:n}){const[o,l]=r.useState(new Set),[c,h]=r.useState(null),[f,j]=r.useState(""),[p,E]=r.useState([]),[L,g]=r.useState("target"),[d,v]=r.useState("any"),[y,S]=r.useState(""),[M,R]=r.useState(""),[m,b]=r.useState("status"),[k,$]=r.useState("default"),F=za({authToken:a,embedMode:n}),te=r.useCallback(V=>{l(pe=>{const ae=new Set(pe);return ae.has(V)?ae.delete(V):ae.add(V),ae})},[]),re=r.useCallback(V=>{l(pe=>{if(pe.has(V))return pe;const ae=new Set(pe);return ae.add(V),ae})},[]),X=r.useCallback(V=>{l(new Set(V))},[]),O=r.useCallback(()=>{l(new Set)},[]),w=r.useCallback(V=>{h(V)},[]),Q=r.useCallback(()=>{h(null)},[]),A=r.useCallback(V=>{const pe=Array.from(new Set((V??[]).map(ae=>ae.trim().toLowerCase()).filter(Boolean)));E(pe)},[]),H=r.useCallback(V=>{E(pe=>{const ae=V.trim().toLowerCase();return ae?pe.includes(ae)?pe.filter(Se=>Se!==ae):[...pe,ae]:pe})},[]),K=r.useCallback(()=>{j(""),E([]),g("target"),v("any"),S(""),R("")},[]),de=y.trim().length>0||M.trim().length>0,q=d!=="any"&&(d!=="custom_range"||de),P=p.length+(q?1:0),B=f.trim().length>0||P>0,U=r.useMemo(()=>({agentEntityMap:s,expandedInitiatives:o,modalTarget:c,searchQuery:f,statusFilters:p,dateField:L,datePreset:d,dateStart:y,dateEnd:M,activeFilterCount:P,hasActiveFilters:B,groupBy:m,sortBy:k,authToken:a,embedMode:n,mutations:F,toggleExpanded:te,expandInitiative:re,expandAll:X,collapseAll:O,openModal:w,closeModal:Q,setSearchQuery:j,setStatusFilters:A,toggleStatusFilter:H,setDateField:g,setDatePreset:v,setDateStart:S,setDateEnd:R,setGroupBy:b,setSortBy:$,clearFilters:K}),[s,o,c,f,p,L,d,y,M,P,B,m,k,a,n,F,te,re,X,O,w,Q,A,H,g,v,S,R,b,$,K]);return e.jsx(_r.Provider,{value:U,children:t})}function Wa(t){if(typeof t!="number"||!Number.isFinite(t))return;const s=Math.max(0,Math.trunc(t));return s>0?s-1:s}function Qa(t){return t==="workstream"?"W":t==="milestone"?"M":t==="task"?"T":"I"}function un(t){return{initiative:{id:t,title:"Initiative",status:"active",summary:null,assignedAgents:[]},nodes:[],edges:[],recentTodos:[]}}function Ha(t){const s=new Date().toISOString(),a=t==="init-2"?"Black Friday Email":"Q4 Feature Ship",n=`${t}:ws:design`,o=`${t}:ms:polish`,l=`${t}:task:tokens`,c=`${t}:task:qa`;return{initiative:{id:t,title:a,status:"active",summary:"Demo mode graph from local fixture data.",assignedAgents:[{id:"dana",name:"Dana",domain:"design"}]},nodes:[{id:n,type:"workstream",title:"Dashboard UI pass",status:"active",parentId:t,initiativeId:t,workstreamId:n,milestoneId:null,priorityNum:1,priorityLabel:"P1",dependencyIds:[],dueDate:null,etaEndAt:null,expectedDurationHours:8,expectedBudgetUsd:1500,assignedAgents:[{id:"dana",name:"Dana",domain:"design"}],updatedAt:s},{id:o,type:"milestone",title:"Polish pass",status:"active",parentId:n,initiativeId:t,workstreamId:n,milestoneId:o,priorityNum:1,priorityLabel:"P1",dependencyIds:[n],dueDate:null,etaEndAt:null,expectedDurationHours:4,expectedBudgetUsd:900,assignedAgents:[{id:"dana",name:"Dana",domain:"design"}],updatedAt:s},{id:l,type:"task",title:"Refine queue action ergonomics",status:"todo",parentId:o,initiativeId:t,workstreamId:n,milestoneId:o,priorityNum:1,priorityLabel:"P1",dependencyIds:[o],dueDate:null,etaEndAt:null,expectedDurationHours:2,expectedBudgetUsd:450,assignedAgents:[{id:"dana",name:"Dana",domain:"design"}],updatedAt:s},{id:c,type:"task",title:"Mobile QA sweep",status:"active",parentId:o,initiativeId:t,workstreamId:n,milestoneId:o,priorityNum:2,priorityLabel:"P2",dependencyIds:[l],dueDate:null,etaEndAt:null,expectedDurationHours:2,expectedBudgetUsd:420,assignedAgents:[{id:"mark",name:"Mark",domain:"engineering"}],updatedAt:s}],edges:[{from:n,to:o,kind:"depends_on"},{from:o,to:l,kind:"depends_on"},{from:l,to:c,kind:"depends_on"}],recentTodos:[l,c]}}function Va({initiativeId:t,authToken:s=null,embedMode:a=!1,enabled:n=!0}){var j,p;const o=ws(),l=da(t),c=r.useMemo(()=>vs.missionControlGraph({initiativeId:t,authToken:s,embedMode:a}),[t,s,a]),h=ss({queryKey:c,enabled:n&&!!t&&l,queryFn:async()=>{if(!t)throw new Error("initiativeId is required");if(o)return Ha(t);if(!l)return un(t);const E=new URLSearchParams({initiative_id:t}),L={};a&&(L["X-Orgx-Embed"]="true"),s&&(L.Authorization=`Bearer ${s}`);const g=Object.keys(L).length>0?L:void 0,d=await fetch(`/orgx/api/mission-control/graph?${E.toString()}`,{headers:g});if(!d.ok){const S=await d.json().catch(()=>null),M=typeof(S==null?void 0:S.error)=="string"&&S.error||typeof(S==null?void 0:S.message)=="string"&&S.message||`Failed to fetch Mission Control graph (${d.status})`;return{...un(t),degraded:[M]}}const v=await d.json(),y=Array.isArray(v.nodes)?v.nodes.map(S=>{const M=S,R=Wa(M.sequenceIndex??M.sequence);if(typeof R!="number")return S;const m=typeof M.hierarchyLabel=="string"&&M.hierarchyLabel.trim().length>0;return{...M,sequenceIndex:R,hierarchyLabel:m?M.hierarchyLabel:`${Qa(String(M.type??"initiative"))}${R+1}`}}):[];return{...v,nodes:y.length>0?y:v.nodes}}});return{graph:h.data??(t?un(t):null),isLoading:l?h.isLoading:!1,error:l?((j=h.error)==null?void 0:j.message)??null:null,degraded:l?((p=h.data)==null?void 0:p.degraded)??[]:[],refetch:h.refetch}}const Ka=["initiative","workstream","milestone","task"],Ga={initiative:"Initiatives",workstream:"Workstreams",milestone:"Milestones",task:"Tasks"},Ja=8,mn=30;function Ya(t){const s=t.trim().toLowerCase();return s==="blocked"?z.red:s==="done"||s==="completed"?z.teal:["in_progress","active","running","queued"].includes(s)?z.lime:"rgba(255,255,255,0.35)"}function Xa({nodes:t,edges:s,selectedNodeId:a,focusedWorkstreamId:n,onSelectNode:o}){r.useMemo(()=>new Map(t.map(m=>[m.id,m])),[t]);const l=r.useRef(null),c=r.useRef(new Map),[h,f]=r.useState([]),[j,p]=r.useState(new Set),E=r.useMemo(()=>{if(!n)return new Set(t.map(k=>k.id));const m=new Set;for(const k of t)(k.type==="initiative"||k.id===n||k.workstreamId===n)&&m.add(k.id);let b=!0;for(;b;){b=!1;for(const k of s)(m.has(k.from)||m.has(k.to))&&(!m.has(k.from)||!m.has(k.to))&&(m.add(k.from),m.add(k.to),b=!0)}return m},[n,t,s]),L=r.useMemo(()=>{var $;const b=t.filter(F=>E.has(F.id)).slice(0,mn),k={initiative:[],workstream:[],milestone:[],task:[]};for(const F of b)($=k[F.type])==null||$.push(F);return k},[t,E]),g=Object.values(L).reduce((m,b)=>m+b.length,0),d=t.filter(m=>E.has(m.id)).length>mn,v=r.useMemo(()=>{const m=new Set(Object.values(L).flat().map(b=>b.id));return s.filter(b=>m.has(b.from)&&m.has(b.to))},[s,L]),y=r.useMemo(()=>{if(!a)return new Set;const m=new Set([a]);let b=!0;for(;b;){b=!1;for(const k of v)m.has(k.from)&&!m.has(k.to)&&(m.add(k.to),b=!0),m.has(k.to)&&!m.has(k.from)&&(m.add(k.from),b=!0)}return m},[a,v]),S=r.useCallback(()=>{const m=l.current;if(!m)return;const b=m.getBoundingClientRect(),k=[];for(const $ of v){const F=c.current.get($.from),te=c.current.get($.to);if(!F||!te)continue;const re=F.getBoundingClientRect(),X=te.getBoundingClientRect(),O=re.right-b.left,w=re.top+re.height/2-b.top,Q=X.left-b.left,A=X.top+X.height/2-b.top,H=Math.min(Math.abs(Q-O)*.4,60),K=`M ${O} ${w} C ${O+H} ${w}, ${Q-H} ${A}, ${Q} ${A}`,de=a!==null&&y.has($.from)&&y.has($.to);k.push({key:`${$.from}-${$.to}`,d:K,highlighted:de})}f(k)},[v,a,y]);r.useLayoutEffect(()=>{S()},[S,L,j]),r.useEffect(()=>{const m=l.current;if(!m||typeof ResizeObserver>"u")return;const b=new ResizeObserver(()=>S());return b.observe(m),()=>b.disconnect()},[S]);const M=Ka.filter(m=>{var b;return(((b=L[m])==null?void 0:b.length)??0)>0});if(g===0)return e.jsx("div",{className:"rounded-xl border border-white/[0.07] bg-black/[0.14] px-3 py-3 text-caption text-secondary",children:"No dependencies mapped"});const R=(m,b)=>{b?c.current.set(m,b):c.current.delete(m)};return e.jsxs("section",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:[g," nodes · ",v.length," links"]}),n&&e.jsx("span",{className:"status-pill","data-tone":"active",children:"Focused workstream"})]}),e.jsxs("div",{ref:l,className:"relative overflow-x-auto rounded-xl border border-white/[0.07] bg-black/[0.14] p-3",children:[e.jsx("svg",{className:"pointer-events-none absolute inset-0 h-full w-full",style:{zIndex:1},children:h.map(({key:m,d:b,highlighted:k})=>e.jsx("path",{d:b,fill:"none",stroke:k?z.lime:"rgba(255,255,255,0.12)",strokeWidth:k?1.5:1,strokeDasharray:k?void 0:"4 3",opacity:k?.85:.5},m))}),e.jsx("div",{className:"relative z-[2] flex gap-3",style:{minWidth:M.length*160},children:M.map(m=>{const b=L[m]??[],k=j.has(m),$=k?b:b.slice(0,Ja),F=b.length-$.length;return e.jsxs("div",{className:"flex-1 min-w-[140px]",children:[e.jsxs("div",{className:"mb-2 text-micro uppercase tracking-[0.09em] text-secondary",children:[Ga[m]," (",b.length,")"]}),e.jsxs("div",{className:"space-y-1",children:[$.map(te=>{const re=a===te.id,X=!re&&y.has(te.id);return e.jsxs("button",{ref:O=>R(te.id,O),type:"button",onClick:()=>o(te.id),title:te.title,className:`flex w-full items-center gap-1.5 rounded-md border px-2 py-1 text-left transition-colors ${re?"border-lime/35 bg-lime/12":X?"border-lime/20 bg-lime/[0.06]":"border-white/[0.06] bg-white/[0.03] hover:bg-white/[0.08]"}`,children:[e.jsx("span",{className:"h-1.5 w-1.5 flex-shrink-0 rounded-full",style:{backgroundColor:Ya(te.status)}}),e.jsx("span",{className:"max-w-[140px] truncate text-micro text-primary",children:te.title})]},te.id)}),F>0&&!k&&e.jsxs("button",{type:"button",onClick:()=>p(te=>new Set([...te,m])),className:"w-full rounded-md px-2 py-1 text-center text-micro text-muted transition-colors hover:bg-white/[0.04] hover:text-secondary",children:["Show all (",b.length,")"]})]})]},m)})})]}),d&&e.jsxs("div",{className:"text-micro text-muted",children:["Showing ",mn," of ",t.filter(m=>E.has(m.id)).length," nodes. Focus a workstream to narrow scope."]})]})}function Je(t){return ua(t)}function Ws(t){return Number.isFinite(t)?Math.max(0,Math.min(100,Math.round(t))):0}function ts(t,s){return s<=0?0:Ws(t/s*100)}function wn({type:t,className:s=""}){return e.jsx(Rs,{type:t,className:s,size:14})}function Za({dependencies:t,allNodes:s,disabled:a=!1,onSave:n}){const[o,l]=r.useState(!1),[c,h]=r.useState(""),[f,j]=r.useState(t),p=r.useMemo(()=>new Map(s.map(d=>[d.id,d])),[s]),E=r.useMemo(()=>{const d=c.trim().toLowerCase(),v=[...s].sort((y,S)=>y.title.localeCompare(S.title));return d?v.filter(y=>y.title.toLowerCase().includes(d)||y.id.toLowerCase().includes(d)).slice(0,16):v.slice(0,16)},[s,c]),L=()=>{n(Array.from(new Set(f))),l(!1)},g=d=>{j(v=>v.includes(d)?v.filter(y=>y!==d):[...v,d])};return e.jsxs("div",{className:"relative",children:[e.jsx("button",{type:"button",disabled:a,onClick:()=>{h(""),j(t),l(d=>!d)},className:"rounded-md border border-strong bg-white/[0.04] px-2 py-1 text-micro text-primary transition-colors hover:bg-white/[0.08] disabled:opacity-40",children:t.length>0?`${t.length} linked`:"Set links"}),o&&e.jsxs("div",{className:"surface-tier-2 absolute right-0 z-20 mt-1.5 w-[320px] rounded-xl p-2.5 shadow-[0_20px_40px_rgba(0,0,0,0.45)]",children:[e.jsx("label",{className:"text-micro uppercase tracking-[0.08em] text-secondary",children:"Link dependencies"}),e.jsx("input",{value:c,onChange:d=>h(d.target.value),placeholder:"Search by title or id...",className:"mt-1.5 h-9 w-full rounded-md border border-strong bg-black/25 px-2.5 text-caption text-bright outline-none transition-colors placeholder:text-muted focus:border-lime/35"}),e.jsx("div",{className:"mt-2 flex max-h-[84px] flex-wrap gap-1.5 overflow-y-auto rounded-md border border-white/[0.08] bg-black/20 p-1.5",children:f.length===0?e.jsx("span",{className:"text-micro text-muted",children:"No links selected"}):f.map(d=>{var y;const v=((y=p.get(d))==null?void 0:y.title)??d;return e.jsxs("button",{type:"button",onClick:()=>g(d),className:"inline-flex items-center gap-1 rounded-full border border-strong bg-white/[0.05] px-2 py-0.5 text-micro text-primary transition-colors hover:bg-white/[0.1]",title:v,children:[e.jsx("span",{className:"max-w-[180px] truncate",children:v}),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:E.length===0?e.jsx("div",{className:"px-1 text-micro text-muted",children:"No matching nodes"}):E.map(d=>{const v=f.includes(d.id);return e.jsxs("button",{type:"button",onClick:()=>g(d.id),className:`flex w-full items-center justify-between rounded-md border px-2 py-1 text-left text-micro transition-colors ${v?"border-lime/32 bg-lime/12 text-lime":"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:v?"Linked":"Link"})]},d.id)})}),e.jsxs("div",{className:"mt-2 flex items-center justify-end gap-1.5",children:[e.jsx("button",{type:"button",onClick:()=>l(!1),className:"rounded-md border border-strong px-2 py-1 text-micro text-secondary transition-colors hover:bg-white/[0.08]",children:"Cancel"}),e.jsx("button",{type:"button",onClick:L,className:"rounded-md border border-lime/30 bg-lime/15 px-2 py-1 text-micro text-lime transition-colors hover:bg-lime/22",children:"Save links"})]})]})]})}const ei={bottom:"Add to queue"},ti=[{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 si({scope:t,size:s=12}){const a=s,n=Math.round(a*.14),o=Math.round(a*.06);if(t==="task")return e.jsx("svg",{width:a,height:a,viewBox:`0 0 ${a} ${a}`,fill:"currentColor","aria-hidden":!0,children:e.jsx("circle",{cx:a/2,cy:a/2,r:n+1})});if(t==="milestone"){const c=a/2;return e.jsxs("svg",{width:a,height:a,viewBox:`0 0 ${a} ${a}`,fill:"currentColor","aria-hidden":!0,children:[e.jsx("circle",{cx:c,cy:n+o,r:n}),e.jsx("circle",{cx:c,cy:a/2,r:n}),e.jsx("circle",{cx:c,cy:a-n-o,r:n})]})}const l=n+o+1;return e.jsxs("svg",{width:a,height:a,viewBox:`0 0 ${a} ${a}`,fill:"currentColor","aria-hidden":!0,children:[e.jsx("circle",{cx:l,cy:l,r:n}),e.jsx("circle",{cx:a-l,cy:l,r:n}),e.jsx("circle",{cx:l,cy:a-l,r:n}),e.jsx("circle",{cx:a-l,cy:a-l,r:n})]})}function Qs({label:t="Queue",defaultPlacement:s="bottom",size:a="sm",align:n="right",menuDirection:o="up",disabled:l=!1,busy:c=!1,className:h="",menuClassName:f="",title:j,stopPropagation:p=!1,onSelectPlacement:E}){const[L,g]=r.useState(!1),d=r.useRef(null),v=r.useRef(`queue-placement-${Math.random().toString(36).slice(2,10)}`),y=l||c,S=a==="md"?"h-8 text-caption":"h-7 text-micro",M=a==="md"?"px-3":"px-2.5",R=a==="md"?"h-8 w-8":"h-7 w-7",m=n==="left"?"left-0":"right-0",b=o==="up"?"bottom-[calc(100%+6px)]":"top-[calc(100%+6px)]";r.useEffect(()=>{if(!L)return;const $=te=>{var X;const re=te.target;re&&((X=d.current)!=null&&X.contains(re)||g(!1))},F=te=>{te.key==="Escape"&&g(!1)};return document.addEventListener("mousedown",$),document.addEventListener("touchstart",$),document.addEventListener("keydown",F),()=>{document.removeEventListener("mousedown",$),document.removeEventListener("touchstart",$),document.removeEventListener("keydown",F)}},[L]);const k=($,F,te)=>{p&&$.stopPropagation(),g(!1),E(F,te)};return e.jsxs("div",{ref:d,className:`relative inline-flex items-center ${h}`,children:[e.jsxs("button",{type:"button",title:j??`Queue ${s==="top"?"to top":"to end"}`,onClick:$=>k($,s),disabled:y,className:`control-pill ${S} ${M} rounded-r-none border-r-0 font-semibold text-primary disabled:opacity-45`,children:[e.jsxs("svg",{width:a==="md"?13:12,height:a==="md"?13:12,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"opacity-90","aria-hidden":!0,children:[e.jsx("path",{d:"M4 6h16"}),e.jsx("path",{d:"M4 12h11"}),e.jsx("path",{d:"M4 18h9"}),e.jsx("path",{d:"m17 15 3 3 3-3"}),e.jsx("path",{d:"M20 8v10"})]}),e.jsx("span",{children:c?"Queueing...":t})]}),e.jsx("button",{type:"button","aria-label":"Choose queue placement","aria-haspopup":"menu","aria-expanded":L,"aria-controls":v.current,onClick:$=>{p&&$.stopPropagation(),!y&&g(F=>!F)},disabled:y,className:`control-pill ${R} 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 ${L?"rotate-180":""}`,"aria-hidden":!0,children:e.jsx("path",{d:"m6 9 6 6 6-6"})})}),L&&e.jsxs("div",{id:v.current,role:"menu",className:`absolute ${m} ${b} z-[260] min-w-[196px] rounded-lg border border-strong bg-[#0B0F16]/95 p-1 shadow-[0_16px_32px_rgba(0,0,0,0.38)] backdrop-blur ${f}`,children:[ti.map($=>e.jsxs("button",{type:"button",role:"menuitem",onClick:F=>k(F,"top",$.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(si,{scope:$.scope,size:12}),e.jsx("span",{className:"text-caption font-medium text-primary",children:$.label}),e.jsx("span",{className:"ml-auto text-micro text-tertiary",children:$.description})]},$.scope)),e.jsx("div",{className:"my-1 border-t border-strong"}),e.jsx("button",{type:"button",role:"menuitem",onClick:$=>k($,"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:ei.bottom})})]})]})}function nr(t){if(!t)return{label:"—",tone:"none"};const s=new Date(t);if(Number.isNaN(s.getTime()))return{label:"—",tone:"none"};const a=new Date,n=s.getTime()-a.getTime(),o=Math.round(n/(1e3*60*60*24));if(o<-1)return{label:`${Math.abs(o)}d overdue`,tone:"overdue"};if(o===-1)return{label:"Yesterday",tone:"overdue"};if(o===0)return{label:"Today",tone:"soon"};if(o===1)return{label:"Tomorrow",tone:"soon"};if(o<=7)return{label:`In ${o} days`,tone:"soon"};const l=s.toLocaleString("en-US",{month:"short"}),c=s.getDate();return{label:`${l} ${c}`,tone:"normal"}}function rr(t){return t==="overdue"?"text-red-300/90":t==="soon"?"text-amber-200/85":""}function ni(t){if(!t)return"";const s=new Date(t);if(Number.isNaN(s.getTime()))return"";const a=s.getFullYear(),n=String(s.getMonth()+1).padStart(2,"0"),o=String(s.getDate()).padStart(2,"0"),l=String(s.getHours()).padStart(2,"0"),c=String(s.getMinutes()).padStart(2,"0");return`${a}-${n}-${o}T${l}:${c}`}const ar=["not_started","planned","todo","in_progress","active","blocked","done"];function ir(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 _s(t){const s=t.trim().toLowerCase();return s==="completed"?"done":s==="running"||s==="queued"?"active":s==="pending"||s==="backlog"?"todo":s}function ri(t,s){return s==="all"?!0:s==="blocked"?t==="blocked":s==="done"?t==="done":t!=="blocked"&&t!=="done"}function ai(t){const s=Number.isFinite(t)?Math.max(1,Math.min(100,Math.round(t))):50;return s<=12?{label:"Urgent",toneClass:"font-bold text-red-200/90"}:s<=30?{label:"High",toneClass:"font-semibold text-amber-100/80"}:s<=60?{label:"Medium",toneClass:"font-medium text-secondary"}:{label:"Low",toneClass:"font-normal text-muted"}}function ii(t,s){const a=new Map(s.map(l=>[l.id,l])),n=new Set,o=[t];for(;o.length>0;){const l=o.shift(),c=a.get(l);c&&(c.parentId&&!n.has(c.parentId)&&(n.add(c.parentId),o.push(c.parentId)),c.workstreamId&&!n.has(c.workstreamId)&&(n.add(c.workstreamId),o.push(c.workstreamId)),c.milestoneId&&!n.has(c.milestoneId)&&(n.add(c.milestoneId),o.push(c.milestoneId)))}return n}function oi(t,s,a,n){let o=0;if(a==="title")o=t.title.localeCompare(s.title);else if(a==="status")o=Jn(t.status)-Jn(s.status);else if(a==="priority")o=t.priorityNum-s.priorityNum;else if(a==="eta"){const l=t.etaEndAt?Date.parse(t.etaEndAt):1/0,c=s.etaEndAt?Date.parse(s.etaEndAt):1/0;o=l-c}return n==="desc"?-o:o}function fs(t,s){return!t||t.trim().length===0?s:Nt(t.trim())||s}function li({nodes:t,edges:s,selectedNodeId:a,highlightedNodeIds:n,editMode:o,onToggleEditMode:l,onSelectNode:c,onFocusWorkstream:h,onOpenNode:f,onUpdateNode:j,mutations:p}){const{authToken:E,embedMode:L}=Ht(),g=js({authToken:E,embedMode:L}),[d,v]=r.useState(""),[y,S]=r.useState(new Set),[M,R]=r.useState("all"),[m,b]=r.useState(!1),[k,$]=r.useState(null),[F,te]=r.useState("asc"),[re,X]=r.useState(new Set),[O,w]=r.useState(!1),[Q,A]=r.useState(null),H=r.useRef(null),K=r.useRef(null),de=r.useRef(null),q=r.useRef(null),P=r.useRef(null),B=r.useRef(null),[U,V]=r.useState(!1);r.useEffect(()=>{if(!Q)return;const i=Q.tone==="success"?6500:9e3,N=window.setTimeout(()=>A(null),i);return()=>window.clearTimeout(N)},[Q==null?void 0:Q.message,Q==null?void 0:Q.tone]),r.useEffect(()=>{if(!Q)return;const i=Q.tone==="success"?6500:9e3,N=window.setTimeout(()=>A(null),i);return()=>window.clearTimeout(N)},[Q==null?void 0:Q.message,Q==null?void 0:Q.tone]);const pe=r.useMemo(()=>new Map(t.map(i=>[i.id,i])),[t]),ae=r.useMemo(()=>t.map(i=>({id:i.id,title:i.title})),[t]),Se=r.useMemo(()=>{const i=new Map;for(const N of t){const D=_s(N.status);i.set(D,(i.get(D)??0)+1)}return i},[t]),Ue=r.useMemo(()=>{let i=0,N=0,D=0;for(const ee of t){const ie=_s(ee.status);ie==="blocked"?N+=1:ie==="done"?D+=1:i+=1}return{all:t.length,open:i,blocked:N,done:D}},[t]),Ke=r.useMemo(()=>{const i=d.trim().toLowerCase(),N=i.length>0,D=y.size>0;if(!N&&!D&&!(M!=="all"))return null;const ie=new Set;for(const Te of t){const xt=_s(Te.status),me=!N||Te.title.toLowerCase().includes(i)||Te.assignedAgents.some(jt=>jt.name.toLowerCase().includes(i)),Ge=!D||y.has(xt),Ee=ri(xt,M);me&&Ge&&Ee&&ie.add(Te.id)}const Ne=new Set(ie);for(const Te of ie)for(const xt of ii(Te,t))Ne.add(xt);return Ne},[y,t,d,M]),x=r.useMemo(()=>t.filter(i=>i.type==="workstream").sort((i,N)=>i.priorityNum-N.priorityNum||i.title.localeCompare(N.title)),[t]),Y=r.useMemo(()=>{const i=new Map;for(const N of t.filter(D=>D.type==="milestone")){const D=N.workstreamId??"unscoped",ee=i.get(D)??[];ee.push(N),i.set(D,ee)}for(const N of i.values())N.sort((D,ee)=>D.priorityNum-ee.priorityNum||D.title.localeCompare(ee.title));return i},[t]),Z=r.useMemo(()=>{const i=new Map;for(const N of t.filter(D=>D.type==="task"&&D.milestoneId)){const D=N.milestoneId??"unscoped",ee=i.get(D)??[];ee.push(N),i.set(D,ee)}for(const N of i.values())N.sort((D,ee)=>D.priorityNum-ee.priorityNum||D.title.localeCompare(ee.title));return i},[t]),ge=r.useMemo(()=>{const i=new Map;for(const N of t.filter(D=>D.type==="task"&&!D.milestoneId)){const D=N.workstreamId??"unscoped",ee=i.get(D)??[];ee.push(N),i.set(D,ee)}for(const N of i.values())N.sort((D,ee)=>D.priorityNum-ee.priorityNum||D.title.localeCompare(ee.title));return i},[t]),De=r.useMemo(()=>{const i=new Set;for(const N of x)i.add(N.id);for(const N of t.filter(D=>D.type==="milestone"))i.add(N.id);return i},[t,x]),[We,Be]=r.useState(De);r.useEffect(()=>{Be(De)},[De]);const T=i=>k?[...i].sort((N,D)=>oi(N,D,k,F)):i,G=r.useMemo(()=>{const i=[],N=ie=>Ke===null||Ke.has(ie);for(const ie of T(x)){if(!N(ie.id))continue;const Ne=T(Y.get(ie.id)??[]),Te=T(ge.get(ie.id)??[]),xt=Ne.length>0||Te.length>0;if(i.push({node:ie,depth:0,canCollapse:xt}),!!We.has(ie.id)){for(const me of Ne){if(!N(me.id))continue;const Ge=T(Z.get(me.id)??[]);if(i.push({node:me,depth:1,canCollapse:Ge.length>0}),We.has(me.id))for(const Ee of Ge)N(Ee.id)&&i.push({node:Ee,depth:2,canCollapse:!1})}for(const me of Te)N(me.id)&&i.push({node:me,depth:1,canCollapse:!1})}}const D=T(Y.get("unscoped")??[]),ee=T(ge.get("unscoped")??[]);for(const ie of D)if(N(ie.id)&&(i.push({node:ie,depth:0,canCollapse:(Z.get(ie.id)??[]).length>0}),We.has(ie.id)))for(const Ne of T(Z.get(ie.id)??[]))N(Ne.id)&&i.push({node:Ne,depth:1,canCollapse:!1});for(const ie of ee)N(ie.id)&&i.push({node:ie,depth:0,canCollapse:!1});return i},[ge,We,Ke,Y,k,F,Z,x]),oe=r.useMemo(()=>G.map(({node:i})=>i.id),[G]),{handleSelect:Ce}=Lr(oe),Ie=r.useMemo(()=>new Set(oe),[oe]),Fe=r.useMemo(()=>G.filter(({node:i})=>re.has(i.id)),[G,re]),Oe=(M!=="all"?1:0)+y.size,St=d.trim().length>0||M!=="all"||y.size>0,Me=Fe.length,xe=G.length>0&&Me===G.length,ye=(p==null?void 0:p.bulkEntityMutation.isPending)??!1;r.useEffect(()=>{X(i=>{if(i.size===0)return i;const N=new Set(Array.from(i).filter(D=>Ie.has(D)));return N.size===i.size?i:N})},[Ie]),r.useEffect(()=>{H.current&&(H.current.indeterminate=Me>0&&!xe)},[xe,Me]),r.useEffect(()=>{Me===0&&O&&w(!1)},[O,Me]),r.useEffect(()=>{if(!m)return;const i=D=>{var ie;const ee=D.target;ee&&((ie=K.current)!=null&&ie.contains(ee)||b(!1))},N=D=>{D.key==="Escape"&&b(!1)};return document.addEventListener("mousedown",i),document.addEventListener("touchstart",i),document.addEventListener("keydown",N),()=>{document.removeEventListener("mousedown",i),document.removeEventListener("touchstart",i),document.removeEventListener("keydown",N)}},[m]);const ot=i=>i.dependencyIds.length,ht=g.isPinning||g.isMoving,Vt=async i=>{await g.pin({initiativeId:i.initiativeId,workstreamId:i.workstreamId,taskId:i.taskId??null,milestoneId:i.milestoneId??null}),await g.move({initiativeId:i.initiativeId,workstreamId:i.workstreamId,placement:i.placement})},Ye=async(i,N="bottom")=>{if(i.type==="initiative"){const Te=x.filter(jt=>jt.initiativeId===i.id);if(Te.length===0){A({tone:"error",message:"Cannot queue initiative: no workstreams found."});return}const xt=N==="top"?[...Te].reverse():Te;let me=0,Ge=0,Ee=null;for(const jt of xt)try{await Vt({initiativeId:i.id,workstreamId:jt.id,placement:N}),me+=1}catch(Ze){Ge+=1,Ee||(Ee=fs(Ze instanceof Error?Ze.message:"","Failed to add initiative workstream to queue."))}Ge>0?A({tone:me>0?"success":"error",message:me>0?`Queued ${me}/${Te.length} workstreams (${Ge} failed). ${Ee??""}`.trim():Ee??"Failed to queue initiative workstreams."}):A({tone:"success",message:`Queued ${me} workstream${me===1?"":"s"} to ${N==="top"?"top":"end"}.`}),window.setTimeout(()=>A(null),Ge>0?4200:2400);return}const D=i.initiativeId??"",ee=i.type==="workstream"?i.id:i.workstreamId??"",ie=i.type==="task"?i.id:null,Ne=i.type==="milestone"?i.id:null;if(!D||!ee){A({tone:"error",message:"Cannot add to queue: missing initiative/workstream id."});return}try{await Vt({initiativeId:D,workstreamId:ee,taskId:ie,milestoneId:Ne,placement:N}),A({tone:"success",message:i.type==="task"?`Queued task workstream to ${N==="top"?"top":"end"}.`:i.type==="milestone"?`Queued milestone workstream to ${N==="top"?"top":"end"}.`:`Queued workstream to ${N==="top"?"top":"end"}.`}),window.setTimeout(()=>A(null),2e3)}catch(Te){A({tone:"error",message:fs(Te instanceof Error?Te.message:"","Failed to add workstream to queue.")}),window.setTimeout(()=>A(null),2400)}},tt=i=>{if(i.type==="workstream")return i.id;if(i.type==="milestone"||i.type==="task")return i.workstreamId??null;if(i.type==="initiative"){const N=x.filter(ee=>ee.initiativeId===i.id);if(N.length===0)return null;const D=N.find(ee=>!Je(ee.status))??N[0];return(D==null?void 0:D.id)??null}return null},Rt=async(i,N)=>{const D=i.type==="initiative"?i.id:i.initiativeId??"",ee=N??(i.type==="workstream"?i.id:i.workstreamId??"");if(!D||!ee){A({tone:"error",message:"Cannot start now: missing initiative/workstream id."});return}try{const ie=await fetch("/orgx/api/mission-control/next-up/play",{method:"POST",headers:yt({authToken:E,embedMode:L,contentTypeJson:!0}),body:JSON.stringify({initiativeId:D,workstreamId:ee,fastAck:!0,ignoreSpawnGuardRateLimit:!0})}),Ne=await ie.json().catch(()=>null);if(!ie.ok)throw new Error((Ne==null?void 0:Ne.error)??(Ne==null?void 0:Ne.message)??`Failed to start workstream (${ie.status})`);A({tone:"success",message:`Started ${i.title}.`}),window.setTimeout(()=>A(null),1800)}catch(ie){A({tone:"error",message:fs(ie instanceof Error?ie.message:"","Failed to start workstream now.")}),window.setTimeout(()=>A(null),2400)}},Bt=r.useMemo(()=>{const i=new Map,N=(D,ee)=>{if(D.length>0){const ie=D.filter(Ne=>Je(Ne.status)).length;return ts(ie,D.length)}return Je(ee)?100:0};for(const D of t.filter(ee=>ee.type==="milestone")){const ee=Z.get(D.id)??[];i.set(D.id,N(ee,D.status))}for(const D of x){const ie=(Y.get(D.id)??[]).flatMap(Te=>Z.get(Te.id)??[]),Ne=ge.get(D.id)??[];i.set(D.id,N([...Ne,...ie],D.status))}return i},[ge,Y,t,Z,x]),Xe=r.useMemo(()=>{if(G.length===0)return null;const i=G.filter(({node:ee})=>ee.assignedAgents.length>0);if(i.length===0)return null;const N=i[0].node.assignedAgents.map(ee=>ee.id).sort().join(",");return!i.every(({node:ee})=>ee.assignedAgents.map(ie=>ie.id).sort().join(",")===N)||i.length<G.length*.7?null:i[0].node.assignedAgents},[G]),ft=Xe!==null&&!o,mt=i=>{k===i?te(N=>N==="asc"?"desc":"asc"):($(i),te("asc"))},pt=i=>{S(N=>{const D=new Set(N);return D.has(i)?D.delete(i):D.add(i),D})},Qe=()=>{v(""),R("all"),S(new Set)},st=(i,N,D)=>{A(null),w(!1),Ce(i,N,D,X)},wt=()=>{A(null),w(!1),X(()=>G.length===0||xe?new Set:new Set(oe))},vt=()=>{w(!1),X(new Set)},He=async i=>{if(!(!p||Fe.length===0)){w(!1),A(null);try{const N=await p.bulkEntityMutation.mutateAsync({items:Fe.map(({node:D})=>({type:D.type,id:D.id})),mode:"update",updates:{status:i}});N.failed>0?A({tone:"error",message:`Updated ${N.updated}, failed ${N.failed}.`}):A({tone:"success",message:`Updated ${N.updated} item${N.updated===1?"":"s"} to ${ze(i)}.`})}catch(N){A({tone:"error",message:fs(N instanceof Error?N.message:"","Bulk status update failed.")})}}},ns=async()=>{if(!(!p||Fe.length===0)){A(null);try{const i=await p.bulkEntityMutation.mutateAsync({items:Fe.map(({node:N})=>({type:N.type,id:N.id})),mode:"delete"});i.failed>0?A({tone:"error",message:`Deleted ${i.updated}, failed ${i.failed}.`}):(A({tone:"success",message:`Deleted ${i.updated} item${i.updated===1?"":"s"}.`}),X(new Set),w(!1))}catch(i){A({tone:"error",message:fs(i instanceof Error?i.message:"","Bulk delete failed.")})}}},lt=({field:i})=>k!==i?e.jsx("span",{className:"text-faint ml-0.5",children:"↕"}):e.jsx("span",{className:"text-lime ml-0.5",children:F==="asc"?"↑":"↓"}),Lt=U?"0px":"calc(var(--mc-toolbar-offset, 0px) + 12px)",Kt=i=>{if(B.current==="body"){B.current=null;return}const N=i.currentTarget.scrollLeft,D=q.current;!D||D.scrollLeft===N||(B.current="header",D.scrollLeft=N)},Et=i=>{if(B.current==="header"){B.current=null;return}const N=i.currentTarget.scrollLeft,D=de.current;!D||D.scrollLeft===N||(B.current="body",D.scrollLeft=N)};r.useEffect(()=>{const i=q.current,N=de.current;!i||!N||N.scrollLeft!==i.scrollLeft&&(N.scrollLeft=i.scrollLeft)},[G.length]),r.useEffect(()=>{if(typeof window>"u")return;const i=P.current;if(!i)return;const N=()=>{const ee=Math.min(window.innerHeight*.62,560),ie=i.scrollHeight;V(ie>ee+1)};N();const D=typeof ResizeObserver<"u"?new ResizeObserver(()=>N()):null;return D==null||D.observe(i),window.addEventListener("resize",N),()=>{D==null||D.disconnect(),window.removeEventListener("resize",N)}},[G.length]);const Ot=()=>o?e.jsxs("colgroup",{children:[e.jsx("col",{style:{width:40}}),e.jsx("col",{style:{width:360}}),e.jsx("col",{style:{width:188}}),e.jsx("col",{style:{width:124}}),e.jsx("col",{style:{width:120}}),e.jsx("col",{style:{width:96}}),e.jsx("col",{style:{width:156}}),e.jsx("col",{style:{width:100}}),e.jsx("col",{style:{width:100}}),e.jsx("col",{style:{width:180}})]}):e.jsxs("colgroup",{children:[e.jsx("col",{style:{width:40}}),e.jsx("col",{})," ",!ft&&e.jsx("col",{style:{width:72}}),e.jsx("col",{style:{width:160}})," ",e.jsx("col",{style:{width:80}})," ",e.jsx("col",{style:{width:120}})," "]});return e.jsxs("section",{className:"space-y-2.5",children:[e.jsxs("div",{className:"mb-3.5 flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between",children:[e.jsx("div",{className:"w-full xl:max-w-[380px]",children:e.jsx(In,{value:d,onChange:v,placeholder:"Search items or agents..."})}),e.jsxs("div",{className:"flex min-h-[40px] min-w-0 flex-wrap items-center gap-2.5",children:[l&&e.jsxs("button",{type:"button",onClick:l,"data-state":o?"active":"idle",className:`control-pill inline-flex h-8 items-center gap-1.5 px-3.5 text-caption font-semibold ${o?"text-lime":"text-secondary hover:text-bright"}`,children:[e.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e.jsx("path",{d:"M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"})}),o?"Editing":"Edit"]}),e.jsxs("div",{ref:K,className:"relative",children:[e.jsxs("button",{type:"button",onClick:()=>b(i=>!i),"data-state":m||Oe>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"}),Oe>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:Oe})]}),e.jsx(at,{children:m&&e.jsxs(le.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:Ue.all},{id:"open",label:"Open",count:Ue.open},{id:"blocked",label:"Blocked",count:Ue.blocked},{id:"done",label:"Done",count:Ue.done}].map(i=>{const N=M===i.id;return e.jsxs("button",{type:"button",onClick:()=>R(i.id),className:`inline-flex h-7 items-center gap-1.5 rounded-full border px-2.5 text-micro font-semibold transition-colors ${N?"border-lime/30 bg-lime/10 text-lime":"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:ar.map(i=>{const N=y.has(i),D=Se.get(i)??0;return e.jsxs("button",{type:"button",onClick:()=>pt(i),className:`inline-flex h-7 items-center gap-1 rounded-full border px-2.5 text-micro transition-colors ${N?"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:ze(i)}),e.jsx("span",{className:"text-micro text-current/75",children:D})]},i)})})]}),(M!=="all"||y.size>0)&&e.jsx("button",{type:"button",onClick:()=>{R("all"),S(new Set)},className:"text-micro text-secondary transition-colors hover:text-primary",children:"Reset filters"})]})})]}),e.jsx(at,{initial:!1,children:St&&e.jsx(le.button,{type:"button",onClick:Qe,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:wt,"data-state":xe?"active":"idle",className:"control-pill inline-flex h-8 items-center gap-1.5 px-3.5 text-caption font-semibold",children:xe?"Clear all":"Select all"})]})]}),e.jsx("div",{className:"mb-1.5",children:e.jsx("div",{className:`rounded-xl border px-3 ${Me>0?"border-lime/24 bg-lime/[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:H,type:"checkbox",checked:xe,onChange:wt,className:"h-3.5 w-3.5 rounded border-white/20 bg-black/40 text-lime focus:ring-lime/35"}),"Select all"]}),e.jsx("span",{className:"flex-shrink-0 text-caption text-white/58",children:Me>0?`${Me} selected`:`${G.length} visible`}),Me>0&&e.jsxs("div",{className:"flex flex-shrink-0 items-center gap-2 whitespace-nowrap",children:[e.jsx("button",{type:"button",onClick:()=>{He("planned")},disabled:ye,className:"control-pill h-8 flex-shrink-0 px-3 text-caption font-semibold disabled:opacity-45",children:"Plan"}),e.jsx("button",{type:"button",onClick:()=>{He("in_progress")},disabled:ye,className:"control-pill h-8 flex-shrink-0 px-3 text-caption font-semibold disabled:opacity-45","data-state":"active",children:"Start"}),e.jsx("button",{type:"button",onClick:()=>{He("blocked")},disabled:ye,className:"control-pill h-8 flex-shrink-0 px-3 text-caption font-semibold disabled:opacity-45",children:"Block"}),e.jsx("button",{type:"button",onClick:()=>{He("done")},disabled:ye,className:"control-pill h-8 flex-shrink-0 px-3 text-caption font-semibold disabled:opacity-45",children:"Complete"}),O?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:()=>{ns()},disabled:ye,className:"control-pill h-8 flex-shrink-0 border-red-400/35 bg-red-500/14 px-3 text-caption font-semibold text-red-100 disabled:opacity-45",children:"Delete"}),e.jsx("button",{type:"button",onClick:()=>w(!1),disabled:ye,className:"control-pill h-8 flex-shrink-0 px-2.5 text-caption disabled:opacity-45",children:"Keep"})]}):e.jsx("button",{type:"button",onClick:()=>w(!0),disabled:ye,className:"control-pill h-8 flex-shrink-0 border-red-400/24 bg-red-500/[0.08] px-3 text-caption font-semibold text-red-100/85 disabled:opacity-45",children:"Delete"}),e.jsx("button",{type:"button",onClick:vt,disabled:ye,className:"text-caption text-secondary transition-colors hover:text-primary disabled:opacity-45",children:"Clear"})]})]})})}),Q&&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 ${Q.tone==="success"?"bg-emerald-300/90":"bg-amber-300/90"}`}),e.jsx("span",{className:"min-w-0 leading-snug",children:Q.message})]}),e.jsx("button",{type:"button",onClick:()=>A(null),className:"inline-flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-md text-secondary transition-colors hover:bg-white/[0.06] hover:text-primary","aria-label":"Dismiss notice",title:"Dismiss",children:e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("path",{d:"M18 6 6 18"}),e.jsx("path",{d:"m6 6 12 12"})]})})]})}),o&&e.jsx("div",{className:"mb-2 text-micro text-secondary",children:"Edit mode: select a row to edit its fields inline."}),Xe&&!o&&e.jsxs("div",{className:"mb-2 flex items-center gap-2 rounded-lg border border-white/[0.06] bg-white/[0.02] px-3 py-1.5",children:[e.jsx("div",{className:"flex items-center -space-x-1.5",children:Xe.slice(0,2).map(i=>e.jsx("div",{className:"rounded-full ring-1 ring-[#02040A]",children:e.jsx(bn,{name:i.name,hint:i.id,size:"xs"})},i.id))}),e.jsxs("span",{className:"text-caption text-secondary",children:["Assigned to ",Xe.map(i=>i.name).join(", ")]})]}),e.jsx("div",{className:"relative min-w-0 max-w-full overflow-visible rounded-xl border border-white/[0.07] bg-black/[0.14] p-2",children:e.jsxs("div",{ref:P,"data-hierarchy-table-viewport":!0,className:`${U?"max-h-[min(62vh,560px)] overflow-y-auto":"overflow-visible"} overflow-x-hidden rounded-lg`,children:[e.jsx("div",{"data-hierarchy-table-header":!0,className:"sticky z-30 rounded-t-lg border-b border-subtle bg-[#090B11]/92 backdrop-blur-xl",style:{top:Lt},children:e.jsx("div",{ref:de,onScroll:Kt,className:"overflow-x-auto overflow-y-hidden [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",children:e.jsxs("table",{className:`w-full table-fixed border-separate border-spacing-y-0 ${o?"min-w-[1464px]":""}`,children:[Ot(),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:()=>mt("title"),children:["Item ",e.jsx(lt,{field:"title"})]}),o?e.jsxs(e.Fragment,{children:[e.jsx("th",{className:"px-2 py-1.5",children:"Assigned"}),e.jsxs("th",{className:"px-2 py-1.5 cursor-pointer select-none",onClick:()=>mt("status"),children:["Status ",e.jsx(lt,{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:()=>mt("priority"),children:["Priority ",e.jsx(lt,{field:"priority"})]}),e.jsxs("th",{className:"px-2 py-1.5 cursor-pointer select-none",onClick:()=>mt("eta"),children:["ETA ",e.jsx(lt,{field:"eta"})]}),e.jsx("th",{className:"px-2 py-1.5",children:"Duration (h)"}),e.jsx("th",{className:"px-2 py-1.5",children:"Budget ($)"}),e.jsx("th",{className:"px-2 py-1.5",children:"Dependencies"})]}):e.jsxs(e.Fragment,{children:[!ft&&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:()=>mt("status"),children:["Status ",e.jsx(lt,{field:"status"})]}),e.jsxs("th",{className:"px-2 py-1.5 cursor-pointer select-none",onClick:()=>mt("priority"),children:["Priority ",e.jsx(lt,{field:"priority"})]}),e.jsxs("th",{className:"px-2 py-1.5 cursor-pointer select-none",onClick:()=>mt("eta"),children:["ETA ",e.jsx(lt,{field:"eta"})]})]})]})})]})})}),e.jsx("div",{ref:q,onScroll:Et,className:"overflow-x-auto",children:e.jsxs("table",{className:`w-full table-fixed border-separate border-spacing-y-1.5 ${o?"min-w-[1464px]":""}`,children:[Ot(),e.jsx("tbody",{children:G.map(({node:i,depth:N,canCollapse:D})=>{const ee=a===i.id,ie=n.has(i.id),Ne=re.has(i.id),Te=i.assignedAgents.map(J=>J.name).join(", "),xt=i.dependencyIds.map(J=>{var je;return((je=pe.get(J))==null?void 0:je.title)??J}).slice(0,3).join(", "),me=Bt.get(i.id),Ge=ai(i.priorityNum),Ee=o&&ee,jt=i.type==="initiative"||i.type==="workstream"||i.type==="milestone"||i.type==="task",Ze=tt(i),qt=!!Ze;return e.jsxs("tr",{onClick:()=>{c(i.id),i.type==="workstream"&&h(i.id)},className:`group/row cursor-pointer rounded-lg border transition-colors ${ee?"border-lime/[0.22] bg-lime/[0.08]":ie?"border-[#14B8A6]/[0.2] bg-[#14B8A6]/[0.08]":"border-subtle bg-white/[0.02] hover:border-strong hover:bg-white/[0.05]"}`,children:[e.jsx("td",{className:"rounded-l-lg px-2 py-1.5",children:e.jsx("input",{type:"checkbox",checked:Ne,onChange:J=>{J.stopPropagation();const je=J.nativeEvent.shiftKey??!1;st(i.id,J.currentTarget.checked,je)},onClick:J=>J.stopPropagation(),"aria-label":`Select ${i.type}: ${i.title}`,className:"h-3.5 w-3.5 rounded border-white/20 bg-black/40 text-lime focus:ring-lime/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:N*14}}),D?e.jsx("button",{type:"button",onClick:J=>{J.stopPropagation(),Be(je=>{const ct=new Set(je);return ct.has(i.id)?ct.delete(i.id):ct.add(i.id),ct})},"aria-label":`${We.has(i.id)?"Collapse":"Expand"} ${i.type}: ${i.title}`,className:"rounded text-secondary focus:outline-none focus-visible:ring-2 focus-visible:ring-lime/35 focus-visible:ring-offset-2 focus-visible:ring-offset-[#02040A]",children:We.has(i.id)?"▾":"▸"}):e.jsx("span",{className:"w-2.5"}),e.jsx(wn,{type:i.type}),e.jsx("button",{type:"button",onClick:J=>{J.stopPropagation(),f(i)},"aria-label":`Open ${i.type} details: ${i.title}`,className:"min-w-0 max-w-[560px] flex-1 truncate rounded text-left text-body text-bright hover:text-white focus:outline-none focus-visible:ring-2 focus-visible:ring-lime/35 focus-visible:ring-offset-2 focus-visible:ring-offset-[#02040A]",children:i.title})]}),!o&&!Je(i.status)&&e.jsxs("div",{className:"ml-1 grid w-[168px] min-w-[168px] grid-cols-[124px_34px] items-center justify-end gap-2 opacity-0 translate-x-1 transition-all duration-150 group-hover/row:opacity-100 group-hover/row:translate-x-0 group-focus-within/row:opacity-100 group-focus-within/row:translate-x-0 touch-device:opacity-60 touch-device:translate-x-0",children:[jt?e.jsx(Qs,{label:"Queue",size:"sm",busy:ht,stopPropagation:!0,title:`Queue ${i.type}: ${i.title}`,onSelectPlacement:J=>Ye(i,J)}):e.jsx("span",{className:"h-7 w-[124px]"}),e.jsx("button",{type:"button",disabled:!qt,title:qt?"Start":"No runnable workstream",onClick:J=>{J.stopPropagation(),Ze&&Rt(i,Ze)},"aria-label":qt?`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-lime 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"})})})]})]})}),!ft&&e.jsx("td",{className:"px-2 py-1.5 text-caption text-primary whitespace-nowrap",children:Ee?e.jsx("input",{type:"text",defaultValue:Te,placeholder:"Agent A, Agent B",onClick:J=>J.stopPropagation(),onBlur:J=>{const je=J.currentTarget.value.split(",").map(ct=>ct.trim()).filter(Boolean);j(i,{assigned_agent_names:je,assigned_agent_ids:je.map(ct=>`name:${ct}`),assignment_source:"manual"})},className:"w-[190px] rounded border border-strong bg-white/[0.06] px-2 py-1 text-micro text-white/82"}):e.jsx("div",{className:"flex items-center gap-2",children:i.assignedAgents.length>0?e.jsx("div",{className:"flex items-center -space-x-1.5",title:Te,children:i.assignedAgents.slice(0,3).map(J=>e.jsx("div",{title:J.name,className:"rounded-full ring-1 ring-[#02040A]",children:e.jsx(bn,{name:J.name,hint:`${J.id} ${i.title}`,size:"xs"})},`${i.id}:${J.id}`))}):e.jsx("span",{className:"text-muted",children:"—"})})}),o?e.jsxs(e.Fragment,{children:[e.jsx("td",{className:"px-2 py-1.5 text-caption text-primary",children:Ee?e.jsx("select",{defaultValue:_s(i.status),onClick:J=>J.stopPropagation(),onChange:J=>{j(i,{status:J.target.value})},className:"rounded border border-strong bg-white/[0.06] px-2 py-1 text-micro text-white/82",children:ar.map(J=>e.jsx("option",{value:J,children:ze(J)},J))}):e.jsx("span",{className:"status-pill whitespace-nowrap","data-tone":ir(i.status),children:ze(i.status)})}),e.jsx("td",{className:"px-2 py-1.5 text-caption text-primary",children:me!==void 0&&(i.type==="workstream"||i.type==="milestone")?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-1 w-[72px] rounded-full bg-white/[0.06] overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${me}%`,backgroundColor:i.type==="milestone"?z.teal:z.lime}})}),e.jsxs("span",{className:"text-micro text-secondary",style:{fontVariantNumeric:"tabular-nums"},children:[me,"%"]})]}):e.jsx("span",{className:"text-muted",children:"—"})}),e.jsx("td",{className:"px-2 py-1.5 text-caption text-primary",children:Ee?e.jsx("input",{type:"number",min:1,max:100,defaultValue:i.priorityNum,onClick:J=>J.stopPropagation(),onBlur:J=>{const je=Number(J.currentTarget.value);Number.isFinite(je)&&j(i,{priority_num:je})},className:"w-[72px] rounded border border-strong bg-white/[0.06] px-2 py-1 text-micro text-white/82"}):e.jsx("span",{className:`text-micro tracking-[0.02em] ${Ge.toneClass}`,children:Ge.label})}),e.jsx("td",{className:"px-2 py-1.5 text-caption text-primary",children:Ee?e.jsx("input",{type:"datetime-local",defaultValue:ni(i.etaEndAt),onClick:J=>J.stopPropagation(),onBlur:J=>{const je=J.currentTarget.value;j(i,{eta_end_at:je?new Date(je).toISOString():null})},className:"w-[176px] rounded border border-strong bg-white/[0.06] px-2 py-1 text-micro text-white/82"}):(()=>{const J=nr(i.etaEndAt);return e.jsx("span",{className:rr(J.tone),title:i.etaEndAt?new Date(i.etaEndAt).toLocaleString():void 0,children:J.label})})()}),e.jsx("td",{className:"px-2 py-1.5 text-caption text-primary",children:Ee&&i.type!=="task"?e.jsx("input",{type:"number",min:0,step:.5,defaultValue:i.expectedDurationHours,onClick:J=>J.stopPropagation(),onBlur:J=>{const je=Number(J.currentTarget.value);Number.isFinite(je)&&j(i,{expected_duration_hours:je})},className:"w-[82px] rounded border border-strong bg-white/[0.06] px-2 py-1 text-micro text-white/82"}):e.jsx("span",{children:i.expectedDurationHours})}),e.jsx("td",{className:"px-2 py-1.5 text-caption text-primary",children:Ee&&i.type!=="task"?e.jsx("input",{type:"number",min:0,step:1,defaultValue:i.expectedBudgetUsd,onClick:J=>J.stopPropagation(),onBlur:J=>{const je=Number(J.currentTarget.value);Number.isFinite(je)&&j(i,{expected_budget_usd:je})},className:"w-[92px] rounded border border-strong bg-white/[0.06] px-2 py-1 text-micro text-white/82"}):e.jsxs("span",{children:["$",i.expectedBudgetUsd.toLocaleString()]})}),e.jsx("td",{className:"rounded-r-lg px-2 py-1.5 text-caption text-primary",children:Ee?e.jsx("div",{onClick:J=>J.stopPropagation(),children:e.jsx(Za,{dependencies:i.dependencyIds,allNodes:ae,onSave:J=>void j(i,{depends_on:J})})}):e.jsx("div",{className:"max-w-[250px] truncate",children:ot(i)>0?`${ot(i)} · ${xt}`:"—"})})]}):e.jsxs(e.Fragment,{children:[e.jsx("td",{className:"px-2 py-1.5 text-caption text-primary",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"status-pill whitespace-nowrap","data-tone":ir(i.status),children:ze(i.status)}),me!==void 0&&(i.type==="workstream"||i.type==="milestone")&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:"h-1 w-[40px] rounded-full bg-white/[0.06] overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${me}%`,backgroundColor:i.type==="milestone"?z.teal:z.lime}})}),e.jsxs("span",{className:"text-micro text-secondary",style:{fontVariantNumeric:"tabular-nums"},children:[me,"%"]})]})]})}),e.jsx("td",{className:"px-2 py-1.5 text-caption text-primary",children:e.jsx("span",{className:`text-micro tracking-[0.02em] ${Ge.toneClass}`,children:Ge.label})}),e.jsx("td",{className:"rounded-r-lg px-2 py-1.5 text-caption text-primary",children:(()=>{const J=nr(i.etaEndAt);return e.jsx("span",{className:rr(J.tone),title:i.etaEndAt?new Date(i.etaEndAt).toLocaleString():void 0,children:J.label})})()})]})]},i.id)})})]})})]})}),G.length===0&&e.jsxs("div",{className:"flex flex-col items-center py-10",children:[e.jsxs("svg",{width:"32",height:"32",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",className:"text-faint",children:[e.jsx("path",{d:"M9 5H7a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2h-2"}),e.jsx("rect",{x:"9",y:"3",width:"6",height:"4",rx:"1"}),e.jsx("path",{d:"M9 14h6M9 18h4"})]}),e.jsx("div",{className:"mt-3 text-body font-medium text-secondary",children:d||y.size>0||M!=="all"?"No items match the current filters":"No work items yet"}),e.jsx("div",{className:"mt-1 text-caption text-muted",children:d||y.size>0||M!=="all"?"Try adjusting your search or filter criteria.":"Workstreams, milestones, and tasks will appear here."})]})]})}function ci(t){if(!t)return{label:"—",tone:"none"};const s=new Date(t);if(Number.isNaN(s.getTime()))return{label:"—",tone:"none"};const a=new Date,n=s.getTime()-a.getTime(),o=Math.round(n/(1e3*60*60*24));if(o<-1)return{label:`${Math.abs(o)}d overdue`,tone:"overdue"};if(o===-1)return{label:"Yesterday",tone:"overdue"};if(o===0)return{label:"Today",tone:"soon"};if(o===1)return{label:"Tomorrow",tone:"soon"};if(o<=7)return{label:`In ${o} days`,tone:"soon"};const l=s.toLocaleString("en-US",{month:"short"}),c=s.getDate();return{label:`${l} ${c}`,tone:"normal"}}function or(t){if(!t)return{label:"No target date",tone:"none"};const s=ci(t);return s.tone==="none"?{label:"No target date",tone:"none"}:s}function Ps(t){if(!t)return!1;const s=new Date(t);return Number.isNaN(s.getTime())?!1:s.getTime()<Date.now()}function lr(t){return t==="milestone"?"Milestone":t==="workstream"?"Workstream":"Task"}const di=5;function ui({recentTodoIds:t,nodesById:s,selectedNodeId:a,onSelectNode:n}){const[o,l]=r.useState(!1),c=t.map(g=>s.get(g)).filter(g=>!!g).sort((g,d)=>{const v=Ps(g.dueDate),y=Ps(d.dueDate);if(v!==y)return v?-1:1;if(g.priorityNum!==d.priorityNum)return g.priorityNum-d.priorityNum;const S=g.dueDate?Date.parse(g.dueDate):Number.POSITIVE_INFINITY,M=d.dueDate?Date.parse(d.dueDate):Number.POSITIVE_INFINITY;return S-M}).slice(0,14);if(c.length===0)return null;const h=c[0],f=or(h.dueDate),j=Ps(h.dueDate),p=c.slice(1),E=o?p:p.slice(0,di-1),L=p.length-E.length;return e.jsxs("section",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:"Queue overview"}),e.jsxs("span",{className:"rounded-full border border-white/15 bg-black/20 px-2 py-0.5 text-micro text-secondary",children:[c.length," in queue"]})]}),e.jsx("button",{type:"button",onClick:()=>n(h.id),className:`surface-hero group w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${j?"border-l-2 border-l-red-400/60 ":""}${a===h.id?"border-lime/35 bg-lime/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(wn,{type:h.type}),e.jsx("span",{children:lr(h.type)})]}),e.jsx("p",{className:"mt-1 line-clamp-2 text-body font-semibold leading-snug text-white",children:h.title}),e.jsx("p",{className:`mt-1 text-caption ${f.tone==="overdue"?"text-red-300/90":f.tone==="soon"?"text-amber-200/85":"text-secondary"}`,children:f.label})]}),h.priorityNum<=30&&e.jsx("span",{className:`inline-flex flex-shrink-0 text-micro tracking-[0.02em] ${h.priorityNum<=12?"font-bold text-red-200/90":"font-semibold text-amber-100/80"}`,children:h.priorityNum<=12?"Urgent":"High"})]})}),E.length>0&&e.jsxs("div",{className:"space-y-1.5",children:[E.map(g=>{const d=or(g.dueDate),v=Ps(g.dueDate);return e.jsxs("button",{type:"button",onClick:()=>n(g.id),className:`flex min-h-[54px] min-w-0 items-start justify-between gap-2 rounded-lg border px-2.5 py-2 text-left transition-colors ${v?"border-l-2 border-l-red-400/60 ":""}${a===g.id?"border-lime/30 bg-lime/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(wn,{type:g.type}),e.jsx("span",{children:lr(g.type)})]}),e.jsx("p",{className:"mt-1 line-clamp-1 break-words text-caption leading-snug text-bright",title:g.title,children:g.title}),e.jsx("p",{className:`mt-1 text-micro ${d.tone==="overdue"?"text-red-300/90":d.tone==="soon"?"text-amber-200/85":"text-secondary"}`,children:d.label})]}),g.priorityNum<=30&&e.jsx("span",{className:`inline-flex flex-shrink-0 text-micro tracking-[0.02em] ${g.priorityNum<=12?"font-bold text-red-200/90":"font-semibold text-amber-100/80"}`,children:g.priorityNum<=12?"Urgent":"High"})]},g.id)}),L>0&&!o&&e.jsxs("button",{type:"button",onClick:()=>l(!0),className:"w-full rounded-lg px-2.5 py-1.5 text-center text-micro text-secondary transition-colors hover:bg-white/[0.04] hover:text-primary",children:["View all (",p.length+1,")"]})]})]})}function mi(t,s){try{const a=localStorage.getItem(`orgx.section.${t}`);if(a==="0")return!1;if(a==="1")return!0}catch{}return s}function pi(t,s){try{localStorage.setItem(`orgx.section.${t}`,s?"1":"0")}catch{}}function pn({title:t,defaultOpen:s=!0,storageKey:a,sticky:n=!1,stickyOffsetClass:o="top-0",stickyTop:l,contentOverflowVisible:c=!1,badge:h,children:f}){const[j,p]=r.useState(()=>a?mi(a,s):s),[E,L]=r.useState(!1),g=r.useRef(null),[d,v]=r.useState(40),y=()=>{const S=!j;p(S),a&&pi(a,S)};return r.useEffect(()=>{if(!n)return;const S=g.current;if(!S)return;const M=()=>{const m=Math.max(34,S.offsetHeight);v(b=>b===m?b:m)};if(M(),typeof ResizeObserver>"u")return;const R=new ResizeObserver(()=>M());return R.observe(S),()=>R.disconnect()},[n,l,t]),e.jsxs("div",{style:n?{"--mc-collapsible-header-offset":`${d}px`}:void 0,children:[e.jsxs("button",{ref:n?g:void 0,type:"button","data-mc-section-header":t,onClick:y,className:`flex w-full items-center gap-2 rounded-lg border px-2 py-2 text-left transition-colors ${n?`sticky ${o} z-20 border-white/[0.08] bg-[#090B11]/92 shadow-[0_8px_18px_rgba(0,0,0,0.24)] backdrop-blur-xl`:"border-transparent hover:border-subtle hover:bg-white/[0.03]"}`,style:n&&l?{top:l}:void 0,children:[e.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",className:`text-muted transition-transform ${j?"rotate-180":""}`,style:{transitionDuration:"320ms",transitionTimingFunction:"cubic-bezier(0.22, 1, 0.36, 1)"},children:e.jsx("path",{d:"m6 9 6 6 6-6"})}),e.jsx("span",{className:"text-caption font-semibold tracking-[0.02em] text-white/68",children:t}),h&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-micro text-white/45",children:"·"}),e.jsx("span",{className:`text-micro ${h.tone==="error"?"text-red-200/80":h.tone==="warning"?"text-amber-200/80":"text-secondary"}`,children:h.label}),h.action&&e.jsx("span",{role:"button",tabIndex:0,onClick:S=>{S.stopPropagation(),h.action.onClick()},onKeyDown:S=>{(S.key==="Enter"||S.key===" ")&&(S.stopPropagation(),S.preventDefault(),h.action.onClick())},className:`text-micro font-semibold text-lime transition-colors hover:text-white active:scale-95 ${h.action.busy?"pointer-events-none opacity-45":"cursor-pointer"}`,children:h.action.busy?"Fixing…":h.action.label})]})]}),e.jsx(at,{initial:!1,children:j&&e.jsx(le.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{type:"spring",stiffness:400,damping:35},onAnimationStart:()=>L(!0),onAnimationComplete:()=>L(!1),className:c&&!E?"overflow-visible":"overflow-hidden",children:f})})]})}function xi(t){if(!t)return{priorityNum:60,priorityLabel:null};const s=t.trim().toLowerCase();if(s==="urgent"||s==="p0")return{priorityNum:10,priorityLabel:"urgent"};if(s==="high"||s==="p1")return{priorityNum:25,priorityLabel:"high"};if(s==="medium"||s==="p2")return{priorityNum:50,priorityLabel:"medium"};if(s==="low"||s==="p3"||s==="p4")return{priorityNum:75,priorityLabel:"low"};const a=Number(s.replace(/^p/,""));return Number.isFinite(a)?{priorityNum:Math.max(1,Math.min(100,Math.round(a))),priorityLabel:null}:{priorityNum:60,priorityLabel:null}}function hi(t){const s=t.toLowerCase();return["todo","not_started","planned","pending","backlog"].includes(s)}function fi(t){const s=t.toLowerCase();return["in_progress","active","running","queued"].includes(s)}function gi(t,s){const a={id:t.id,type:"initiative",title:t.name,status:t.rawStatus??t.status,parentId:null,initiativeId:t.id,workstreamId:null,milestoneId:null,priorityNum:60,priorityLabel:null,dependencyIds:[],dueDate:t.targetDate??null,etaEndAt:t.targetDate??null,expectedDurationHours:40,expectedBudgetUsd:1500,assignedAgents:[],updatedAt:t.updatedAt??t.createdAt??null},o=(s.workstreams.length>0?s.workstreams:(t.workstreams??[]).map(p=>({id:p.id,name:p.name,summary:null,status:p.status,progress:null,initiativeId:t.id,createdAt:null}))).map(p=>({id:p.id,type:"workstream",title:p.name,status:p.status,parentId:t.id,initiativeId:t.id,workstreamId:p.id,milestoneId:null,priorityNum:50,priorityLabel:"medium",dependencyIds:[],dueDate:null,etaEndAt:null,expectedDurationHours:16,expectedBudgetUsd:300,assignedAgents:[],updatedAt:p.createdAt,sequenceIndex:typeof p.sequenceIndex=="number"?p.sequenceIndex??void 0:void 0,hierarchyLabel:typeof p.hierarchyLabel=="string"?p.hierarchyLabel??void 0:void 0})),l=new Set(o.map(p=>p.id)),c=s.milestones.map(p=>({id:p.id,type:"milestone",title:p.title,status:p.status,parentId:p.workstreamId&&l.has(p.workstreamId)?p.workstreamId:t.id,initiativeId:t.id,workstreamId:p.workstreamId&&l.has(p.workstreamId)?p.workstreamId:null,milestoneId:p.id,priorityNum:50,priorityLabel:"medium",dependencyIds:[],dueDate:p.dueDate,etaEndAt:p.dueDate,expectedDurationHours:6,expectedBudgetUsd:120,assignedAgents:[],updatedAt:p.createdAt,sequenceIndex:p.sequenceIndex,hierarchyLabel:p.hierarchyLabel})),h=new Set(c.map(p=>p.id)),f=s.tasks.map(p=>{const E=xi(p.priority),L=p.milestoneId&&h.has(p.milestoneId),g=p.workstreamId&&l.has(p.workstreamId);return{id:p.id,type:"task",title:p.title,status:p.status,parentId:L?p.milestoneId:g?p.workstreamId:t.id,initiativeId:t.id,workstreamId:g?p.workstreamId:null,milestoneId:L?p.milestoneId:null,priorityNum:E.priorityNum,priorityLabel:E.priorityLabel,dependencyIds:[],dueDate:p.dueDate,etaEndAt:p.dueDate,expectedDurationHours:2,expectedBudgetUsd:40,assignedAgents:[],updatedAt:p.createdAt,sequenceIndex:p.sequenceIndex,hierarchyLabel:p.hierarchyLabel}}),j=f.filter(p=>["todo","not_started","planned","pending","backlog"].includes(p.status.toLowerCase())).sort((p,E)=>{const L=p.priorityNum-E.priorityNum;if(L!==0)return L;const g=p.etaEndAt?Date.parse(p.etaEndAt):1/0,d=E.etaEndAt?Date.parse(E.etaEndAt):1/0;if(g!==d)return g-d;const v=p.updatedAt?Date.parse(p.updatedAt):0;return(E.updatedAt?Date.parse(E.updatedAt):0)-v}).map(p=>p.id);return{nodes:[a,...o,...c,...f],edges:[],recentTodos:j}}function bi(t,s){if(!t)return new Set;const a=new Map(s.map(c=>[c.id,c])),n=new Map;for(const c of s)for(const h of c.dependencyIds){const f=n.get(h)??[];f.push(c.id),n.set(h,f)}const o=new Set,l=[t];for(;l.length>0;){const c=l.shift();if(o.has(c))continue;o.add(c);const h=a.get(c);if(h){for(const f of h.dependencyIds)o.has(f)||l.push(f);for(const f of n.get(c)??[])o.has(f)||l.push(f)}}return o}function yi(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 wi(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 vi(t,s){return{id:t.id,title:t.title,description:null,status:t.status,priority:t.priorityLabel??`p${t.priorityNum}`,dueDate:t.dueDate,initiativeId:s.id,milestoneId:t.milestoneId,workstreamId:t.workstreamId,createdAt:t.updatedAt,sequenceIndex:t.sequenceIndex,hierarchyLabel:t.hierarchyLabel}}const Fs={hidden:{opacity:0},show:{opacity:1}};function ji({initiative:t,selected:s=!1,onSelectionChange:a,isSquished:n=!1,runtimeActivity:o=null}){var rs;const{expandedInitiatives:l,toggleExpanded:c,openModal:h,agentEntityMap:f,authToken:j,embedMode:p,mutations:E}=Ht(),[L,g]=r.useState(!1),[d,v]=r.useState(null),[y,S]=r.useState(null),[M,R]=r.useState(!1),[m,b]=r.useState(!1),[k,$]=r.useState(null),[F,te]=r.useState(!1),re=r.useRef(null),[X,O]=r.useState(52),[w,Q]=r.useState(0),A=l.has(t.id),{graph:H,isLoading:K,degraded:de,error:q,refetch:P}=Va({initiativeId:t.id,authToken:j,embedMode:p}),{details:B,isLoading:U,error:V}=ks({initiativeId:t.id,authToken:j,embedMode:p}),pe=js({authToken:j,embedMode:p}),ae=r.useMemo(()=>gi(t,B),[t,B]),Se=!!(H&&H.nodes.length>0),Ue=ae.nodes.length>0,Ke=!Se&&Ue,x=Ke?ae.nodes:Se?(H==null?void 0:H.nodes)??[]:ae.nodes,Y=Ke?ae.edges:Se?(H==null?void 0:H.edges)??[]:ae.edges,Z=Ke?ae.recentTodos:Se?(H==null?void 0:H.recentTodos)??[]:ae.recentTodos,ge=de.some(C=>/401|unauthorized/i.test(C))||!!(q&&/401|unauthorized/i.test(q))||!!(V&&/401|unauthorized/i.test(V)),De=q&&/unknown api endpoint/i.test(q)?"Graph API unavailable. Showing session-derived data.":q,We=V,Be=[...de,...De?[De]:[],...We?[`Entity data partially unavailable: ${We}`]:[],...ge?["OrgX auth is missing or expired in this local plugin instance. Reconnect in onboarding to load full workstreams/milestones/tasks."]:[]],T=Be.filter(C=>/cyclic dependency edge/i.test(C)),G=T.reduce((C,se)=>{const Re=/detected\s+(\d+)\s+cyclic dependency edge/i.exec(se);return C+(Re&&Number(Re[1])||0)},0),oe=T.length>0,Ce=async()=>{if(!F){te(!0);try{const C=await fetch("/orgx/api/mission-control/graph/cycles/auto-fix",{method:"POST",headers:yt({authToken:j,embedMode:p,contentTypeJson:!0}),body:JSON.stringify({initiativeId:t.id})}),se=await C.json().catch(()=>null);if(!C.ok)throw new Error((se==null?void 0:se.error)??(se==null?void 0:se.message)??`Failed to auto-fix dependency cycles (${C.status})`);const Re=typeof(se==null?void 0:se.cycleEdgesDetected)=="number"?se.cycleEdgesDetected:G,Ve=typeof(se==null?void 0:se.nodesUpdated)=="number"?se.nodesUpdated:0,et=typeof(se==null?void 0:se.nodesFailed)=="number"?se.nodesFailed:0;$({tone:et>0?"error":"success",message:et>0?`Auto-fix removed ${Re} cyclic edge${Re===1?"":"s"} and updated ${Ve} nodes (${et} failed).`:`Auto-fix removed ${Re} cyclic edge${Re===1?"":"s"} and updated ${Ve} nodes.`}),P()}catch(C){$({tone:"error",message:C instanceof Error?C.message:"Failed to auto-fix dependency cycles."})}finally{te(!1)}}},Ie=r.useMemo(()=>new Map(x.map(C=>[C.id,C])),[x]),Fe=r.useMemo(()=>bi(d,x),[d,x]),Oe=r.useMemo(()=>Z.some(C=>Ie.has(C)),[Ie,Z]);r.useEffect(()=>{const C=re.current;if(!C||!A)return;const se=()=>{const Ve=Math.max(48,C.offsetHeight);O(et=>et===Ve?et:Ve)};if(se(),typeof ResizeObserver>"u")return;const Re=new ResizeObserver(()=>se());return Re.observe(C),()=>Re.disconnect()},[A,t.status,t.targetDate,t.name]),r.useEffect(()=>{const C=re.current;if(!C||!A){Q(0);return}const se=C.closest('[data-mc-scroll-host="true"]')??C.closest(".h-full.overflow-y-auto.overflow-x-hidden"),Re=se??window;let Ve=0;const et=()=>{Ve=0;const as=Number.parseFloat(getComputedStyle(C).top||"0"),ke=C.getBoundingClientRect(),Vs=(se==null?void 0:se.getBoundingClientRect().top)??0,Gt=1-(ke.top-Vs-as)/56,Ss=Math.pow(Math.max(0,Math.min(1,Gt)),1.2);Q(At=>Math.abs(At-Ss)<.015?At:Ss)},Ct=()=>{Ve||(Ve=window.requestAnimationFrame(et))};return et(),Re.addEventListener("scroll",Ct,{passive:!0}),window.addEventListener("resize",Ct),()=>{Ve&&window.cancelAnimationFrame(Ve),Re.removeEventListener("scroll",Ct),window.removeEventListener("resize",Ct)}},[A,t.id]),r.useEffect(()=>{var C;A&&!d&&x.length>0&&v(((C=x[0])==null?void 0:C.id)??null)},[A,x,d]),r.useEffect(()=>{if(!k)return;const C=window.setTimeout(()=>$(null),k.tone==="success"?2800:4200);return()=>window.clearTimeout(C)},[k]);const St=((H==null?void 0:H.initiative.assignedAgents)??[]).map(C=>({id:C.id,name:C.name,confidence:"high"})),Me=f.get(t.id)??[];St.length>0;const xe=x.filter(C=>C.type==="task"),ye=xe.filter(C=>fi(C.status)).length,ot=xe.filter(C=>hi(C.status)).length,ht=xe.filter(C=>Je(C.status)).length,Vt=(o==null?void 0:o.activeCount)??0;o==null||o.totalCount;const Ye=ye>0||Vt>0,tt=t.status==="active"&&Ye?"in_progress":t.status,Rt=tt==="in_progress"?qs.active:qs[tt],Bt=tt==="in_progress"?"In Progress":ze(tt),Xe=xe.length>0?xe:x.some(C=>C.type==="milestone")?x.filter(C=>C.type==="milestone"):x.filter(C=>C.type==="workstream"),ft=Math.round(Xe.reduce((C,se)=>C+(se.expectedDurationHours||0),0)*10)/10,mt=Math.round(Xe.reduce((C,se)=>C+(se.expectedBudgetUsd||0),0)*100)/100,pt=x.filter(C=>C.type==="milestone"),Qe=x.filter(C=>C.type==="workstream"),st=pe.isPinning||pe.isMoving,wt=(t.rawStatus??t.status??"").trim().toLowerCase().replace(/[\s-]+/g,"_"),vt=new Set(["active","in_progress","running"]).has(wt),He=new Set(["paused","draft","planned","todo","backlog","queued"]).has(wt)||vt,ns=vt?"Play next":wt==="paused"?"Resume":"Start",lt=r.useMemo(()=>He?null:Be.length>0?"Live sync is degraded. Refresh sync or reconnect OrgX, then retry.":(["blocked"].includes(wt)||["completed","done","archived","cancelled","deleted"].includes(wt),null),[He,wt,Be.length]),Lt=!n,Kt=n,Et=r.useMemo(()=>Qe.filter(C=>C.initiativeId===t.id).sort((C,se)=>C.priorityNum-se.priorityNum||C.title.localeCompare(se.title)),[t.id,Qe]),Ot=Se||B.workstreams.length>0||B.milestones.length>0||B.tasks.length>0,i=xe.length>0?ts(ht,xe.length):pt.length>0?ts(pt.filter(C=>Je(C.status)).length,pt.length):Ot&&Qe.length>0?ts(Qe.filter(C=>Je(C.status)).length,Qe.length):null,N=Ws(i===null?t.health:i),D=N===0?2:N,ee=(t.workstreams??[]).some(C=>C.status.toLowerCase()==="blocked")||Qe.some(C=>C.status.toLowerCase()==="blocked"),ie=t.status==="blocked"||ee,Ne=Je(t.status),Te=N>0&&N<100&&!ie&&!Ne,me=ie?"border-l-2 border-l-red-400/60":Ne?"border-l-2 border-l-teal-400/60":Te?"border-l-2 border-l-lime-400/60":N===0&&!ie&&!Ne&&!Ye?"border-l-2 border-l-white/10":"",Ge=N===0&&t.status==="active"&&!Ye,Ee=Math.pow(w,.82),jt=Math.max(0,Number((16*(1-Ee)).toFixed(2))),Ze=`0 10px 26px rgba(0,0,0,${(.18+Ee*.24).toFixed(3)}), 0 1px 0 rgba(191,255,0,${(Ee*.09).toFixed(3)})`,qt=async C=>{if(Et.length===0){$({tone:"error",message:"No workstreams available to queue for this initiative."});return}const se=C==="top"?[...Et].reverse():Et;let Re=0,Ve=0,et=null;for(const Ct of se)try{await pe.pin({initiativeId:t.id,workstreamId:Ct.id}),await pe.move({initiativeId:t.id,workstreamId:Ct.id,placement:C}),Re+=1}catch(as){Ve+=1,et||(et=as instanceof Error?as.message:"Failed to queue this initiative.")}if(Ve>0){$({tone:Re>0?"success":"error",message:Re>0?`Queued ${Re}/${Et.length} workstreams (${Ve} failed).`:et??"Failed to queue initiative workstreams."});return}$({tone:"success",message:`Queued ${Re} workstream${Re===1?"":"s"} to ${C==="top"?"top":"end"}.`})},J=C=>{if(C.type==="initiative"){h({type:"initiative",entity:t});return}if(C.type==="workstream"){h({type:"workstream",entity:yi(C,t),initiative:t});return}if(C.type==="milestone"){h({type:"milestone",entity:wi(C,t),initiative:t});return}h({type:"task",entity:vi(C,t),initiative:t})},je=async(C,se)=>{await E.updateEntity.mutateAsync({type:C.type,id:C.id,...se})},ct=C=>se=>{se.stopPropagation(),E.entityAction.mutate({type:"initiative",id:t.id,action:C})},qe=C=>{if(C.stopPropagation(),vt){qt("bottom");return}E.updateEntity.mutate({type:"initiative",id:t.id,status:"active"})};return e.jsxs("div",{id:`initiative-${t.id}`,className:`surface-tier-1 overflow-visible rounded-2xl transition-[background-color,border-color,box-shadow,opacity] duration-200 ${A?"bg-[--orgx-surface-elevated]":"bg-[--orgx-surface]"} ${s?"ring-1 ring-lime/30 shadow-[0_0_0_1px_rgba(191,255,0,0.12)]":""} ${me} ${Ge?"opacity-60":""}`,style:{"--mc-initiative-header-offset":`${X}px`},children:[e.jsxs("div",{ref:re,role:"button",tabIndex:0,"aria-expanded":A,onClick:()=>c(t.id),onKeyDown:C=>{(C.key==="Enter"||C.key===" ")&&(C.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 ${A?"sticky z-30 border-b border-subtle bg-[#0C0E14]/95 shadow-[0_8px_20px_rgba(0,0,0,0.3)] backdrop-blur-xl":""}`,style:A?{top:"var(--mc-toolbar-offset, 88px)",borderTopLeftRadius:`${jt}px`,borderTopRightRadius:`${jt}px`,boxShadow:Ze}:void 0,children:[e.jsx(le.div,{animate:{rotate:A?90:0},transition:{type:"spring",stiffness:400,damping:25},className:"flex-shrink-0 flex items-center justify-center w-6 h-6 rounded-md transition-colors group-hover:bg-white/[0.06]",children:e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",className:"text-muted",children:e.jsx("path",{d:"m9 18 6-6-6-6"})})}),a&&e.jsx("div",{className:"flex h-6 w-6 flex-shrink-0 items-center justify-center",children:e.jsx("input",{type:"checkbox",checked:s,onChange:C=>{const se=C.nativeEvent.shiftKey??!1;a(t.id,C.currentTarget.checked,se)},onClick:C=>C.stopPropagation(),"aria-label":`Select initiative ${t.name}`,className:"h-3.5 w-3.5 rounded border-white/20 bg-black/40 text-lime focus:ring-lime/35"})}),e.jsx("span",{className:`w-2 h-2 rounded-full flex-shrink-0 ${Ye?"status-breathe":""}`,style:{backgroundColor:Ds(tt)}}),e.jsx("div",{className:"min-w-[80px] flex-[1_1_auto] overflow-hidden pr-1.5 sm:min-w-0 sm:pr-2",children:e.jsx("button",{type:"button",onClick:C=>{C.stopPropagation(),h({type:"initiative",entity:t})},className:"block w-full max-w-full overflow-hidden text-ellipsis whitespace-nowrap text-left text-body font-semibold text-white transition-colors hover:text-primary sm:text-heading",title:t.name,children:t.name})}),e.jsxs("div",{className:`ml-1 flex flex-shrink-0 justify-start ${n?"w-[80px] min-w-[80px]":"w-[80px] min-w-[80px] sm:w-[90px] sm:min-w-[90px] md:w-[102px] md:min-w-[102px]"}`,children:[e.jsx("span",{className:`w-full truncate text-center text-micro rounded-full border py-0.5 uppercase tracking-[0.08em] leading-none whitespace-nowrap ${n?"px-1.5":"px-2"} ${Rt}`,children:Bt}),de.length>0&&e.jsx("span",{className:"ml-1 h-2 w-2 flex-shrink-0 rounded-full bg-amber-400/70 animate-pulse",title:`Sync degraded: ${de.length} issue${de.length!==1?"s":""}`})]}),e.jsx("div",{className:`ml-1.5 flex-shrink-0 ${Kt?"flex":"lg:hidden"}`,title:`${N}% complete`,children:e.jsxs("svg",{viewBox:"0 0 36 36",className:"h-9 w-9","aria-label":`${N}% complete`,children:[e.jsx("circle",{cx:"18",cy:"18",r:"15",fill:"none",stroke:"rgba(255,255,255,0.06)",strokeWidth:"3"}),e.jsx(le.circle,{cx:"18",cy:"18",r:"15",fill:"none",stroke:Ds(tt),strokeWidth:"3",strokeLinecap:"round",initial:!1,animate:{strokeDasharray:`${D/100*94.25} 94.25`,opacity:N===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:[N,"%"]})]})}),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] ${Kt?"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(le.div,{className:"h-full rounded-full transition-all",initial:!1,animate:{width:`${D}%`,opacity:N===0?.45:1},transition:{type:"spring",stiffness:260,damping:34,mass:.75},style:{backgroundColor:Ds(tt)}})})}),e.jsxs("span",{className:"w-[42px] text-right text-micro text-muted xl:w-[48px] xl:text-caption",style:{fontVariantNumeric:"tabular-nums"},children:[N,"%"]})]}),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:[Lt&&e.jsx(Qs,{label:"Queue",size:"sm",busy:st,disabled:Et.length===0,stopPropagation:!0,title:`Queue initiative: ${t.name}`,onSelectPlacement:qt}),e.jsxs("button",{type:"button",onClick:C=>{He&&qe(C)},disabled:!He||E.updateEntity.isPending,title:He?`${ns} initiative`:`Cannot start while status is ${ze(wt)}`,className:`control-pill inline-flex items-center justify-center gap-1.5 text-micro font-semibold text-lime 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:ns})]})]}),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:ct("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:ct("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:C=>{C.stopPropagation(),h({type:"initiative",entity:t})},title:"Details",className:"flex items-center justify-center w-6 h-6 rounded-lg text-secondary hover:text-white hover:bg-white/[0.08] transition-colors",children:e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("circle",{cx:"12",cy:"12",r:"10"}),e.jsx("path",{d:"M12 16v-4M12 8h.01"})]})})]})]}),k&&e.jsx("div",{role:"status","aria-live":"polite",className:`mx-3 mb-2 rounded-lg border px-2.5 py-1.5 text-micro ${k.tone==="success"?"border-lime/24 bg-lime/[0.1] text-lime":"border-red-400/24 bg-red-500/[0.1] text-red-100"}`,children:k.message}),lt&&Be.length>0&&e.jsx("div",{role:"note",className:"mx-3 mb-2 rounded-lg border border-amber-300/20 bg-amber-500/[0.08] px-2.5 py-1.5 text-micro text-amber-100/90",children:lt}),e.jsx(at,{children:A&&e.jsx(le.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:()=>b(!0),onAnimationComplete:()=>b(!1),className:m?"overflow-hidden":"overflow-visible",children:e.jsxs("div",{className:"space-y-2.5 px-4 pb-4 pt-2.5",children:[e.jsx("div",{className:"section-divider"}),K||!Se&&U?e.jsx("div",{className:"space-y-2",children:Array.from({length:3}).map((C,se)=>e.jsx($t,{className:"h-24 w-full rounded-xl"},`mc-loading-${se}`))}):e.jsxs(le.div,{initial:"hidden",animate:"show",variants:{hidden:{},show:{transition:{staggerChildren:.08}}},className:"space-y-3.5",children:[(ot>0||ye>0||ht>0||ft>0)&&e.jsx(le.div,{variants:Fs,children:e.jsxs("div",{className:"flex items-center gap-4 py-1",children:[e.jsxs("svg",{viewBox:"0 0 68 68",className:"h-16 w-16 flex-shrink-0","aria-label":`${N}% complete`,children:[e.jsx("circle",{cx:"34",cy:"34",r:"28",fill:"none",stroke:"rgba(255,255,255,0.06)",strokeWidth:"5"}),e.jsx(le.circle,{cx:"34",cy:"34",r:"28",fill:"none",stroke:Ds(tt),strokeWidth:"5",strokeLinecap:"round",initial:!1,animate:{strokeDasharray:`${(N===0?2:N)/100*175.93} 175.93`,opacity:N===0?.45:1},transition:{type:"spring",stiffness:260,damping:34,mass:.75},transform:"rotate(-90 34 34)"}),e.jsxs("text",{x:"34",y:"32",textAnchor:"middle",dominantBaseline:"central",fill:"currentColor",fontSize:"14",fontWeight:"700",className:"text-bright",children:[N,"%"]}),e.jsxs("text",{x:"34",y:"46",textAnchor:"middle",dominantBaseline:"central",fill:"currentColor",fontSize:"8",className:"text-muted",children:[ht,"/",xe.length," done"]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-1 text-caption text-secondary",children:[e.jsxs("span",{children:[e.jsx("span",{className:"text-bright font-medium",children:"Queue:"})," ",ot,ye>0?` (${ye} active)`:""]}),ft>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-white/20",children:"·"}),e.jsxs("span",{children:[e.jsx("span",{className:"text-bright font-medium",children:"Duration:"})," ",ft,"h"]})]}),mt>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-white/20",children:"·"}),e.jsxs("span",{children:[e.jsx("span",{className:"text-bright font-medium",children:"Budget:"})," $",mt.toLocaleString()]})]})]})]})}),y&&e.jsxs("div",{className:"subsection-shell flex items-center justify-between rounded-lg px-3 py-2 text-caption text-lime",children:[e.jsxs("span",{children:["Focused on workstream ",((rs=Ie.get(y))==null?void 0:rs.title)??y]}),e.jsx("button",{type:"button",onClick:()=>S(null),className:"text-micro underline underline-offset-2",children:"Clear focus"})]}),e.jsx(le.div,{variants:Fs,children:e.jsxs(pn,{title:"Dependency Map",storageKey:`depmap.${t.id}`,defaultOpen:!0,badge:oe?{label:`${G||T.length} cycle${(G||T.length)===1?"":"s"}`,tone:"warning",action:{label:"Fix",onClick:Ce,busy:F}}:null,children:[e.jsx(Xa,{nodes:x,edges:Y,selectedNodeId:d,focusedWorkstreamId:y,onSelectNode:C=>{v(C);const se=Ie.get(C);(se==null?void 0:se.type)==="workstream"&&S(se.id)}}),Be.filter(C=>!/cyclic dependency edge/i.test(C)).length>0&&e.jsxs("div",{className:"mt-2",children:[e.jsxs("button",{type:"button",onClick:()=>R(C=>!C),className:"flex items-center gap-1.5 text-micro text-amber-200/65 transition-colors hover:text-amber-100/85",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-amber-300/60"}),Be.filter(C=>!/cyclic dependency edge/i.test(C)).length," warning",Be.filter(C=>!/cyclic dependency edge/i.test(C)).length!==1?"s":"",e.jsx("svg",{width:"8",height:"8",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",className:`transition-transform ${M?"rotate-180":""}`,children:e.jsx("path",{d:"m6 9 6 6 6-6"})})]}),e.jsx(at,{children:M&&e.jsx(le.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.15},className:"overflow-hidden",children:e.jsx("div",{className:"space-y-1 pt-1.5",children:Be.filter(C=>!/cyclic dependency edge/i.test(C)).map((C,se)=>e.jsx("div",{className:"text-micro text-amber-100/60",children:Nt(C)},se))})})})]})]})}),Oe&&e.jsx(le.div,{variants:Fs,children:e.jsx(pn,{title:"Next Up",storageKey:`nextup.${t.id}`,defaultOpen:!0,children:e.jsx(ui,{recentTodoIds:Z,nodesById:Ie,selectedNodeId:d,onSelectNode:C=>{v(C);const se=Ie.get(C);(se==null?void 0:se.type)==="workstream"&&S(se.id)}})})}),e.jsx(le.div,{variants:Fs,children:e.jsx(pn,{title:"Hierarchy",storageKey:`hierarchy.${t.id}`,defaultOpen:!0,contentOverflowVisible:!0,children:e.jsx(li,{nodes:x,edges:Y,selectedNodeId:d,highlightedNodeIds:Fe,editMode:L,onSelectNode:v,onFocusWorkstream:S,onOpenNode:J,onUpdateNode:je,onToggleEditMode:()=>g(C=>!C),mutations:E})})})]}),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 ki={hidden:{opacity:0},show:{opacity:1,transition:{staggerChildren:.045,delayChildren:.02}}},Ni={hidden:{opacity:0,y:10,scale:.995},show:{opacity:1,y:0,scale:1,transition:{type:"spring",stiffness:320,damping:28,mass:.7}}};function cr({initiatives:t,selectedInitiativeIds:s,onToggleInitiativeSelection:a,isSquished:n=!1,runtimeActivityByInitiativeId:o}){return e.jsx(le.div,{variants:ki,initial:"hidden",animate:"show",className:"space-y-2",children:t.map(l=>e.jsx(le.div,{variants:Ni,layout:!0,transition:{type:"spring",stiffness:280,damping:32,mass:.75},children:e.jsx(ji,{initiative:l,selected:(s==null?void 0:s.has(l.id))??!1,onSelectionChange:a,isSquished:n,runtimeActivity:(o==null?void 0:o.get(l.id))??null})},l.id))})}function xn({mode:t="empty",hasActiveFilters:s=!1,detail:a=null,onClearFilters:n,onCreateInitiative:o,onPlayNextUp:l,onStartAutopilot:c,onRefresh:h,onOpenSettings:f}){const[j,p]=r.useState(null),[E,L]=r.useState(null),g=r.useCallback(async(y,S)=>{if(S){L(null),p(y);try{await S()}catch(M){const R=M instanceof Error?M.message:"";L(R?Nt(R):"Action failed")}finally{p(M=>M===y?null:M)}}},[]),d=t==="filtered"?"No initiatives match this view":t==="degraded"?"Initiatives are temporarily unavailable":"No initiatives yet",v=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(ma,{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:`${z.iris}1a`,border:`1px solid ${z.iris}33`},children:e.jsxs("svg",{width:"22",height:"22",viewBox:"0 0 24 24",fill:"none",stroke:z.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:v})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[t==="filtered"&&n&&e.jsx("button",{type:"button",onClick:n,className:"rounded-full border border-strong bg-white/[0.03] px-3 py-1.5 text-caption font-semibold text-primary transition hover:bg-white/[0.08]",children:"Clear filters"}),t==="degraded"&&f&&e.jsx("button",{type:"button",onClick:f,className:"rounded-full border border-white/[0.12] bg-white/[0.03] px-3 py-1.5 text-caption font-semibold text-primary transition hover:bg-white/[0.08]",children:"Open settings"}),o&&e.jsx("button",{type:"button",onClick:o,className:"rounded-full border border-lime/30 bg-lime/12 px-3 py-1.5 text-caption font-semibold text-lime transition hover:bg-lime/18",children:"Create initiative"}),l&&e.jsx("button",{type:"button",onClick:()=>void g("play",l),disabled:j!==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:j==="play"?"Dispatching...":"Play Next Up"}),c&&e.jsx("button",{type:"button",onClick:()=>void g("autopilot",c),disabled:j!==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:j==="autopilot"?"Starting...":"Start Autopilot"}),h&&e.jsx("button",{type:"button",onClick:h,className:"rounded-full border border-strong bg-white/[0.03] px-3 py-1.5 text-caption font-semibold text-secondary transition hover:bg-white/[0.08] hover:text-primary",children:"Refresh"})]}),t==="degraded"&&a&&e.jsx("p",{className:"text-caption text-secondary",children:Nt(a)}),E&&e.jsx("p",{className:"text-caption text-amber-200/80",children:E})]})})})}function Pr({percent:t,size:s=56,strokeWidth:a=4,className:n}){const o=Math.max(0,Math.min(100,t)),l=(s-a)/2,c=2*Math.PI*l,h=c-o/100*c,f=o>66?"#BFFF00":o>33?"#F5B700":"rgba(255,255,255,0.38)";return e.jsxs("div",{className:n,style:{width:s,height:s,position:"relative"},children:[e.jsxs("svg",{width:s,height:s,viewBox:`0 0 ${s} ${s}`,children:[e.jsx("circle",{cx:s/2,cy:s/2,r:l,fill:"none",stroke:"rgba(255,255,255,0.06)",strokeWidth:a}),e.jsx(le.circle,{cx:s/2,cy:s/2,r:l,fill:"none",stroke:f,strokeWidth:a,strokeLinecap:"round",strokeDasharray:c,initial:{strokeDashoffset:c},animate:{strokeDashoffset:h},transition:{duration:pa.durationEntrance/1e3,ease:[.22,1,.36,1]},transform:`rotate(-90 ${s/2} ${s/2})`})]}),e.jsx("span",{className:"absolute inset-0 flex items-center justify-center text-[18px] font-light",style:{fontVariantNumeric:"tabular-nums",color:f},children:Math.round(o)})]})}function we({label:t,icon:s,color:a="#BFFF00",variant:n="secondary",size:o="md",className:l="",type:c="button",...h}){const f=o==="sm"?"px-2.5 py-1 text-micro":"px-3 py-1.5 text-caption",j=n==="primary"?{backgroundColor:a,color:"#05060A",borderColor:`${a}CC`}:n==="destructive"?{backgroundColor:`${a}18`,color:a,borderColor:`${a}45`}:n==="ghost"?{backgroundColor:"rgba(255,255,255,0.03)",color:"rgba(255,255,255,0.75)",borderColor:"rgba(255,255,255,0.12)"}:{backgroundColor:`${a}20`,color:a,borderColor:`${a}30`};return e.jsxs("button",{type:c,className:`inline-flex items-center gap-1.5 rounded-lg border transition-colors disabled:cursor-not-allowed disabled:opacity-50 ${f} ${l}`,style:j,...h,children:[s,t&&e.jsx("span",{children:t})]})}const dr={draft:z.textMuted,in_review:z.amber,approved:z.lime,changes_requested:z.red,superseded:z.textMuted,archived:z.textMuted};function Si(t,s){const a=new Date().toISOString();return t==="initiative"&&s==="init-1"?[{id:"artifact-demo-init-1-brief",name:"Q4 dashboard polish brief",description:"Summary of final polish checklist and open items.",artifact_url:"#",artifact_type:"shared.project_handbook",status:"approved",metadata:{source:"demo"},created_at:a,updated_at:a},{id:"artifact-demo-init-1-copy",name:"Launch copy variants",description:"Three launch-ready copy variants for review.",artifact_url:"#",artifact_type:"document",status:"in_review",metadata:{source:"demo"},created_at:a,updated_at:a}]:t==="initiative"&&s==="init-2"?[{id:"artifact-demo-init-2-subjects",name:"Subject line variants",description:"Email subject line candidates with performance notes.",artifact_url:"#",artifact_type:"document",status:"approved",metadata:{source:"demo"},created_at:a,updated_at:a}]:[]}function Ci(){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 ur(t,s,a){if(ws())return Si(t,s);try{const n=yt(a),o=new URLSearchParams({entity_type:t,entity_id:s,limit:"20"}),l=await fetch(`/orgx/api/work-artifacts/by-entity?${o.toString()}`,{headers:n});if(!l.ok)return[];const c=await l.json();return(c==null?void 0:c.artifacts)??[]}catch{return[]}}function Hs({entityType:t,entityId:s,title:a="Artifacts",authToken:n=null,embedMode:o=!1,finalOnly:l=!1,milestoneIds:c}){const{open:h}=xa(),[f,j]=r.useState(!l),p=!!(c!=null&&c.length),E=ss({queryKey:vs.artifactsByEntity({entityType:t,entityId:s,authToken:n,embedMode:o}),enabled:!p&&!!s,queryFn:()=>ur(t,s,{authToken:n,embedMode:o})}),L=ss({queryKey:["artifacts-by-milestones",c,n,o],enabled:p,queryFn:async()=>{if(!(c!=null&&c.length))return[];const y=await Promise.all(c.map(M=>ur("milestone",M,{authToken:n,embedMode:o}))),S=new Map;for(const M of y)for(const R of M)S.has(R.id)||S.set(R.id,R);return[...S.values()].sort((M,R)=>Date.parse(R.updated_at)-Date.parse(M.updated_at))}}),g=p?L:E,d=g.data??[],v=f?d:d.filter(y=>y.status==="approved");return g.isLoading?e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-caption font-medium text-secondary",children:a}),e.jsx("div",{className:"shimmer-skeleton h-10 w-full rounded-lg"})]}):d.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h4",{className:"text-caption font-medium text-secondary",children:[a," (",v.length,")"]}),l&&e.jsx("button",{type:"button",onClick:()=>j(y=>!y),className:"text-micro text-faint transition-colors hover:text-secondary",children:f?"Final only":"Show all"})]}),e.jsxs("div",{className:"space-y-1.5",children:[v.slice(0,10).map(y=>e.jsxs("button",{type:"button",onClick:()=>h(y.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(Ci,{}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-body text-primary",children:y.name}),e.jsx("span",{className:"text-micro text-faint",children:y.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:dr[y.status]??z.textMuted,backgroundColor:`${dr[y.status]??z.textMuted}15`},children:y.status})]},y.id)),v.length>10&&e.jsxs("p",{className:"text-micro text-faint pl-2",children:["+",v.length-10," more"]})]})]})}function ut({level:t,size:s=12,className:a=""}){return t==="initiative"?e.jsxs("svg",{width:s,height:s,viewBox:"0 0 24 24",className:a,fill:"none",stroke:z.iris,strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[e.jsx("circle",{cx:"12",cy:"12",r:"9",fill:"rgba(124,124,255,0.14)"}),e.jsx("circle",{cx:"12",cy:"12",r:"4.5"}),e.jsx("circle",{cx:"12",cy:"12",r:"1.6",fill:z.iris,stroke:"none"})]}):t==="workstream"?e.jsx(ha,{size:s,className:a,stroke:z.lime,strokeWidth:1.9,withBackground:!0,backgroundColor:"rgba(191,255,0,0.12)"}):t==="milestone"?e.jsxs("svg",{width:s,height:s,viewBox:"0 0 24 24",className:a,fill:"none",stroke:z.teal,strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[e.jsx("path",{d:"M7 5v14"}),e.jsx("path",{d:"m7 6 10 1.1-1.8 3.5L17 14 7 12.9z",fill:"rgba(20,184,166,0.12)"}),e.jsx("circle",{cx:"7",cy:"5",r:"1.2",fill:z.teal,stroke:"none"})]}):e.jsxs("svg",{width:s,height:s,viewBox:"0 0 24 24",className:a,fill:"none",stroke:"rgba(255,255,255,0.72)",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[e.jsx("rect",{x:"4.5",y:"4.5",width:"15",height:"15",rx:"4",fill:"rgba(255,255,255,0.1)"}),e.jsx("path",{d:"M9 12.2 11.1 14.3 15.2 10.1"})]})}function it(t){return t==="initiative"?"I":t==="workstream"?"W":t==="milestone"?"M":"T"}function Ii({initiative:t}){const{agentEntityMap:s,openModal:a,closeModal:n,authToken:o,embedMode:l,mutations:c}=Ht(),h=s.get(t.id)??[],[f,j]=r.useState(!1),[p,E]=r.useState(""),[L,g]=r.useState(!1),[d,v]=r.useState(!1),[y,S]=r.useState(!1),M=r.useRef(null),[R,m]=r.useState(null),[b,k]=r.useState(t.name),[$,F]=r.useState(t.description??""),[te,re]=r.useState(gs(t.priority)),[X,O]=r.useState(hn(t.targetDate)),[w,Q]=r.useState(null),{details:A,isLoading:H}=ks({initiativeId:t.id,authToken:o,embedMode:l}),K=js({authToken:o,embedMode:l}),de=A.tasks.filter(T=>["active","in_progress"].includes(T.status.toLowerCase())).length,q=A.tasks.filter(T=>T.status.toLowerCase()==="blocked").length,P=A.tasks.filter(T=>Je(T.status)).length,B=w??t.status,U=Ei(w??t.rawStatus??t.status),V=["active","in_progress","running","queued"].includes(U),pe=["paused","draft","planned","todo","backlog","pending","not_started"].includes(U),ae=c.entityAction.isPending||c.createEntity.isPending||c.updateEntity.isPending||c.deleteEntity.isPending,Se=K.isPinning||K.isMoving,Ue=r.useMemo(()=>A.workstreams.length>0?A.workstreams.map(T=>({id:T.id,name:T.name})):(t.workstreams??[]).map(T=>({id:T.id,name:T.name})),[A.workstreams,t.workstreams]),Ke=r.useMemo(()=>{const T=new Map,G=[];for(const oe of A.milestones){if(!oe.workstreamId){G.push(oe);continue}const Ce=T.get(oe.workstreamId);Ce?Ce.push(oe):T.set(oe.workstreamId,[oe])}return{grouped:T,unscoped:G}},[A.milestones]),x=r.useMemo(()=>{const T=new Map;for(const G of A.tasks){if(!G.workstreamId)continue;const oe=T.get(G.workstreamId);oe?oe.push(G):T.set(G.workstreamId,[G])}return T},[A.tasks]),Y=r.useMemo(()=>{const T=new Map;for(const G of A.tasks){if(!G.milestoneId)continue;const oe=T.get(G.milestoneId);oe?oe.push(G):T.set(G.milestoneId,[G])}return T},[A.tasks]),Z=r.useMemo(()=>A.tasks.filter(T=>!T.workstreamId&&!T.milestoneId),[A.tasks]),ge=(T,G)=>T&&T.trim().length>0?Nt(T.trim()):G;r.useEffect(()=>{L||(k(t.name),F(t.description??""),O(hn(t.targetDate)),re(gs(t.priority)))},[L,t.description,t.name,t.priority,t.targetDate]),r.useEffect(()=>{Q(null),v(!1)},[t.id,t.status,t.rawStatus]),r.useEffect(()=>{if(!y)return;const T=oe=>{M.current&&!M.current.contains(oe.target)&&S(!1)},G=oe=>{oe.key==="Escape"&&S(!1)};return document.addEventListener("mousedown",T),document.addEventListener("keydown",G),()=>{document.removeEventListener("mousedown",T),document.removeEventListener("keydown",G)}},[y]);const De=(T,G,oe)=>{m(null),c.entityAction.mutate({type:"initiative",id:t.id,action:T},{onSuccess:()=>{Q(G),m(oe)},onError:Ce=>{m(ge(Ce instanceof Error?Ce.message:"",`Failed to ${T} initiative.`))}})},We=()=>{const T=b.trim();if(!T){m("Initiative title is required.");return}m(null),c.updateEntity.mutate({type:"initiative",id:t.id,title:T,summary:$.trim()||null,priority:te,target_date:X||null},{onSuccess:()=>{g(!1),m("Initiative updated.")},onError:G=>{m(ge(G instanceof Error?G.message:"","Failed to update initiative."))}})},Be=async T=>{if(Ue.length===0){m("No workstreams available to queue.");return}const G=T==="top"?[...Ue].reverse():Ue;let oe=0,Ce=0,Ie=null;for(const Fe of G)try{await K.pin({initiativeId:t.id,workstreamId:Fe.id}),await K.move({initiativeId:t.id,workstreamId:Fe.id,placement:T}),oe+=1}catch(Oe){Ce+=1,Ie||(Ie=ge(Oe instanceof Error?Oe.message:"","Failed to queue initiative workstream."))}if(Ce>0){m(oe>0?`Queued ${oe}/${Ue.length} workstreams (${Ce} failed).`:Ie??"Failed to queue initiative workstreams.");return}m(`Queued ${oe} workstream${oe===1?"":"s"} to ${T==="top"?"top":"end"}.`)};return e.jsxs("div",{className:"flex h-full w-full min-h-0 flex-col",children:[e.jsxs("div",{className:"min-h-0 flex-1 space-y-5 overflow-y-auto p-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ut,{level:"initiative",size:16}),e.jsx("h2",{className:"text-display 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-micro font-semibold uppercase tracking-[0.08em] ${qs[B]??qs.active}`,children:ze(B)}),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:Ai(t.priority)})]})]}),(()=>{const T=A.tasks.length||0,G=T>0?Math.round(P/T*100):0;return T>0?e.jsx(Pr,{percent:G,size:56}):null})()]}),L?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:b,onChange:T=>k(T.target.value),className:"mt-1 w-full rounded-lg border border-white/15 bg-white/[0.06] px-3 py-2 text-body text-bright outline-none focus:border-white/30"})]}),e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:"Summary"}),e.jsx("textarea",{value:$,onChange:T=>F(T.target.value),rows:3,className:"mt-1 w-full resize-y rounded-lg border border-white/15 bg-white/[0.06] px-3 py-2 text-body text-bright outline-none focus:border-white/30"})]}),e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:"Target date"}),e.jsx("input",{type:"date",value:X,onChange:T=>O(T.target.value),className:"mt-1 w-full rounded-lg border border-white/15 bg-white/[0.06] px-3 py-2 text-body text-bright outline-none focus:border-white/30"})]}),e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:"Priority"}),e.jsxs("select",{value:te,onChange:T=>re(gs(T.target.value)),className:"mt-1 w-full rounded-lg border border-white/15 bg-white/[0.06] px-3 py-2 text-body text-bright outline-none focus:border-white/30",children:[e.jsx("option",{value:"critical",children:"Critical (P0)"}),e.jsx("option",{value:"high",children:"High (P1)"}),e.jsx("option",{value:"medium",children:"Medium (P2)"}),e.jsx("option",{value:"low",children:"Low (P3)"})]})]})]}):t.description?e.jsx("p",{className:"text-body text-secondary leading-relaxed",children:t.description}):e.jsx("p",{className:"text-body text-muted",children:"No summary yet."}),h.length>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-micro text-muted uppercase tracking-wider",children:"Agents"}),e.jsx(Sn,{agents:h,max:6})]}),R&&e.jsx("div",{className:"text-caption text-secondary",children:R})]}),e.jsx(Ia,{metrics:[{label:"Done",value:P,color:z.teal},{label:"Active",value:de,color:z.lime},{label:"Blocked",value:q,color:z.red},...t.targetDate?[{label:"ETA",value:Mi(t.targetDate)}]:[]],className:"pt-2 pb-4 border-b border-white/[0.04]"}),A.tasks.length>0&&(()=>{const T=A.tasks.length,G=Math.round(P/T*100);return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-1 flex-1 rounded-full bg-white/[0.06] overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full transition-all duration-500",style:{width:`${Math.max(G,2)}%`,background:`linear-gradient(90deg, ${z.teal}, ${z.lime})`}})}),e.jsxs("span",{className:"text-micro text-secondary tabular-nums",children:[G,"%"]})]})})(),H?e.jsx("div",{className:"space-y-2",children:Array.from({length:3}).map((T,G)=>e.jsx($t,{className:"h-14 w-full rounded-lg"},`init-detail-${G}`))}):e.jsxs(e.Fragment,{children:[(A.workstreams.length>0||A.milestones.length>0||Z.length>0)&&e.jsxs("section",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("h3",{className:"text-[11px] font-semibold uppercase tracking-[0.12em] text-white/55",children:"IWMT Composition"}),e.jsxs("p",{className:"text-micro text-muted",children:[A.workstreams.length," workstreams · ",A.milestones.length," milestones ·"," ",A.tasks.length," tasks"]})]}),e.jsxs("div",{className:"space-y-2.5",children:[A.workstreams.map(T=>{const G=Ke.grouped.get(T.id)??[],oe=x.get(T.id)??[],Ce=oe.filter(Me=>Je(Me.status)).length,Ie=oe.length>0?ts(Ce,oe.length):typeof T.progress=="number"?Ws(T.progress<=1?T.progress*100:T.progress):Je(T.status)?100:0,Fe=T.status.toLowerCase(),Oe=!["done","completed","archived"].includes(Fe),St=T.hierarchyLabel??it("workstream");return e.jsxs("article",{className:"rounded-xl border border-white/[0.08] bg-white/[0.02] px-3 py-2.5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("button",{onClick:()=>a({type:"workstream",entity:T,initiative:t}),className:"group min-w-0 flex-1 text-left",children:e.jsxs("div",{className:"flex min-w-0 items-start gap-2.5",children:[e.jsx("span",{className:"mt-0.5 inline-flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-md border border-white/[0.12] bg-white/[0.04]",children:e.jsx(ut,{level:"workstream",size:12})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("span",{className:"text-micro font-semibold uppercase tracking-[0.08em] text-white/58",children:St}),e.jsx("span",{className:"truncate text-body text-bright",children:T.name})]}),e.jsxs("p",{className:"mt-0.5 text-caption text-muted",children:[G.length," milestone",G.length===1?"":"s"," ·"," ",oe.length," task",oe.length===1?"":"s"," · ",Ie,"% done"]})]})]})}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[Oe&&e.jsx("button",{type:"button",className:"inline-flex items-center gap-1 rounded-md border border-white/[0.12] bg-white/[0.05] px-1.5 py-0.5 text-micro text-white/70 transition-colors hover:bg-white/[0.1] hover:text-white",onClick:async Me=>{Me.stopPropagation(),m(null);try{await K.pin({initiativeId:t.id,workstreamId:T.id}),await K.move({initiativeId:t.id,workstreamId:T.id,placement:"bottom"}),m(`Queued "${T.name}" to end.`)}catch(xe){m(ge(xe instanceof Error?xe.message:"","Failed to queue workstream."))}},children:"Queue"}),e.jsx("span",{className:`text-micro px-1.5 py-0.5 rounded-full border uppercase tracking-[0.08em] ${Tr(T.status)}`,children:ze(T.status)})]})]}),G.length>0?e.jsx("div",{className:"ml-7 mt-2.5 space-y-1.5 border-l border-white/[0.08] pl-3",children:G.map(Me=>{const xe=Y.get(Me.id)??[],ye=xe.filter(ht=>Je(ht.status)).length,ot=Me.hierarchyLabel??it("milestone");return e.jsxs("button",{onClick:()=>a({type:"milestone",entity:Me,initiative:t}),className:"flex w-full items-center justify-between gap-2 rounded-lg bg-white/[0.015] px-2 py-1.5 text-left transition-colors hover:bg-white/[0.06]",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx(ut,{level:"milestone",size:11,className:"flex-shrink-0"}),e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-white/52",children:ot}),e.jsx("span",{className:"truncate text-caption text-bright",children:Me.title})]}),e.jsxs("p",{className:"mt-0.5 text-micro text-muted",children:[ye,"/",xe.length," tasks done"]})]}),e.jsx("span",{className:`text-micro px-1.5 py-0.5 rounded-full border uppercase tracking-[0.08em] ${zs(Me.status)}`,children:ze(Me.status)})]},Me.id)})}):e.jsx("div",{className:"ml-7 mt-2 rounded-lg border border-dashed border-white/[0.1] bg-white/[0.01] px-3 py-2 text-micro text-muted",children:"No milestones yet."})]},T.id)}),Ke.unscoped.length>0&&e.jsxs("article",{className:"rounded-xl border border-white/[0.08] bg-white/[0.015] px-3 py-2.5",children:[e.jsx("p",{className:"text-micro uppercase tracking-[0.1em] text-white/50",children:"Unscoped milestones"}),e.jsx("div",{className:"mt-2 space-y-1.5",children:Ke.unscoped.map(T=>e.jsxs("button",{onClick:()=>a({type:"milestone",entity:T,initiative:t}),className:"flex w-full items-center justify-between gap-2 rounded-lg bg-white/[0.015] px-2 py-1.5 text-left transition-colors hover:bg-white/[0.06]",children:[e.jsx("div",{className:"min-w-0",children:e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx(ut,{level:"milestone",size:11,className:"flex-shrink-0"}),e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-white/52",children:T.hierarchyLabel??it("milestone")}),e.jsx("span",{className:"truncate text-caption text-bright",children:T.title})]})}),e.jsx("span",{className:`text-micro px-1.5 py-0.5 rounded-full border uppercase tracking-[0.08em] ${zs(T.status)}`,children:ze(T.status)})]},T.id))})]}),Z.length>0&&e.jsxs("article",{className:"rounded-xl border border-white/[0.08] bg-white/[0.015] px-3 py-2.5",children:[e.jsx("p",{className:"text-micro uppercase tracking-[0.1em] text-white/50",children:"Unscoped tasks"}),e.jsxs("p",{className:"mt-1 text-caption text-muted",children:[Z.length," task",Z.length===1?"":"s"," without a workstream or milestone."]})]})]})]}),e.jsx("div",{className:"h-px bg-gradient-to-r from-transparent via-white/[0.06] to-transparent"}),e.jsx(Hs,{entityType:"initiative",entityId:t.id,authToken:o,embedMode:l}),e.jsx("div",{className:"space-y-2",children:e.jsx(Us,{entityType:"initiative",entityId:t.id,authToken:o,embedMode:l})})]})]}),e.jsx("div",{className:"border-t border-subtle bg-[#070b12]/85 px-6 py-3 backdrop-blur",children:e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[V&&e.jsx(we,{label:"Pause",color:z.amber,onClick:()=>De("pause","paused","Initiative paused."),disabled:ae}),pe&&e.jsx(we,{label:U==="paused"?"Resume":"Start",color:z.lime,variant:"primary",onClick:()=>De("resume","active",U==="paused"?"Initiative resumed.":"Initiative started."),disabled:ae}),e.jsx(Qs,{label:"Queue",size:"md",busy:Se,disabled:ae||Ue.length===0,title:`Queue initiative: ${t.name}`,onSelectPlacement:Be}),L?e.jsxs(e.Fragment,{children:[e.jsx(we,{label:"Save",color:z.teal,variant:"primary",onClick:We,disabled:ae||!b.trim()}),e.jsx(we,{label:"Cancel",variant:"ghost",onClick:()=>{g(!1),k(t.name),F(t.description??""),re(gs(t.priority)),O(hn(t.targetDate)),m(null)},disabled:ae})]}):e.jsx(we,{label:"Edit",variant:"ghost",onClick:()=>{g(!0),m(null)},disabled:ae}),e.jsx("div",{className:"flex-1"}),e.jsxs("div",{className:"relative",ref:M,children:[e.jsx("button",{type:"button",className:"rounded-lg border border-white/10 bg-white/5 px-2 py-1.5 text-secondary hover:bg-white/10 hover:text-primary transition-colors text-sm leading-none",onClick:()=>{S(T=>!T),v(!1)},"aria-label":"More actions",disabled:ae,children:"⋯"}),y&&e.jsx("div",{className:"popover-enter absolute bottom-full right-0 mb-1 min-w-[160px] rounded-lg border border-white/10 bg-[#0c1322] shadow-xl z-50",children:d?e.jsxs("div",{className:"flex flex-col gap-1 p-2",children:[e.jsx("span",{className:"text-caption text-secondary px-2",children:"Delete initiative?"}),e.jsx("button",{type:"button",className:"w-full text-left rounded-md px-3 py-1.5 text-sm hover:bg-white/5 transition-colors",style:{color:z.red},onClick:()=>c.deleteEntity.mutate({type:"initiative",id:t.id},{onSuccess:()=>n(),onError:T=>m(T instanceof Error?T.message:"Failed to delete initiative.")}),disabled:ae,children:"Confirm Delete"}),e.jsx("button",{type:"button",className:"w-full text-left rounded-md px-3 py-1.5 text-sm text-secondary hover:bg-white/5 transition-colors",onClick:()=>v(!1),disabled:ae,children:"Cancel"})]}):e.jsx("div",{className:"p-1",children:e.jsx("button",{type:"button",className:"w-full text-left rounded-md px-3 py-1.5 text-sm hover:bg-white/5 transition-colors",style:{color:z.red},onClick:()=>v(!0),disabled:ae,children:"Delete"})})})]}),f?e.jsxs("form",{className:"flex flex-wrap items-center gap-2",onSubmit:T=>{T.preventDefault(),p.trim()&&c.createEntity.mutate({type:"workstream",title:p.trim(),initiative_id:t.id,status:"not_started"},{onSuccess:()=>{E(""),j(!1)}})},children:[e.jsx("input",{type:"text",value:p,onChange:T=>E(T.target.value),placeholder:"Workstream name...",autoFocus:!0,className:"text-body bg-white/5 border border-white/10 rounded-lg px-2.5 py-1.5 text-primary placeholder-white/30 w-[180px] outline-none focus:border-white/25"}),e.jsx(we,{type:"submit",label:"Add",color:z.lime,disabled:!p.trim()||c.createEntity.isPending,size:"sm"}),e.jsx(we,{label:"Cancel",variant:"ghost",onClick:()=>{j(!1),E("")},size:"sm"})]}):e.jsx(we,{label:"+ Workstream",variant:"ghost",onClick:()=>j(!0),disabled:ae})]})})]})}function hn(t){if(!t)return"";const s=Date.parse(t);return Number.isFinite(s)?new Date(s).toISOString().slice(0,10):""}function Ei(t){return(t??"").trim().toLowerCase().replace(/[\s-]+/g,"_")}function gs(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 Ai(t){const s=gs(t);return s==="critical"?"Priority: Critical":s==="high"?"Priority: High":s==="low"?"Priority: Low":"Priority: Medium"}function Mi(t){return t?fa(t):"—"}function Ti({workstream:t,initiative:s}){const{agentEntityMap:a,openModal:n,closeModal:o,authToken:l,embedMode:c,mutations:h}=Ht(),f=a.get(t.id)??a.get(s.id)??[],[j,p]=r.useState(!1),[E,L]=r.useState(""),[g,d]=r.useState(!1),[v,y]=r.useState(!1),[S,M]=r.useState(!1),R=r.useRef(null),[m,b]=r.useState(null),[k,$]=r.useState(t.name),[F,te]=r.useState(t.summary??""),[re,X]=r.useState(t.status);r.useEffect(()=>{if(!S)return;const x=Z=>{R.current&&!R.current.contains(Z.target)&&M(!1)},Y=Z=>{Z.key==="Escape"&&M(!1)};return document.addEventListener("mousedown",x),document.addEventListener("keydown",Y),()=>{document.removeEventListener("mousedown",x),document.removeEventListener("keydown",Y)}},[S]);const{details:O,isLoading:w}=ks({initiativeId:s.id,authToken:l,embedMode:c}),Q=js({authToken:l,embedMode:c}),A=r.useMemo(()=>O.milestones.filter(x=>x.workstreamId===t.id),[O.milestones,t.id]),H=r.useMemo(()=>new Set(A.map(x=>x.id)),[A]),K=r.useMemo(()=>O.tasks.filter(x=>x.workstreamId===t.id||x.milestoneId!==null&&H.has(x.milestoneId)).sort((x,Y)=>{const Z=typeof x.sequenceIndex=="number"?x.sequenceIndex:Number.POSITIVE_INFINITY,ge=typeof Y.sequenceIndex=="number"?Y.sequenceIndex:Number.POSITIVE_INFINITY;if(Z!==ge)return Z-ge;const De=x.createdAt?Date.parse(x.createdAt):0,We=Y.createdAt?Date.parse(Y.createdAt):0;return De-We}),[O.tasks,H,t.id]),de=r.useMemo(()=>{const x=new Map;for(const Y of K){if(!Y.milestoneId)continue;const Z=x.get(Y.milestoneId);Z?Z.push(Y):x.set(Y.milestoneId,[Y])}return x},[K]),q=r.useMemo(()=>K.filter(x=>!x.milestoneId),[K]),P=K.filter(x=>Je(x.status)).length,B=K.length>0?ts(P,K.length):typeof t.progress=="number"?Ws(t.progress<=1?t.progress*100:t.progress):Je(t.status)?100:null,U=t.status.toLowerCase(),V=h.entityAction.isPending||h.createEntity.isPending||h.updateEntity.isPending||h.deleteEntity.isPending,pe=Q.isPinning||Q.isMoving,ae=(x,Y)=>x&&x.trim().length>0?Nt(x.trim()):Y,Se=(x,Y,Z)=>{b(null),h.entityAction.mutate({type:"workstream",id:t.id,action:x},{onSuccess:()=>b(Y),onError:ge=>{b(ae(ge instanceof Error?ge.message:"",Z))}})},Ue=()=>{const x=k.trim();if(!x){b("Workstream name is required.");return}b(null),h.updateEntity.mutate({type:"workstream",id:t.id,title:x,summary:F.trim()||null,status:re},{onSuccess:()=>{d(!1),b("Workstream updated.")},onError:Y=>{b(ae(Y instanceof Error?Y.message:"","Failed to update workstream."))}})},Ke=async x=>{b(null);try{await Q.pin({initiativeId:s.id,workstreamId:t.id}),await Q.move({initiativeId:s.id,workstreamId:t.id,placement:x}),b(`Queued workstream to ${x==="top"?"top":"end"}.`)}catch(Y){b(ae(Y instanceof Error?Y.message:"","Failed to queue workstream."))}};return e.jsxs("div",{className:"flex h-full w-full min-h-0 flex-col",children:[e.jsxs("div",{className:"min-h-0 flex-1 space-y-5 overflow-y-auto p-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ut,{level:"workstream",size:16}),e.jsx("h2",{className:"text-title font-semibold text-white",children:t.name}),e.jsx("span",{className:"rounded-full border border-white/[0.12] bg-white/[0.04] px-1.5 py-0.5 text-micro font-semibold uppercase tracking-[0.08em] text-white/65",children:t.hierarchyLabel??it("workstream")}),e.jsx("span",{className:`text-micro px-2.5 py-0.5 rounded-full border uppercase tracking-[0.08em] ${Tr(t.status)}`,children:ze(t.status)})]}),g?e.jsxs("div",{className:"space-y-2 rounded-xl border border-white/[0.08] bg-white/[0.02] p-3",children:[e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:"Name"}),e.jsx("input",{type:"text",value:k,onChange:x=>$(x.target.value),className:"mt-1 w-full rounded-lg border border-white/15 bg-white/[0.06] px-3 py-2 text-body text-bright outline-none focus:border-white/30"})]}),e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:"Summary"}),e.jsx("textarea",{value:F,onChange:x=>te(x.target.value),rows:3,className:"mt-1 w-full resize-y rounded-lg border border-white/15 bg-white/[0.06] px-3 py-2 text-body text-bright outline-none focus:border-white/30"})]}),e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:"Status"}),e.jsx("select",{value:re,onChange:x=>X(x.target.value),className:"mt-1 w-full rounded-lg border border-white/15 bg-white/[0.06] px-3 py-2 text-body text-bright outline-none focus:border-white/30",children:["not_started","planned","active","in_progress","paused","blocked","done"].map(x=>e.jsx("option",{value:x,children:ze(x)},x))})]})]}):t.summary?e.jsx("p",{className:"text-body text-secondary leading-relaxed",children:t.summary}):e.jsx("p",{className:"text-body text-muted",children:"No summary yet."}),f.length>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-micro text-muted uppercase tracking-wider",children:"Agents"}),e.jsx(Sn,{agents:f,max:6})]}),m&&e.jsx("div",{className:"text-caption text-secondary",children:m})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-caption text-secondary",children:[K.length," ",K.length===1?"task":"tasks"," · ",P,"/",K.length," done",A.length>0&&` · ${A.length} milestone${A.length===1?"":"s"}`]}),B!==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(B,2)}%`,backgroundColor:z.lime}})}),e.jsxs("span",{className:"text-micro text-secondary tabular-nums",children:[B,"%"]})]})]}),w?e.jsx("div",{className:"space-y-2",children:Array.from({length:3}).map((x,Y)=>e.jsx($t,{className:"h-12 w-full rounded-lg"},`ws-detail-${Y}`))}):e.jsxs(e.Fragment,{children:[(A.length>0||q.length>0)&&e.jsxs("section",{className:"space-y-3",children:[e.jsx("h3",{className:"text-[11px] font-semibold uppercase tracking-[0.12em] text-white/55",children:"IWMT Composition"}),e.jsxs("div",{className:"space-y-2.5",children:[A.map(x=>{const Y=de.get(x.id)??[],Z=Y.filter(ge=>Je(ge.status)).length;return e.jsxs("article",{className:"rounded-xl border border-white/[0.08] bg-white/[0.02] px-3 py-2.5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("button",{onClick:()=>n({type:"milestone",entity:x,initiative:s}),className:"group min-w-0 flex-1 text-left",children:e.jsxs("div",{className:"flex min-w-0 items-start gap-2.5",children:[e.jsx("span",{className:"mt-0.5 inline-flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-md border border-white/[0.12] bg-white/[0.04]",children:e.jsx(ut,{level:"milestone",size:12})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("span",{className:"text-micro font-semibold uppercase tracking-[0.08em] text-white/58",children:x.hierarchyLabel??it("milestone")}),e.jsx("span",{className:"truncate text-body text-bright",children:x.title})]}),e.jsxs("p",{className:"mt-0.5 text-caption text-muted",children:[Z,"/",Y.length," tasks done"]})]})]})}),e.jsx("span",{className:`text-micro px-1.5 py-0.5 rounded-full border uppercase tracking-[0.08em] ${zs(x.status)}`,children:ze(x.status)})]}),e.jsx("div",{className:"ml-7 mt-2.5 border-l border-white/[0.08] pl-3",children:Y.length>0?e.jsx("div",{className:"space-y-1.5",children:Y.map(ge=>e.jsxs("button",{onClick:()=>n({type:"task",entity:ge,initiative:s}),className:"flex w-full items-center justify-between gap-2 rounded-lg bg-white/[0.015] px-2 py-1.5 text-left transition-colors hover:bg-white/[0.06]",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx(ut,{level:"task",size:11,className:"flex-shrink-0"}),e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-white/50",children:ge.hierarchyLabel??it("task")}),e.jsx("span",{className:"truncate text-caption text-bright",children:ge.title})]}),ge.priority&&e.jsx("p",{className:"mt-0.5 text-micro uppercase tracking-[0.08em] text-muted",children:ge.priority})]}),e.jsx("span",{className:`text-micro px-1.5 py-0.5 rounded-full border uppercase tracking-[0.08em] ${yn(ge.status)}`,children:ze(ge.status)})]},ge.id))}):e.jsx("p",{className:"rounded-lg border border-dashed border-white/[0.1] bg-white/[0.01] px-3 py-2 text-micro text-muted",children:"No tasks yet."})})]},x.id)}),q.length>0&&e.jsxs("article",{className:"rounded-xl border border-white/[0.08] bg-white/[0.015] px-3 py-2.5",children:[e.jsx("p",{className:"text-micro uppercase tracking-[0.1em] text-white/50",children:"Unscoped tasks"}),e.jsx("div",{className:"mt-2 space-y-1.5",children:q.map(x=>e.jsxs("button",{onClick:()=>n({type:"task",entity:x,initiative:s}),className:"flex w-full items-center justify-between gap-2 rounded-lg bg-white/[0.015] px-2 py-1.5 text-left transition-colors hover:bg-white/[0.06]",children:[e.jsx("div",{className:"min-w-0",children:e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx(ut,{level:"task",size:11,className:"flex-shrink-0"}),e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-white/50",children:x.hierarchyLabel??it("task")}),e.jsx("span",{className:"truncate text-caption text-bright",children:x.title})]})}),e.jsx("span",{className:`text-micro px-1.5 py-0.5 rounded-full border uppercase tracking-[0.08em] ${yn(x.status)}`,children:ze(x.status)})]},x.id))})]})]})]}),e.jsx("div",{className:"h-px bg-gradient-to-r from-transparent via-white/[0.06] to-transparent"}),e.jsx(Hs,{entityType:"workstream",entityId:t.id,title:"Artifacts (from milestones)",authToken:l,embedMode:c,finalOnly:!0,milestoneIds:A.map(x=>x.id)}),e.jsx("div",{className:"space-y-2",children:e.jsx(Us,{entityType:"workstream",entityId:t.id,authToken:l,embedMode:c})})]})]}),e.jsx("div",{className:"border-t border-subtle bg-[#070b12]/85 px-6 py-3 backdrop-blur",children:e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[["not_started","planned","todo"].includes(U)&&e.jsx(we,{label:"Start",color:z.lime,variant:"primary",onClick:()=>Se("start","Workstream started.","Failed to start workstream."),disabled:V}),["active","in_progress"].includes(U)&&e.jsxs(e.Fragment,{children:[e.jsx(we,{label:"Complete",color:z.teal,variant:"primary",onClick:()=>Se("complete","Workstream marked complete.","Failed to complete workstream."),disabled:V}),e.jsx(we,{label:"Pause",color:z.amber,onClick:()=>Se("pause","Workstream paused.","Failed to pause workstream."),disabled:V}),e.jsx(we,{label:"Block",color:z.red,variant:"destructive",onClick:()=>Se("block","Workstream blocked.","Failed to block workstream."),disabled:V})]}),["paused","blocked"].includes(U)&&e.jsx(we,{label:"Resume",color:z.lime,variant:"primary",onClick:()=>Se("resume","Workstream resumed.","Failed to resume workstream."),disabled:V}),e.jsx(Qs,{label:"Queue",size:"md",busy:pe,disabled:V,title:`Queue workstream: ${t.name}`,onSelectPlacement:Ke}),g?e.jsxs(e.Fragment,{children:[e.jsx(we,{label:"Save",color:z.teal,variant:"primary",onClick:Ue,disabled:V||!k.trim()}),e.jsx(we,{label:"Cancel",variant:"ghost",onClick:()=>{d(!1),$(t.name),te(t.summary??""),X(t.status),b(null)},disabled:V})]}):e.jsx(we,{label:"Edit",variant:"ghost",onClick:()=>{d(!0),b(null)},disabled:V}),e.jsx("div",{className:"flex-1"}),e.jsxs("div",{className:"relative",ref:R,children:[e.jsx("button",{type:"button",className:"rounded-lg border border-white/10 bg-white/5 px-2 py-1.5 text-secondary hover:bg-white/10 hover:text-primary transition-colors text-sm leading-none",onClick:()=>{M(x=>!x),y(!1)},"aria-label":"More actions",disabled:V,children:"⋯"}),S&&e.jsx("div",{className:"popover-enter absolute bottom-full right-0 mb-1 min-w-[160px] rounded-lg border border-white/10 bg-[#0c1322] shadow-xl z-50",children:v?e.jsxs("div",{className:"flex flex-col gap-1 p-2",children:[e.jsx("span",{className:"text-caption text-secondary px-2",children:"Delete workstream?"}),e.jsx("button",{type:"button",className:"w-full text-left rounded-md px-3 py-1.5 text-sm hover:bg-white/5 transition-colors",style:{color:z.red},onClick:()=>h.deleteEntity.mutate({type:"workstream",id:t.id},{onSuccess:()=>o(),onError:x=>b(ae(x instanceof Error?x.message:"","Failed to delete workstream."))}),disabled:V,children:"Confirm Delete"}),e.jsx("button",{type:"button",className:"w-full text-left rounded-md px-3 py-1.5 text-sm text-secondary hover:bg-white/5 transition-colors",onClick:()=>y(!1),disabled:V,children:"Cancel"})]}):e.jsx("div",{className:"p-1",children:e.jsx("button",{type:"button",className:"w-full text-left rounded-md px-3 py-1.5 text-sm hover:bg-white/5 transition-colors",style:{color:z.red},onClick:()=>y(!0),disabled:V,children:"Delete"})})})]}),j?e.jsxs("form",{className:"flex flex-wrap items-center gap-2",onSubmit:x=>{x.preventDefault(),E.trim()&&h.createEntity.mutate({type:"task",title:E.trim(),workstream_id:t.id,initiative_id:s.id,status:"todo"},{onSuccess:()=>{L(""),p(!1)},onError:Y=>{b(ae(Y instanceof Error?Y.message:"","Failed to create task."))}})},children:[e.jsx("input",{type:"text",value:E,onChange:x=>L(x.target.value),placeholder:"Task title...",autoFocus:!0,className:"text-body bg-white/5 border border-white/10 rounded-lg px-2.5 py-1.5 text-primary placeholder-white/30 w-[160px] outline-none focus:border-white/25"}),e.jsx(we,{label:"Add",color:z.lime,type:"submit",size:"sm",disabled:!E.trim()||h.createEntity.isPending}),e.jsx(we,{label:"Cancel",variant:"ghost",size:"sm",onClick:()=>{p(!1),L("")}})]}):e.jsx(we,{label:"+ Task",variant:"ghost",onClick:()=>p(!0),disabled:V})]})})]})}function Di({milestone:t,initiative:s}){const{openModal:a,closeModal:n,authToken:o,embedMode:l,mutations:c}=Ht(),[h,f]=r.useState(!1),[j,p]=r.useState(!1),[E,L]=r.useState(!1),g=r.useRef(null),[d,v]=r.useState(!1),[y,S]=r.useState(""),[M,R]=r.useState(null),[m,b]=r.useState(t.title),[k,$]=r.useState(t.description??""),[F,te]=r.useState(mr(t.dueDate)),[re,X]=r.useState(t.status);r.useEffect(()=>{if(!E)return;const P=U=>{g.current&&!g.current.contains(U.target)&&L(!1)},B=U=>{U.key==="Escape"&&L(!1)};return document.addEventListener("mousedown",P),document.addEventListener("keydown",B),()=>{document.removeEventListener("mousedown",P),document.removeEventListener("keydown",B)}},[E]);const{details:O}=ks({initiativeId:s.id,authToken:o,embedMode:l}),w=O.tasks.filter(P=>P.milestoneId===t.id);O.workstreams.find(P=>P.id===t.workstreamId);const Q=t.status.toLowerCase()==="done"||t.status.toLowerCase()==="completed",A=w.filter(P=>Je(P.status)).length,H=w.length>0?ts(A,w.length):Q?100:0,K=c.entityAction.isPending||c.createEntity.isPending||c.updateEntity.isPending||c.deleteEntity.isPending,de=(P,B)=>P&&P.trim().length>0?Nt(P.trim()):B,q=()=>{const P=m.trim();if(!P){R("Milestone title is required.");return}R(null),c.updateEntity.mutate({type:"milestone",id:t.id,title:P,description:k.trim()||null,due_date:F||null,status:re},{onSuccess:()=>{f(!1),R("Milestone updated.")},onError:B=>{R(de(B instanceof Error?B.message:"","Failed to update milestone."))}})};return e.jsxs("div",{className:"flex h-full w-full min-h-0 flex-col",children:[e.jsxs("div",{className:"min-h-0 flex-1 space-y-5 overflow-y-auto p-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ut,{level:"milestone",size:16}),e.jsx("h2",{className:"text-title font-semibold text-white",children:t.title}),e.jsx("span",{className:"rounded-full border border-white/[0.12] bg-white/[0.04] px-1.5 py-0.5 text-micro font-semibold uppercase tracking-[0.08em] text-white/65",children:t.hierarchyLabel??it("milestone")}),e.jsx("span",{className:`text-micro px-2.5 py-0.5 rounded-full border uppercase tracking-[0.08em] ${zs(t.status)}`,children:ze(t.status)})]}),h?e.jsxs("div",{className:"space-y-2 rounded-xl border border-white/[0.08] bg-white/[0.02] p-3",children:[e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:"Title"}),e.jsx("input",{type:"text",value:m,onChange:P=>b(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=>$(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-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:F,onChange:P=>te(P.target.value),className:"mt-1 w-full rounded-lg border border-white/15 bg-white/[0.06] px-3 py-2 text-body text-bright outline-none focus:border-white/30"})]}),e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:"Status"}),e.jsx("select",{value:re,onChange:P=>X(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:["planned","active","in_progress","at_risk","blocked","done"].map(P=>e.jsx("option",{value:P,children:ze(P)},P))})]})]})]}):t.description?e.jsx("p",{className:"text-body text-secondary leading-relaxed",children:t.description}):e.jsx("p",{className:"text-body text-muted",children:"No description yet."}),M&&e.jsx("div",{className:"text-caption text-secondary",children:M})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-caption text-secondary",children:[e.jsxs("span",{children:[w.length," ",w.length===1?"task":"tasks"]}),e.jsx("span",{className:"text-faint",children:"·"}),e.jsxs("span",{style:{fontVariantNumeric:"tabular-nums"},children:[A,"/",w.length," done"]}),t.dueDate&&(()=>{const P=Date.parse(t.dueDate);if(!Number.isFinite(P))return null;const B=Math.ceil((P-Date.now())/864e5),U=B<0?z.red:B<=3?z.red:B<=7?z.amber:"rgba(255,255,255,0.5)",V=B<0?`${Math.abs(B)}d overdue`:`Due in ${B}d`;return e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-faint",children:"·"}),e.jsx("span",{style:{color:U},children:V})]})})()]}),w.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(H,2)}%`,backgroundColor:z.teal}})}),e.jsxs("span",{className:"text-micro text-secondary tabular-nums",children:[H,"%"]})]})]}),e.jsxs("section",{className:"space-y-3",children:[e.jsx("h3",{className:"text-[11px] font-semibold uppercase tracking-[0.12em] text-white/55",children:"IWMT Composition"}),w.length>0?e.jsx("div",{className:"rounded-xl border border-white/[0.08] bg-white/[0.02] px-3 py-2.5",children:e.jsx("div",{className:"space-y-1.5",children:w.map(P=>e.jsxs("button",{onClick:()=>a({type:"task",entity:P,initiative:s}),className:"flex w-full items-center justify-between gap-2 rounded-lg bg-white/[0.015] px-2 py-1.5 text-left transition-colors hover:bg-white/[0.06]",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx(ut,{level:"task",size:11,className:"flex-shrink-0"}),e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-white/50",children:P.hierarchyLabel??it("task")}),e.jsx("span",{className:"truncate text-caption text-bright",children:P.title})]}),P.priority&&e.jsx("p",{className:"mt-0.5 text-micro uppercase tracking-[0.08em] text-muted",children:P.priority})]}),e.jsx("span",{className:`text-micro px-1.5 py-0.5 rounded-full border uppercase tracking-[0.08em] ${yn(P.status)}`,children:ze(P.status)})]},P.id))})}):e.jsx("div",{className:"rounded-xl border border-dashed border-white/[0.1] bg-white/[0.01] px-3 py-2 text-micro text-muted",children:"No tasks linked to this milestone yet."})]}),e.jsx("div",{className:"h-px bg-gradient-to-r from-transparent via-white/[0.06] to-transparent"}),e.jsx(Hs,{entityType:"milestone",entityId:t.id,authToken:o,embedMode:l}),e.jsx("div",{className:"space-y-2",children:e.jsx(Us,{entityType:"milestone",entityId:t.id,authToken:o,embedMode:l})})]}),e.jsx("div",{className:"border-t border-subtle bg-[#070b12]/85 px-6 py-3 backdrop-blur",children:e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[!Q&&t.status.toLowerCase()==="planned"&&e.jsx(we,{label:"Start",color:z.lime,variant:"primary",onClick:()=>c.entityAction.mutate({type:"milestone",id:t.id,action:"start"}),disabled:K}),!Q&&(t.status.toLowerCase()==="in_progress"||t.status.toLowerCase()==="at_risk")&&e.jsx(we,{label:w.length>0&&!w.every(P=>Je(P.status))?"Complete (force)":"Complete",color:z.teal,variant:"primary",onClick:()=>{const P=w.length===0||w.every(B=>Je(B.status));c.entityAction.mutate({type:"milestone",id:t.id,action:"complete",force:!P})},disabled:K}),h?e.jsxs(e.Fragment,{children:[e.jsx(we,{label:"Save",color:z.teal,variant:"primary",onClick:q,disabled:K||!m.trim()}),e.jsx(we,{label:"Cancel",variant:"ghost",onClick:()=>{f(!1),b(t.title),$(t.description??""),te(mr(t.dueDate)),X(t.status),R(null)},disabled:K})]}):e.jsx(we,{label:"Edit",variant:"ghost",onClick:()=>{f(!0),R(null)},disabled:K}),e.jsx("div",{className:"flex-1"}),e.jsxs("div",{className:"relative",ref:g,children:[e.jsx("button",{type:"button",className:"rounded-lg border border-white/10 bg-white/5 px-2 py-1.5 text-secondary hover:bg-white/10 hover:text-primary transition-colors text-sm leading-none",onClick:()=>{L(P=>!P),p(!1)},"aria-label":"More actions",disabled:K,children:"⋯"}),E&&e.jsx("div",{className:"popover-enter absolute bottom-full right-0 mb-1 min-w-[160px] rounded-lg border border-white/10 bg-[#0c1322] shadow-xl z-50",children:j?e.jsxs("div",{className:"flex flex-col gap-1 p-2",children:[e.jsx("span",{className:"text-caption text-secondary px-2",children:"Delete milestone?"}),e.jsx("button",{type:"button",className:"w-full text-left rounded-md px-3 py-1.5 text-sm hover:bg-white/5 transition-colors",style:{color:z.red},onClick:()=>c.deleteEntity.mutate({type:"milestone",id:t.id},{onSuccess:()=>n(),onError:P=>R(de(P instanceof Error?P.message:"","Failed to delete milestone."))}),disabled:K,children:"Confirm Delete"}),e.jsx("button",{type:"button",className:"w-full text-left rounded-md px-3 py-1.5 text-sm text-secondary hover:bg-white/5 transition-colors",onClick:()=>p(!1),disabled:K,children:"Cancel"})]}):e.jsx("div",{className:"p-1",children:e.jsx("button",{type:"button",className:"w-full text-left rounded-md px-3 py-1.5 text-sm hover:bg-white/5 transition-colors",style:{color:z.red},onClick:()=>p(!0),disabled:K,children:"Delete"})})})]}),d?e.jsxs("form",{className:"flex flex-wrap items-center gap-2",onSubmit:P=>{P.preventDefault(),y.trim()&&c.createEntity.mutate({type:"task",title:y.trim(),milestone_id:t.id,workstream_id:t.workstreamId??void 0,initiative_id:s.id,status:"todo"},{onSuccess:()=>{S(""),v(!1)},onError:B=>{R(de(B instanceof Error?B.message:"","Failed to create task."))}})},children:[e.jsx("input",{type:"text",value:y,onChange:P=>S(P.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(we,{label:"Add",color:z.lime,type:"submit",size:"sm",disabled:!y.trim()||c.createEntity.isPending}),e.jsx(we,{label:"Cancel",variant:"ghost",size:"sm",onClick:()=>{v(!1),S("")}})]}):e.jsx(we,{label:"+ Task",variant:"ghost",onClick:()=>v(!0),disabled:K})]})})]})}function mr(t){if(!t)return"";const s=Date.parse(t);return Number.isFinite(s)?new Date(s).toISOString().slice(0,10):""}function $i(t){if(!t)return null;const s=Date.parse(t);if(!Number.isFinite(s))return null;const a=Date.now(),n=Math.ceil((s-a)/864e5);return n<0?{text:`${Math.abs(n)}d overdue`,tone:z.red}:n<=3?{text:`Due in ${n}d`,tone:z.red}:n<=7?{text:`Due in ${n}d`,tone:z.amber}:{text:`Due ${new Date(s).toLocaleDateString()}`,tone:"rgba(255,255,255,0.5)"}}function Li(t){const s=t.toLowerCase();return["active","in_progress","running"].includes(s)?$s.active.text:["done","completed"].includes(s)?$s.done.text:s==="blocked"?$s.blocked.text:$s.planned.text}function _i({task:t,initiative:s}){const{agentEntityMap:a,openModal:n,mutations:o,closeModal:l,authToken:c,embedMode:h}=Ht(),{details:f}=ks({initiativeId:s.id,authToken:c,embedMode:h}),j=a.get(t.id)??a.get(s.id)??[],[p,E]=r.useState(!1),[L,g]=r.useState(!1),d=r.useRef(null),[v,y]=r.useState(!1),[S,M]=r.useState(null),[R,m]=r.useState(t.title),[b,k]=r.useState(t.description??""),[$,F]=r.useState(t.priority??""),[te,re]=r.useState(pr(t.dueDate)),[X,O]=r.useState(t.status),w=t.status.toLowerCase(),Q=r.useMemo(()=>$i(t.dueDate),[t.dueDate]),A=r.useMemo(()=>f.milestones.find(U=>U.id===t.milestoneId),[f.milestones,t.milestoneId]),H=r.useMemo(()=>{if(t.workstreamId)return f.workstreams.find(U=>U.id===t.workstreamId);if(A!=null&&A.workstreamId)return f.workstreams.find(U=>U.id===A.workstreamId)},[f.workstreams,A==null?void 0:A.workstreamId,t.workstreamId]),K=(U,V)=>U&&U.trim().length>0?Nt(U.trim()):V,de=o.entityAction.isPending||o.updateEntity.isPending||o.deleteEntity.isPending,q=U=>{M(null),o.entityAction.mutate({type:"task",id:t.id,action:U},{onError:V=>{M(K(V instanceof Error?V.message:"","Task action failed."))}})},P=()=>{const U=R.trim();if(!U){M("Task title is required.");return}M(null),o.updateEntity.mutate({type:"task",id:t.id,title:U,description:b.trim()||null,priority:$.trim()||null,due_date:te||null,status:X},{onSuccess:()=>{y(!1),M("Task updated.")},onError:V=>{M(K(V instanceof Error?V.message:"","Failed to update task."))}})},B=()=>{M(null),o.deleteEntity.mutate({type:"task",id:t.id},{onSuccess:()=>l(),onError:U=>{M(K(U instanceof Error?U.message:"","Failed to delete task."))}})};return r.useEffect(()=>{if(!L)return;const U=pe=>{d.current&&!d.current.contains(pe.target)&&g(!1)},V=pe=>{pe.key==="Escape"&&g(!1)};return document.addEventListener("mousedown",U),document.addEventListener("keydown",V),()=>{document.removeEventListener("mousedown",U),document.removeEventListener("keydown",V)}},[L]),e.jsxs("div",{className:"flex h-full w-full min-h-0 flex-col",children:[e.jsxs("div",{className:"min-h-0 flex-1 space-y-5 overflow-y-auto p-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(ut,{level:"task",size:16}),e.jsx("h2",{className:"break-words text-title font-semibold text-white",children:t.title}),e.jsx("span",{className:"rounded-full border border-white/[0.12] bg-white/[0.04] px-1.5 py-0.5 text-micro font-semibold uppercase tracking-[0.08em] text-white/65",children:t.hierarchyLabel??it("task")})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-caption text-secondary",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx("span",{className:"inline-block h-1.5 w-1.5 rounded-full",style:{backgroundColor:Li(t.status)}}),ze(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})]}),Q&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-faint",children:"·"}),e.jsx("span",{style:{color:Q.tone},children:Q.text})]})]}),(H||A)&&e.jsxs("div",{className:"rounded-xl border border-white/[0.08] bg-white/[0.02] px-3 py-2.5",children:[e.jsx("p",{className:"text-micro uppercase tracking-[0.1em] text-white/50",children:"IWMT scope"}),e.jsxs("div",{className:"mt-2 space-y-1.5",children:[H&&e.jsxs("button",{type:"button",onClick:()=>n({type:"workstream",entity:H,initiative:s}),className:"flex w-full items-center gap-2 rounded-lg bg-white/[0.015] px-2 py-1.5 text-left transition-colors hover:bg-white/[0.06]",children:[e.jsx(ut,{level:"workstream",size:11,className:"flex-shrink-0"}),e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-white/50",children:H.hierarchyLabel??it("workstream")}),e.jsx("span",{className:"truncate text-caption text-bright",children:H.name})]}),A&&e.jsxs("button",{type:"button",onClick:()=>n({type:"milestone",entity:A,initiative:s}),className:"ml-4 flex w-[calc(100%-1rem)] items-center gap-2 rounded-lg bg-white/[0.015] px-2 py-1.5 text-left transition-colors hover:bg-white/[0.06]",children:[e.jsx(ut,{level:"milestone",size:11,className:"flex-shrink-0"}),e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-white/50",children:A.hierarchyLabel??it("milestone")}),e.jsx("span",{className:"truncate text-caption text-bright",children:A.title})]})]})]}),v?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:R,onChange:U=>m(U.target.value),className:"mt-1 w-full rounded-lg border border-white/15 bg-white/[0.06] px-3 py-2 text-body text-bright outline-none focus:border-white/30"})]}),e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:"Description"}),e.jsx("textarea",{value:b,onChange:U=>k(U.target.value),rows:3,className:"mt-1 w-full resize-y rounded-lg border border-white/15 bg-white/[0.06] px-3 py-2 text-body text-bright outline-none focus:border-white/30"})]}),e.jsxs("div",{className:"grid gap-2 sm:grid-cols-3",children:[e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:"Priority"}),e.jsx("input",{type:"text",value:$,onChange:U=>F(U.target.value),placeholder:"p1, high, p50",className:"mt-1 w-full rounded-lg border border-white/15 bg-white/[0.06] px-3 py-2 text-body text-bright outline-none focus:border-white/30"})]}),e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:"Due date"}),e.jsx("input",{type:"date",value:te,onChange:U=>re(U.target.value),className:"mt-1 w-full rounded-lg border border-white/15 bg-white/[0.06] px-3 py-2 text-body text-bright outline-none focus:border-white/30"})]}),e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:"Status"}),e.jsx("select",{value:X,onChange:U=>O(U.target.value),className:"mt-1 w-full rounded-lg border border-white/15 bg-white/[0.06] px-3 py-2 text-body text-bright outline-none focus:border-white/30",children:["not_started","planned","todo","in_progress","active","blocked","done"].map(U=>e.jsx("option",{value:U,children:ze(U)},U))})]})]})]}):t.description?e.jsx(ga,{text:t.description,mode:"block",className:"text-body text-secondary leading-relaxed"}):e.jsx("p",{className:"text-body text-muted",children:"No description yet."}),j.length>0&&e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(Sn,{agents:j,max:4})})]}),S&&e.jsx("div",{className:"text-caption px-1",style:{color:`${z.red}b3`},children:S}),e.jsx("div",{className:"h-px bg-gradient-to-r from-transparent via-white/[0.06] to-transparent"}),e.jsx(Hs,{entityType:"task",entityId:t.id,authToken:c,embedMode:h}),e.jsx("div",{className:"space-y-2",children:e.jsx(Us,{entityType:"task",entityId:t.id,authToken:c,embedMode:h})})]}),e.jsx("div",{className:"border-t border-subtle bg-[#070b12]/85 px-6 py-3 backdrop-blur",children:e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[w==="todo"&&e.jsx(we,{label:"Start",color:z.lime,variant:"primary",onClick:()=>q("start"),disabled:de}),(w==="in_progress"||w==="active")&&e.jsx(we,{label:"Complete",color:z.teal,variant:"primary",onClick:()=>q("complete"),disabled:de}),(w==="todo"||w==="in_progress"||w==="active")&&e.jsx(we,{label:"Block",color:z.red,variant:"destructive",onClick:()=>q("block"),disabled:de}),w==="blocked"&&e.jsx(we,{label:"Unblock",color:z.amber,onClick:()=>q("unblock"),disabled:de}),v?e.jsxs(e.Fragment,{children:[e.jsx(we,{label:"Save",color:z.teal,variant:"primary",onClick:P,disabled:de||!R.trim()}),e.jsx(we,{label:"Cancel",variant:"ghost",onClick:()=>{y(!1),M(null),m(t.title),k(t.description??""),F(t.priority??""),re(pr(t.dueDate)),O(t.status)},disabled:de})]}):e.jsx(we,{label:"Edit",variant:"ghost",onClick:()=>{y(!0),M(null)},disabled:de}),e.jsx("div",{className:"flex-1"}),e.jsxs("div",{className:"relative",ref:d,children:[e.jsx("button",{type:"button",className:"rounded-lg border border-white/10 bg-white/5 px-2 py-1.5 text-secondary hover:bg-white/10 hover:text-primary transition-colors text-sm leading-none",onClick:()=>{g(U=>!U),E(!1)},"aria-label":"More actions",disabled:de,children:"⋯"}),L&&e.jsx("div",{className:"popover-enter absolute bottom-full right-0 mb-1 min-w-[160px] rounded-lg border border-white/10 bg-[#0c1322] shadow-xl z-50",children:p?e.jsxs("div",{className:"flex flex-col gap-1 p-2",children:[e.jsx("span",{className:"text-caption",style:{color:`${z.red}b3`},children:"Delete task?"}),e.jsx("button",{type:"button",className:"w-full text-left rounded-md px-3 py-1.5 text-sm hover:bg-white/5 transition-colors",style:{color:z.red},onClick:B,disabled:de,children:"Confirm Delete"}),e.jsx("button",{type:"button",className:"w-full text-left rounded-md px-3 py-1.5 text-sm text-secondary hover:bg-white/5 transition-colors",onClick:()=>E(!1),disabled:de,children:"Cancel"})]}):e.jsx("div",{className:"p-1",children:e.jsx("button",{type:"button",className:"w-full text-left rounded-md px-3 py-1.5 text-sm hover:bg-white/5 transition-colors",style:{color:z.red},onClick:()=>E(!0),disabled:de,children:"Delete"})})})]})]})})]})}function pr(t){if(!t)return"";const s=Date.parse(t);return Number.isFinite(s)?new Date(s).toISOString().slice(0,10):""}function Pi(t){var a,n;if(t.type==="initiative")return null;if(t.type==="workstream")return t.entity.name;const s=t.entity.workstreamId;return s?((n=(a=t.initiative.workstreams)==null?void 0:a.find(o=>o.id===s))==null?void 0:n.name)??null:null}function Fi(t){if(t.type==="initiative")return[{id:t.entity.id,label:t.entity.name,level:"initiative"}];const s=[{id:t.initiative.id,label:t.initiative.name,level:"initiative"}],a=Pi(t),n=t.type==="workstream"?t.entity.id:t.entity.workstreamId;return a&&n&&s.push({id:n,label:a,level:"workstream"}),t.type==="milestone"?s.push({id:t.entity.id,label:t.entity.title,level:"milestone"}):t.type==="task"&&s.push({id:t.entity.id,label:t.entity.title,level:"task"}),s}function Ri(t){return t.type==="initiative"?t.entity.hierarchyLabel??it("initiative"):t.type==="workstream"?t.entity.hierarchyLabel??it("workstream"):t.type==="milestone"?t.entity.hierarchyLabel??it("milestone"):t.entity.hierarchyLabel??it("task")}function Bi({target:t,onClose:s}){return e.jsx(ba,{open:t!==null,onClose:s,maxWidth:"max-w-5xl",children:t&&e.jsxs("div",{className:"flex h-full w-full min-h-0 flex-col",children:[e.jsx("div",{className:"border-b border-subtle bg-[linear-gradient(180deg,rgba(255,255,255,0.03),rgba(255,255,255,0))] px-5 py-3 sm:px-6",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsx("div",{className:"min-w-0 flex-1",children:e.jsx("div",{className:"-mx-0.5 overflow-x-auto pb-0.5",children:e.jsx("ol",{className:"flex min-w-max items-center gap-1 px-0.5 text-body text-secondary",children:Fi(t).map((a,n,o)=>{const l=n===o.length-1;return e.jsxs("li",{className:"flex min-w-0 items-center gap-1",children:[n>0&&e.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"flex-shrink-0 text-faint","aria-hidden":!0,children:e.jsx("path",{d:"m9 18 6-6-6-6"})}),e.jsx(ut,{level:a.level,size:11,className:`flex-shrink-0 ${l?"opacity-95":"opacity-75"}`}),e.jsx("span",{className:`max-w-[320px] truncate sm:max-w-[420px] ${l?"font-medium text-primary":"text-secondary"}`,children:a.label})]},a.id)})})})}),e.jsxs("span",{className:"inline-flex flex-shrink-0 items-center gap-1.5 rounded-full border border-white/[0.12] bg-white/[0.04] px-2.5 py-1 text-micro uppercase tracking-[0.08em] text-white/72",children:[e.jsx(ut,{level:t.type,size:11,className:"opacity-90"}),e.jsx("span",{className:"font-semibold text-white/82",children:Ri(t)}),e.jsx("span",{children:t.type})]}),e.jsx(le.button,{type:"button",onClick:s,"aria-label":"Close detail",whileHover:{scale:1.06},whileTap:{scale:.92},transition:{duration:.12},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.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:e.jsx(at,{mode:"wait",children:e.jsxs(le.div,{initial:{opacity:0,y:4},animate:{opacity:1,y:0},exit:{opacity:0,y:-4},transition:{duration:.18,ease:[.22,1,.36,1]},children:[t.type==="initiative"&&e.jsx(Ii,{initiative:t.entity}),t.type==="workstream"&&e.jsx(Ti,{workstream:t.entity,initiative:t.initiative}),t.type==="milestone"&&e.jsx(Di,{milestone:t.entity,initiative:t.initiative}),t.type==="task"&&e.jsx(_i,{task:t.entity,initiative:t.initiative})]},`${t.type}-${t.entity.id}`)})})]})})}function xr(t){return(t??"").trim().toLowerCase().replace(/[\s-]+/g,"_")}function Oi(t){return t.split("_").map(s=>s.slice(0,1).toUpperCase()+s.slice(1)).join(" ")}const fn=["active","in_progress","not_started","planned","blocked","at_risk","paused","completed","done","backlog","todo","pending","draft"],qi=[{value:"target",label:"Target date"},{value:"created",label:"Created at"},{value:"updated",label:"Updated at"}],zi=[{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"}],Ui=[{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:a,dateField:n,datePreset:o,dateStart:l,dateEnd:c,activeFilterCount:h,groupBy:f,setGroupBy:j,sortBy:p,setSortBy:E,setStatusFilters:L,toggleStatusFilter:g,setDateField:d,setDatePreset:v,setDateStart:y,setDateEnd:S,clearFilters:M}=Ht(),[R,m]=r.useState(!1),[b,k]=r.useState(!1),$=r.useRef(null);r.useEffect(()=>{if(!R)return;const q=B=>{var V;const U=B.target;U&&((V=$.current)!=null&&V.contains(U)||m(!1))},P=B=>{B.key==="Escape"&&m(!1)};return document.addEventListener("mousedown",q),document.addEventListener("keydown",P),()=>{document.removeEventListener("mousedown",q),document.removeEventListener("keydown",P)}},[R]);const F=r.useMemo(()=>{const q=new Map;for(const B of t){const U=new Set([xr(B.status),xr(B.rawStatus)]);for(const V of U)V&&q.set(V,(q.get(V)??0)+1)}for(const B of fn)q.has(B)||q.set(B,0);return Array.from(q.entries()).sort((B,U)=>{const V=fn.indexOf(B[0]),pe=fn.indexOf(U[0]);return V>=0&&pe>=0?V-pe:V>=0?-1:pe>=0?1:B[0].localeCompare(U[0])}).map(([B,U])=>({key:B,count:U}))},[t]),te=a.length,re=r.useMemo(()=>F.filter(q=>b||q.count>0||a.includes(q.key)),[b,a,F]),X=F.length-re.length,O=r.useMemo(()=>n==="target"?zi:Ui,[n]);r.useEffect(()=>{O.some(q=>q.value===o)||v("any")},[o,O,v]);const w=[{value:"none",label:"None"},{value:"status",label:"Status"},{value:"date",label:"Date"},{value:"category",label:"Category"}],Q=[{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)"}],A=f!=="status"||p!=="default",H=h>0,K=h,de=H||A;return e.jsxs("div",{ref:$,className:"relative flex items-center gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>{m(q=>{const P=!q;return P||k(!1),P})},"data-state":R||K>0?"active":"idle",className:"control-pill flex items-center gap-1.5 px-3 text-caption font-semibold",children:[e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e.jsx("path",{d:"M22 3H2l8 9.46V19l4 2v-8.54L22 3z"})}),e.jsx("span",{children:"Filters"}),K>0&&e.jsx("span",{className:"inline-flex min-w-[16px] items-center justify-center rounded-full border border-current/30 bg-black/25 px-1 text-micro leading-4",children:K})]}),s<t.length&&e.jsxs("span",{className:"text-micro text-muted whitespace-nowrap",children:[s,"/",t.length]}),e.jsx(at,{initial:!1,children:H&&e.jsx(le.button,{type:"button",onClick:M,initial:{opacity:0,x:-4},animate:{opacity:1,x:0},exit:{opacity:0,x:-4},transition:{duration:.15,ease:[.22,1,.36,1]},className:"text-micro text-muted transition-colors whitespace-nowrap hover:text-primary",children:"Clear"})}),e.jsx(at,{children:R&&e.jsxs(le.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"})]}),H?e.jsxs("span",{className:"rounded-full border border-strong bg-white/[0.04] px-2 py-0.5 text-micro text-primary",children:[K," active"]}):A?e.jsx("span",{className:"rounded-full border border-strong bg-white/[0.04] px-2 py-0.5 text-micro text-secondary",children:"view modified"}):null]}),e.jsxs("div",{className:"subsection-shell p-2.5",children:[e.jsx("div",{className:"section-kicker mb-2",children:"Layout"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("label",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:"Group"}),e.jsx("select",{value:f,onChange:q=>j(q.target.value),className:"h-9 rounded-lg border border-white/[0.08] bg-black/30 px-2 text-caption text-primary focus:border-lime/40 focus:outline-none",children:w.map(q=>e.jsx("option",{value:q.value,children:q.label},q.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:p,onChange:q=>E(q.target.value),className:"h-9 rounded-lg border border-white/[0.08] bg-black/30 px-2 text-caption text-primary focus:border-lime/40 focus:outline-none",children:Q.map(q=>e.jsx("option",{value:q.value,children:q.label},q.value))})]})]})]}),e.jsxs("div",{className:"mt-2.5 subsection-shell p-2.5",children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between",children:[e.jsx("div",{className:"section-kicker",children:"Status"}),X>0&&e.jsx("button",{type:"button",onClick:()=>k(q=>!q),className:"text-micro text-muted transition-colors hover:text-white/72",children:b?"Hide empty":`Show empty (${X})`})]}),e.jsx("div",{className:"max-h-40 space-y-1 overflow-auto pr-1",children:re.map(q=>{const P=a.includes(q.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 ${P?"border-lime/30 bg-lime/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:P,onChange:()=>g(q.key),className:"h-3.5 w-3.5 accent-lime"}),e.jsx("span",{children:Oi(q.key)})]}),e.jsx("span",{className:"text-micro text-secondary",children:q.count})]},q.key)})}),e.jsxs("div",{className:"mt-2 flex items-center justify-between",children:[e.jsx("button",{type:"button",onClick:()=>L([]),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:q=>d(q.target.value),className:"h-9 rounded-lg border border-strong bg-black/30 px-2 text-caption text-white focus:border-lime/40 focus:outline-none",children:qi.map(q=>e.jsx("option",{value:q.value,children:q.label},q.value))})]}),e.jsxs("label",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-secondary",children:"Condition"}),e.jsx("select",{value:o,onChange:q=>v(q.target.value),className:"h-9 rounded-lg border border-strong bg-black/30 px-2 text-caption text-white focus:border-lime/40 focus:outline-none",children:O.map(q=>e.jsx("option",{value:q.value,children:q.label},q.value))})]})]}),o==="custom_range"&&e.jsxs("div",{className:"mt-2 grid grid-cols-2 gap-2",children:[e.jsxs("label",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-secondary",children:"Start"}),e.jsx("input",{type:"date",value:l,onChange:q=>y(q.target.value),className:"h-9 rounded-lg border border-strong bg-black/30 px-2 text-caption text-white focus:border-lime/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:q=>S(q.target.value),className:"h-9 rounded-lg border border-strong bg-black/30 px-2 text-caption text-white focus:border-lime/40 focus:outline-none"})]})]})]}),de&&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:[A&&e.jsx("button",{type:"button",onClick:()=>{j("status"),E("default")},className:"text-micro uppercase tracking-[0.09em] text-secondary transition-colors hover:text-bright",children:"Reset layout"}),H&&e.jsx("button",{type:"button",onClick:M,className:"text-micro uppercase tracking-[0.09em] text-secondary transition-colors hover:text-bright",children:"Clear filters"})]})]})]})})]})}function Tt(t){return!t||typeof t!="object"||Array.isArray(t)?null:t}function fe(t){if(typeof t!="string")return null;const s=t.trim();return s.length>0?s:null}function Ae(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 Qi(t){const s=(fe(t)??"").toLowerCase();return s==="assigned"||s==="inferred"||s==="fallback"?s:null}function ys(t){const s=fe(t);if(!s)return null;const a=s.toLowerCase();return a==="undefined"||a==="null"||a==="main"||a==="unassigned"?null:s}function Fr(t){return ys(t)}function Hi(t,s,a){if(!Array.isArray(t)){if(s||a){const l=s??a??"",c=a??s??"";if(l.trim().length>0&&c.trim().length>0)return[{id:l,name:c}]}return[]}const n=[],o=new Set;for(const l of t){const c=Tt(l);if(!c)continue;const h=Fr(c.id)??ys(c.name),f=ys(c.name)??h;if(!h||!f)continue;const j=h.toLowerCase();o.has(j)||(o.add(j),n.push({id:h,name:f}))}if(n.length===0&&(s||a)){const l=s??a??"",c=a??s??"";if(l.trim().length>0&&c.trim().length>0)return[{id:l,name:c}]}return n}function vn(t,s){const a=(fe(t)??"").toLowerCase();return a==="initiative"?"initiative":a==="milestone"?"milestone":a==="task"?"task":a==="workstream"?"workstream":s}function Vi(t){return(fe(t)??"").toLowerCase()==="algorithmic"?"algorithmic":"manual"}function Zt(t){return Array.isArray(t)?t.map(s=>fe(s)).filter(s=>!!s):[]}function Ki(t,s,a){const n=Tt(t);if(!n)return null;const o=fe(n.sliceId)??fe(n.id);if(!o)return null;const l=vn(n.level??n.scope,s),c=fe(n.title)??fe(n.workstreamTitle)??fe(n.milestoneTitle)??fe(n.taskTitle)??fe(n.initiativeTitle)??o,h=Tt(n.order),f=Tt(n.dispatch),j=Tt(n.objectiveSnapshot??n.objective??n.ranking),p=Tt(n.factors),E=Tt(n.iwmt),L=Tt(n.lineage),g=Fr(n.runnerAgentId??n.agentId),d=ys(n.runnerAgentName??n.agentName)??ys(n.runner),v=Hi(n.runnerAgents,g,d??g),y=v[0]??null;return{sliceId:o,level:l,title:c,initiativeId:fe(n.initiativeId),initiativeTitle:fe(n.initiativeTitle),workstreamId:fe(n.workstreamId),workstreamTitle:fe(n.workstreamTitle),milestoneId:fe(n.milestoneId),milestoneTitle:fe(n.milestoneTitle),taskId:fe(n.taskId),taskTitle:fe(n.taskTitle),status:fe(n.status)??fe(n.queueState)??(f&&f.runnable===!1?"blocked":"queued"),priorityNum:Ae(n.priorityNum??n.nextTaskPriority),dueAt:fe(n.dueAt??n.nextTaskDueAt),dependencyState:fe(n.dependencyState),objectiveScore:Ae(n.objectiveScore)??Ae(j==null?void 0:j.objectiveScore)??Ae(n.mixScore),roiPerToken:Ae(n.roiPerToken)??Ae(j==null?void 0:j.roiPerToken),expectedTokens:Ae(n.expectedTokens)??Ae(j==null?void 0:j.expectedTokens),expectedValueUsd:Ae(n.expectedValueUsd)??Ae(j==null?void 0:j.expectedValueUsd),goalAlignment:Ae(n.goalAlignment)??Ae(p==null?void 0:p.goalAlignment),riskPenalty:Ae(n.riskPenalty)??Ae(p==null?void 0:p.riskPenalty),runnable:typeof(f==null?void 0:f.runnable)=="boolean"?f.runnable:void 0,blockReason:fe((f==null?void 0:f.blockReason)??n.blockReason),suggestedScope:f&&f.suggestedScope?vn(f.suggestedScope,l):null,manualRank:Ae(n.manualRank)??Ae(h==null?void 0:h.manualRank),algorithmRank:Ae(n.algorithmRank)??Ae(h==null?void 0:h.algorithmRank)??a,finalRank:Ae(n.finalRank)??Ae(h==null?void 0:h.finalRank)??a,iwmt:E?{laneId:fe(E.laneId),mixScore:Ae(E.mixScore),factors:Array.isArray(E.factors)?E.factors.map(S=>{const M=Tt(S);return M?{key:fe(M.key)??void 0,label:fe(M.label)??fe(M.key)??void 0,value:Ae(M.value)??void 0,weight:Ae(M.weight)??void 0}:null}).filter(S=>!!S):void 0}:null,lineage:L?{initiativeIds:Zt(L.initiativeIds),workstreamIds:Zt(L.workstreamIds),milestoneIds:Zt(L.milestoneIds),taskIds:Zt(L.taskIds),iwmtIds:Zt(L.iwmtIds)}:null,sourceWorkstreamIds:Zt(n.sourceWorkstreamIds),queueState:fe(n.queueState),sliceTaskIds:Zt(n.sliceTaskIds),sliceTaskCount:Ae(n.sliceTaskCount),sliceMilestoneId:fe(n.sliceMilestoneId),runnerAgentId:(y==null?void 0:y.id)??g,runnerAgentName:(y==null?void 0:y.name)??d,runnerAgents:v,runnerSource:Qi(n.runnerSource)??((y==null?void 0:y.id)??g?"inferred":"fallback"),updatedAt:fe(n.updatedAt)}}function Gi(t,s,a,n){return{ok:!0,generatedAt:new Date().toISOString(),level:t,orderMode:s,mixPolicy:"iwmt_v1",total:0,items:[],degraded:["Demo mode: slice explorer uses fixture data only."],source:"local",pagination:{offset:a,limit:n,total:0,nextCursor:null,hasMore:!1}}}function Ji(t){const s=t.offset+t.limit,a=s<t.total;return{offset:t.offset,limit:t.limit,total:t.total,nextCursor:a?String(s):null,hasMore:a}}function Yi({workspaceId:t=null,initiativeId:s=null,level:a,orderMode:n=null,includeCompleted:o=!1,search:l="",offset:c=0,limit:h=24,authToken:f=null,embedMode:j=!1,enabled:p=!0}){var M,R,m,b,k,$,F,te,re;const E=ws(),L=Math.max(0,c),g=Math.max(1,Math.min(300,h)),d=l.trim(),v=r.useMemo(()=>vs.missionControlSlices({workspaceId:t,initiativeId:s,level:a,orderMode:n,includeCompleted:o,search:d,offset:L,limit:g,authToken:f,embedMode:j}),[f,j,o,s,a,g,L,d,n,t]),y=ss({queryKey:v,enabled:p,queryFn:async()=>{if(E)return Gi(a,n??"manual",L,g);const X=new URLSearchParams;Yn(X,t,{allTokenWhenMissing:!0}),s&&X.set("initiative_id",s),X.set("level",a),X.set("include_completed",o?"1":"0"),X.set("offset",String(L)),X.set("limit",String(g)),X.set("mix_policy","iwmt_v1"),n&&X.set("order_mode",n),d.length>0&&X.set("q",d);const O=await fetch(`/orgx/api/mission-control/slices?${X.toString()}`,{headers:yt({authToken:f,embedMode:j})}),w=await O.json().catch(()=>null);if(!O.ok){const P=w&&typeof w.error=="string"&&w.error||w&&typeof w.message=="string"&&w.message||`Failed to fetch mission-control slices (${O.status})`;throw new Error(P)}const Q=Array.isArray(w==null?void 0:w.items)?w.items:[],A=vn((w==null?void 0:w.level)??(w==null?void 0:w.scope),a),H=Q.map((P,B)=>Ki(P,A,B+1)).filter(P=>!!P),K=Tt(w==null?void 0:w.pagination),de=Ae(w==null?void 0:w.total)??Ae(K==null?void 0:K.total)??H.length,q=K?{offset:Ae(K.offset)??L,limit:Ae(K.limit)??g,total:de,nextCursor:fe(K.nextCursor),hasMore:typeof K.hasMore=="boolean"?K.hasMore:!1}:Ji({offset:L,limit:g,total:de});return{ok:!0,generatedAt:fe(w==null?void 0:w.generatedAt)??new Date().toISOString(),workspaceId:fe((w==null?void 0:w.workspaceId)??(w==null?void 0:w.workspace_id)),initiativeId:fe((w==null?void 0:w.initiativeId)??(w==null?void 0:w.initiative_id)??s),level:A,mixPolicy:fe((w==null?void 0:w.mixPolicy)??(w==null?void 0:w.mix_policy))??"iwmt_v1",orderMode:Vi((w==null?void 0:w.orderMode)??(w==null?void 0:w.order_mode)??(w==null?void 0:w.order)),total:de,items:H,degraded:Array.isArray(w==null?void 0:w.degraded)?w.degraded.map(P=>fe(P)).filter(P=>!!P):void 0,source:fe(w==null?void 0:w.source)==="canonical"?"canonical":fe(w==null?void 0:w.source)==="local_fallback"?"local_fallback":"local",pagination:q}}}),S=r.useRef(null);return r.useEffect(()=>{var Q;const X=(Q=y.data)==null?void 0:Q.pagination;if(!p||!(X!=null&&X.hasMore)||!X.nextCursor||S.current===X.nextCursor)return;const O=Number.parseInt(X.nextCursor,10);if(!Number.isFinite(O))return;S.current=X.nextCursor;const w=new URLSearchParams;Yn(w,t,{allTokenWhenMissing:!0}),s&&w.set("initiative_id",s),w.set("level",a),w.set("include_completed",o?"1":"0"),w.set("offset",String(O)),w.set("limit",String(g)),w.set("mix_policy","iwmt_v1"),n&&w.set("order_mode",n),d.length>0&&w.set("q",d),fetch(`/orgx/api/mission-control/slices?${w.toString()}`,{headers:yt({authToken:f,embedMode:j})}).catch(()=>{})},[p,(R=(M=y.data)==null?void 0:M.pagination)==null?void 0:R.hasMore,(b=(m=y.data)==null?void 0:m.pagination)==null?void 0:b.nextCursor,t,s,a,n,o,d,g,f,j]),{...y,slices:((k=y.data)==null?void 0:k.items)??[],orderMode:(($=y.data)==null?void 0:$.orderMode)??n??"manual",degraded:((F=y.data)==null?void 0:F.degraded)??[],source:((te=y.data)==null?void 0:te.source)??null,pagination:((re=y.data)==null?void 0:re.pagination)??null}}function hr(t,s){if(!s||s.trim().length===0)return;const a=s.trim();t.workspace_id=a}async function fr(t){const s=await t.json().catch(()=>null);if(!t.ok){const a=s&&typeof s.error=="string"&&s.error||s&&typeof s.message=="string"&&s.message||`Request failed (${t.status})`;throw new Error(a)}return s??{}}function Xi({workspaceId:t=null,initiativeId:s=null,level:a,authToken:n=null,embedMode:o=!1}){const l=Nn(),c=Dt({mutationFn:async f=>{const j={level:a,order:f.map(E=>({sliceId:E}))};hr(j,t),s&&(j.initiative_id=s);const p=await fetch("/orgx/api/mission-control/slices/reorder",{method:"POST",headers:yt({authToken:n,embedMode:o,contentTypeJson:!0,workspaceId:t}),body:JSON.stringify(j)});return fr(p)},onMutate:async f=>{const j=l.getQueriesData({queryKey:["mission-control-slices"]});for(const[p,E]of j){if(!E||E.level!==a||s&&E.initiativeId&&E.initiativeId!==s)continue;const L=new Map(E.items.map(v=>[v.sliceId,v])),g=f.map(v=>L.get(v)??null).filter(v=>!!v);if(g.length===0)continue;const d=new Set(g.map(v=>v.sliceId));for(const v of E.items)d.has(v.sliceId)||g.push(v);l.setQueryData(p,{...E,items:g.map((v,y)=>({...v,manualRank:y+1,finalRank:y+1})),orderMode:"manual"})}return{snapshots:j}},onError:(f,j,p)=>{for(const[E,L]of(p==null?void 0:p.snapshots)??[])l.setQueryData(E,L)},onSettled:()=>{Os(l,{initiativeId:s,projectId:t,authToken:n,embedMode:o,includeQueue:!1,includeGraph:!1,includeAutoContinue:!1})}}),h=Dt({mutationFn:async f=>{const j={level:a,order_mode:f};hr(j,t),s&&(j.initiative_id=s);const p=await fetch("/orgx/api/mission-control/slices/order-mode",{method:"POST",headers:yt({authToken:n,embedMode:o,contentTypeJson:!0,workspaceId:t}),body:JSON.stringify(j)});return fr(p)},onMutate:async f=>{const j=l.getQueriesData({queryKey:["mission-control-slices"]});for(const[p,E]of j)!E||E.level!==a||s&&E.initiativeId&&E.initiativeId!==s||l.setQueryData(p,{...E,orderMode:f});return{snapshots:j}},onError:(f,j,p)=>{for(const[E,L]of(p==null?void 0:p.snapshots)??[])l.setQueryData(E,L)},onSettled:()=>{Os(l,{initiativeId:s,projectId:t,authToken:n,embedMode:o,includeQueue:!1,includeGraph:!1,includeAutoContinue:!1})}});return{reorder:c.mutateAsync,setOrderMode:h.mutateAsync,isReordering:c.isPending,isSettingOrderMode:h.isPending,error:(c.error instanceof Error?c.error.message:null)??(h.error instanceof Error?h.error.message:null)}}const jn=[{value:"initiative",label:"Initiative"},{value:"workstream",label:"Workstream"},{value:"milestone",label:"Milestone"},{value:"task",label:"Task"}];function gr(t){var s;return((s=jn.find(a=>a.value===t))==null?void 0:s.label)??"Workstream"}function br(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-lime/24 bg-lime/[0.08] text-lime/92"}function yr(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-lime/0 via-lime/70 to-lime/0"}function xs(t,s=2){return typeof t!="number"||!Number.isFinite(t)?"—":t.toFixed(s)}function bs(t,s){if(!t)return s;const a=t.trim();return a?Cn(a)?`${s} ${Dr(a)}`:a:s}function wr(t){var a,n,o,l;const s=t.title.trim()||((a=t.taskTitle)==null?void 0:a.trim())||((n=t.milestoneTitle)==null?void 0:n.trim())||((o=t.workstreamTitle)==null?void 0:o.trim())||((l=t.initiativeTitle)==null?void 0:l.trim())||"";return s&&!Cn(s)?hs(s):t.level==="task"?bs(t.taskId??t.sliceId,"Task"):t.level==="milestone"?bs(t.milestoneId??t.sliceId,"Milestone"):t.level==="initiative"?bs(t.initiativeId??t.sliceId,"Initiative"):bs(t.workstreamId??t.sliceId,"Workstream")}function vr(t){const s=[t.initiativeTitle,t.workstreamTitle,t.milestoneTitle,t.taskTitle].filter(n=>!!(n&&n.trim().length>0));return s.length===0?hs(bs(t.sliceId,"Slice")):s.map(n=>hs(n)).filter(n=>n.length>0).join(" / ")}function jr(t){var o,l;const s=((o=t.runnerAgentName)==null?void 0:o.trim())??"",a=((l=t.runnerAgentId)==null?void 0:l.trim().toLowerCase())??"";if(!s)return a&&a!=="main"?hs(a):"Unassigned";const n=s.toLowerCase();return n==="undefined"||n==="null"||n==="main"&&(a==="main"||t.runnerSource==="fallback")?"Unassigned":hs(s)}function kr(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 Nr(t,s){return!t||t.trim().length===0?s:Nt(t.trim())||s}function Sr({workspaceId:t=null,initiativeId:s=null,authToken:a=null,embedMode:n=!1,className:o="",title:l="Slice Explorer",compact:c=!1,onOpenInitiative:h}){var Ue,Ke;const[f,j]=r.useState("workstream"),[p,E]=r.useState(""),[L,g]=r.useState(0),[d]=r.useState(c?18:28),[v,y]=r.useState(null),[S,M]=r.useState([]),[R,m]=r.useState(!1),[b,k]=r.useState(null),[$,F]=r.useState(!1),te=r.useRef(null),re=Yi({workspaceId:t,initiativeId:s,level:f,orderMode:b,includeCompleted:!1,search:p,offset:L,limit:d,authToken:a,embedMode:n,enabled:!!(t||s)}),X=Xi({workspaceId:t,initiativeId:s,level:f,authToken:a,embedMode:n}),O=re.slices,w=re.source,Q=re.pagination,A=re.orderMode??"manual",H=(Q==null?void 0:Q.offset)??L,K=(Q==null?void 0:Q.total)??((Ue=re.data)==null?void 0:Ue.total)??O.length,de=O.length===0?0:H+1,q=O.length===0?0:H+O.length;r.useEffect(()=>{if(!v)return;const x=window.setTimeout(()=>y(null),5e3);return()=>window.clearTimeout(x)},[v]),r.useEffect(()=>{if(!$)return;const x=Z=>{var De;const ge=Z.target;ge&&((De=te.current)!=null&&De.contains(ge)||F(!1))},Y=Z=>{Z.key==="Escape"&&F(!1)};return document.addEventListener("mousedown",x),document.addEventListener("touchstart",x),document.addEventListener("keydown",Y),()=>{document.removeEventListener("mousedown",x),document.removeEventListener("touchstart",x),document.removeEventListener("keydown",Y)}},[$]),r.useEffect(()=>{g(0)},[f,p]);const P=r.useMemo(()=>O.map(x=>x.sliceId).join("|"),[O]);r.useEffect(()=>{M(O.map(x=>x.sliceId)),m(!1)},[P,A]);const B=r.useMemo(()=>new Map(O.map(x=>[x.sliceId,x])),[O]),U=r.useMemo(()=>{if(!R||S.length!==O.length)return O;const x=S.map(Y=>B.get(Y)??null).filter(Y=>!!Y);return x.length!==O.length?O:x},[R,S,O,B]),V=A==="manual"&&O.length>1&&!X.isReordering&&H===0&&!((Q==null?void 0:Q.hasMore)??!1),pe=async()=>{if(!(!V||!R))try{await X.reorder(S),m(!1),y({tone:"success",message:`Saved ${S.length} slice positions.`})}catch(x){y({tone:"error",message:Nr(x instanceof Error?x.message:"","Failed to save slice order.")})}},ae=async x=>{if(!(x===A&&b===null)){k(x);try{await X.setOrderMode(x),y({tone:"success",message:`Slice ordering set to ${x}.`})}catch(Y){y({tone:"error",message:Nr(Y instanceof Error?Y.message:"",`Failed to set ${x} ordering.`)})}finally{k(null)}}},Se=x=>{!h||!x.initiativeId||h(x.initiativeId,x.initiativeTitle??void 0)};return e.jsxs("section",{className:ps("flex min-h-0 flex-col rounded-2xl border border-strong bg-[#070b12]/88",o),children:[e.jsxs("div",{className:"flex flex-col gap-2 border-b border-strong px-3 py-3",children:[e.jsxs("div",{className:"flex min-h-[34px] items-center gap-2",children:[e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-lime/70"}),e.jsx("h3",{className:"text-caption font-semibold uppercase tracking-[0.1em] text-secondary",children:l}),e.jsx("span",{className:"rounded-full border border-strong bg-white/[0.04] px-2 py-0.5 text-micro text-secondary",children:K}),e.jsxs("div",{className:"ml-auto flex items-center gap-1.5",children:[e.jsxs("div",{ref:te,className:"relative",children:[e.jsxs("button",{type:"button",onClick:()=>F(x=>!x),className:"control-pill h-8 px-2.5 text-micro font-semibold","aria-haspopup":"menu","aria-expanded":$,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"})]}),$?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:jn.map(x=>e.jsxs("button",{type:"button",onClick:()=>{j(x.value),F(!1)},className:ps("control-pill flex h-8 items-center gap-1.5 px-2 text-micro font-semibold",f===x.value?"border-lime/34 bg-lime/[0.12] text-lime":"text-secondary"),children:[e.jsx(Rs,{type:x.value,size:10,className:"opacity-80"}),e.jsx("span",{children:x.label})]},x.value))})]}),e.jsxs("div",{children:[e.jsx("p",{className:"section-kicker",children:"Ordering"}),e.jsxs("div",{className:"mt-1.5 flex items-center gap-1.5",children:[e.jsx("button",{type:"button",className:ps("control-pill h-8 px-2.5 text-micro font-semibold",A==="manual"?"border-lime/34 bg-lime/[0.12] text-lime":"text-secondary"),disabled:X.isSettingOrderMode,onClick:()=>void ae("manual"),children:"Manual"}),e.jsx("button",{type:"button",className:ps("control-pill h-8 px-2.5 text-micro font-semibold",A==="algorithmic"?"border-teal-300/34 bg-teal-400/[0.13] text-teal-100":"text-secondary"),disabled:X.isSettingOrderMode,onClick:()=>void ae("algorithmic"),children:"Algorithmic"})]})]})]})}):null]}),A==="manual"&&e.jsx("button",{type:"button",className:"control-pill h-8 px-2.5 text-micro font-semibold disabled:opacity-45",disabled:!R||!V,onClick:()=>void pe(),children:"Save order"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"min-w-0 flex-1",children:e.jsx(In,{value:p,onChange:E,placeholder:"Search slices, entities, or IDs..."})}),e.jsx("span",{className:"chip whitespace-nowrap text-micro",children:((Ke=jn.find(x=>x.value===f))==null?void 0:Ke.label)??"Workstream"})]}),(w==="local_fallback"||re.degraded.length>0)&&e.jsx("div",{className:"rounded-xl border border-amber-300/24 bg-amber-400/[0.08] px-2.5 py-1.5 text-micro text-amber-100/90",children:w==="local_fallback"?"Canonical slices unavailable; showing local fallback.":re.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:re.isLoading?e.jsx("div",{className:"space-y-2 px-1",children:Array.from({length:c?4:7}).map((x,Y)=>e.jsxs("div",{className:"rounded-xl border border-strong bg-white/[0.02] px-3 py-2",children:[e.jsx($t,{className:"h-3.5 w-1/2 rounded-full"}),e.jsx($t,{className:"mt-2 h-3 w-4/5 rounded-full"})]},`slice-loading-${Y}`))}):U.length===0?e.jsx("div",{className:"rounded-xl border border-strong bg-white/[0.02] px-3 py-3 text-caption text-secondary",children:"No slices match this view."}):V?e.jsx(ka,{axis:"y",values:S,onReorder:x=>{M(x),m(!0)},className:"space-y-2",children:S.map((x,Y)=>{var Ce;const Z=B.get(x);if(!Z)return null;const ge=Z.finalRank??Z.manualRank??Z.algorithmRank??Y+1,We=(((Ce=Z.iwmt)==null?void 0:Ce.factors)??[]).filter(Ie=>typeof Ie.value=="number"&&Number.isFinite(Ie.value)),Be=typeof Z.roiPerToken=="number"&&Number.isFinite(Z.roiPerToken),T=typeof Z.objectiveScore=="number"&&Number.isFinite(Z.objectiveScore),G=jr(Z),oe=vr(Z);return e.jsxs(Na,{value:Z.sliceId,className:"group hover-lift relative overflow-hidden rounded-2xl border border-white/[0.08] bg-white/[0.02] px-3 py-2.5 transition-colors hover:border-white/[0.14]",children:[e.jsx("div",{className:`pointer-events-none absolute inset-x-3 top-0 h-px bg-gradient-to-r ${yr(Z.status)}`,"aria-hidden":!0}),e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("button",{type:"button",className:"mt-0.5 inline-flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-md border border-strong bg-white/[0.04] text-caption text-secondary","aria-label":"Drag to reorder",title:"Drag to reorder",children:"⋮⋮"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsxs("span",{className:"rounded-md border border-lime/22 bg-lime/[0.08] px-1.5 py-0.5 text-micro font-semibold text-[#DFFFB5]",children:["#",ge]}),e.jsx("div",{className:"min-w-0 flex-1",children:e.jsxs("div",{className:"flex min-w-0 items-start gap-1.5",children:[e.jsx(Rs,{type:Z.level,size:11,className:"mt-0.5 flex-shrink-0 opacity-80"}),e.jsx("p",{className:"min-w-0 flex-1 line-clamp-2 text-caption font-semibold leading-snug text-primary",children:wr(Z)})]})}),e.jsxs("div",{className:"ml-auto flex flex-shrink-0 items-center gap-1.5",children:[e.jsx("span",{className:ps("rounded-full border px-2 py-0.5 text-micro uppercase tracking-[0.08em]",br(Z.status)),children:Z.status.replace(/_/g," ")}),Z.initiativeId&&h?e.jsx("button",{type:"button",className:"control-pill h-6 px-2 text-micro font-semibold",onClick:()=>Se(Z),children:"Open"}):null]})]}),e.jsx("p",{className:"mt-1 inline-flex min-w-0 items-center gap-1 truncate text-micro text-secondary",title:oe,children:e.jsx("span",{className:"truncate",children:oe})}),e.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-1.5 text-micro text-secondary",children:[e.jsx("span",{className:"chip text-micro",children:gr(Z.level)}),e.jsx("span",{className:"chip text-micro",children:kr(Z)}),e.jsxs("span",{className:"chip text-micro",children:["Agent ",G]}),Be?e.jsxs("span",{className:"chip text-micro",children:["ROI/token ",xs(Z.roiPerToken,3)]}):null,T?e.jsxs("span",{className:"chip text-micro",children:["Obj ",xs(Z.objectiveScore,2)]}):null]}),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((Ie,Fe)=>e.jsxs("p",{children:[(Ie.label??Ie.key??"factor").replace(/_/g," "),":"," ",xs(Ie.value,2)]},`${Z.sliceId}-factor-${Fe}`))})]})]})]})]},Z.sliceId)})}):e.jsx("div",{className:"space-y-2",children:U.map((x,Y)=>{var oe;const Z=x.finalRank??x.manualRank??x.algorithmRank??Y+1,De=(((oe=x.iwmt)==null?void 0:oe.factors)??[]).filter(Ce=>typeof Ce.value=="number"&&Number.isFinite(Ce.value)),We=typeof x.roiPerToken=="number"&&Number.isFinite(x.roiPerToken),Be=typeof x.objectiveScore=="number"&&Number.isFinite(x.objectiveScore),T=jr(x),G=vr(x);return e.jsxs(le.article,{initial:{opacity:0,y:10,scale:.985},animate:{opacity:1,y:0,scale:1},transition:{duration:.22,delay:Math.min(Y,7)*.02,ease:[.22,1,.36,1]},className:"group hover-lift relative overflow-hidden rounded-2xl border border-white/[0.08] bg-white/[0.02] px-3 py-2.5 transition-colors hover:border-white/[0.14]",children:[e.jsx("div",{className:`pointer-events-none absolute inset-x-3 top-0 h-px bg-gradient-to-r ${yr(x.status)}`,"aria-hidden":!0}),e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsxs("span",{className:"rounded-md border border-lime/22 bg-lime/[0.08] px-1.5 py-0.5 text-micro font-semibold text-[#DFFFB5]",children:["#",Z]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex min-w-0 items-start gap-1.5",children:[e.jsx(Rs,{type:x.level,size:11,className:"mt-0.5 flex-shrink-0 opacity-80"}),e.jsx("p",{className:"min-w-0 flex-1 line-clamp-2 text-caption font-semibold leading-snug text-primary",children:wr(x)})]}),e.jsx("p",{className:"mt-1 inline-flex min-w-0 items-center gap-1 truncate text-micro text-secondary",title:G,children:e.jsx("span",{className:"truncate",children:G})}),e.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-1.5 text-micro text-secondary",children:[e.jsx("span",{className:"chip text-micro",children:gr(x.level)}),e.jsx("span",{className:"chip text-micro",children:kr(x)}),e.jsxs("span",{className:"chip text-micro",children:["Agent ",T]}),We?e.jsxs("span",{className:"chip text-micro",children:["ROI/token ",xs(x.roiPerToken,3)]}):null,Be?e.jsxs("span",{className:"chip text-micro",children:["Obj ",xs(x.objectiveScore,2)]}):null,e.jsx("span",{className:ps("rounded-full border px-2 py-0.5 uppercase tracking-[0.08em]",br(x.status)),children:x.status.replace(/_/g," ")})]}),De.length>0&&e.jsxs("details",{className:"mt-1.5",children:[e.jsx("summary",{className:"cursor-pointer text-micro text-secondary",children:"Why this slice"}),e.jsx("div",{className:"mt-1 space-y-1 text-micro text-secondary",children:De.slice(0,3).map((Ce,Ie)=>e.jsxs("p",{children:[(Ce.label??Ce.key??"factor").replace(/_/g," "),":"," ",xs(Ce.value,2)]},`${x.sliceId}-factor-static-${Ie}`))})]})]}),x.initiativeId&&h?e.jsx("button",{type:"button",className:"control-pill h-7 px-2 text-micro font-semibold",onClick:()=>Se(x),children:"Open"}):null]})]},x.sliceId)})})}),e.jsxs("div",{className:"flex items-center gap-2 border-t border-strong px-3 py-2",children:[e.jsxs("p",{className:"text-micro text-secondary",children:[de,"-",q," of ",K]}),e.jsx("button",{type:"button",className:"control-pill ml-auto h-7 px-2 text-micro font-semibold disabled:opacity-40",disabled:H===0,onClick:()=>g(Math.max(0,H-d)),children:"Prev"}),e.jsx("button",{type:"button",className:"control-pill h-7 px-2 text-micro font-semibold disabled:opacity-40",disabled:!((Q==null?void 0:Q.hasMore)??!1),onClick:()=>g(H+d),children:"Next"})]}),v&&e.jsx("div",{className:"border-t border-strong px-3 py-2",children:e.jsx($r,{open:!0,tone:v.tone==="error"?"error":"success",title:v.tone==="error"?"Slice explorer error":"Slice explorer updated",message:v.message,onDismiss:()=>y(null),autoDismissMs:4200})})]})}function Zi({completionPercent:t,totalTasks:s,doneTasks:a,blockedCount:n,activeAgents:o,className:l}){const c=t*.6,h=Math.min(n*10,30),f=Math.min(o*5,10),j=Math.max(0,Math.min(100,c+f-h+40)),p=Math.round(j/10),E=p>=7;return e.jsx("div",{className:`${E?"surface-hero":"surface-tier-2"} rounded-2xl px-5 py-4 ${l??""}`,children:e.jsxs("div",{className:"flex items-center gap-5",children:[e.jsx(Pr,{percent:j,size:56}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"text-display font-light",style:{color:p>=7?z.lime:p>=5?z.amber:z.red,fontVariantNumeric:"tabular-nums"},children:[p,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:z.teal},children:[a,"/",s]}),e.jsx("p",{className:"text-micro text-muted",children:"tasks"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-body font-light tabular-nums",style:{color:n>0?z.red:"rgba(255,255,255,0.2)"},children:n}),e.jsx("p",{className:"text-micro text-muted",children:"blocked"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-body font-light tabular-nums",style:{color:o>0?z.lime:"rgba(255,255,255,0.2)"},children:o}),e.jsx("p",{className:"text-micro text-muted",children:"agents"})]})]})]})})}function gn(t){return t>=1e4?`$${(t/100).toFixed(0)}`:`$${(t/100).toFixed(2)}`}function eo({usage:t,className:s}){if(!t)return null;const a=t.actual.costCents,n=t.plan.includedBudgetCents,o=t.headroom.budgetRemainingCents,l=t.utilization.budgetPct??0,c=t.velocity.dailyAvgCostCents,h=l>85?z.red:l>60?z.amber:z.lime,f=l>85?z.red:l>60?z.amber:z.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-micro font-semibold uppercase tracking-[0.08em] text-muted",children:"Spent"}),e.jsx("p",{className:"mt-1 text-title font-light tabular-nums text-primary",children:gn(a)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-micro font-semibold uppercase tracking-[0.08em] text-muted",children:"Remaining"}),e.jsx("p",{className:"mt-1 text-title font-light tabular-nums",style:{color:f},children:gn(o)})]})]}),n>0&&e.jsxs("div",{className:"mt-3",children:[e.jsx("div",{className:"h-1.5 rounded-full bg-white/[0.06] overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full transition-all duration-500",style:{width:`${Math.min(l,100)}%`,background:`linear-gradient(90deg, ${h}, ${h}cc)`}})}),e.jsxs("div",{className:"mt-1.5 flex items-center justify-between text-micro text-muted",children:[e.jsxs("span",{className:"tabular-nums",children:[Math.round(l),"% utilized"]}),c>0&&e.jsxs("span",{className:"tabular-nums",children:["~",gn(c),"/day"]})]})]})]})}function to({enabled:t=!0,projectId:s=null}={}){return ss({queryKey:["live-initiatives-summary",{projectId:s??null}],queryFn:async()=>{const a=new URLSearchParams;s&&s.trim().length>0&&a.set("workspace_id",s);const n=`/orgx/api/live/initiatives/summary${a.toString()?`?${a}`:""}`,o=await fetch(n,{headers:yt({workspaceId:s})});if(!o.ok)throw new Error(`Failed to load initiative summary (${o.status})`);return await o.json()},enabled:t,refetchInterval:6e4})}function Bs(t){return(t??"").trim().toLowerCase().replace(/[\s-]+/g,"_")}function kn(t){return new Date(t.getFullYear(),t.getMonth(),t.getDate()).getTime()}function Cr(t){if(!t)return null;const s=Date.parse(`${t}T00:00:00`);return Number.isFinite(s)?s:null}function so(t,s){return s==="target"?t.targetDate??null:s==="created"?t.createdAt??null:t.updatedAt??t.createdAt??null}function Ir(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 Er(t){return t==="active"?0:t==="blocked"?1:t==="paused"?2:3}function no(t){const s=Bs(t);return s==="completed"||s==="done"||s==="resolved"||s==="success"||s==="succeeded"||s==="archived"}function Ar(t,s){if(s==="status"){const a=new Map,n=["active","blocked","paused","completed"];for(const o of t){const l=o.status??"active",c=a.get(l)??[];c.push(o),a.set(l,c)}return n.filter(o=>a.has(o)).concat(Array.from(a.keys()).filter(o=>!n.includes(o))).map(o=>{var l;return{key:o,label:o.charAt(0).toUpperCase()+o.slice(1),count:((l=a.get(o))==null?void 0:l.length)??0,initiatives:a.get(o)??[]}})}if(s==="category"){const a=new Map;for(const n of t){const o=n.category??"Uncategorized",l=a.get(o)??[];l.push(n),a.set(o,l)}return Array.from(a.entries()).sort((n,o)=>n[0].localeCompare(o[0])).map(([n,o])=>({key:n,label:n,count:o.length,initiatives:o}))}if(s==="date"){const n=kn(new Date),o=n+7*864e5,l=n+30*864e5,c={overdue:[],this_week:[],this_month:[],later:[],no_date:[]};for(const f of t){const j=f.targetDate?Date.parse(f.targetDate):null;j===null||!Number.isFinite(j)?c.no_date.push(f):j<n?c.overdue.push(f):j<o?c.this_week.push(f):j<l?c.this_month.push(f):c.later.push(f)}const h={overdue:"Overdue",this_week:"This Week",this_month:"This Month",later:"Later",no_date:"No Date"};return["overdue","this_week","this_month","later","no_date"].filter(f=>c[f].length>0).map(f=>({key:f,label:h[f],count:c[f].length,initiatives:c[f]}))}return[]}function es(t,s){return`${t}:${s}`}function ro(t){return`mc-group-${t}`.toLowerCase().replace(/[^a-z0-9_-]+/g,"-")}function Mr(t,s){if(t.size!==s.size)return!1;for(const a of t)if(!s.has(a))return!1;return!0}function ao(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 io(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-lime/18 bg-lime/[0.06] text-lime/95":t==="completed"?"border-strong bg-white/[0.05] text-secondary":"border-strong bg-white/[0.04] text-white/68"}function oo(t){const s=t.trim().toLowerCase();if(s.includes("timed out")||s.includes("timeout")||s.includes("request cancelled")||s.includes("signal is aborted"))return"Live sync is taking longer than expected. Initiatives and Next Up will repopulate as soon as sync completes.";if(s.includes("unauthorized")||s.includes("forbidden")||s.includes("api key")||s.includes("auth"))return"OrgX authentication needs attention. Reconnect your API key in Settings.";if(s.includes("unknown api endpoint")||s.includes("missing required live routes"))return"This runtime is missing required live routes. Restart and update the plugin build.";const a=t.split("|").map(n=>n.trim()).filter(Boolean).map(n=>n.replace(/^[^:]+:\s*/,"").trim()).filter(Boolean).slice(0,2).join(" ");return Nt(a||t)||"Live data is temporarily unavailable."}function Qt(t,s){return!t||t.trim().length===0?s:Nt(t.trim())||s}const lo=[12,24,36,48,72];function Co({initiatives:t,activities:s,agents:a,runtimeInstances:n=[],workspaceInitiativeId:o=null,isLoading:l,authToken:c,embedMode:h,initialInitiativeId:f,connection:j,lastSnapshotAt:p,error:E,hasApiKey:L,onOpenSettings:g,onRefresh:d,onCreateInitiative:v,onPlayNextUp:y,onStartAutopilot:S,nextUpQueueModel:M,nextUpActionsModel:R,snapshotVersion:m=null,devMode:b=!1}){const k=Aa({activities:s,agents:a,initiatives:t});return e.jsx(Ua,{agentEntityMap:k,authToken:c,embedMode:h,children:e.jsx(mo,{initiatives:t,runtimeInstances:n,workspaceInitiativeId:o,isLoading:l,initialInitiativeId:f,connection:j,lastSnapshotAt:p,error:E,hasApiKey:L,onOpenSettings:g,onRefresh:d,onCreateInitiative:v,onPlayNextUp:y,onStartAutopilot:S,nextUpQueueModel:M,nextUpActionsModel:R,snapshotVersion:m,devMode:b})})}function co(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 uo(t,s){var a,n;return{...s,...t,rawStatus:t.rawStatus??s.rawStatus??null,priority:t.priority??s.priority??null,targetDate:t.targetDate??s.targetDate??null,createdAt:t.createdAt??s.createdAt??null,updatedAt:t.updatedAt??s.updatedAt??null,description:t.description??s.description,activeAgents:Math.max(t.activeAgents,s.activeAgents),totalAgents:Math.max(t.totalAgents,s.totalAgents),avatars:(a=t.avatars)!=null&&a.length?t.avatars:s.avatars,workstreams:(n=t.workstreams)!=null&&n.length?t.workstreams:s.workstreams,health:t.health>0?t.health:s.health}}function mo({initiatives:t,runtimeInstances:s,workspaceInitiativeId:a=null,isLoading:n,initialInitiativeId:o,connection:l,lastSnapshotAt:c,error:h,hasApiKey:f,onOpenSettings:j,onRefresh:p,onCreateInitiative:E,onPlayNextUp:L,onStartAutopilot:g,nextUpQueueModel:d,nextUpActionsModel:v,snapshotVersion:y=null,devMode:S=!1}){var zn,Un,Wn,Qn,Hn;const{searchQuery:M,setSearchQuery:R,statusFilters:m,setStatusFilters:b,dateField:k,setDateField:$,datePreset:F,setDatePreset:te,dateStart:re,setDateStart:X,dateEnd:O,setDateEnd:w,clearFilters:Q,hasActiveFilters:A,groupBy:H,sortBy:K,expandedInitiatives:de,expandAll:q,collapseAll:P,modalTarget:B,closeModal:U,expandInitiative:V,authToken:pe,embedMode:ae,mutations:Se}=Ht(),Ue=r.useRef(!1),Ke=r.useRef(null),x=r.useRef(0),[Y,Z]=r.useState(0),[ge,De]=r.useState(new Set),[We,Be]=r.useState(!1),[T,G]=r.useState(!1),[oe,Ce]=r.useState(!1),[Ie,Fe]=r.useState(!1),[Oe,St]=r.useState("next-up"),[Me,xe]=r.useState(null),[ye,ot]=r.useState(null),[ht,Vt]=r.useState(!1),[Ye,tt]=r.useState(null),[Rt,Bt]=r.useState(null),[Xe,ft]=r.useState(new Set),[mt,pt]=r.useState(!1),[Qe,st]=r.useState(null),[wt,vt]=r.useState(0),[He,ns]=r.useState(24),lt=M.trim(),Lt=Ba(lt,lt.length>=2,a),Kt=r.useMemo(()=>{var I;if(lt.length<2||!((I=Lt.data)!=null&&I.length))return t;const u=new Map;for(const _ of t)u.set(_.id,_);for(const _ of Lt.data){const W=u.get(_.id);u.set(_.id,W?uo(W,_):_)}return Array.from(u.values())},[Lt.data,t,lt.length]),Et=r.useMemo(()=>new Set((Lt.data??[]).map(u=>u.id)),[Lt.data]);r.useEffect(()=>{if(!Qe)return;const u=Qe.tone==="success"?6500:9e3,I=window.setTimeout(()=>st(null),u);return()=>window.clearTimeout(I)},[Qe==null?void 0:Qe.message,Qe==null?void 0:Qe.tone]);const Ot=r.useMemo(()=>{const I=kn(new Date),_=M.toLowerCase().trim().split(/\s+/).filter(Boolean);return Kt.filter(W=>{if(m.length>0&&![Bs(W.status),Bs(W.rawStatus)].filter(Boolean).some(ce=>m.includes(ce)))return!1;const he=so(W,k),$e=he?Date.parse(he):Number.NaN,Pe=Number.isFinite($e)?kn(new Date($e)):null,ue=Pe===null?null:Math.round((Pe-I)/864e5);if(F==="missing"&&Pe!==null||F==="overdue"&&!(ue!==null&&ue<0)||F==="today"&&ue!==0||F==="next_7_days"&&!(ue!==null&&ue>=0&&ue<=7)||F==="next_30_days"&&!(ue!==null&&ue>=0&&ue<=30)||F==="past_7_days"&&!(ue!==null&&ue<=0&&ue>=-7)||F==="past_30_days"&&!(ue!==null&&ue<=0&&ue>=-30))return!1;if(F==="custom_range"){const rt=Cr(re),ce=Cr(O);if(Pe===null||rt!==null&&Pe<rt||ce!==null&&Pe>ce)return!1}if(_.length===0||Et.has(W.id))return!0;const bt=[W.name,W.description??"",W.status,W.rawStatus??"",W.category??""].join(" ").toLowerCase();return _.every(rt=>bt.includes(rt))})},[Kt,M,Et,m,k,F,re,O]),i=r.useMemo(()=>{const u=(I,_,W)=>{const he=I.targetDate?Date.parse(I.targetDate):Number.NaN,$e=_.targetDate?Date.parse(_.targetDate):Number.NaN,Pe=Number.isFinite(he),ue=Number.isFinite($e);return!Pe&&!ue?0:Pe?ue?W==="asc"?he-$e:$e-he:-1:1};return[...Ot].sort((I,_)=>{if(K==="date_asc")return u(I,_,"asc");if(K==="date_desc")return u(I,_,"desc");const W=Ir(I.priority),he=Ir(_.priority);if(K==="priority_high"&&W!==he)return W-he;if(K==="priority_low"&&W!==he)return he-W;if(K==="default"){const ue=typeof I.sequenceIndex=="number"?I.sequenceIndex:Number.POSITIVE_INFINITY,bt=typeof _.sequenceIndex=="number"?_.sequenceIndex:Number.POSITIVE_INFINITY;if(ue!==bt)return ue-bt;const rt=Er(I.status)-Er(_.status);if(rt!==0)return rt;if(W!==he)return W-he}const $e=I.updatedAt?Date.parse(I.updatedAt):0,Pe=_.updatedAt?Date.parse(_.updatedAt):0;return $e!==Pe?Pe-$e:I.name.localeCompare(_.name)})},[Ot,K]),N=i.length,D=Math.max(1,Math.ceil(N/He)),ee=N===0?0:Math.min(wt,D-1),ie=ee*He,Ne=Math.min(N,ie+He),Te=N===0?0:ie+1,xt=N===0?0:Ne,me=r.useMemo(()=>i.slice(ie,Ne),[Ne,ie,i]),Ge=r.useMemo(()=>new Set(i.map(u=>u.id)),[i]),Ee=r.useMemo(()=>i.filter(u=>Xe.has(u.id)),[Xe,i]),jt=r.useMemo(()=>me.filter(u=>Xe.has(u.id)),[me,Xe]),Ze=Ee.length,qt=jt.length,J=me.length>0&&qt===me.length,je=Se.bulkEntityMutation.isPending,ct=r.useMemo(()=>{var _;const u=new Map;for(const W of s){const he=(_=W.initiativeId)==null?void 0:_.trim();if(!he)continue;const $e=u.get(he)??{activeCount:0,totalCount:0,lastHeartbeatAt:null,lastHeartbeatMs:0};$e.totalCount+=1,W.state==="active"&&($e.activeCount+=1);const Pe=W.lastHeartbeatAt??W.lastEventAt??null,ue=Pe?Date.parse(Pe):Number.NaN;Number.isFinite(ue)&&ue>$e.lastHeartbeatMs&&($e.lastHeartbeatMs=ue,$e.lastHeartbeatAt=new Date(ue).toISOString()),u.set(he,$e)}const I=new Map;for(const[W,he]of u.entries())I.set(W,{activeCount:he.activeCount,totalCount:he.totalCount,lastHeartbeatAt:he.lastHeartbeatAt});return I},[s]),qe=r.useMemo(()=>H!=="none"?Ar(me,H):null,[H,me]),rs=r.useMemo(()=>(qe==null?void 0:qe.map(u=>es(H,u.key)))??[],[H,qe]),C=r.useMemo(()=>{if(!qe)return me.map(I=>I.id);const u=[];for(const I of qe){const _=es(H,I.key);if(ge.has(_))for(const W of I.initiatives)u.push(W.id)}return u},[ge,H,qe,me]),{handleSelect:se}=Lr(C),Re=r.useCallback(u=>{De(I=>{const _=new Set(I);return _.has(u)?_.delete(u):_.add(u),_})},[]);r.useEffect(()=>{if(!qe||qe.length===0){De(I=>I.size===0?I:new Set);return}const u=new Set(qe.map(I=>es(H,I.key)));De(I=>{const _=new Set(Array.from(I).filter(W=>u.has(W)));return _.size===0&&_.add(es(H,qe[0].key)),Mr(_,I)?I:_})},[H,qe]),r.useEffect(()=>{ft(u=>{if(u.size===0)return u;const I=new Set(Array.from(u).filter(_=>Ge.has(_)));return Mr(I,u)?u:I})},[Ge]),r.useEffect(()=>{if(o&&!Ue.current&&!n&&t.length>0){const u=i.findIndex(I=>I.id===o);if(u>=0&&vt(Math.floor(u/He)),V(o),qe){const I=qe.find(_=>_.initiatives.some(W=>W.id===o));if(I){const _=es(H,I.key);De(W=>{if(W.has(_))return W;const he=new Set(W);return he.add(_),he})}}Ue.current=!0,requestAnimationFrame(()=>{const I=document.getElementById(`initiative-${o}`);I==null||I.scrollIntoView({behavior:"smooth",block:"start"})})}},[o,n,t.length,V,He,H,qe,i]),r.useEffect(()=>{Ze===0&&mt&&pt(!1)},[mt,Ze]),r.useEffect(()=>{vt(u=>Math.min(u,Math.max(D-1,0)))},[D]),r.useEffect(()=>{vt(0)},[M,m,k,F,re,O,H,K,He]);const Ve=me.length>0&&me.every(u=>de.has(u.id)),et=r.useMemo(()=>B?B.type==="initiative"?B.entity.id:B.initiative.id:Xe.size===1?Array.from(Xe)[0]??null:de.size===1?Array.from(de)[0]??null:o||null,[de,o,B,Xe]),Ct=r.useMemo(()=>et?i.find(u=>u.id===et)??null:null,[et,i]),as=ya({projectId:a,limit:40,authToken:pe,embedMode:ae,enabled:d?!1:t.length>0,snapshotVersion:y}),ke=d??as,Vs=Ea({authToken:pe,embedMode:ae,enabled:t.length>0}),Ns=to({enabled:t.length>0,projectId:a}),Gt=r.useMemo(()=>{var rt;if((rt=Ns.data)!=null&&rt.aggregate){const ce=Ns.data.aggregate;return{completionPercent:ce.completionPercent,totalTasks:ce.totalTasks,doneTasks:ce.doneTasks,blockedCount:ce.blockedCount,activeAgents:ce.activeAgents}}const u=new Set;let I=0,_=0,W=0;const he=ce=>typeof ce!="string"?"":ce.trim().toLowerCase().replace(/\s+/g," "),$e=(ce,Le)=>{var on;const Mt=typeof ce.id=="string"&&ce.id.trim().length>0?ce.id.trim():"";if(Mt)return Mt;const us=he(ce.title??ce.name??null),ms=he(ce.description??ce.summary??null),Ts=typeof ce.milestoneId=="string"&&ce.milestoneId.trim().length>0?ce.milestoneId.trim():typeof ce.milestone_id=="string"&&ce.milestone_id.trim().length>0?ce.milestone_id.trim():((on=Le.milestoneId)==null?void 0:on.trim())??"none";return[Le.initiativeId,Le.workstreamId,Ts,us||"untitled",ms||"no-description"].join(":")},Pe=(ce,Le)=>{const Mt=$e(ce,Le);u.has(Mt)||(u.add(Mt),I+=1,no(String(ce.status??""))&&(_+=1),String(ce.status??"").trim().toLowerCase()==="blocked"&&(W+=1))};for(const ce of t){ce.status==="blocked"&&(W+=1);for(const Le of ce.workstreams??[]){String(Le.status??"").trim().toLowerCase()==="blocked"&&(W+=1);const Mt=Array.isArray(Le.milestones)?Le.milestones:[],us=ce.id,ms=typeof Le.id=="string"&&Le.id.trim().length>0?Le.id.trim():"workstream",Ts=new Set;for(const Pt of Mt){String(Pt.status??"").trim().toLowerCase()==="blocked"&&(W+=1);const ln=Array.isArray(Pt.tasks)?Pt.tasks:[],Vn=typeof Pt.id=="string"&&Pt.id.trim().length>0?Pt.id.trim():"milestone";ln.forEach(Kn=>{const oa=$e(Kn,{initiativeId:us,workstreamId:ms,milestoneId:Vn});Ts.add(oa),Pe(Kn,{initiativeId:us,workstreamId:ms,milestoneId:Vn})})}(Array.isArray(Le.tasks)?Le.tasks:[]).forEach(Pt=>{const ln=$e(Pt,{initiativeId:us,workstreamId:ms});Ts.has(ln)||Pe(Pt,{initiativeId:us,workstreamId:ms})})}}const ue=I>0?_/I*100:t.length>0?t.reduce((ce,Le)=>ce+Math.max(0,Le.health),0)/t.length:0,bt=t.reduce((ce,Le)=>ce+Le.activeAgents,0);return{completionPercent:ue,totalTasks:I,doneTasks:_,blockedCount:W,activeAgents:bt}},[t,Ns.data]),Ss=js({authToken:pe,embedMode:ae,projectId:a}),At=v??Ss,ve=ke.items[0]??null,ne=r.useMemo(()=>ke.items.find(u=>u.playbackState==="running"||u.playbackState==="blocked")??ke.items.find(u=>u.queueState==="running"||u.queueState==="blocked")??null,[ke.items]),nt=r.useMemo(()=>ke.items.find(u=>ne&&u.initiativeId===ne.initiativeId&&u.workstreamId===ne.workstreamId?!1:u.playbackState==="queued"||u.playbackState==="idle"||u.queueState==="queued"||u.queueState==="idle")??null,[ke.items,ne]),be=r.useMemo(()=>ve?t.find(u=>u.id===ve.initiativeId)??Ct:Ct,[Ct,t,ve]),Jt=ne??nt??ve??null,Ks=r.useMemo(()=>ke.items.find(u=>{var I,_;return((I=u.autoContinue)==null?void 0:I.status)==="running"||((_=u.autoContinue)==null?void 0:_.status)==="stopping"})??ke.items.find(u=>{var I,_;return((I=u.autoContinue)==null?void 0:I.stopReason)==="blocked"||((_=u.autoContinue)==null?void 0:_.stopReason)==="error"})??null,[ke.items]),It=(Ks==null?void 0:Ks.initiativeId)??(Jt==null?void 0:Jt.initiativeId)??(be==null?void 0:be.id)??null,gt=r.useMemo(()=>It?t.find(u=>u.id===It)??be??null:be??null,[It,t,be]),En=r.useCallback((u,I,_)=>{st(null),pt(!1),se(u,I,_,ft)},[se]),Rr=r.useCallback(()=>{st(null),pt(!1),ft(u=>{if(me.length===0)return u;const I=new Set(u);if(J)for(const _ of me)I.delete(_.id);else for(const _ of me)I.add(_.id);return I})},[J,me]),Br=r.useCallback(()=>{pt(!1),ft(new Set)},[]),An=ee>0,Mn=ee<D-1,zt=r.useCallback(u=>{vt(Math.max(0,Math.min(u,D-1)))},[D]),Or=r.useCallback(()=>{zt(0)},[zt]),qr=r.useCallback(()=>{zt(ee-1)},[ee,zt]),zr=r.useCallback(()=>{zt(ee+1)},[ee,zt]),Ur=r.useCallback(()=>{zt(D-1)},[zt,D]),Cs=r.useCallback(async u=>{if(Ee.length!==0){pt(!1),st(null);try{const I=await Se.bulkEntityMutation.mutateAsync({items:Ee.map(_=>({type:"initiative",id:_.id})),mode:"update",updates:{status:u}});I.failed>0?st({tone:"error",message:`Updated ${I.updated}, failed ${I.failed}.`}):st({tone:"success",message:`Updated ${I.updated} initiative${I.updated===1?"":"s"} to ${u}.`})}catch(I){st({tone:"error",message:Qt(I instanceof Error?I.message:"","Bulk initiative update failed.")})}}},[Se.bulkEntityMutation,Ee]),Wr=r.useCallback(async()=>{if(Ee.length!==0){st(null);try{const u=await Se.bulkEntityMutation.mutateAsync({items:Ee.map(I=>({type:"initiative",id:I.id})),mode:"delete"});u.failed>0?st({tone:"error",message:`Deleted ${u.updated}, failed ${u.failed}.`}):(st({tone:"success",message:`Deleted ${u.updated} initiative${u.updated===1?"":"s"}.`}),ft(new Set),pt(!1))}catch(u){st({tone:"error",message:Qt(u instanceof Error?u.message:"","Bulk initiative delete failed.")})}}},[Se.bulkEntityMutation,Ee]),Gs=r.useCallback(()=>{x.current+=1,Be(!1)},[]),Qr=r.useCallback(u=>{if(u.length===0){Gs();return}const I=1,_=x.current+1;x.current=_,Be(!0);const W=he=>{if(x.current===_){if(q(u.slice(0,he)),he>=u.length){Be(!1);return}requestAnimationFrame(()=>W(Math.min(u.length,he+I)))}};W(Math.min(I,u.length))},[Gs,q]),_e=Ma({initiativeId:It,projectId:a,authToken:pe,embedMode:ae,enabled:!!It}),[Yt,is]=r.useState(null),Is=_e.run,Js=((zn=_e.error)==null?void 0:zn.toLowerCase())??"",Ys=!It||Js.includes("404")||Js.includes("400")||Js.includes("not found"),kt=It?ct.get(It)??null:null,Xs=((kt==null?void 0:kt.activeCount)??0)>0,Hr=((kt==null?void 0:kt.totalCount)??0)>0,Tn=Yt?`Upgrade required · ${Xn(Yt.currentPlan)} → ${Xn(Yt.requiredPlan)}`:It?_e.isRunning?Xs?`Running · ${(kt==null?void 0:kt.activeCount)??0} live`:Hr?`Enabled · ${(kt==null?void 0:kt.totalCount)??0} idle`:"Enabled · waiting":Is!=null&&Is.stopReason?`Idle · ${Is.stopReason.replace(/_/g," ")}`:"Idle":"No target",os=!!Yt&&!_e.isRunning,Vr=os?"amber":"teal",Kr=r.useMemo(()=>{const u=new URL("https://www.useorgx.com/integrations/openclaw");return u.searchParams.set("utm_source",ae?"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()},[ae]);r.useEffect(()=>{is(null)},[It]),r.useEffect(()=>{const u=Ke.current;if(!u)return;const I=()=>{Z(Math.max(64,u.offsetHeight))};if(I(),typeof ResizeObserver>"u")return;const _=new ResizeObserver(()=>I());return _.observe(u),()=>_.disconnect()},[Tn,l,h,n,i.length]);const Es=!!(!n&&f&&(l==="disconnected"||h)),Dn=l==="disconnected"||h?"critical":"info",$n=l==="disconnected"?"Offline":h?"Live degraded":"Connected",Zs=h?oo(h):l==="disconnected"?"Live updates are offline. Data may be stale until reconnect.":`Last snapshot ${co(c)}`;r.useEffect(()=>{Es||G(!1)},[Es]);const _t=r.useCallback((u,I)=>{if(!t.find(ue=>ue.id===u)){const ue=(I??"").trim(),bt=ue?Cn(ue)?`Initiative ${Dr(ue)}`:hs(ue):"This initiative";return xe({tone:"error",message:`${bt} is not in this workspace view. Switch workspace or clear filters to find it.`}),!1}xe(null);const W=i.findIndex(ue=>ue.id===u),he=W<0;if(W>=0&&vt(Math.floor(W/He)),he&&(R(""),b([]),$("target"),te("any"),X(""),w("")),V(u),H!=="none"){const ue=W>=0?i:t,rt=Ar(ue,H).find(ce=>ce.initiatives.some(Le=>Le.id===u));if(rt){const ce=es(H,rt.key);De(Le=>{if(Le.has(ce))return Le;const Mt=new Set(Le);return Mt.add(ce),Mt})}}const $e=(ue=0)=>{const bt=document.getElementById(`initiative-${u}`);if(bt){bt.scrollIntoView({behavior:ue===0?"smooth":"auto",block:"start"});const rt=Math.max(72,Y)+8,ce=bt.getBoundingClientRect();!(ce.top>=rt&&ce.top<=window.innerHeight-72)&&ue<18&&window.setTimeout(()=>$e(ue+1),90);return}ue>=60||requestAnimationFrame(()=>$e(ue+1))},Pe=()=>requestAnimationFrame(()=>$e());return he?window.setTimeout(Pe,90):Pe(),!0},[t,He,xe,vt,R,b,$,te,X,w,V,H,i,Y]),Gr=r.useCallback(()=>{be&&(xe(null),Se.updateEntity.mutateAsync({type:"initiative",id:be.id,status:"active"}).then(()=>{xe({tone:"success",message:`Started ${be.name}.`}),_t(be.id,be.name)}).catch(u=>{xe({tone:"error",message:Qt(u instanceof Error?u.message:"","Failed to start initiative.")})}))},[Se.updateEntity,be,_t]),Ut=r.useCallback(async(u,I,_)=>{Bt(u),xe(null);try{await I(),xe({tone:"success",message:_})}catch(W){xe({tone:"error",message:Qt(W instanceof Error?W.message:"","Action failed.")})}finally{Bt(null)}},[]),en=r.useCallback(async(u,I)=>{const _=(I==null?void 0:I.surface)!=="card";_&&(Bt("start"),xe(null)),ot(null);try{const W=await ke.playWorkstream({initiativeId:u.initiativeId,workstreamId:u.workstreamId,agentId:u.runnerAgentId});return _&&xe({tone:"success",message:`Started ${u.workstreamTitle}.`}),W}catch(W){if(Zn(W)&&W.code==="auto_continue_already_running"){const he=W.details,$e=he&&typeof he.activeWorkstreamTitle=="string"?he.activeWorkstreamTitle:null,Pe=he&&typeof he.activeWorkstreamId=="string"?he.activeWorkstreamId:null;if(ot({target:u,message:W.message||"A workstream is already running. Stop it before starting another.",activeWorkstreamTitle:$e,activeWorkstreamId:Pe}),!_)throw W;return null}if(_)return xe({tone:"error",message:Qt(W instanceof Error?W.message:"","Unable to start workstream.")}),null;throw W}finally{_&&Bt(null)}},[ke]),Jr=r.useCallback(()=>ne?Ut("pause",()=>At.stopTriage({initiativeId:ne.initiativeId,workstreamId:ne.workstreamId,placement:"bottom",resetToTodo:!1}),`Paused ${ne.workstreamTitle} and moved it to bottom of queue.`):Promise.resolve(),[At,ne,Ut]),Yr=r.useCallback(()=>{if(!ne)return Promise.resolve();const u=ne.playbackState==="running"||ne.playbackState==="blocked"||ne.queueState==="running"||ne.queueState==="blocked";return Ut("defer",()=>u?At.stopTriage({initiativeId:ne.initiativeId,workstreamId:ne.workstreamId,placement:"bottom",resetToTodo:!1}):At.move({initiativeId:ne.initiativeId,workstreamId:ne.workstreamId,placement:"bottom"}),`Deferred ${ne.workstreamTitle} to bottom of queue.`)},[At,ne,Ut]),Xr=r.useCallback(()=>{const u=ne??nt??ve;return u?u.autoIntentEnabled===!0&&(u.autoRuntimeState==="running"||u.autoRuntimeState==="stopping")?Ut("auto",()=>ke.stopInitiativeAutoContinue({initiativeId:u.initiativeId}),`Stopped auto-continue for ${u.initiativeTitle}.`):(tt(u),Promise.resolve()):Promise.resolve()},[ke,ve,nt,ne,Ut]),Zr=r.useCallback(()=>{if(!Ye)return;const u=Ye;tt(null),Ut("auto",()=>ke.startWorkstreamAutoContinue({initiativeId:u.initiativeId,workstreamId:u.workstreamId,agentId:u.runnerAgentId,scope:"initiative"}),`Auto-continue enabled for ${u.initiativeTitle}; starting with ${u.workstreamTitle}.`)},[Ye,ke,Ut]),ea=r.useCallback(async()=>{if(!(!ye||ht)){Vt(!0),xe(null);try{try{await ke.stopInitiativeAutoContinue({initiativeId:ye.target.initiativeId})}catch(u){if(!Zn(u)||u.status!==404)throw u}await ke.playWorkstream({initiativeId:ye.target.initiativeId,workstreamId:ye.target.workstreamId,agentId:ye.target.runnerAgentId}),ot(null),xe({tone:"success",message:`Switched run to ${ye.target.workstreamTitle}.`})}catch(u){xe({tone:"error",message:Qt(u instanceof Error?u.message:"","Unable to switch run.")})}finally{Vt(!1)}}},[ht,ke,ye]),Ln=r.useCallback(()=>{be&&(_t(be.id,be.name),typeof window<"u"&&window.innerWidth>=1280&&Ce(!0))},[be,_t]),tn=r.useCallback(()=>{if(typeof window>"u")return;if(window.innerWidth>=1280){const I=!oe;Fe(!1),Ce(I),xe({tone:"success",message:I?"Opened queue rail.":"Closed queue rail."});return}const u=!Ie;Ce(!1),Fe(u),xe({tone:"success",message:u?"Opened queue panel.":"Closed queue panel."})},[Ie,oe]),ls=Bs((be==null?void 0:be.rawStatus)??(be==null?void 0:be.status)??null),_n=r.useMemo(()=>new Set(["paused","draft","planned","todo","backlog","queued"]),[]),dt=r.useMemo(()=>be?(ne==null?void 0:ne.queueState)==="running"||(ne==null?void 0:ne.playbackState)==="running"||(ve==null?void 0:ve.autoIntentEnabled)===!0&&(ve.autoRuntimeState==="running"||ve.autoRuntimeState==="stopping")?"running":(ve==null?void 0:ve.queueState)==="blocked"||be.status==="blocked"?"blocked":ve?"queued":_n.has(ls)?"startable":ls==="completed"||ls==="done"?"completed":"active_no_queue":"none",[be,ve,_n,ls,ne]),sn=r.useMemo(()=>be?dt==="running"&&ve?{headline:`${ve.workstreamTitle} is running`,detail:`Runner: ${ve.runnerAgentName}. Follow live updates in Activity.`}:dt==="queued"&&ve?{headline:ve.workstreamTitle,detail:`Ready to dispatch${ve.nextTaskTitle?` · ${ve.nextTaskTitle}`:""}.`}:dt==="startable"?{headline:ls==="paused"?`${be.name} is paused`:`${be.name} is ready to start`,detail:"Start initiative to queue and dispatch the next workstream."}:dt==="blocked"?{headline:(ve==null?void 0:ve.queueState)==="blocked"?`${ve.workstreamTitle} is blocked`:`${be.name} is blocked`,detail:(ve==null?void 0:ve.blockReason)??"Resolve blockers or approvals before dispatching more work."}:dt==="completed"?{headline:`${be.name} is complete`,detail:"Choose another active initiative or queue new workstreams."}:{headline:be.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."},[be,dt,ve,ls]),As=ke.isPlaying||ke.isStartingAutoContinue||ke.isStoppingAutoContinue||ht||Se.updateEntity.isPending,ta=r.useMemo(()=>dt==="blocked"?"Review blockers":dt==="active_no_queue"?"Open and queue work":dt==="completed"?"Review initiative":"Open initiative",[dt]),Pn=r.useMemo(()=>(ne==null?void 0:ne.playbackState)==="running"||(ne==null?void 0:ne.queueState)==="running"?"running":(ne==null?void 0:ne.playbackState)==="blocked"||(ne==null?void 0:ne.queueState)==="blocked"?"blocked":nt?"queued":dt==="startable"?"startable":dt==="completed"?"completed":be?"active_no_queue":"none",[be,dt,nt,ne]),Fn=(ne==null?void 0:ne.workstreamTitle)??"No active workstream",sa=(ne==null?void 0:ne.initiativeTitle)??(be==null?void 0:be.name)??"No initiative selected",nn=ne?[ne.nextTaskTitle?`Next: ${ne.nextTaskTitle}`:null,ne.blockReason?`Blocked: ${ne.blockReason}`:null].filter(Boolean).join(" · "):nt?`Next up: ${nt.workstreamTitle}`:sn.detail,Rn=(nt==null?void 0:nt.workstreamTitle)??"Queue is empty",Bn=nt!=null&&nt.nextTaskTitle?`Next task: ${nt.nextTaskTitle}`:"Add or reorder workstreams in queue.",na=ao(Pn),ra=io(Pn),cs=ne??nt??ve,rn=(cs==null?void 0:cs.autoIntentEnabled)===!0&&(cs.autoRuntimeState==="running"||cs.autoRuntimeState==="stopping"),ds=Sa(),an="next-up-surface",Wt=r.useMemo(()=>ds?{duration:.01}:Ft.railMorphSpring,[ds]),On=r.useMemo(()=>ds?{duration:.01}:Ft.surfaceSwitch,[ds]),Ms=r.useMemo(()=>ds?{initial:{opacity:1,y:0},animate:{opacity:1,y:0},exit:{opacity:1,y:0},transition:{duration:.01}}:Ft.contentCrossFade,[ds]),aa=r.useMemo(()=>({backgroundColor:"rgba(10, 14, 21, 0.66)",borderColor:"rgba(255, 255, 255, 0.10)"}),[]),qn=r.useMemo(()=>({backgroundColor:"rgba(10, 14, 21, 0.95)",borderColor:"rgba(255, 255, 255, 0.11)"}),[]),ia=r.useMemo(()=>{if(!B)return null;const u=_=>t.find(W=>W.id===_)??null;if(B.type==="initiative"){const _=u(B.entity.id);return _?{...B,entity:_}:B}const I=u(B.initiative.id);return I?{...B,initiative:I}:B},[t,B]);return r.useEffect(()=>{if(!ye)return;ke.items.some(I=>I.initiativeId===ye.target.initiativeId&&I.workstreamId===ye.target.workstreamId)||ot(null)},[ke.items,ye]),r.useEffect(()=>{if(!Ye)return;ke.items.some(I=>I.initiativeId===Ye.initiativeId&&I.workstreamId===Ye.workstreamId)||tt(null)},[Ye,ke.items]),r.useEffect(()=>{if(!B)return;const u=B.type==="initiative"?B.entity.id:B.initiative.id;t.some(_=>_.id===u)||U()},[U,t,B]),r.useEffect(()=>{if(typeof window>"u")return;const u=()=>{window.innerWidth>=1280?Fe(!1):Ce(!1)};return u(),window.addEventListener("resize",u),()=>window.removeEventListener("resize",u)},[]),e.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden",children:[e.jsxs("div",{className:"relative flex-1 min-h-0",children:[e.jsx("div",{className:"pointer-events-none absolute top-0 left-0 right-0 h-6 bg-gradient-to-b from-[#02040A] to-transparent z-10"}),e.jsx("div",{className:"pointer-events-none absolute bottom-0 left-0 right-0 h-12 bg-gradient-to-t from-[#02040A] to-transparent z-10"}),e.jsx("div",{"data-mc-scroll-host":"true",className:"h-full overflow-y-auto overflow-x-hidden",children:e.jsxs("div",{className:"mx-auto max-w-6xl px-4 sm:px-6",style:{"--mc-toolbar-offset":`${Y}px`},children:[e.jsxs(Ca,{id:"next-up-morph",children:[e.jsxs("div",{ref:Ke,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 hidden sm:block sm:right-6",children:e.jsx($r,{open:Es&&!T,tone:Dn==="critical"?"error":"warning",title:$n,message:Zs,onDismiss:()=>G(!0),primaryAction:p?{label:"Refresh",onClick:p}:null,secondaryAction:j?{label:"Settings",onClick:j}:null})}),Es&&!T?e.jsxs("div",{className:"mb-2 flex items-center gap-2 rounded-lg border border-white/[0.08] bg-white/[0.03] px-3 py-2 sm:hidden",children:[e.jsx("span",{className:`h-2 w-2 rounded-full ${Dn==="critical"?"bg-red-400":"bg-amber-300"}`,"aria-hidden":!0}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-micro font-semibold text-white/88",children:$n}),e.jsx("p",{className:"truncate text-micro text-white/56",children:Zs})]}),e.jsx("button",{type:"button",onClick:()=>G(!0),className:"control-pill h-7 px-2 text-micro font-semibold",children:"Hide"})]}):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(In,{value:M,onChange:R,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:Ot.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:(gt==null?void 0:gt.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:Tn}),gt&&e.jsx("div",{className:"truncate text-micro text-white/44",children:gt.name})]})]}),e.jsxs("button",{type:"button",onClick:()=>{if(Ys||!It)return;if(os&&Yt){ja({actions:Yt.actions,requiredPlan:Yt.requiredPlan}).catch(_=>{xe({tone:"error",message:Qt(_ instanceof Error?_.message:"","Unable to open checkout right now.")})});return}const u=_e.isRunning;(u?_e.stop:_e.start)().then(()=>{is(null);const _=(gt==null?void 0:gt.name)??"selected initiative";xe({tone:"success",message:u?`Stopped Autopilot for ${_}.`:`Started Autopilot for ${_}.`})}).catch(_=>{_ instanceof wa?is(_):(is(null),xe({tone:"error",message:Qt(_ instanceof Error?_.message:"","Autopilot action failed.")}))})},disabled:Ys||_e.isStarting||_e.isGracefullyStopping,title:Ys?"Select an initiative to run Autopilot":os?"Upgrade to enable auto-continue for BYOK agents":_e.isRunning?"Stop Autopilot":`Start Autopilot${gt?` for ${gt.name}`:""}`,"data-state":_e.isRunning||os?"active":"idle","data-tone":Vr,className:"control-pill flex items-center gap-1.5 px-3 text-caption font-semibold disabled:opacity-40",children:[os?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?Xs?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:os?"Upgrade Autopilot":_e.isGracefullyStopping?"Stopping Autopilot…":`${_e.isRunning?"Stop":"Start"} Autopilot`}),_e.isRunning&&Xs&&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 mt-1.5 hidden items-center gap-2 rounded-lg px-3 py-1.5 sm:flex","data-state":(Un=_e.run)!=null&&Un.lastError?"error":((Wn=_e.run)==null?void 0:Wn.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"}),((Qn=_e.run)==null?void 0:Qn.tokensUsed)!=null&&((Hn=_e.run)==null?void 0:Hn.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"]})]}),ae&&e.jsxs("a",{href:Kr,target:"_blank",rel:"noreferrer noopener",onClick:()=>{try{va("live_install_cta_click",{surface:"mission_control",embedMode:!0,initiativeId:(gt==null?void 0:gt.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:()=>{Ve?(Gs(),P(),qe&&rs.length>0&&De(new Set)):(Qr(me.map(u=>u.id)),qe&&rs.length>0&&De(new Set(rs)))},title:Ve?"Collapse all":"Expand all","aria-busy":We&&!Ve,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:Ve?e.jsxs(e.Fragment,{children:[e.jsx("path",{d:"M4 14h16"}),e.jsx("path",{d:"M4 10h16"})]}):e.jsxs(e.Fragment,{children:[e.jsx("path",{d:"M4 12h16"}),e.jsx("path",{d:"M12 4v16"})]})})})]})]})]}),!1,i.length>0&&e.jsxs("div",{"data-mc-selection-bar":"true",className:`mt-3 relative grid overflow-hidden rounded-xl border xl:grid-cols-[minmax(0,1fr)_560px] xl:gap-0 xl:items-center ${Ze>0?"border-lime/14 bg-[#0A0E15]/72":"border-white/[0.10] bg-[#0A0E15]/66"}`,children:[Ze>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 ${Ze>0?"xl:min-h-[92px] xl:items-start":"xl:min-h-[70px] xl:items-center"}`,children:e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("label",{className:"inline-flex flex-shrink-0 items-center gap-2 text-caption text-primary",children:[e.jsx("input",{type:"checkbox",checked:J,onChange:Rr,className:"h-3.5 w-3.5 rounded border-white/20 bg-black/40 text-lime focus:ring-lime/35"}),"Select page"]}),e.jsx("span",{className:"flex-shrink-0 text-caption text-white/58",children:Ze>0?`${Ze} selected`:N===0?"0 visible":`${Te}-${xt} of ${N}`}),Ze>0&&e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("button",{type:"button",onClick:()=>{Cs("active")},disabled:je,className:"control-pill h-8 flex-shrink-0 px-3 text-caption font-semibold disabled:opacity-45","data-state":"active",children:"Mark active"}),e.jsx("button",{type:"button",onClick:()=>{Cs("paused")},disabled:je,className:"control-pill h-8 flex-shrink-0 px-3 text-caption font-semibold disabled:opacity-45",children:"Pause"}),e.jsx("button",{type:"button",onClick:()=>{Cs("blocked")},disabled:je,className:"control-pill h-8 flex-shrink-0 px-3 text-caption font-semibold disabled:opacity-45",children:"Block"}),e.jsx("button",{type:"button",onClick:()=>{Cs("completed")},disabled:je,className:"control-pill h-8 flex-shrink-0 px-3 text-caption font-semibold disabled:opacity-45",children:"Complete"}),mt?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:()=>{Wr()},disabled:je,className:"control-pill h-8 flex-shrink-0 border-red-400/35 bg-red-500/14 px-3 text-caption font-semibold text-red-100 disabled:opacity-45",children:"Delete"}),e.jsx("button",{type:"button",onClick:()=>pt(!1),disabled:je,className:"control-pill h-8 flex-shrink-0 px-2.5 text-caption disabled:opacity-45",children:"Keep"})]}):e.jsx("button",{type:"button",onClick:()=>pt(!0),disabled:je,className:"control-pill h-8 flex-shrink-0 border-red-400/24 bg-red-500/[0.08] px-3 text-caption font-semibold text-red-100/85 disabled:opacity-45",children:"Delete"}),e.jsx("button",{type:"button",onClick:Br,disabled:je,className:"text-caption text-secondary transition-colors hover:text-primary disabled:opacity-45",children:"Clear"})]})]})}),e.jsx(at,{initial:!1,mode:"popLayout",children:!oe&&!Ie&&e.jsxs(le.div,{layout:"position",layoutId:an,initial:{opacity:0,y:4},animate:{opacity:1,y:0,...aa},exit:{opacity:0,y:-4},transition:{layout:Wt,...On},className:"flex w-full min-w-0 flex-col gap-2 overflow-hidden rounded-xl border border-strong px-2.5 py-2 shadow-[0_10px_24px_rgba(0,0,0,0.22)] backdrop-blur-[10px] sm:flex-row sm:items-center xl:h-full xl:rounded-none xl:border-b-0 xl:border-l xl:border-r-0 xl:border-t-0 xl:border-white/[0.10] xl:bg-transparent xl:px-3 xl:py-2 xl:shadow-none xl:backdrop-blur-none",children:[e.jsxs("div",{className:"flex min-w-0 w-full flex-1 items-center gap-2.5",children:[ke.isLoading?e.jsx($t,{className:"h-6 w-6 rounded-full"}):Jt?e.jsx(bn,{name:Jt.runnerAgentName,hint:`${Jt.runnerAgentId} ${Jt.runnerSource}`,size:"xs"}):e.jsx("div",{className:"h-6 w-6 rounded-full border border-strong bg-white/[0.05]"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-micro font-semibold uppercase tracking-[0.08em] text-white/76",children:"Now Working"}),ke.isLoading?e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full border border-strong bg-white/[0.04] px-1.5 py-0.5 text-micro uppercase tracking-[0.08em] text-secondary",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-lime/70 status-breathe"}),"Syncing"]}):e.jsx("span",{className:`rounded-full border px-1.5 py-0.5 text-micro uppercase tracking-[0.08em] ${ra}`,children:na})]}),ke.isLoading?e.jsxs("div",{className:"mt-1.5 space-y-1",children:[e.jsx($t,{className:"h-3 w-56 rounded"}),e.jsx($t,{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:Fn,children:Fn}),e.jsxs("p",{className:"truncate text-caption leading-snug text-secondary",title:nn,children:[sa,nn?` · ${nn}`:""]}),e.jsxs("p",{className:"hidden truncate text-micro leading-snug text-secondary/85 sm:block",title:Rn,children:["Up next: ",Rn,Bn?` · ${Bn}`:""]})]})]})]}),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=nt??ve;if(ne){Jr();return}if(u){en(u);return}Ln()},disabled:As||Rt==="start"||Rt==="pause",className:"control-pill h-8 flex-shrink-0 px-3 text-caption font-semibold disabled:opacity-45",title:ne?`Pause ${ne.workstreamTitle}`:"Start next workstream",children:ne?"Pause":"Start"}),e.jsx("button",{type:"button",onClick:()=>void Yr(),disabled:!ne||Rt==="defer"||As,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 Xr(),disabled:!cs||Rt==="auto"||As,className:"control-pill h-8 flex-shrink-0 px-3 text-caption font-semibold disabled:opacity-45","data-state":rn?"active":"idle","data-tone":"teal",title:rn?"Stop automatic continuation":"Continue automatically for this initiative",children:rn?"Auto on":"Auto"}),e.jsx("button",{type:"button",onClick:tn,className:"control-pill h-8 flex-shrink-0 px-3 text-caption font-semibold",title:"Open queue",children:"Open queue"})]})]},"next-up-inline-card")})]}),Qe&&e.jsxs("div",{role:"status","aria-live":"polite",className:"mt-2 flex items-start justify-between gap-3 rounded-lg border border-white/[0.08] bg-white/[0.02] px-3 py-2 text-caption text-white/72",children:[e.jsxs("div",{className:"flex min-w-0 items-start gap-2",children:[e.jsx("span",{"aria-hidden":!0,className:`mt-[3px] h-1.5 w-1.5 flex-shrink-0 rounded-full ${Qe.tone==="success"?"bg-emerald-300/90":"bg-amber-300/90"}`}),e.jsx("span",{className:"min-w-0 leading-snug",children:Qe.message})]}),e.jsx("button",{type:"button",onClick:()=>st(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(le.div,{layout:!0,transition:{type:"spring",stiffness:260,damping:30},className:`mt-3 grid gap-4 pb-8 ${oe?"xl:grid-cols-[minmax(0,1fr)_320px] xl:gap-0":"grid-cols-1"}`,children:[e.jsxs(le.div,{layout:!0,className:`min-w-0 ${oe?"xl:pr-4":""}`,children:[S&&!n&&be&&e.jsxs(le.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:sn.headline}),e.jsx("p",{className:"mt-1 text-body leading-relaxed text-secondary",children:sn.detail}),Me&&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 ${Me.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:Me.message})]}),e.jsxs("div",{className:"ml-auto flex flex-wrap items-center gap-2.5 xl:self-end",children:[dt==="startable"?e.jsx("button",{type:"button",onClick:Gr,disabled:As,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:Ln,className:"control-pill h-9 px-4 text-body font-semibold","data-state":dt==="blocked"?"active":"idle",children:ta}),e.jsx("button",{type:"button",onClick:tn,className:"control-pill h-9 px-4 text-body font-semibold",children:oe?"Hide Queue":"Open Queue"})]})]})]}),S&&!n&&t.length>0&&e.jsxs("div",{className:"grid grid-cols-1 gap-4 xl:grid-cols-2",children:[e.jsx(Zi,{completionPercent:Gt.completionPercent,totalTasks:Gt.totalTasks,doneTasks:Gt.doneTasks,blockedCount:Gt.blockedCount,activeAgents:Gt.activeAgents}),e.jsx(eo,{usage:Vs.summary})]}),n?e.jsx("div",{className:"space-y-3 pb-8",children:Array.from({length:4}).map((u,I)=>e.jsxs("div",{className:"bg-[--orgx-surface] border border-[--orgx-border] soft-shadow rounded-2xl p-4",children:[e.jsx($t,{className:"h-4 w-2/5 rounded"}),e.jsx($t,{className:"h-1 w-full rounded mt-3"})]},`mc-skeleton-${I}`))}):t.length===0?f?l==="disconnected"||h?e.jsx("div",{className:"pb-8",children:e.jsx(xn,{mode:"degraded",detail:Zs,onCreateInitiative:E,onPlayNextUp:L,onStartAutopilot:g,onRefresh:p,onOpenSettings:j})}):e.jsx("div",{className:"pb-8",children:e.jsx(xn,{mode:"empty",onCreateInitiative:E,onPlayNextUp:L,onStartAutopilot:g,onRefresh:p})}):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."}),j&&e.jsx("div",{className:"mt-4 flex items-center justify-center",children:e.jsx("button",{type:"button",onClick:j,className:"h-10 rounded-full border border-lime/30 bg-lime/15 px-4 text-body font-semibold text-lime transition-colors hover:bg-lime/20",children:"Open settings"})})]})}):i.length===0?e.jsx("div",{className:"pb-8",children:e.jsx(xn,{mode:"filtered",hasActiveFilters:A,onClearFilters:A?Q:void 0,onCreateInitiative:E,onPlayNextUp:L,onStartAutopilot:g,onRefresh:p})}):qe?e.jsx("div",{className:"space-y-4 pb-8",children:qe.map(u=>{const I=es(H,u.key),_=ro(I),W=ge.has(I);return e.jsxs(le.div,{layout:!0,transition:{type:"spring",stiffness:260,damping:30},children:[e.jsxs("button",{type:"button","aria-expanded":W,"aria-controls":_,onClick:()=>Re(I),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(at,{initial:!1,children:W&&e.jsx(le.div,{id:_,initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{height:{type:"spring",stiffness:320,damping:32},opacity:{duration:.14}},className:"overflow-hidden",children:e.jsx("div",{className:"pt-0.5",children:e.jsx(cr,{initiatives:u.initiatives,selectedInitiativeIds:Xe,onToggleInitiativeSelection:En,isSquished:oe,runtimeActivityByInitiativeId:ct})})})})]},u.key)})}):e.jsx("div",{className:"pb-8",children:e.jsx(cr,{initiatives:me,selectedInitiativeIds:Xe,onToggleInitiativeSelection:En,isSquished:oe,runtimeActivityByInitiativeId:ct})}),i.length>0&&e.jsxs("div",{className:"mt-2.5 flex flex-wrap items-center justify-between gap-2 rounded-xl border border-white/[0.08] bg-white/[0.02] px-3 py-2",children:[e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-2 text-caption text-white/70",children:[e.jsxs("span",{className:"font-medium text-white/80",children:["Showing ",Te,"-",xt]}),e.jsx("span",{className:"text-white/50",children:"of"}),e.jsx("span",{className:"font-medium text-white/80",children:N}),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:He,onChange:u=>{const I=Number.parseInt(u.target.value,10);Number.isFinite(I)&&ns(I)},className:"h-6 rounded-md border border-transparent bg-transparent px-1 text-caption text-white/90 outline-none",children:lo.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:Or,disabled:!An,className:"control-pill h-7 px-2 text-micro font-semibold disabled:opacity-40",title:"First page",children:"«"}),e.jsx("button",{type:"button",onClick:qr,disabled:!An,className:"control-pill h-7 px-2 text-micro font-semibold disabled:opacity-40",title:"Previous page",children:"‹"}),e.jsxs("span",{className:"px-1.5 text-micro text-white/64",children:["Page ",ee+1," / ",D]}),e.jsx("button",{type:"button",onClick:zr,disabled:!Mn,className:"control-pill h-7 px-2 text-micro font-semibold disabled:opacity-40",title:"Next page",children:"›"}),e.jsx("button",{type:"button",onClick:Ur,disabled:!Mn,className:"control-pill h-7 px-2 text-micro font-semibold disabled:opacity-40",title:"Last page",children:"»"})]})]})]})]}),e.jsx(at,{initial:!1,children:oe&&e.jsx(le.aside,{layout:!0,initial:{opacity:0,x:14},animate:{opacity:1,x:0},exit:{opacity:0,x:14},transition:On,className:"hidden xl:block",children:e.jsx("div",{className:"sticky",style:{top:"calc(var(--mc-toolbar-offset) + 12px)"},children:e.jsx(le.div,{layout:"position",layoutId:an,initial:{borderRadius:12},animate:{borderRadius:16,...qn},transition:{layout:Wt},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(le.button,{type:"button",onClick:()=>St("next-up"),...Ft.segmentedTap,className:`control-pill relative h-7 px-2 text-micro font-semibold ${Oe==="next-up"?"text-lime":"text-secondary"}`,children:[Oe==="next-up"?e.jsx(le.span,{layoutId:"next-up-rail-surface-indicator",transition:Wt,className:"pointer-events-none absolute inset-0 rounded-md border border-lime/34 bg-lime/[0.12]","aria-hidden":!0}):null,e.jsx("span",{className:"relative z-[1]",children:"Next Up"})]}),e.jsxs(le.button,{type:"button",onClick:()=>St("slices"),...Ft.segmentedTap,className:`control-pill relative h-7 px-2 text-micro font-semibold ${Oe==="slices"?"text-teal-100":"text-secondary"}`,children:[Oe==="slices"?e.jsx(le.span,{layoutId:"next-up-rail-surface-indicator",transition:Wt,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(at,{initial:!1,mode:"wait",children:Oe==="next-up"?e.jsx(le.div,{...Ms,className:"h-full min-h-0",children:e.jsx(er,{title:"Next Up",panelStyle:"flat",className:"!bg-transparent !shadow-none !border-transparent",disableEnterAnimation:!0,showHeader:!1,projectId:a,authToken:pe,embedMode:ae,queueModel:ke,queueActions:At,snapshotVersion:y,onPlayWorkstream:u=>en(u,{surface:"card"}),onOpenInitiative:_t,onOpenSettings:j,onUpgradeGate:is,excludeRunning:!0})},"next-up-rail"):e.jsx(le.div,{...Ms,className:"h-full min-h-0",children:e.jsx(Sr,{title:"Slice Explorer",className:"h-full !rounded-none !border-0 !bg-transparent",workspaceId:a,authToken:pe,embedMode:ae,compact:!0,onOpenInitiative:(u,I)=>{_t(u,I)}})},"slices-rail")})}),e.jsx("button",{type:"button",onClick:tn,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(at,{children:Ie&&e.jsxs(e.Fragment,{children:[e.jsx(le.button,{type:"button","aria-label":"Close next up panel",onClick:()=>Fe(!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(le.aside,{initial:{x:"100%",opacity:.85},animate:{x:0,opacity:1},exit:{x:"100%",opacity:.9},transition:Wt,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:()=>Fe(!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(le.div,{layout:"position",layoutId:an,initial:{borderRadius:12},animate:{borderRadius:16,...qn},transition:{layout:Wt},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(le.button,{type:"button",onClick:()=>St("next-up"),...Ft.segmentedTap,className:`control-pill relative h-7 px-2 text-micro font-semibold ${Oe==="next-up"?"text-lime":"text-secondary"}`,children:[Oe==="next-up"?e.jsx(le.span,{layoutId:"next-up-rail-surface-indicator-mobile",transition:Wt,className:"pointer-events-none absolute inset-0 rounded-md border border-lime/34 bg-lime/[0.12]","aria-hidden":!0}):null,e.jsx("span",{className:"relative z-[1]",children:"Next Up"})]}),e.jsxs(le.button,{type:"button",onClick:()=>St("slices"),...Ft.segmentedTap,className:`control-pill relative h-7 px-2 text-micro font-semibold ${Oe==="slices"?"text-teal-100":"text-secondary"}`,children:[Oe==="slices"?e.jsx(le.span,{layoutId:"next-up-rail-surface-indicator-mobile",transition:Wt,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(at,{initial:!1,mode:"wait",children:Oe==="next-up"?e.jsx(le.div,{...Ms,className:"h-full min-h-0",children:e.jsx(er,{title:"Next Up",panelStyle:"flat",className:"!bg-transparent !shadow-none !border-transparent",disableEnterAnimation:!0,showHeader:!1,projectId:a,authToken:pe,embedMode:ae,queueModel:ke,queueActions:At,snapshotVersion:y,onPlayWorkstream:u=>en(u,{surface:"card"}),onOpenInitiative:(u,I)=>{_t(u,I),Fe(!1)},onOpenSettings:j,onUpgradeGate:is,excludeRunning:!0})},"next-up-drawer"):e.jsx(le.div,{...Ms,className:"h-full min-h-0",children:e.jsx(Sr,{title:"Slice Explorer",className:"h-full !rounded-none !border-0 !bg-transparent",workspaceId:a,authToken:pe,embedMode:ae,compact:!0,onOpenInitiative:(u,I)=>{_t(u,I),Fe(!1)}})},"slices-drawer")})})]})})]})},"next-up-drawer")]})}),e.jsx(at,{children:Ye&&e.jsxs(e.Fragment,{children:[e.jsx(le.button,{type:"button","aria-label":"Close auto-enable dialog",onClick:()=>tt(null),initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"fixed inset-0 z-[320] bg-black/50"},"auto-enable-backdrop"),e.jsxs(le.div,{initial:{opacity:0,y:12,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:10,scale:.98},transition:Ft.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:Ye.initiativeTitle})]}),e.jsxs("p",{className:"mt-1 text-caption text-secondary",children:["Starting workstream:"," ",e.jsx("span",{className:"text-primary",children:Ye.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:()=>tt(null),className:"control-pill h-8 px-3 text-caption font-semibold",children:"Cancel"}),e.jsx("button",{type:"button",onClick:Zr,className:"control-pill h-8 px-3 text-caption font-semibold","data-tone":"teal",children:"Enable Auto"})]})]},"auto-enable-dialog")]})}),e.jsx(at,{children:ye&&e.jsxs(e.Fragment,{children:[e.jsx(le.button,{type:"button","aria-label":"Close switch-run dialog",onClick:()=>ot(null),initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"fixed inset-0 z-[320] bg-black/50"},"play-conflict-backdrop"),e.jsxs(le.div,{initial:{opacity:0,y:12,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:10,scale:.98},transition:Ft.surfaceSwitch,className:"fixed inset-x-4 top-1/2 z-[330] -translate-y-1/2 rounded-2xl border border-white/[0.12] bg-[#080d14]/96 p-4 shadow-[0_24px_60px_rgba(0,0,0,0.5)] backdrop-blur-xl sm:left-1/2 sm:right-auto sm:w-[460px] sm:-translate-x-1/2",children:[e.jsx("p",{className:"text-caption uppercase tracking-[0.08em] text-secondary",children:"Run conflict"}),e.jsx("h3",{className:"mt-1 text-heading font-semibold text-bright",children:"Another workstream is already running"}),e.jsx("p",{className:"mt-2 text-caption text-secondary",children:ye.activeWorkstreamTitle?`Running now: ${ye.activeWorkstreamTitle}`:ye.message}),e.jsxs("p",{className:"mt-1 text-caption text-secondary",children:["Requested: ",e.jsx("span",{className:"text-primary",children:ye.target.workstreamTitle})]}),e.jsxs("div",{className:"mt-4 flex flex-wrap items-center justify-end gap-2",children:[e.jsx("button",{type:"button",onClick:()=>ot(null),className:"control-pill h-8 px-3 text-caption font-semibold",children:"Keep current"}),e.jsx("button",{type:"button",onClick:()=>{_t(ye.target.initiativeId,ye.target.initiativeTitle),ot(null)},className:"control-pill h-8 px-3 text-caption font-semibold",children:"Open running"}),e.jsx("button",{type:"button",disabled:ht,onClick:()=>void ea(),className:"control-pill h-8 px-3 text-caption font-semibold disabled:opacity-45","data-tone":"teal",children:ht?"Switching…":"Switch run"})]})]},"play-conflict-dialog")]})})]})})]}),e.jsx(Bi,{target:ia,onClose:U})]})}export{Co as MissionControlView};
|