@useorgx/openclaw-plugin 0.4.8 → 0.7.0
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/README.md +35 -0
- package/dashboard/dist/assets/BJgZIVUQ.js +53 -0
- package/dashboard/dist/assets/BJgZIVUQ.js.br +0 -0
- package/dashboard/dist/assets/BJgZIVUQ.js.gz +0 -0
- package/dashboard/dist/assets/BXWDRGm-.js +1 -0
- package/dashboard/dist/assets/BXWDRGm-.js.br +0 -0
- package/dashboard/dist/assets/BXWDRGm-.js.gz +0 -0
- package/dashboard/dist/assets/BgOYB78t.js +4 -0
- package/dashboard/dist/assets/BgOYB78t.js.br +0 -0
- package/dashboard/dist/assets/BgOYB78t.js.gz +0 -0
- package/dashboard/dist/assets/C-KIc3Wc.js.br +0 -0
- package/dashboard/dist/assets/C-KIc3Wc.js.gz +0 -0
- package/dashboard/dist/assets/CE38zU4U.js +1 -0
- package/dashboard/dist/assets/CE38zU4U.js.br +0 -0
- package/dashboard/dist/assets/CE38zU4U.js.gz +0 -0
- package/dashboard/dist/assets/CFGKRAzG.js +1 -0
- package/dashboard/dist/assets/CFGKRAzG.js.br +0 -0
- package/dashboard/dist/assets/CFGKRAzG.js.gz +0 -0
- package/dashboard/dist/assets/CGGR2GZh.js +1 -0
- package/dashboard/dist/assets/CGGR2GZh.js.br +0 -0
- package/dashboard/dist/assets/CGGR2GZh.js.gz +0 -0
- package/dashboard/dist/assets/CL_wXqR7.js +1 -0
- package/dashboard/dist/assets/CL_wXqR7.js.br +0 -0
- package/dashboard/dist/assets/CL_wXqR7.js.gz +0 -0
- package/dashboard/dist/assets/CPFiTmlw.js +8 -0
- package/dashboard/dist/assets/CPFiTmlw.js.br +0 -0
- package/dashboard/dist/assets/CPFiTmlw.js.gz +0 -0
- package/dashboard/dist/assets/CZZTvkQZ.js +1 -0
- package/dashboard/dist/assets/CZZTvkQZ.js.br +0 -0
- package/dashboard/dist/assets/CZZTvkQZ.js.gz +0 -0
- package/dashboard/dist/assets/{CpJsfbXo.js → CxQ08qFN.js} +2 -2
- package/dashboard/dist/assets/CxQ08qFN.js.br +0 -0
- package/dashboard/dist/assets/CxQ08qFN.js.gz +0 -0
- package/dashboard/dist/assets/D-bf6hEI.js +213 -0
- package/dashboard/dist/assets/D-bf6hEI.js.br +0 -0
- package/dashboard/dist/assets/D-bf6hEI.js.gz +0 -0
- package/dashboard/dist/assets/DG6y9wJI.js +2 -0
- package/dashboard/dist/assets/DG6y9wJI.js.br +0 -0
- package/dashboard/dist/assets/DG6y9wJI.js.gz +0 -0
- package/dashboard/dist/assets/DNxKz-GV.js +1 -0
- package/dashboard/dist/assets/DNxKz-GV.js.br +0 -0
- package/dashboard/dist/assets/DNxKz-GV.js.gz +0 -0
- package/dashboard/dist/assets/DW_rKUic.js +11 -0
- package/dashboard/dist/assets/DW_rKUic.js.br +0 -0
- package/dashboard/dist/assets/DW_rKUic.js.gz +0 -0
- package/dashboard/dist/assets/DbNoijHm.js +1 -0
- package/dashboard/dist/assets/DbNoijHm.js.br +0 -0
- package/dashboard/dist/assets/DbNoijHm.js.gz +0 -0
- package/dashboard/dist/assets/DjcdE6jC.js +2 -0
- package/dashboard/dist/assets/DjcdE6jC.js.br +0 -0
- package/dashboard/dist/assets/DjcdE6jC.js.gz +0 -0
- package/dashboard/dist/assets/FZYuCDnt.js +1 -0
- package/dashboard/dist/assets/FZYuCDnt.js.br +0 -0
- package/dashboard/dist/assets/FZYuCDnt.js.gz +0 -0
- package/dashboard/dist/assets/PAUiij_z.js +1 -0
- package/dashboard/dist/assets/PAUiij_z.js.br +0 -0
- package/dashboard/dist/assets/PAUiij_z.js.gz +0 -0
- package/dashboard/dist/assets/cNrhgGc1.js +8 -0
- package/dashboard/dist/assets/cNrhgGc1.js.br +0 -0
- package/dashboard/dist/assets/cNrhgGc1.js.gz +0 -0
- package/dashboard/dist/assets/h5biQs2I.css +1 -0
- package/dashboard/dist/assets/h5biQs2I.css.br +0 -0
- package/dashboard/dist/assets/h5biQs2I.css.gz +0 -0
- package/dashboard/dist/assets/ic2FaMnh.js +1 -0
- package/dashboard/dist/assets/ic2FaMnh.js.br +0 -0
- package/dashboard/dist/assets/ic2FaMnh.js.gz +0 -0
- package/dashboard/dist/assets/nByHNHoW.js +1 -0
- package/dashboard/dist/assets/nByHNHoW.js.br +0 -0
- package/dashboard/dist/assets/nByHNHoW.js.gz +0 -0
- package/dashboard/dist/assets/qm8xLgv-.css +1 -0
- package/dashboard/dist/assets/qm8xLgv-.css.br +0 -0
- package/dashboard/dist/assets/qm8xLgv-.css.gz +0 -0
- package/dashboard/dist/assets/tS9mbYZi.js +1 -0
- package/dashboard/dist/assets/tS9mbYZi.js.br +0 -0
- package/dashboard/dist/assets/tS9mbYZi.js.gz +0 -0
- package/dashboard/dist/brand/anthropic-mark.svg.br +0 -0
- package/dashboard/dist/brand/anthropic-mark.svg.gz +0 -0
- package/dashboard/dist/brand/openai-mark.svg.br +0 -0
- package/dashboard/dist/brand/openai-mark.svg.gz +0 -0
- package/dashboard/dist/brand/openclaw-mark.svg.br +0 -0
- package/dashboard/dist/brand/openclaw-mark.svg.gz +0 -0
- package/dashboard/dist/brand/xandy-orchestrator.png +0 -0
- package/dashboard/dist/index.html +7 -5
- package/dashboard/dist/index.html.br +0 -0
- package/dashboard/dist/index.html.gz +0 -0
- package/dist/activity-actor-fields.js +26 -4
- package/dist/activity-store.js +38 -26
- package/dist/agent-context-store.js +84 -42
- package/dist/agent-run-store.js +49 -28
- package/dist/agent-suite.d.ts +9 -0
- package/dist/agent-suite.js +150 -17
- package/dist/artifacts/artifact-domain-schemas.d.ts +66 -0
- package/dist/artifacts/artifact-domain-schemas.js +357 -0
- package/dist/artifacts/register-artifact.d.ts +4 -3
- package/dist/artifacts/register-artifact.js +170 -57
- package/dist/auth/flows.d.ts +47 -0
- package/dist/auth/flows.js +169 -0
- package/dist/auth-store.js +6 -26
- package/dist/byok-store.js +5 -19
- package/dist/chat-store.d.ts +157 -0
- package/dist/chat-store.js +586 -0
- package/dist/cli/orgx.d.ts +66 -0
- package/dist/cli/orgx.js +102 -0
- package/dist/config/refresh.d.ts +32 -0
- package/dist/config/refresh.js +55 -0
- package/dist/config/resolution.d.ts +37 -0
- package/dist/config/resolution.js +178 -0
- package/dist/contracts/client.d.ts +43 -3
- package/dist/contracts/client.js +159 -30
- package/dist/contracts/retro-schema.d.ts +81 -0
- package/dist/contracts/retro-schema.js +80 -0
- package/dist/contracts/shared-types.d.ts +306 -0
- package/dist/contracts/shared-types.js +179 -0
- package/dist/contracts/skill-pack-schema.d.ts +192 -0
- package/dist/contracts/skill-pack-schema.js +180 -0
- package/dist/contracts/types.d.ts +224 -132
- package/dist/contracts/types.js +5 -0
- package/dist/entities/auto-assignment.d.ts +36 -0
- package/dist/entities/auto-assignment.js +141 -0
- package/dist/entity-comment-store.js +5 -25
- package/dist/event-sanitization.d.ts +11 -0
- package/dist/event-sanitization.js +113 -0
- package/dist/fs-utils.js +13 -1
- package/dist/gateway-watchdog.d.ts +5 -0
- package/dist/gateway-watchdog.js +50 -0
- package/dist/hash-utils.d.ts +2 -0
- package/dist/hash-utils.js +12 -0
- package/dist/hooks/post-reporting-event.mjs +1 -5
- package/dist/http/helpers/activity-headline.d.ts +10 -0
- package/dist/http/helpers/activity-headline.js +73 -0
- package/dist/http/helpers/artifact-fallback.d.ts +13 -0
- package/dist/http/helpers/artifact-fallback.js +148 -0
- package/dist/http/helpers/auto-continue-engine.d.ts +486 -0
- package/dist/http/helpers/auto-continue-engine.js +3563 -0
- package/dist/http/helpers/autopilot-operations.d.ts +176 -0
- package/dist/http/helpers/autopilot-operations.js +554 -0
- package/dist/http/helpers/autopilot-runtime.d.ts +43 -0
- package/dist/http/helpers/autopilot-runtime.js +607 -0
- package/dist/http/helpers/autopilot-slice-utils.d.ts +56 -0
- package/dist/http/helpers/autopilot-slice-utils.js +899 -0
- package/dist/http/helpers/decision-mapper.d.ts +52 -0
- package/dist/http/helpers/decision-mapper.js +260 -0
- package/dist/http/helpers/dispatch-lifecycle.d.ts +119 -0
- package/dist/http/helpers/dispatch-lifecycle.js +809 -0
- package/dist/http/helpers/hash-utils.d.ts +1 -0
- package/dist/http/helpers/hash-utils.js +1 -0
- package/dist/http/helpers/kickoff-context.d.ts +12 -0
- package/dist/http/helpers/kickoff-context.js +228 -0
- package/dist/http/helpers/llm-client.d.ts +47 -0
- package/dist/http/helpers/llm-client.js +256 -0
- package/dist/http/helpers/mission-control.d.ts +193 -0
- package/dist/http/helpers/mission-control.js +1383 -0
- package/dist/http/helpers/openclaw-cli.d.ts +37 -0
- package/dist/http/helpers/openclaw-cli.js +283 -0
- package/dist/http/helpers/runtime-sse.d.ts +20 -0
- package/dist/http/helpers/runtime-sse.js +110 -0
- package/dist/http/helpers/sentinel-catalog.d.ts +23 -0
- package/dist/http/helpers/sentinel-catalog.js +193 -0
- package/dist/http/helpers/session-classification.d.ts +9 -0
- package/dist/http/helpers/session-classification.js +564 -0
- package/dist/http/helpers/slice-experience-v2.d.ts +137 -0
- package/dist/http/helpers/slice-experience-v2.js +677 -0
- package/dist/http/helpers/slice-run-projections.d.ts +72 -0
- package/dist/http/helpers/slice-run-projections.js +860 -0
- package/dist/http/helpers/triage-mapper.d.ts +43 -0
- package/dist/http/helpers/triage-mapper.js +549 -0
- package/dist/http/helpers/value-utils.d.ts +6 -0
- package/dist/http/helpers/value-utils.js +72 -0
- package/dist/http/helpers/workspace-scope.d.ts +15 -0
- package/dist/http/helpers/workspace-scope.js +170 -0
- package/dist/http/index.d.ts +88 -0
- package/dist/http/index.js +3610 -0
- package/dist/http/router.d.ts +23 -0
- package/dist/http/router.js +23 -0
- package/dist/http/routes/agent-control.d.ts +79 -0
- package/dist/http/routes/agent-control.js +684 -0
- package/dist/http/routes/agent-suite.d.ts +38 -0
- package/dist/http/routes/agent-suite.js +397 -0
- package/dist/http/routes/agents-catalog.d.ts +40 -0
- package/dist/http/routes/agents-catalog.js +128 -0
- package/dist/http/routes/billing.d.ts +23 -0
- package/dist/http/routes/billing.js +55 -0
- package/dist/http/routes/chat.d.ts +19 -0
- package/dist/http/routes/chat.js +522 -0
- package/dist/http/routes/debug.d.ts +14 -0
- package/dist/http/routes/debug.js +21 -0
- package/dist/http/routes/decision-actions.d.ts +20 -0
- package/dist/http/routes/decision-actions.js +103 -0
- package/dist/http/routes/delegation.d.ts +19 -0
- package/dist/http/routes/delegation.js +32 -0
- package/dist/http/routes/dispatch-gateway-envelope.d.ts +25 -0
- package/dist/http/routes/dispatch-gateway-envelope.js +26 -0
- package/dist/http/routes/entities.d.ts +63 -0
- package/dist/http/routes/entities.js +440 -0
- package/dist/http/routes/entity-dynamic.d.ts +25 -0
- package/dist/http/routes/entity-dynamic.js +191 -0
- package/dist/http/routes/health.d.ts +22 -0
- package/dist/http/routes/health.js +49 -0
- package/dist/http/routes/live-legacy.d.ts +115 -0
- package/dist/http/routes/live-legacy.js +112 -0
- package/dist/http/routes/live-misc.d.ts +81 -0
- package/dist/http/routes/live-misc.js +426 -0
- package/dist/http/routes/live-snapshot.d.ts +136 -0
- package/dist/http/routes/live-snapshot.js +916 -0
- package/dist/http/routes/live-terminal.d.ts +11 -0
- package/dist/http/routes/live-terminal.js +261 -0
- package/dist/http/routes/live-triage.d.ts +61 -0
- package/dist/http/routes/live-triage.js +248 -0
- package/dist/http/routes/mission-control-actions.d.ts +131 -0
- package/dist/http/routes/mission-control-actions.js +1791 -0
- package/dist/http/routes/mission-control-read.d.ts +73 -0
- package/dist/http/routes/mission-control-read.js +1640 -0
- package/dist/http/routes/onboarding.d.ts +34 -0
- package/dist/http/routes/onboarding.js +101 -0
- package/dist/http/routes/realtime-orchestrator.d.ts +10 -0
- package/dist/http/routes/realtime-orchestrator.js +74 -0
- package/dist/http/routes/run-control.d.ts +27 -0
- package/dist/http/routes/run-control.js +96 -0
- package/dist/http/routes/runtime-hooks.d.ts +69 -0
- package/dist/http/routes/runtime-hooks.js +437 -0
- package/dist/http/routes/sentinels-catalog.d.ts +7 -0
- package/dist/http/routes/sentinels-catalog.js +24 -0
- package/dist/http/routes/settings-byok.d.ts +23 -0
- package/dist/http/routes/settings-byok.js +163 -0
- package/dist/http/routes/summary.d.ts +18 -0
- package/dist/http/routes/summary.js +49 -0
- package/dist/http/routes/usage.d.ts +24 -0
- package/dist/http/routes/usage.js +362 -0
- package/dist/http/routes/work-artifacts.d.ts +9 -0
- package/dist/http/routes/work-artifacts.js +55 -0
- package/dist/http/shared-state.d.ts +16 -0
- package/dist/http/shared-state.js +1 -0
- package/dist/http-handler.d.ts +1 -88
- package/dist/http-handler.js +1 -10605
- package/dist/index.js +287 -2284
- package/dist/json-utils.d.ts +1 -0
- package/dist/json-utils.js +8 -0
- package/dist/local-openclaw.js +29 -6
- package/dist/mcp-client-setup.js +3 -3
- package/dist/mcp-http-handler.js +33 -59
- package/dist/next-up-queue-store.d.ts +16 -1
- package/dist/next-up-queue-store.js +93 -25
- package/dist/outbox.d.ts +5 -0
- package/dist/outbox.js +113 -9
- package/dist/paths.js +24 -5
- package/dist/reporting/rollups.d.ts +53 -0
- package/dist/reporting/rollups.js +148 -0
- package/dist/retro/domain-templates.d.ts +45 -0
- package/dist/retro/domain-templates.js +297 -0
- package/dist/retro/quality-rubric.d.ts +33 -0
- package/dist/retro/quality-rubric.js +213 -0
- package/dist/runtime-cleanup.d.ts +18 -0
- package/dist/runtime-cleanup.js +87 -0
- package/dist/runtime-instance-store.js +5 -31
- package/dist/services/background.d.ts +34 -0
- package/dist/services/background.js +45 -0
- package/dist/services/experiment-randomization.d.ts +21 -0
- package/dist/services/experiment-randomization.js +63 -0
- package/dist/services/instrumentation.d.ts +29 -0
- package/dist/services/instrumentation.js +136 -0
- package/dist/skill-pack-state.d.ts +36 -5
- package/dist/skill-pack-state.js +273 -29
- package/dist/snapshot-store.js +5 -25
- package/dist/stores/json-store.d.ts +11 -0
- package/dist/stores/json-store.js +42 -0
- package/dist/sync/local-agent-telemetry.d.ts +13 -0
- package/dist/sync/local-agent-telemetry.js +128 -0
- package/dist/sync/outbox-replay.d.ts +55 -0
- package/dist/sync/outbox-replay.js +621 -0
- package/dist/team-context-store.d.ts +23 -0
- package/dist/team-context-store.js +116 -0
- package/dist/telemetry/posthog.js +4 -2
- package/dist/tools/core-tools.d.ts +72 -0
- package/dist/tools/core-tools.js +2270 -0
- package/dist/types.d.ts +2 -0
- package/dist/types.js +2 -0
- package/dist/worker-supervisor.js +23 -0
- package/package.json +14 -4
- package/dashboard/dist/assets/B3ziCA02.js +0 -8
- package/dashboard/dist/assets/BNeJ0kpF.js +0 -1
- package/dashboard/dist/assets/BzkiMPmM.js +0 -215
- package/dashboard/dist/assets/CUV9IHHi.js +0 -1
- package/dashboard/dist/assets/Ie7d9Iq2.css +0 -1
- package/dashboard/dist/assets/sAhvFnpk.js +0 -4
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import{r as a,a as rs,j as e,u as Gn,b as Mt}from"./cNrhgGc1.js";import{I as Jn,u as Ir,o as Ar,N as wn}from"./BXWDRGm-.js";import{n as Yn,q as ws,i as vs,a as Er,t as Dr,b as Ft,h as pt,c as Mr,E as tt,d as ee,u as ls,f as nt,A as Xn,s as gs,e as js,g as vn,l as kt,j as bs,I as as,P as Tr,k as $r,m as _r,o as Lr,p as Ys,M as Br,r as Pr,v as jn,w as Kt,x as Yt,y as Xs,z as Zn,B as Rr,C as kn,U as qr,D as Or}from"./D-bf6hEI.js";import{S as jt}from"./nByHNHoW.js";import{A as mt,m as je,L as er,R as zr,a as Ur}from"./CxQ08qFN.js";import{E as ks}from"./DNxKz-GV.js";import"./C-KIc3Wc.js";import"./BJgZIVUQ.js";const tr=new Set(["completed","complete","done","resolved","success","succeeded","archived","cancelled","canceled","stopped","deleted"]),Qr=new Set(["failed","error","timed_out","timeout","aborted","crashed","fatal"]),Wr=new Set(["running","active","in_progress","working","planning","dispatching","queued","pending","resumed","handoff","review"]),Hr=new Set(["blocked","paused","rate_limited","waiting_dependency","stopping","stalled","awaiting_input","needs_review","needs_decision","review_required"]);function Vr(t){return tr.has(Yn(t))}function is(t,s){const n=Yn(t);if(tr.has(n))return"Completed";if(Qr.has(n))return"Failed";if(n==="blocked"||n==="paused")return n==="paused"?"Paused":"Blocked";if(Hr.has(n))return"Blocked";if(s){if(s.hasDispatchingStreams)return"Dispatching";if(s.hasActiveStreams)return"In Progress";if(s.totalTasks&&s.completedTasks===s.totalTasks)return"Completed";if(s.blockedTasks&&s.blockedTasks>0&&!s.hasActiveStreams)return"Blocked"}return n==="dispatching"?"Dispatching":n==="queued"||n==="pending"?"Queued":Wr.has(n)?"In Progress":"Queued"}function Kr({activities:t,agents:s,initiatives:n}){return a.useMemo(()=>{const r=new Map,c=(o,d,x,h)=>{const y=r.get(o)??[];y.some(m=>m.id===d)||(y.push({id:d,name:x,confidence:h}),r.set(o,y))};return t.forEach(o=>{const d="metadata"in o&&o.metadata&&typeof o.metadata=="object"?o.metadata:null,x=d&&typeof d=="object"?d:{},h=("initiativeId"in o&&typeof o.initiativeId=="string"?o.initiativeId:void 0)??x.initiativeId??void 0,y=o.agentId??void 0,m=("agentName"in o&&typeof o.agentName=="string"?o.agentName:"agent"in o&&typeof o.agent=="string"?o.agent:void 0)??y??"Unknown";h&&y&&c(h,y,m,"high")}),n.forEach(o=>{var d;(d=o.avatars)!=null&&d.length&&o.avatars.forEach(x=>{const h=s.find(y=>y.name.toLowerCase()===x.toLowerCase());h?c(o.id,h.id,h.name,"medium"):c(o.id,`avatar:${x}`,x,"medium")})}),s.forEach(o=>{if(!o.task)return;const d=o.task.toLowerCase();n.forEach(x=>{x.name.toLowerCase().split(/\s+/).filter(S=>S.length>3).some(S=>d.includes(S))&&c(x.id,o.id,o.name,"low")})}),r},[t,s,n])}function sr(t){const s=a.useRef(null),n=a.useCallback((r,c,o,d)=>{if(o&&s.current!==null){const x=t.indexOf(s.current),h=t.indexOf(r);if(x!==-1&&h!==-1){const y=Math.min(x,h),m=Math.max(x,h),S=t.slice(y,m+1);d(I=>{const k=new Set(I);for(const l of S)c?k.add(l):k.delete(l);return k});return}}d(x=>{const h=new Set(x);return c?h.add(r):h.delete(r),h}),s.current=r},[t]);return{lastClickedId:s,handleSelect:n}}const Gr=100,Jr=5,Yr=75,Xr=3,Zr=["workstream","milestone","task"],ea=60;function ms(t){const s=Date.parse(t??"");return Number.isFinite(s)?s:0}function ta(t){return t.toLowerCase().trim().split(/\s+/).filter(Boolean)}function sa(t,s){const n=[];for(let r=0;r<t.length;r+=s)n.push(t.slice(r,r+s));return n}async function Nn(t,s,n){var o;const r=[];let c=0;for(let d=0;d<n;d+=1){const x=new URLSearchParams(t);x.set("limit",String(s)),x.set("offset",String(c));const h=await fetch(`/orgx/api/entities?${x.toString()}`);if(!h.ok)break;const y=await h.json(),m=y.data??[];if(r.push(...m),!!!((o=y.pagination)!=null&&o.has_more)||m.length===0)break;c+=s}return r}function Sn(t,s,n,r){const c=t.name.toLowerCase(),o=(t.description??"").toLowerCase();let d=0;r&&(d+=65),c===s&&(d+=140),c.startsWith(s)&&(d+=100),c.includes(s)&&(d+=80),o.includes(s)&&(d+=40);for(const x of n)c.includes(x)&&(d+=22),o.includes(x)&&(d+=8);return d}function na(t,s,n=null){const r=t.trim().toLowerCase(),c=(n==null?void 0:n.trim())??"";return rs({queryKey:ws.initiativeSearch({query:r,projectId:c||null}),enabled:s&&r.length>=2,queryFn:async()=>{var k;if(r.length<2||vs())return[];const o=l=>{const v=new URLSearchParams(l);return c.length>0&&v.set("workspace_id",c),v},d=await Nn(o({type:"initiative",search:r}),Gr,Jr),x=await Promise.all(Zr.map(l=>Nn(o({type:l,search:r}),Yr,Xr))),h=new Set;for(const l of x)for(const v of l){const g=(k=v.initiative_id)==null?void 0:k.trim();g&&h.add(g)}const y=[];for(const l of sa(Array.from(h),ea)){if(l.length===0)continue;const v=o({type:"initiative",ids:l.join(","),limit:String(l.length),offset:"0"}),g=await fetch(`/orgx/api/entities?${v.toString()}`);if(!g.ok)continue;const w=await g.json();y.push(...w.data??[])}const m=[...d,...y],S=new Map;for(const l of m){const v=S.get(l.id);if(!v){S.set(l.id,l);continue}ms(l.updated_at??l.created_at)>ms(v.updated_at??v.created_at)&&S.set(l.id,l)}const I=ta(r);return Array.from(S.values()).filter(l=>Er(l.status)).map(Dr).filter(l=>{if(h.has(l.id))return!0;const v=[l.name,l.description??"",l.rawStatus??"",l.status].join(" ").toLowerCase();return I.every(g=>v.includes(g))}).sort((l,v)=>{const g=Sn(v,r,I,h.has(v.id))-Sn(l,r,I,h.has(l.id));return g!==0?g:ms(v.updatedAt??v.createdAt)-ms(l.updatedAt??l.createdAt)})},staleTime:15e3})}function Zs({value:t,onChange:s,placeholder:n}){return e.jsxs("label",{className:"relative block",children:[e.jsx("span",{className:"sr-only",children:n}),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:r=>s(r.target.value),placeholder:n,className:"w-full rounded-xl border border-white/[0.08] bg-white/[0.03] py-2.5 pl-10 pr-8 text-body text-white placeholder:text-muted transition-all focus:border-[#BFFF00]/30 focus:bg-white/[0.05] focus:outline-none"}),t.length>0&&e.jsx("button",{type:"button",onClick:()=>s(""),className:"absolute right-2.5 top-1/2 -translate-y-1/2 rounded-full p-0.5 text-muted transition-colors hover:text-primary","aria-label":"Clear search",children:e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:e.jsx("path",{d:"M18 6 6 18M6 6l12 12"})})})]})}async function Pt(t){if(!t.ok){const s=await t.json().catch(()=>null),n=typeof(s==null?void 0:s.error)=="string"&&s.error||typeof(s==null?void 0:s.message)=="string"&&s.message||`Request failed (${t.status})`;throw new Error(pt(n))}return t}function ra(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 Ps(t){const s=t.trim().toLowerCase();return s==="deleted"||s==="archived"||s==="cancelled"}function aa(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 ia(t){const s=Gn(),n=Ft({authToken:t.authToken,embedMode:t.embedMode,contentTypeJson:!0}),r=()=>{s.invalidateQueries({queryKey:["live-data"]}),s.invalidateQueries({queryKey:["live-initiatives"]}),s.invalidateQueries({queryKey:["initiative-details"]}),s.invalidateQueries({queryKey:["entities"]}),s.invalidateQueries({queryKey:["mission-control-graph"]}),s.invalidateQueries({queryKey:["mission-control-next-up"]})},c=(k,l)=>{s.setQueryData(["initiative-tombstones"],v=>{const g=Array.isArray(v)?v.filter(F=>typeof F=="string"):[],w=g.includes(k);return l?w?g:[...g,k]:w?g.filter(F=>F!==k):g})},o=(k,l)=>{const v=ra(l),g=new Date().toISOString(),w=Ps(l);c(k,w);const F=_=>{if(!Array.isArray(_))return _;if(w){const L=_.filter(B=>{if(!B||typeof B!="object")return!0;const G=B;return!(typeof G.id=="string"&&G.id===k)});return L.length===_.length?_:L}let f=!1;const $=_.map(L=>{if(!L||typeof L!="object")return L;const B=L;return typeof B.id!="string"||B.id!==k?L:(f=!0,{...B,status:v,rawStatus:l,updatedAt:g})});return f?$:_};s.setQueriesData({queryKey:["entities"]},F),s.setQueriesData({queryKey:["live-initiatives"]},F)},d=(k,l,v="status")=>{const g=aa(l);s.setQueriesData({queryKey:["live-data"]},w=>{if(!w||typeof w!="object")return w;const F=w,_=F.sessions;if(!_||typeof _!="object")return w;const f=_,$=f.nodes;if(!Array.isArray($))return w;let L=!1;const B=v==="delete"?$.filter(E=>{if(!E||typeof E!="object")return!0;const H=E,D=(typeof H.initiativeId=="string"?H.initiativeId:null)===k;return D&&(L=!0),!D}):$.map(E=>{if(!E||typeof E!="object")return E;const H=E;return(typeof H.initiativeId=="string"?H.initiativeId:null)!==k||H.status===g?E:(L=!0,{...H,status:g})});if(!L)return w;const G=new Set,se=new Set;for(const E of B){if(!E||typeof E!="object")continue;const H=E;typeof H.id=="string"&&G.add(H.id),typeof H.groupId=="string"&&se.add(H.groupId)}const K=Array.isArray(f.edges)?f.edges.filter(E=>{if(!E||typeof E!="object")return!1;const H=E,z=typeof H.parentId=="string"?H.parentId:null,D=typeof H.childId=="string"?H.childId:null;return z!==null&&D!==null&&G.has(z)&&G.has(D)}):f.edges,J=Array.isArray(f.groups)?f.groups.filter(E=>{if(!E||typeof E!="object")return!1;const H=E;return typeof H.id=="string"&&se.has(H.id)}):f.groups;return{...F,sessions:{...f,nodes:B,edges:K,groups:J}}})},x={start:"in_progress",complete:"done",block:"blocked",unblock:"in_progress",pause:"paused",resume:"active"},h=Mt({mutationFn:async k=>{const{type:l,...v}=k,g=await fetch("/orgx/api/entities",{method:"POST",headers:n,body:JSON.stringify({type:l,...v})});return await Pt(g),g.json()},onSuccess:r}),y=Mt({mutationFn:async k=>{const{type:l,id:v,...g}=k,w=await fetch("/orgx/api/entities",{method:"PATCH",headers:n,body:JSON.stringify({type:l,id:v,...g})});return await Pt(w),w.json()},onSuccess:(k,l)=>{l.type.trim().toLowerCase()==="initiative"&&typeof l.status=="string"&&l.status.trim().length>0&&(o(l.id,l.status),d(l.id,l.status,Ps(l.status)?"delete":"status")),r()}}),m=Mt({mutationFn:async k=>{const l=await fetch(`/orgx/api/entities/${encodeURIComponent(k.type)}/${encodeURIComponent(k.id)}/delete`,{method:"POST",headers:n,body:"{}"});return await Pt(l),l.json()},onSuccess:(k,l)=>{l.type.trim().toLowerCase()==="initiative"&&(o(l.id,"archived"),d(l.id,"archived","delete")),r()}}),S=Mt({mutationFn:async k=>{const l=await fetch(`/orgx/api/entities/${encodeURIComponent(k.type)}/${encodeURIComponent(k.id)}/${encodeURIComponent(k.action)}`,{method:"POST",headers:n,body:JSON.stringify({force:k.force??!1})});return await Pt(l),l.json()},onSuccess:(k,l)=>{if(l.type.trim().toLowerCase()==="initiative"){const v=x[l.action.trim().toLowerCase()];v&&(o(l.id,v),d(l.id,v,"status"))}r()}}),I=Mt({mutationFn:async k=>{const l=Array.from(new Map((k.items??[]).filter(f=>typeof(f==null?void 0:f.type)=="string"&&f.type.trim().length>0&&typeof(f==null?void 0:f.id)=="string"&&f.id.trim().length>0).map(f=>[`${f.type}:${f.id}`,f])).values());if(l.length===0)return{updated:0,failed:0,errors:[]};if(k.mode==="action"&&!k.action)throw new Error("bulk action requires an action name");const v=async f=>{try{if(k.mode==="delete"){const L=await fetch(`/orgx/api/entities/${encodeURIComponent(f.type)}/${encodeURIComponent(f.id)}/delete`,{method:"POST",headers:n,body:"{}"});return await Pt(L),{ok:!0}}if(k.mode==="update"){const L=await fetch("/orgx/api/entities",{method:"PATCH",headers:n,body:JSON.stringify({type:f.type,id:f.id,...k.updates??{}})});return await Pt(L),{ok:!0}}const $=await fetch(`/orgx/api/entities/${encodeURIComponent(f.type)}/${encodeURIComponent(f.id)}/${encodeURIComponent(k.action)}`,{method:"POST",headers:n,body:JSON.stringify({force:k.force??!1})});return await Pt($),{ok:!0}}catch($){return{ok:!1,error:$ instanceof Error?$.message:"Unknown bulk mutation failure"}}},g=await Promise.all(l.map(f=>v(f)));let w=0,F=0;const _=[];for(const f of g)f.ok?w+=1:(F+=1,_.push(f.error));return{updated:w,failed:F,errors:_}},onSuccess:(k,l)=>{var g;const v=(l.items??[]).filter(w=>w.type.trim().toLowerCase()==="initiative");if(v.length>0){if(l.mode==="update"&&typeof((g=l.updates)==null?void 0:g.status)=="string"&&l.updates.status.trim().length>0)for(const w of v)o(w.id,l.updates.status),d(w.id,l.updates.status,Ps(l.updates.status)?"delete":"status");else if(l.mode==="delete")for(const w of v)o(w.id,"archived"),d(w.id,"archived","delete");else if(l.mode==="action"&&l.action){const w=x[l.action.trim().toLowerCase()];if(w)for(const F of v)o(F.id,w),d(F.id,w,"status")}}r()}});return{createEntity:h,updateEntity:y,deleteEntity:m,entityAction:S,bulkEntityMutation:I}}const nr=a.createContext(null);function Tt(){const t=a.useContext(nr);if(!t)throw new Error("useMissionControl must be used within MissionControlProvider");return t}function oa({children:t,agentEntityMap:s,authToken:n,embedMode:r}){const[c,o]=a.useState(new Set),[d,x]=a.useState(null),[h,y]=a.useState(""),[m,S]=a.useState([]),[I,k]=a.useState("target"),[l,v]=a.useState("any"),[g,w]=a.useState(""),[F,_]=a.useState(""),[f,$]=a.useState("status"),[L,B]=a.useState("default"),[G,se]=a.useState("workstream"),[K,J]=a.useState("medium"),E=ia({authToken:n,embedMode:r}),H=a.useCallback(Z=>{o(N=>{const j=new Set(N);return j.has(Z)?j.delete(Z):j.add(Z),j})},[]),z=a.useCallback(Z=>{o(N=>{if(N.has(Z))return N;const j=new Set(N);return j.add(Z),j})},[]),D=a.useCallback(Z=>{o(new Set(Z))},[]),W=a.useCallback(()=>{o(new Set)},[]),xe=a.useCallback(Z=>{x(Z)},[]),Se=a.useCallback(()=>{x(null)},[]),he=a.useCallback(Z=>{const N=Array.from(new Set((Z??[]).map(j=>j.trim().toLowerCase()).filter(Boolean)));S(N)},[]),ne=a.useCallback(Z=>{S(N=>{const j=Z.trim().toLowerCase();return j?N.includes(j)?N.filter(u=>u!==j):[...N,j]:N})},[]),ye=a.useCallback(()=>{y(""),S([]),k("target"),v("any"),w(""),_("")},[]),U=g.trim().length>0||F.trim().length>0,M=l!=="any"&&(l!=="custom_range"||U),me=m.length+(M?1:0),te=h.trim().length>0||me>0,fe=a.useMemo(()=>({agentEntityMap:s,expandedInitiatives:c,modalTarget:d,searchQuery:h,statusFilters:m,dateField:I,datePreset:l,dateStart:g,dateEnd:F,activeFilterCount:me,hasActiveFilters:te,groupBy:f,sortBy:L,zoomLevel:G,setZoomLevel:se,noiseThreshold:K,setNoiseThreshold:J,authToken:n,embedMode:r,mutations:E,toggleExpanded:H,expandInitiative:z,expandAll:D,collapseAll:W,openModal:xe,closeModal:Se,setSearchQuery:y,setStatusFilters:he,toggleStatusFilter:ne,setDateField:k,setDatePreset:v,setDateStart:w,setDateEnd:_,setGroupBy:$,setSortBy:B,clearFilters:ye}),[s,c,d,h,m,I,l,g,F,me,te,f,L,G,K,n,r,E,H,z,D,W,xe,Se,he,ne,k,v,w,_,$,B,ye]);return e.jsx(nr.Provider,{value:fe,children:t})}function Rs(t){return{initiative:{id:t,title:"Initiative",status:"active",summary:null,assignedAgents:[]},nodes:[],edges:[],recentTodos:[]}}function la(t){const s=new Date().toISOString(),n=t==="init-2"?"Black Friday Email":"Q4 Feature Ship",r=`${t}:ws:design`,c=`${t}:ms:polish`,o=`${t}:task:tokens`,d=`${t}:task:qa`;return{initiative:{id:t,title:n,status:"active",summary:"Demo mode graph from local fixture data.",assignedAgents:[{id:"dana",name:"Dana",domain:"design"}]},nodes:[{id:r,type:"workstream",title:"Dashboard UI pass",status:"active",parentId:t,initiativeId:t,workstreamId:r,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:c,type:"milestone",title:"Polish pass",status:"active",parentId:r,initiativeId:t,workstreamId:r,milestoneId:c,priorityNum:1,priorityLabel:"P1",dependencyIds:[r],dueDate:null,etaEndAt:null,expectedDurationHours:4,expectedBudgetUsd:900,assignedAgents:[{id:"dana",name:"Dana",domain:"design"}],updatedAt:s},{id:o,type:"task",title:"Refine queue action ergonomics",status:"todo",parentId:c,initiativeId:t,workstreamId:r,milestoneId:c,priorityNum:1,priorityLabel:"P1",dependencyIds:[c],dueDate:null,etaEndAt:null,expectedDurationHours:2,expectedBudgetUsd:450,assignedAgents:[{id:"dana",name:"Dana",domain:"design"}],updatedAt:s},{id:d,type:"task",title:"Mobile QA sweep",status:"active",parentId:c,initiativeId:t,workstreamId:r,milestoneId:c,priorityNum:2,priorityLabel:"P2",dependencyIds:[o],dueDate:null,etaEndAt:null,expectedDurationHours:2,expectedBudgetUsd:420,assignedAgents:[{id:"mark",name:"Mark",domain:"engineering"}],updatedAt:s}],edges:[{from:r,to:c,kind:"depends_on"},{from:c,to:o,kind:"depends_on"},{from:o,to:d,kind:"depends_on"}],recentTodos:[o,d]}}function ca({initiativeId:t,authToken:s=null,embedMode:n=!1,enabled:r=!0,cursor:c,limit:o}){var k,l;const d=vs(),x=Mr(t),h=a.useMemo(()=>[...ws.missionControlGraph({initiativeId:t,authToken:s,embedMode:n}),{cursor:c??null,limit:o??null}],[t,s,n,c,o]),y=rs({queryKey:h,enabled:r&&!!t&&x,queryFn:async()=>{if(!t)throw new Error("initiativeId is required");if(d)return la(t);if(!x)return Rs(t);const v=new URLSearchParams({initiative_id:t});c&&v.set("cursor",c),o!=null&&Number.isFinite(o)&&v.set("limit",String(o));const g={};n&&(g["X-Orgx-Embed"]="true"),s&&(g.Authorization=`Bearer ${s}`);const w=Object.keys(g).length>0?g:void 0,F=await fetch(`/orgx/api/mission-control/graph?${v.toString()}`,{headers:w});if(!F.ok){const f=await F.json().catch(()=>null),$=typeof(f==null?void 0:f.error)=="string"&&f.error||typeof(f==null?void 0:f.message)=="string"&&f.message||`Failed to fetch Mission Control graph (${F.status})`;return{...Rs(t),degraded:[$]}}return await F.json()}}),m=y.data??(t?Rs(t):null),S=y.data,I=(S==null?void 0:S.nextCursor)??null;return{graph:m,isLoading:x?y.isLoading:!1,error:x?((k=y.error)==null?void 0:k.message)??null:null,degraded:x?((l=y.data)==null?void 0:l.degraded)??[]:[],refetch:y.refetch,nextCursor:I}}function ys({type:t,className:s="",hierarchyLabel:n}){return e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(tt,{type:t,className:s,size:14}),n&&e.jsx("span",{className:"text-[10px] tracking-wider uppercase font-mono tabular-nums opacity-60 hover:opacity-100 transition-opacity leading-none select-none",title:n,children:n})]})}const da=new Set(["blocked","failed","cancelled"]);function ua(t){return t==="initiative"?"Initiatives":t==="workstream"?"Workstreams":t==="milestone"?"Milestones":"Tasks"}function ma({nodes:t,edges:s,selectedNodeId:n,focusedWorkstreamId:r,onSelectNode:c}){const o=a.useMemo(()=>new Map(t.map(f=>[f.id,f])),[t]),[d,x]=a.useState(""),[h,y]=a.useState(!1),m=d.trim().toLowerCase(),S=a.useMemo(()=>{if(!r)return new Set(t.map(L=>L.id));const f=new Set;for(const L of t)(L.type==="initiative"||L.id===r||L.workstreamId===r)&&f.add(L.id);let $=!0;for(;$;){$=!1;for(const L of s)(f.has(L.from)||f.has(L.to))&&(!f.has(L.from)||!f.has(L.to))&&(f.add(L.from),f.add(L.to),$=!0)}return f},[r,t,s]),I=t.filter(f=>S.has(f.id)),k=s.filter(f=>S.has(f.from)&&S.has(f.to)),l=a.useMemo(()=>{if(!n)return new Set;const f=new Set([n]);for(const $ of k)$.from===n&&f.add($.to),$.to===n&&f.add($.from);return f},[n,k]),v=a.useMemo(()=>{const f=new Set;for(const $ of t)da.has($.status)&&f.add($.id);return f},[t]),g=a.useMemo(()=>{let f=new Set(Array.from(S));return h&&n&&(f=new Set(Array.from(f).filter($=>l.has($)))),m.length>0&&(f=new Set(Array.from(f).filter($=>{const L=o.get($);return L?L.title.toLowerCase().includes(m):!1}))),f},[o,m,l,h,n,S]),w=t.filter(f=>g.has(f.id)),F=s.filter(f=>g.has(f.from)&&g.has(f.to)),_={initiative:w.filter(f=>f.type==="initiative"),workstream:w.filter(f=>f.type==="workstream"),milestone:w.filter(f=>f.type==="milestone"),task:w.filter(f=>f.type==="task")};return I.length===0?null:e.jsxs("section",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:[w.length," nodes · ",F.length," links"]}),r&&e.jsx("span",{className:"status-pill","data-tone":"active",children:"Focused workstream"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("input",{value:d,onChange:f=>x(f.target.value),placeholder:"Filter nodes...",className:"h-9 flex-1 min-w-[200px] rounded-lg border border-strong bg-black/30 px-3 text-caption text-primary placeholder:text-faint transition-colors focus:border-[#BFFF00]/35 focus:outline-none"}),n&&e.jsx("button",{type:"button",onClick:()=>y(f=>!f),"aria-pressed":h,"data-state":h?"active":"idle",className:"control-pill px-3 text-caption font-semibold",title:"Show only the selected node and its direct neighbors",children:"Related only"}),(d.trim().length>0||h)&&e.jsx("button",{type:"button",onClick:()=>{x(""),y(!1)},className:"control-pill px-3 text-caption",children:"Reset"})]}),w.length===0?e.jsx("div",{className:"rounded-xl border border-white/[0.07] bg-black/[0.14] px-3 py-3 text-caption text-secondary",children:"No nodes match this view. Clear filters or select a different node to see connected work."}):e.jsx("div",{className:`grid gap-2 ${Object.values(_).filter(f=>f.length>0).length<=2?"grid-cols-1 sm:grid-cols-2":"md:grid-cols-2 xl:grid-cols-4"}`,children:Object.keys(_).filter(f=>_[f].length>0).map(f=>e.jsxs("div",{className:"rounded-xl border border-white/[0.07] bg-black/[0.14] p-2.5",children:[e.jsxs("div",{className:"mb-1.5 text-micro uppercase tracking-[0.09em] text-secondary",children:[ua(f)," (",_[f].length,")"]}),e.jsxs("div",{className:"space-y-1",children:[_[f].slice(0,10).map($=>{const L=n===$.id,B=!L&&l.has($.id),G=v.has($.id);return e.jsxs("button",{type:"button",onClick:()=>c($.id),title:$.title,className:`flex w-full items-center gap-1.5 rounded-md border px-2 py-1 text-left transition-colors ${L?"border-[#BFFF00]/35 bg-[#BFFF00]/12":G?"border-[#FF6B88]/35 bg-[#FF6B88]/8 animate-[pulseSoft_2s_ease-in-out_infinite]":B?"border-[#14B8A6]/35 bg-[#14B8A6]/12":"border-strong bg-white/[0.03] hover:bg-white/[0.08]"}`,children:[e.jsx(ys,{type:$.type}),e.jsx("span",{className:`truncate text-caption ${G&&!L?"text-[#FF6B88]":"text-primary"}`,children:$.title})]},$.id)}),_[f].length>10&&e.jsxs("div",{className:"px-1 text-micro text-muted",children:["+",_[f].length-10," more"]})]})]},f))}),F.length>0&&e.jsxs("div",{className:"rounded-xl border border-white/[0.07] bg-black/[0.14] px-2.5 py-2",children:[e.jsx("div",{className:"mb-1 text-micro uppercase tracking-[0.08em] text-muted",children:"Dependency links"}),e.jsx("div",{className:"max-h-[110px] space-y-1 overflow-auto pr-1",children:F.slice(0,36).map(f=>{const $=o.get(f.from),L=o.get(f.to);if(!$||!L)return null;const B=n===$.id||n===L.id,G=v.has($.id)||v.has(L.id);return e.jsxs("button",{type:"button",onClick:()=>c(L.id),className:`flex w-full items-center gap-1 rounded-md px-1.5 py-1 text-left hover:bg-white/[0.06] ${G&&!B?"bg-[#FF6B88]/[0.04]":""}`,children:[e.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${G&&!B?"animate-[pulseSoft_2s_ease-in-out_infinite]":""}`,style:{backgroundColor:B?ee.lime:G?"#FF6B88":"rgba(255,255,255,0.35)"}}),e.jsx("span",{className:`truncate text-micro ${v.has($.id)?"text-[#FF6B88]":"text-primary"}`,children:$.title}),e.jsx("span",{className:`text-micro ${G?"text-[#FF6B88]/60":"text-muted"}`,children:"→"}),e.jsx("span",{className:`truncate text-micro ${v.has(L.id)?"text-[#FF6B88]":"text-primary"}`,children:L.title})]},`${f.from}-${f.to}`)})})]})]})}function rt(t){return Vr(t)}function Ns(t){return Number.isFinite(t)?Math.max(0,Math.min(100,Math.round(t))):0}function Ot(t,s){return s<=0?0:Ns(t/s*100)}function pa({dependencies:t,allNodes:s,disabled:n=!1,onSave:r}){const[c,o]=a.useState(!1),[d,x]=a.useState(""),[h,y]=a.useState(t),m=a.useMemo(()=>new Map(s.map(l=>[l.id,l])),[s]),S=a.useMemo(()=>{const l=d.trim().toLowerCase(),v=[...s].sort((g,w)=>g.title.localeCompare(w.title));return l?v.filter(g=>g.title.toLowerCase().includes(l)||g.id.toLowerCase().includes(l)).slice(0,16):v.slice(0,16)},[s,d]),I=()=>{r(Array.from(new Set(h))),o(!1)},k=l=>{y(v=>v.includes(l)?v.filter(g=>g!==l):[...v,l])};return e.jsxs("div",{className:"relative",children:[e.jsx("button",{type:"button",disabled:n,onClick:()=>{x(""),y(t),o(l=>!l)},className:"rounded-md border border-strong bg-white/[0.04] px-2 py-1 text-micro text-primary transition-colors hover:bg-white/[0.08] disabled:opacity-40",children:t.length>0?`${t.length} linked`:"Set links"}),c&&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:d,onChange:l=>x(l.target.value),placeholder:"Search by title or id...",className:"mt-1.5 h-9 w-full rounded-md border border-strong bg-black/25 px-2.5 text-caption text-bright outline-none transition-colors placeholder:text-muted focus:border-[#BFFF00]/35"}),e.jsx("div",{className:"mt-2 flex max-h-[84px] flex-wrap gap-1.5 overflow-y-auto rounded-md border border-white/[0.08] bg-black/20 p-1.5",children:h.length===0?e.jsx("span",{className:"text-micro text-muted",children:"No links selected"}):h.map(l=>{var g;const v=((g=m.get(l))==null?void 0:g.title)??l;return e.jsxs("button",{type:"button",onClick:()=>k(l),className:"inline-flex items-center gap-1 rounded-full border border-strong bg-white/[0.05] px-2 py-0.5 text-micro text-primary transition-colors hover:bg-white/[0.1]",title:v,children:[e.jsx("span",{className:"max-w-[180px] truncate",children:v}),e.jsx("span",{className:"text-secondary",children:"×"})]},l)})}),e.jsx("div",{className:"mt-2 max-h-[150px] space-y-1 overflow-y-auto rounded-md border border-white/[0.08] bg-black/20 p-1.5",children:S.length===0?e.jsx("div",{className:"px-1 text-micro text-muted",children:"No matching nodes"}):S.map(l=>{const v=h.includes(l.id);return e.jsxs("button",{type:"button",onClick:()=>k(l.id),className:`flex w-full items-center justify-between rounded-md border px-2 py-1 text-left text-micro transition-colors ${v?"border-[#BFFF00]/32 bg-[#BFFF00]/12 text-[#D8FFA1]":"border-white/[0.1] bg-white/[0.03] text-primary hover:bg-white/[0.08]"}`,children:[e.jsxs("span",{className:"min-w-0 pr-2",children:[e.jsx("span",{className:"block truncate",children:l.title}),e.jsxs("span",{className:"block truncate text-muted",children:[l.id.slice(0,8),"…"]})]}),e.jsx("span",{className:"font-semibold",children:v?"Linked":"Link"})]},l.id)})}),e.jsxs("div",{className:"mt-2 flex items-center justify-end gap-1.5",children:[e.jsx("button",{type:"button",onClick:()=>o(!1),className:"rounded-md border border-strong px-2 py-1 text-micro text-secondary transition-colors hover:bg-white/[0.08]",children:"Cancel"}),e.jsx("button",{type:"button",onClick:I,className:"rounded-md border border-[#BFFF00]/30 bg-[#BFFF00]/15 px-2 py-1 text-micro text-[#D8FFA1] transition-colors hover:bg-[#BFFF00]/22",children:"Save links"})]})]})]})}const xa={bottom:"Add to queue"},ha=[{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 fa({scope:t,size:s=12}){const n=s,r=Math.round(n*.14),c=Math.round(n*.06);if(t==="task")return e.jsx("svg",{width:n,height:n,viewBox:`0 0 ${n} ${n}`,fill:"currentColor","aria-hidden":!0,children:e.jsx("circle",{cx:n/2,cy:n/2,r:r+1})});if(t==="milestone"){const d=n/2;return e.jsxs("svg",{width:n,height:n,viewBox:`0 0 ${n} ${n}`,fill:"currentColor","aria-hidden":!0,children:[e.jsx("circle",{cx:d,cy:r+c,r}),e.jsx("circle",{cx:d,cy:n/2,r}),e.jsx("circle",{cx:d,cy:n-r-c,r})]})}const o=r+c+1;return e.jsxs("svg",{width:n,height:n,viewBox:`0 0 ${n} ${n}`,fill:"currentColor","aria-hidden":!0,children:[e.jsx("circle",{cx:o,cy:o,r}),e.jsx("circle",{cx:n-o,cy:o,r}),e.jsx("circle",{cx:o,cy:n-o,r}),e.jsx("circle",{cx:n-o,cy:n-o,r})]})}function Ss({label:t="Queue",defaultPlacement:s="bottom",size:n="sm",align:r="right",menuDirection:c="up",disabled:o=!1,busy:d=!1,isQueued:x=!1,className:h="",menuClassName:y="",title:m,stopPropagation:S=!1,onSelectPlacement:I,onLaunch:k,onAutopilot:l,onPause:v,onArchive:g}){const[w,F]=a.useState(!1),_=a.useRef(null),f=a.useRef(`queue-placement-${Math.random().toString(36).slice(2,10)}`),$=o||d,L=n==="md"?"h-8 text-caption":"h-7 text-micro",B=n==="md"?"px-3":"px-2.5",G=n==="md"?"h-8 w-8":"h-7 w-7",se=r==="left"?"left-0":"right-0",K=c==="up"?"bottom-[calc(100%+6px)]":"top-[calc(100%+6px)]";a.useEffect(()=>{if(!w)return;const E=z=>{var W;const D=z.target;D&&((W=_.current)!=null&&W.contains(D)||F(!1))},H=z=>{z.key==="Escape"&&F(!1)};return document.addEventListener("mousedown",E),document.addEventListener("touchstart",E),document.addEventListener("keydown",H),()=>{document.removeEventListener("mousedown",E),document.removeEventListener("touchstart",E),document.removeEventListener("keydown",H)}},[w]);const J=(E,H,z)=>{S&&E.stopPropagation(),F(!1),I(H,z)};return e.jsxs("div",{ref:_,className:`relative inline-flex items-center ${h}`,children:[e.jsxs("button",{type:"button",title:m??`Queue ${s==="top"?"to top":"to end"}`,onClick:E=>J(E,s),disabled:$,className:`control-pill ${L} ${B} rounded-r-none border-r-0 font-semibold disabled:opacity-45 ${x?"border-[#BFFF00]/20 bg-[#BFFF00]/[0.06] text-[#D8FFA1]":"text-primary"}`,children:[x?e.jsx("svg",{width:n==="md"?13:12,height:n==="md"?13:12,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:"opacity-90","aria-hidden":!0,children:e.jsx("path",{d:"M20 6 9 17l-5-5"})}):e.jsxs("svg",{width:n==="md"?13:12,height:n==="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:d?"Queueing...":t})]}),e.jsx("button",{type:"button","aria-label":"Choose queue placement","aria-haspopup":"menu","aria-expanded":w,"aria-controls":f.current,onClick:E=>{S&&E.stopPropagation(),!$&&F(H=>!H)},disabled:$,className:`control-pill ${G} rounded-l-none px-0 disabled:opacity-45 ${x?"border-[#BFFF00]/20 bg-[#BFFF00]/[0.06] text-[#D8FFA1]":"text-secondary"}`,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 ${w?"rotate-180":""}`,"aria-hidden":!0,children:e.jsx("path",{d:"m6 9 6 6 6-6"})})}),w&&e.jsxs("div",{id:f.current,role:"menu",className:`absolute ${se} ${K} 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 ${y}`,children:[ha.map(E=>e.jsxs("button",{type:"button",role:"menuitem",onClick:H=>J(H,"top",E.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(fa,{scope:E.scope,size:12}),e.jsx("span",{className:"text-caption font-medium text-primary",children:E.label}),e.jsx("span",{className:"ml-auto text-micro text-tertiary",children:E.description})]},E.scope)),e.jsx("div",{className:"my-1 border-t border-strong"}),e.jsx("button",{type:"button",role:"menuitem",onClick:E=>J(E,"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:xa.bottom})})]})]})}function ga(t){if(!t)return"";const s=new Date(t);if(Number.isNaN(s.getTime()))return"";const n=s.getFullYear(),r=String(s.getMonth()+1).padStart(2,"0"),c=String(s.getDate()).padStart(2,"0"),o=String(s.getHours()).padStart(2,"0"),d=String(s.getMinutes()).padStart(2,"0");return`${n}-${r}-${c}T${o}:${d}`}const Cn=["not_started","planned","todo","in_progress","active","blocked","done"];function ba(t){const s=t.trim().toLowerCase();return s==="blocked"?"blocked":s==="done"||s==="completed"?"done":s==="in_progress"||s==="active"||s==="running"||s==="queued"?"active":"planned"}function ps(t){const s=t.trim().toLowerCase();return s==="completed"?"done":s==="running"||s==="queued"?"active":s==="pending"||s==="backlog"?"todo":s}function ya(t,s){return s==="all"?!0:s==="blocked"?t==="blocked":s==="done"?t==="done":t!=="blocked"&&t!=="done"}function wa(t){const s=Number.isFinite(t)?Math.max(1,Math.min(100,Math.round(t))):50;return s<=12?{label:"P1 Urgent",toneClass:"border-red-300/35 bg-red-500/[0.14] text-red-100"}:s<=30?{label:"P2 High",toneClass:"border-amber-300/35 bg-amber-500/[0.14] text-amber-100"}:s<=60?{label:"P3 Medium",toneClass:"border-[#BFFF00]/35 bg-[#BFFF00]/14 text-[#E1FFB2]"}:{label:"P4 Low",toneClass:"border-white/[0.2] bg-white/[0.08] text-white/70"}}function va(t,s){const n=new Map(s.map(o=>[o.id,o])),r=new Set,c=[t];for(;c.length>0;){const o=c.shift(),d=n.get(o);d&&(d.parentId&&!r.has(d.parentId)&&(r.add(d.parentId),c.push(d.parentId)),d.workstreamId&&!r.has(d.workstreamId)&&(r.add(d.workstreamId),c.push(d.workstreamId)),d.milestoneId&&!r.has(d.milestoneId)&&(r.add(d.milestoneId),c.push(d.milestoneId)))}return r}function ja(t,s,n,r){let c=0;if(n==="title")c=t.title.localeCompare(s.title);else if(n==="status")c=gs(t.status)-gs(s.status);else if(n==="priority")c=t.priorityNum-s.priorityNum;else if(n==="eta"){const o=t.etaEndAt?Date.parse(t.etaEndAt):1/0,d=s.etaEndAt?Date.parse(s.etaEndAt):1/0;c=o-d}return r==="desc"?-c:c}function es(t,s){return!t||t.trim().length===0?s:pt(t.trim())||s}function ka({nodes:t,edges:s,selectedNodeId:n,highlightedNodeIds:r,editMode:c,onToggleEditMode:o,onSelectNode:d,onFocusWorkstream:x,onOpenNode:h,onUpdateNode:y,mutations:m}){const{authToken:S,embedMode:I}=Tt(),k=ls({authToken:S,embedMode:I}),[l,v]=a.useState(""),[g,w]=a.useState(new Set),[F,_]=a.useState("all"),[f,$]=a.useState(!1),[L,B]=a.useState(null),[G,se]=a.useState("asc"),[K,J]=a.useState(new Set),[E,H]=a.useState(!1),[z,D]=a.useState(null),W=a.useRef(null),xe=a.useRef(null),Se=a.useRef(null),he=a.useRef(null),ne=a.useRef(null),ye=a.useRef(null),[U,M]=a.useState(!1);a.useEffect(()=>{if(!z)return;const i=z.tone==="success"?6500:9e3,A=window.setTimeout(()=>D(null),i);return()=>window.clearTimeout(A)},[z==null?void 0:z.message,z==null?void 0:z.tone]);const me=a.useMemo(()=>new Map(t.map(i=>[i.id,i])),[t]),te=a.useMemo(()=>t.map(i=>({id:i.id,title:i.title})),[t]),fe=a.useMemo(()=>{const i=new Map;for(const A of t){const C=ps(A.status);i.set(C,(i.get(C)??0)+1)}return i},[t]),Z=a.useMemo(()=>{let i=0,A=0,C=0;for(const q of t){const re=ps(q.status);re==="blocked"?A+=1:re==="done"?C+=1:i+=1}return{all:t.length,open:i,blocked:A,done:C}},[t]),N=a.useMemo(()=>{const i=l.trim().toLowerCase(),A=i.length>0,C=g.size>0;if(!A&&!C&&!(F!=="all"))return null;const re=new Set;for(const we of t){const Te=ps(we.status),Ue=!A||we.title.toLowerCase().includes(i)||we.assignedAgents.some(Me=>Me.name.toLowerCase().includes(i)),de=!C||g.has(Te),De=ya(Te,F);Ue&&de&&De&&re.add(we.id)}const pe=new Set(re);for(const we of re)for(const Te of va(we,t))pe.add(Te);return pe},[g,t,l,F]),j=a.useMemo(()=>t.filter(i=>i.type==="workstream").sort((i,A)=>{const C=i.sequenceIndex??1/0,q=A.sequenceIndex??1/0;return C!==q?C-q:i.priorityNum-A.priorityNum||i.title.localeCompare(A.title)}),[t]),u=a.useMemo(()=>{const i=new Map;for(const A of t.filter(C=>C.type==="milestone")){const C=A.workstreamId??"unscoped",q=i.get(C)??[];q.push(A),i.set(C,q)}for(const A of i.values())A.sort((C,q)=>{const re=C.sequenceIndex??1/0,pe=q.sequenceIndex??1/0;return re!==pe?re-pe:C.priorityNum-q.priorityNum||C.title.localeCompare(q.title)});return i},[t]),P=a.useMemo(()=>{const i=new Map;for(const A of t.filter(C=>C.type==="task"&&C.milestoneId)){const C=A.milestoneId??"unscoped",q=i.get(C)??[];q.push(A),i.set(C,q)}for(const A of i.values())A.sort((C,q)=>{const re=C.sequenceIndex??1/0,pe=q.sequenceIndex??1/0;return re!==pe?re-pe:C.priorityNum-q.priorityNum||C.title.localeCompare(q.title)});return i},[t]),ie=a.useMemo(()=>{const i=new Map;for(const A of t.filter(C=>C.type==="task"&&!C.milestoneId)){const C=A.workstreamId??"unscoped",q=i.get(C)??[];q.push(A),i.set(C,q)}for(const A of i.values())A.sort((C,q)=>{const re=C.sequenceIndex??1/0,pe=q.sequenceIndex??1/0;return re!==pe?re-pe:C.priorityNum-q.priorityNum||C.title.localeCompare(q.title)});return i},[t]),ke=a.useMemo(()=>{const i=new Set;for(const A of j)i.add(A.id);for(const A of t.filter(C=>C.type==="milestone"))i.add(A.id);return i},[t,j]),[be,Pe]=a.useState(ke);a.useEffect(()=>{Pe(ke)},[ke]);const Ce=i=>L?[...i].sort((A,C)=>ja(A,C,L,G)):[...i].sort((A,C)=>{const q=A.sequenceIndex??1/0,re=C.sequenceIndex??1/0;return q!==re?q-re:A.priorityNum-C.priorityNum||A.title.localeCompare(C.title)}),le=a.useMemo(()=>{const i=[],A=de=>N===null||N.has(de),C=de=>de==="workstream"?"W":de==="milestone"?"M":de==="task"?"T":"",q=Ce(j);let re=0;for(const de of q){if(!A(de.id))continue;re+=1;const De=Ce(u.get(de.id)??[]),Me=Ce(ie.get(de.id)??[]),Ae=De.length>0||Me.length>0;if(i.push({node:de,depth:0,canCollapse:Ae,hierarchyLabel:`${C(de.type)}${re}`}),!be.has(de.id))continue;let ct=0;for(const Ve of De){if(!A(Ve.id))continue;ct+=1;const V=Ce(P.get(Ve.id)??[]);if(i.push({node:Ve,depth:1,canCollapse:V.length>0,hierarchyLabel:`${C(Ve.type)}${ct}`}),be.has(Ve.id)){let b=0;for(const O of V)A(O.id)&&(b+=1,i.push({node:O,depth:2,canCollapse:!1,hierarchyLabel:`${C(O.type)}${b}`}))}}let ht=0;for(const Ve of Me)A(Ve.id)&&(ht+=1,i.push({node:Ve,depth:1,canCollapse:!1,hierarchyLabel:`${C(Ve.type)}${ht}`}))}const pe=Ce(u.get("unscoped")??[]),we=Ce(ie.get("unscoped")??[]);let Te=0;for(const de of pe)if(A(de.id)&&(Te+=1,i.push({node:de,depth:0,canCollapse:(P.get(de.id)??[]).length>0,hierarchyLabel:`${C(de.type)}${Te}`}),be.has(de.id))){let De=0;for(const Me of Ce(P.get(de.id)??[]))A(Me.id)&&(De+=1,i.push({node:Me,depth:1,canCollapse:!1,hierarchyLabel:`${C(Me.type)}${De}`}))}let Ue=0;for(const de of we)A(de.id)&&(Ue+=1,i.push({node:de,depth:0,canCollapse:!1,hierarchyLabel:`${C(de.type)}${Ue}`}));return i},[ie,be,N,u,L,G,P,j]),Fe=a.useMemo(()=>le.map(({node:i})=>i.id),[le]),{handleSelect:ze}=sr(Fe),Re=a.useMemo(()=>new Set(Fe),[Fe]),qe=a.useMemo(()=>le.filter(({node:i})=>K.has(i.id)),[le,K]),gt=(F!=="all"?1:0)+g.size,$t=l.trim().length>0||F!=="all"||g.size>0,Ie=qe.length,at=le.length>0&&Ie===le.length,Ge=(m==null?void 0:m.bulkEntityMutation.isPending)??!1;a.useEffect(()=>{J(i=>{if(i.size===0)return i;const A=new Set(Array.from(i).filter(C=>Re.has(C)));return A.size===i.size?i:A})},[Re]),a.useEffect(()=>{W.current&&(W.current.indeterminate=Ie>0&&!at)},[at,Ie]),a.useEffect(()=>{Ie===0&&E&&H(!1)},[E,Ie]),a.useEffect(()=>{if(!f)return;const i=C=>{var re;const q=C.target;q&&((re=xe.current)!=null&&re.contains(q)||$(!1))},A=C=>{C.key==="Escape"&&$(!1)};return document.addEventListener("mousedown",i),document.addEventListener("touchstart",i),document.addEventListener("keydown",A),()=>{document.removeEventListener("mousedown",i),document.removeEventListener("touchstart",i),document.removeEventListener("keydown",A)}},[f]);const Le=i=>i.dependencyIds.length,ot=k.isPinning||k.isMoving,Nt=async i=>{await k.pin({initiativeId:i.initiativeId,workstreamId:i.workstreamId,taskId:i.taskId??null,milestoneId:i.milestoneId??null}),await k.move({initiativeId:i.initiativeId,workstreamId:i.workstreamId,placement:i.placement})},Ye=async(i,A="bottom")=>{if(i.type==="initiative"){const we=j.filter(Me=>Me.initiativeId===i.id);if(we.length===0){D({tone:"error",message:"Cannot queue initiative: no workstreams found."});return}const Te=A==="top"?[...we].reverse():we;let Ue=0,de=0,De=null;for(const Me of Te)try{await Nt({initiativeId:i.id,workstreamId:Me.id,placement:A}),Ue+=1}catch(Ae){de+=1,De||(De=es(Ae instanceof Error?Ae.message:"","Failed to add initiative workstream to queue."))}de>0?D({tone:Ue>0?"success":"error",message:Ue>0?`Queued ${Ue}/${we.length} workstreams (${de} failed). ${De??""}`.trim():De??"Failed to queue initiative workstreams."}):D({tone:"success",message:`Queued ${Ue} workstream${Ue===1?"":"s"} to ${A==="top"?"top":"end"}.`}),window.setTimeout(()=>D(null),de>0?4200:2400);return}const C=i.initiativeId??"",q=i.type==="workstream"?i.id:i.workstreamId??"",re=i.type==="task"?i.id:null,pe=i.type==="milestone"?i.id:null;if(!C||!q){D({tone:"error",message:"Cannot add to queue: missing initiative/workstream id."});return}try{await Nt({initiativeId:C,workstreamId:q,taskId:re,milestoneId:pe,placement:A}),D({tone:"success",message:i.type==="task"?`Queued task workstream to ${A==="top"?"top":"end"}.`:i.type==="milestone"?`Queued milestone workstream to ${A==="top"?"top":"end"}.`:`Queued workstream to ${A==="top"?"top":"end"}.`}),window.setTimeout(()=>D(null),2e3)}catch(we){D({tone:"error",message:es(we instanceof Error?we.message:"","Failed to add workstream to queue.")}),window.setTimeout(()=>D(null),2400)}},Qe=i=>{if(i.type==="workstream")return i.id;if(i.type==="milestone"||i.type==="task")return i.workstreamId??null;if(i.type==="initiative"){const A=j.filter(q=>q.initiativeId===i.id);if(A.length===0)return null;const C=A.find(q=>!rt(q.status))??A[0];return(C==null?void 0:C.id)??null}return null},We=async(i,A)=>{const C=i.type==="initiative"?i.id:i.initiativeId??"",q=A??(i.type==="workstream"?i.id:i.workstreamId??"");if(!C||!q){D({tone:"error",message:"Cannot start now: missing initiative/workstream id."});return}try{const re=await fetch("/orgx/api/mission-control/next-up/play",{method:"POST",headers:Ft({authToken:S,embedMode:I,contentTypeJson:!0}),body:JSON.stringify({initiativeId:C,workstreamId:q,fastAck:!0,ignoreSpawnGuardRateLimit:!0})}),pe=await re.json().catch(()=>null);if(!re.ok)throw new Error((pe==null?void 0:pe.error)??(pe==null?void 0:pe.message)??`Failed to start workstream (${re.status})`);D({tone:"success",message:`Started ${i.title}.`}),window.setTimeout(()=>D(null),1800)}catch(re){D({tone:"error",message:es(re instanceof Error?re.message:"","Failed to start workstream now.")}),window.setTimeout(()=>D(null),2400)}},zt=a.useMemo(()=>{const i=new Map,A=(C,q)=>{if(C.length>0){const re=C.filter(pe=>rt(pe.status)).length;return Ot(re,C.length)}return rt(q)?100:0};for(const C of t.filter(q=>q.type==="milestone")){const q=P.get(C.id)??[];i.set(C.id,A(q,C.status))}for(const C of j){const re=(u.get(C.id)??[]).flatMap(we=>P.get(we.id)??[]),pe=ie.get(C.id)??[];i.set(C.id,A([...pe,...re],C.status))}return i},[ie,u,t,P,j]),Je=i=>{L===i?se(A=>A==="asc"?"desc":"asc"):(B(i),se("asc"))},Xe=i=>{w(A=>{const C=new Set(A);return C.has(i)?C.delete(i):C.add(i),C})},Xt=()=>{v(""),_("all"),w(new Set)},It=(i,A,C)=>{D(null),H(!1),ze(i,A,C,J)},xt=()=>{D(null),H(!1),J(()=>le.length===0||at?new Set:new Set(Fe))},_t=()=>{H(!1),J(new Set)},bt=async i=>{if(!(!m||qe.length===0)){H(!1),D(null);try{const A=await m.bulkEntityMutation.mutateAsync({items:qe.map(({node:C})=>({type:C.type,id:C.id})),mode:"update",updates:{status:i}});A.failed>0?D({tone:"error",message:`Updated ${A.updated}, failed ${A.failed}.`}):D({tone:"success",message:`Updated ${A.updated} item${A.updated===1?"":"s"} to ${nt(i)}.`})}catch(A){D({tone:"error",message:es(A instanceof Error?A.message:"","Bulk status update failed.")})}}},St=async()=>{if(!(!m||qe.length===0)){D(null);try{const i=await m.bulkEntityMutation.mutateAsync({items:qe.map(({node:A})=>({type:A.type,id:A.id})),mode:"delete"});i.failed>0?D({tone:"error",message:`Deleted ${i.updated}, failed ${i.failed}.`}):(D({tone:"success",message:`Deleted ${i.updated} item${i.updated===1?"":"s"}.`}),J(new Set),H(!1))}catch(i){D({tone:"error",message:es(i instanceof Error?i.message:"","Bulk delete failed.")})}}},Ne=({field:i})=>L!==i?e.jsx("span",{className:"text-faint ml-0.5",children:"↕"}):e.jsx("span",{className:"text-[#BFFF00] ml-0.5",children:G==="asc"?"↑":"↓"}),lt=U?"0px":"calc(var(--mc-toolbar-offset, 0px) + 12px)",st=i=>{if(ye.current==="body"){ye.current=null;return}const A=i.currentTarget.scrollLeft,C=he.current;!C||C.scrollLeft===A||(ye.current="header",C.scrollLeft=A)},it=i=>{if(ye.current==="header"){ye.current=null;return}const A=i.currentTarget.scrollLeft,C=Se.current;!C||C.scrollLeft===A||(ye.current="body",C.scrollLeft=A)};a.useEffect(()=>{const i=he.current,A=Se.current;!i||!A||A.scrollLeft!==i.scrollLeft&&(A.scrollLeft=i.scrollLeft)},[le.length]),a.useEffect(()=>{if(typeof window>"u")return;const i=ne.current;if(!i)return;const A=()=>{const q=Math.min(window.innerHeight*.62,560),re=i.scrollHeight;M(re>q+1)};A();const C=typeof ResizeObserver<"u"?new ResizeObserver(()=>A()):null;return C==null||C.observe(i),window.addEventListener("resize",A),()=>{C==null||C.disconnect(),window.removeEventListener("resize",A)}},[le.length]);const yt=()=>e.jsxs("colgroup",{children:[e.jsx("col",{style:{width:40}}),e.jsx("col",{style:{width:360}}),e.jsx("col",{style:{width:188}}),e.jsx("col",{style:{width:124}}),e.jsx("col",{style:{width:120}}),e.jsx("col",{style:{width:96}}),e.jsx("col",{style:{width:156}}),e.jsx("col",{style:{width:100}}),e.jsx("col",{style:{width:100}}),e.jsx("col",{style:{width:180}})]});return e.jsxs("section",{className:"space-y-2.5",children:[e.jsxs("div",{className:"mb-3.5 flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between",children:[e.jsx("div",{className:"w-full xl:max-w-[380px]",children:e.jsx(Zs,{value:l,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:[o&&e.jsxs("button",{type:"button",onClick:o,"data-state":c?"active":"idle",className:`control-pill inline-flex h-8 items-center gap-1.5 px-3.5 text-caption font-semibold ${c?"text-[#D8FFA1]":"text-secondary hover:text-bright"}`,children:[e.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e.jsx("path",{d:"M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"})}),c?"Editing":"Edit"]}),e.jsxs("div",{ref:xe,className:"relative",children:[e.jsxs("button",{type:"button",onClick:()=>$(i=>!i),"data-state":f||gt>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"}),gt>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:gt})]}),e.jsx(mt,{children:f&&e.jsxs(je.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:Z.all},{id:"open",label:"Open",count:Z.open},{id:"blocked",label:"Blocked",count:Z.blocked},{id:"done",label:"Done",count:Z.done}].map(i=>{const A=F===i.id;return e.jsxs("button",{type:"button",onClick:()=>_(i.id),className:`inline-flex h-7 items-center gap-1.5 rounded-full border px-2.5 text-micro font-semibold transition-colors ${A?"border-[#BFFF00]/30 bg-[#BFFF00]/10 text-[#D8FFA1]":"border-strong bg-white/[0.03] text-secondary hover:bg-white/[0.07] hover:text-white/82"}`,children:[e.jsx("span",{children:i.label}),e.jsx("span",{className:"text-micro text-current/80",children:i.count})]},i.id)})})]}),e.jsxs("div",{className:"mb-2 border-t border-white/[0.08] pt-2",children:[e.jsx("div",{className:"text-micro font-semibold uppercase tracking-[0.08em] text-muted",children:"Status"}),e.jsx("div",{className:"mt-1.5 flex flex-wrap gap-1.5",children:Cn.map(i=>{const A=g.has(i),C=fe.get(i)??0;return e.jsxs("button",{type:"button",onClick:()=>Xe(i),className:`inline-flex h-7 items-center gap-1 rounded-full border px-2.5 text-micro transition-colors ${A?"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:nt(i)}),e.jsx("span",{className:"text-micro text-current/75",children:C})]},i)})})]}),(F!=="all"||g.size>0)&&e.jsx("button",{type:"button",onClick:()=>{_("all"),w(new Set)},className:"text-micro text-secondary transition-colors hover:text-primary",children:"Reset filters"})]})})]}),e.jsx(mt,{initial:!1,children:$t&&e.jsx(je.button,{type:"button",onClick:Xt,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:xt,"data-state":at?"active":"idle",className:"control-pill inline-flex h-8 items-center gap-1.5 px-3.5 text-caption font-semibold",children:at?"Clear all":"Select all"})]})]}),e.jsx("div",{className:"mb-1.5",children:e.jsx("div",{className:`rounded-xl border px-3 ${Ie>0?"border-[#BFFF00]/24 bg-[#BFFF00]/[0.08]":"border-white/[0.08] bg-white/[0.02]"}`,children:e.jsxs("div",{className:"flex h-[48px] min-w-max flex-nowrap items-center gap-2 overflow-x-auto py-1 whitespace-nowrap",children:[e.jsxs("label",{className:"inline-flex flex-shrink-0 items-center gap-2 text-caption text-primary",children:[e.jsx("input",{ref:W,type:"checkbox",checked:at,onChange:xt,className:"h-3.5 w-3.5 rounded border-white/20 bg-black/40 text-[#BFFF00] focus:ring-[#BFFF00]/35"}),"Select all"]}),e.jsx("span",{className:"flex-shrink-0 text-caption text-white/58",children:Ie>0?`${Ie} selected`:`${le.length} visible`}),Ie>0&&e.jsxs("div",{className:"flex flex-shrink-0 items-center gap-2 whitespace-nowrap",children:[e.jsx("button",{type:"button",onClick:()=>{bt("planned")},disabled:Ge,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:()=>{bt("in_progress")},disabled:Ge,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:()=>{bt("blocked")},disabled:Ge,className:"control-pill h-8 flex-shrink-0 px-3 text-caption font-semibold disabled:opacity-45",children:"Block"}),e.jsx("button",{type:"button",onClick:()=>{bt("done")},disabled:Ge,className:"control-pill h-8 flex-shrink-0 px-3 text-caption font-semibold disabled:opacity-45",children:"Complete"}),E?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:()=>{St()},disabled:Ge,className:"control-pill h-8 flex-shrink-0 border-red-400/35 bg-red-500/14 px-3 text-caption font-semibold text-red-100 disabled:opacity-45",children:"Delete"}),e.jsx("button",{type:"button",onClick:()=>H(!1),disabled:Ge,className:"control-pill h-8 flex-shrink-0 px-2.5 text-caption disabled:opacity-45",children:"Keep"})]}):e.jsx("button",{type:"button",onClick:()=>H(!0),disabled:Ge,className:"control-pill h-8 flex-shrink-0 border-red-400/24 bg-red-500/[0.08] px-3 text-caption font-semibold text-red-100/85 disabled:opacity-45",children:"Delete"}),e.jsx("button",{type:"button",onClick:_t,disabled:Ge,className:"text-caption text-secondary transition-colors hover:text-primary disabled:opacity-45",children:"Clear"})]})]})})}),z&&e.jsx("div",{role:"status","aria-live":"polite",className:"rounded-lg border border-white/[0.08] bg-white/[0.02] px-3 py-2 text-caption text-white/72",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex min-w-0 items-start gap-2",children:[e.jsx("span",{"aria-hidden":!0,className:`mt-[3px] h-1.5 w-1.5 flex-shrink-0 rounded-full ${z.tone==="success"?"bg-emerald-300/90":"bg-amber-300/90"}`}),e.jsx("span",{className:"min-w-0 leading-snug",children:z.message})]}),e.jsx("button",{type:"button",onClick:()=>D(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"})]})})]})}),c&&e.jsx("div",{className:"mb-2 text-micro text-secondary",children:"Edit mode: select a row to edit its fields inline."}),e.jsx("div",{className:"relative min-w-0 max-w-full overflow-visible rounded-xl border border-white/[0.07] bg-black/[0.14] p-2",children:e.jsxs("div",{ref:ne,"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:Se,onScroll:st,className:"overflow-x-auto overflow-y-hidden [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",children:e.jsxs("table",{className:"w-full min-w-[1464px] table-fixed border-separate border-spacing-y-0",children:[yt(),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:()=>Je("title"),children:["Item ",e.jsx(Ne,{field:"title"})]}),e.jsx("th",{className:"px-2 py-1.5",children:"Assigned"}),e.jsxs("th",{className:"px-2 py-1.5 cursor-pointer select-none",onClick:()=>Je("status"),children:["Status ",e.jsx(Ne,{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:()=>Je("priority"),children:["Priority ",e.jsx(Ne,{field:"priority"})]}),e.jsxs("th",{className:"px-2 py-1.5 cursor-pointer select-none",onClick:()=>Je("eta"),children:["ETA ",e.jsx(Ne,{field:"eta"})]}),e.jsx("th",{className:"px-2 py-1.5",children:"Duration (h)"}),e.jsx("th",{className:"px-2 py-1.5",children:"Budget ($)"}),e.jsx("th",{className:"px-2 py-1.5",children:"Dependencies"})]})})]})})}),e.jsx("div",{ref:he,onScroll:it,className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full min-w-[1464px] table-fixed border-separate border-spacing-y-1.5",children:[yt(),e.jsx("tbody",{children:le.map(({node:i,depth:A,canCollapse:C,hierarchyLabel:q})=>{var Ve;const re=n===i.id,pe=r.has(i.id),we=K.has(i.id),Te=i.assignedAgents.map(V=>V.name).join(", "),Ue=i.dependencyIds.map(V=>{var b;return((b=me.get(V))==null?void 0:b.title)??V}).slice(0,3).join(", "),de=zt.get(i.id),De=wa(i.priorityNum),Me=c&&re,Ae=i.type==="initiative"||i.type==="workstream"||i.type==="milestone"||i.type==="task",ct=Qe(i),ht=!!ct;return e.jsxs("tr",{onClick:()=>{d(i.id),i.type==="workstream"&&x(i.id)},className:`group/row cursor-pointer rounded-lg border transition-colors ${re?"border-[#BFFF00]/[0.22] bg-[#BFFF00]/[0.08]":pe?"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:we,onChange:V=>{V.stopPropagation();const b=V.nativeEvent.shiftKey??!1;It(i.id,V.currentTarget.checked,b)},onClick:V=>V.stopPropagation(),"aria-label":`Select ${i.type}: ${i.title}`,className:"h-3.5 w-3.5 rounded border-white/20 bg-black/40 text-[#BFFF00] focus:ring-[#BFFF00]/35"})}),e.jsx("td",{className:"px-2 py-1.5",children:e.jsxs("div",{className:"flex min-w-0 items-center",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5 pr-2",children:[e.jsx("div",{style:{width:A*14}}),C?e.jsx("button",{type:"button",onClick:V=>{V.stopPropagation(),Pe(b=>{const O=new Set(b);return O.has(i.id)?O.delete(i.id):O.add(i.id),O})},"aria-label":`${be.has(i.id)?"Collapse":"Expand"} ${i.type}: ${i.title}`,className:"rounded text-secondary focus:outline-none focus-visible:ring-2 focus-visible:ring-[#BFFF00]/35 focus-visible:ring-offset-2 focus-visible:ring-offset-[#02040A]",children:be.has(i.id)?"▾":"▸"}):e.jsx("span",{className:"w-2.5"}),e.jsx(ys,{type:i.type,hierarchyLabel:q}),e.jsx("button",{type:"button",onClick:V=>{V.stopPropagation(),h(i)},"aria-label":`Open ${i.type} details: ${i.title}`,className:"min-w-0 max-w-[560px] flex-1 truncate rounded text-left text-body text-bright hover:text-white focus:outline-none focus-visible:ring-2 focus-visible:ring-[#BFFF00]/35 focus-visible:ring-offset-2 focus-visible:ring-offset-[#02040A]",children:i.title})]}),!c&&e.jsxs("div",{className:"ml-1 grid w-[168px] min-w-[168px] grid-cols-[124px_34px] items-center justify-end gap-2",children:[Ae?e.jsx(Ss,{label:"Queue",size:"sm",busy:ot,stopPropagation:!0,title:`Queue ${i.type}: ${i.title}`,onSelectPlacement:V=>Ye(i,V)}):e.jsx("span",{className:"h-7 w-[124px]"}),e.jsx("button",{type:"button",disabled:!ht,title:ht?"Start":"No runnable workstream",onClick:V=>{V.stopPropagation(),ct&&We(i,ct)},"aria-label":ht?`Start ${i.type}: ${i.title}`:`${i.type} has no runnable workstream`,className:"control-pill flex h-7 w-[34px] items-center justify-center px-0 text-[#D8FFA1] hover:text-[#E9FFBD] disabled:cursor-not-allowed disabled:text-white/25 disabled:hover:text-white/25",children:e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("path",{d:"M8 5v14l11-7z"})})})]})]})}),e.jsx("td",{className:"px-2 py-1.5 text-caption text-primary whitespace-nowrap",children:Me?e.jsx("input",{type:"text",defaultValue:Te,placeholder:"Agent A, Agent B",onClick:V=>V.stopPropagation(),onBlur:V=>{const b=V.currentTarget.value.split(",").map(O=>O.trim()).filter(Boolean);y(i,{assigned_agent_names:b,assigned_agent_ids:b.map(O=>`name:${O}`),assignment_source:"manual"})},className:"w-[190px] rounded border border-strong bg-white/[0.06] px-2 py-1 text-micro text-white/82"}):e.jsx("div",{className:"flex items-center gap-2",children:i.assignedAgents.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex items-center -space-x-1.5",children:i.assignedAgents.slice(0,3).map(V=>e.jsx("div",{title:V.name,className:"rounded-full ring-1 ring-[#02040A]",children:e.jsx(Xn,{name:V.name,hint:`${V.id} ${i.title}`,size:"xs"})},`${i.id}:${V.id}`))}),e.jsxs("span",{className:"max-w-[110px] truncate text-micro text-white/62",title:Te,children:[(Ve=i.assignedAgents[0])==null?void 0:Ve.name,i.assignedAgents.length>1?` +${i.assignedAgents.length-1}`:""]})]}):e.jsx("span",{className:"text-muted",children:"Unassigned"})})}),e.jsx("td",{className:"px-2 py-1.5 text-caption text-primary",children:Me?e.jsx("select",{defaultValue:ps(i.status),onClick:V=>V.stopPropagation(),onChange:V=>{y(i,{status:V.target.value})},className:"rounded border border-strong bg-white/[0.06] px-2 py-1 text-micro text-white/82",children:Cn.map(V=>e.jsx("option",{value:V,children:nt(V)},V))}):e.jsx("span",{className:"status-pill whitespace-nowrap","data-tone":ba(i.status),children:nt(i.status)})}),e.jsx("td",{className:"px-2 py-1.5 text-caption text-primary",children:de!==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:`${de}%`,backgroundColor:i.type==="milestone"?ee.teal:ee.lime}})}),e.jsxs("span",{className:"text-micro text-secondary",style:{fontVariantNumeric:"tabular-nums"},children:[de,"%"]})]}):e.jsx("span",{className:"text-muted",children:"—"})}),e.jsx("td",{className:"px-2 py-1.5 text-caption text-primary",children:Me?e.jsx("input",{type:"number",min:1,max:100,defaultValue:i.priorityNum,onClick:V=>V.stopPropagation(),onBlur:V=>{const b=Number(V.currentTarget.value);Number.isFinite(b)&&y(i,{priority_num:b})},className:"w-[72px] rounded border border-strong bg-white/[0.06] px-2 py-1 text-micro text-white/82"}):e.jsx("span",{className:`inline-flex items-center rounded-full border px-2 py-0.5 text-micro font-semibold uppercase tracking-[0.08em] ${De.toneClass}`,title:`Priority ${De.label}`,children:De.label})}),e.jsx("td",{className:"px-2 py-1.5 text-caption text-primary",children:Me?e.jsx("input",{type:"datetime-local",defaultValue:ga(i.etaEndAt),onClick:V=>V.stopPropagation(),onBlur:V=>{const b=V.currentTarget.value;y(i,{eta_end_at:b?new Date(b).toISOString():null})},className:"w-[176px] rounded border border-strong bg-white/[0.06] px-2 py-1 text-micro text-white/82"}):e.jsx("span",{children:i.etaEndAt?new Date(i.etaEndAt).toLocaleString():"—"})}),e.jsx("td",{className:"px-2 py-1.5 text-caption text-primary",children:Me&&i.type!=="task"?e.jsx("input",{type:"number",min:0,step:.5,defaultValue:i.expectedDurationHours,onClick:V=>V.stopPropagation(),onBlur:V=>{const b=Number(V.currentTarget.value);Number.isFinite(b)&&y(i,{expected_duration_hours:b})},className:"w-[82px] rounded border border-strong bg-white/[0.06] px-2 py-1 text-micro text-white/82"}):e.jsx("span",{children:i.expectedDurationHours})}),e.jsx("td",{className:"px-2 py-1.5 text-caption text-primary",children:Me&&i.type!=="task"?e.jsx("input",{type:"number",min:0,step:1,defaultValue:i.expectedBudgetUsd,onClick:V=>V.stopPropagation(),onBlur:V=>{const b=Number(V.currentTarget.value);Number.isFinite(b)&&y(i,{expected_budget_usd:b})},className:"w-[92px] rounded border border-strong bg-white/[0.06] px-2 py-1 text-micro text-white/82"}):e.jsxs("span",{children:["$",i.expectedBudgetUsd.toLocaleString(),Me&&i.type==="task"?" (from task spec)":""]})}),e.jsx("td",{className:"rounded-r-lg px-2 py-1.5 text-caption text-primary",children:Me?e.jsx("div",{onClick:V=>V.stopPropagation(),children:e.jsx(pa,{dependencies:i.dependencyIds,allNodes:te,onSave:V=>void y(i,{depends_on:V})})}):e.jsx("div",{className:"max-w-[250px] truncate",children:Le(i)>0?`${Le(i)} · ${Ue}`:"—"})})]},i.id)})})]})})]})}),le.length===0&&e.jsxs("div",{className:"flex flex-col items-center py-10",children:[e.jsxs("svg",{width:"32",height:"32",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",className:"text-faint",children:[e.jsx("path",{d:"M9 5H7a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2h-2"}),e.jsx("rect",{x:"9",y:"3",width:"6",height:"4",rx:"1"}),e.jsx("path",{d:"M9 14h6M9 18h4"})]}),e.jsx("div",{className:"mt-3 text-body font-medium text-secondary",children:l||g.size>0||F!=="all"?"No items match the current filters":"No work items yet"}),e.jsx("div",{className:"mt-1 text-caption text-muted",children:l||g.size>0||F!=="all"?"Try adjusting your search or filter criteria.":"Workstreams, milestones, and tasks will appear here."})]})]})}function Fn(t){if(!t)return"No target date";const s=new Date(t);return Number.isNaN(s.getTime())?"No target date":`Due ${s.toLocaleDateString()}`}function Na({recentTodoIds:t,nodesById:s,selectedNodeId:n,onSelectNode:r}){const c=t.map(x=>s.get(x)).filter(x=>!!x).sort((x,h)=>{if(x.priorityNum!==h.priorityNum)return x.priorityNum-h.priorityNum;const y=x.dueDate?Date.parse(x.dueDate):Number.POSITIVE_INFINITY,m=h.dueDate?Date.parse(h.dueDate):Number.POSITIVE_INFINITY;return y-m}).slice(0,14);if(c.length===0)return null;const o=c[0],d=c.slice(1,7);return e.jsxs("section",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:"Queue overview"}),e.jsxs("span",{className:"rounded-full border border-white/15 bg-black/20 px-2 py-0.5 text-micro text-secondary",children:[c.length," in queue"]})]}),e.jsx("button",{type:"button",onClick:()=>r(o.id),className:`surface-hero group w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${n===o.id?"border-[#BFFF00]/35 bg-[#BFFF00]/14":"border-white/15 bg-black/25 hover:border-white/30 hover:bg-white/[0.08]"}`,children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"inline-flex items-center gap-1.5 text-micro uppercase tracking-[0.1em] text-secondary",children:[e.jsx(ys,{type:o.type}),e.jsx("span",{children:"Priority task"})]}),e.jsx("p",{className:"mt-1 line-clamp-2 text-body font-semibold leading-snug text-white",children:o.title}),e.jsx("p",{className:"mt-1 text-caption text-secondary",children:Fn(o.dueDate)})]}),e.jsxs("span",{className:"inline-flex flex-shrink-0 rounded-full border px-2 py-0.5 text-micro font-semibold",style:{borderColor:`${ee.amber}44`,backgroundColor:`${ee.amber}22`,color:ee.amber},children:["P",o.priorityNum]})]})}),d.length>0&&e.jsx("div",{className:"space-y-1.5",children:d.map(x=>e.jsxs("button",{type:"button",onClick:()=>r(x.id),className:`flex min-h-[62px] min-w-0 items-start justify-between gap-2 rounded-lg border px-2.5 py-2 text-left transition-colors ${n===x.id?"border-[#BFFF00]/30 bg-[#BFFF00]/12":"border-strong bg-black/20 hover:bg-white/[0.08]"}`,children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"inline-flex items-center gap-1.5 text-micro uppercase tracking-[0.08em] text-secondary",children:[e.jsx(ys,{type:x.type}),e.jsx("span",{children:"Queued"})]}),e.jsx("p",{className:"mt-1 line-clamp-1 break-words text-caption leading-snug text-bright",title:x.title,children:x.title}),e.jsx("p",{className:"mt-1 text-micro text-secondary",children:Fn(x.dueDate)})]}),e.jsxs("span",{className:"inline-flex flex-shrink-0 rounded-full px-1.5 py-0.5 text-micro",style:{backgroundColor:`${ee.amber}22`,color:`${ee.amber}`},children:["P",x.priorityNum]})]},x.id))})]})}function Sa(t,s){try{const n=localStorage.getItem(`orgx.section.${t}`);if(n==="0")return!1;if(n==="1")return!0}catch{}return s}function Ca(t,s){try{localStorage.setItem(`orgx.section.${t}`,s?"1":"0")}catch{}}function xs({title:t,defaultOpen:s=!0,storageKey:n,sticky:r=!1,stickyOffsetClass:c="top-0",stickyTop:o,contentOverflowVisible:d=!1,badge:x,accentColor:h,children:y}){const[m,S]=a.useState(()=>n?Sa(n,s):s),[I,k]=a.useState(!1),l=a.useRef(null),[v,g]=a.useState(40),w=()=>{const F=!m;S(F),n&&Ca(n,F)};return a.useEffect(()=>{if(!r)return;const F=l.current;if(!F)return;const _=()=>{const $=Math.max(34,F.offsetHeight);g(L=>L===$?L:$)};if(_(),typeof ResizeObserver>"u")return;const f=new ResizeObserver(()=>_());return f.observe(F),()=>f.disconnect()},[r,o,t]),e.jsxs("div",{style:r?{"--mc-collapsible-header-offset":`${v}px`}:void 0,children:[e.jsxs("button",{ref:r?l:void 0,type:"button","data-mc-section-header":t,onClick:w,className:`flex w-full items-center gap-2 rounded-lg border px-2 py-2 text-left transition-colors ${r?`sticky ${c} 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:r&&o?{top:o}:void 0,children:[e.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",className:`text-muted transition-transform duration-200 ${m?"rotate-180":""}`,children:e.jsx("path",{d:"m6 9 6 6 6-6"})}),e.jsx("span",{className:"text-caption font-semibold tracking-[0.02em] text-white/68",children:t}),x!=null&&x!==""&&e.jsx("span",{className:"rounded-full px-1.5 py-0.5 text-[10px] font-medium tabular-nums",style:h?{color:h,backgroundColor:`${h}15`}:{color:"rgba(255,255,255,0.5)",backgroundColor:"rgba(255,255,255,0.06)"},children:x})]}),h&&e.jsx("div",{className:"h-px w-full",style:{backgroundColor:`${h}20`}}),e.jsx(mt,{initial:!1,children:m&&e.jsx(je.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{type:"spring",stiffness:400,damping:35},onAnimationStart:()=>k(!0),onAnimationComplete:()=>k(!1),className:d&&!I?"overflow-visible":"overflow-hidden",children:y})})]})}function Vs(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 n=Number(s.replace(/^p/,""));return Number.isFinite(n)?{priorityNum:Math.max(1,Math.min(100,Math.round(n))),priorityLabel:null}:{priorityNum:60,priorityLabel:null}}function Fa(t){const s=t.toLowerCase();return["todo","not_started","planned","pending","backlog"].includes(s)}function Ia(t){const s=t.toLowerCase();return["in_progress","active","running","queued"].includes(s)}function Aa(t,s){const n={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},c=(s.workstreams.length>0?s.workstreams:(t.workstreams??[]).map(m=>({id:m.id,name:m.name,summary:null,status:m.status,progress:null,initiativeId:t.id,createdAt:null}))).map(m=>({id:m.id,type:"workstream",title:m.name,status:m.status,parentId:t.id,initiativeId:t.id,workstreamId:m.id,milestoneId:null,priorityNum:50,priorityLabel:"medium",dependencyIds:[],dueDate:null,etaEndAt:null,expectedDurationHours:16,expectedBudgetUsd:300,assignedAgents:[],updatedAt:m.createdAt})),o=new Set(c.map(m=>m.id)),d=s.milestones.map(m=>({id:m.id,type:"milestone",title:m.title,status:m.status,parentId:m.workstreamId&&o.has(m.workstreamId)?m.workstreamId:t.id,initiativeId:t.id,workstreamId:m.workstreamId&&o.has(m.workstreamId)?m.workstreamId:null,milestoneId:m.id,priorityNum:50,priorityLabel:"medium",dependencyIds:[],dueDate:m.dueDate,etaEndAt:m.dueDate,expectedDurationHours:6,expectedBudgetUsd:120,assignedAgents:[],updatedAt:m.createdAt})),x=new Set(d.map(m=>m.id)),h=s.tasks.map(m=>{const S=Vs(m.priority),I=m.milestoneId&&x.has(m.milestoneId),k=m.workstreamId&&o.has(m.workstreamId);return{id:m.id,type:"task",title:m.title,status:m.status,parentId:I?m.milestoneId:k?m.workstreamId:t.id,initiativeId:t.id,workstreamId:k?m.workstreamId:null,milestoneId:I?m.milestoneId:null,priorityNum:S.priorityNum,priorityLabel:S.priorityLabel,dependencyIds:[],dueDate:m.dueDate,etaEndAt:m.dueDate,expectedDurationHours:2,expectedBudgetUsd:40,assignedAgents:[],updatedAt:m.createdAt}}),y=h.filter(m=>["todo","not_started","planned","pending","backlog"].includes(m.status.toLowerCase())).sort((m,S)=>{const I=m.priorityNum-S.priorityNum;if(I!==0)return I;const k=m.etaEndAt?Date.parse(m.etaEndAt):1/0,l=S.etaEndAt?Date.parse(S.etaEndAt):1/0;if(k!==l)return k-l;const v=m.updatedAt?Date.parse(m.updatedAt):0;return(S.updatedAt?Date.parse(S.updatedAt):0)-v}).map(m=>m.id);return{nodes:[n,...c,...d,...h],edges:[],recentTodos:y}}function Ea(t,s){if(!t)return new Set;const n=new Map(s.map(d=>[d.id,d])),r=new Map;for(const d of s)for(const x of d.dependencyIds){const h=r.get(x)??[];h.push(d.id),r.set(x,h)}const c=new Set,o=[t];for(;o.length>0;){const d=o.shift();if(c.has(d))continue;c.add(d);const x=n.get(d);if(x){for(const h of x.dependencyIds)c.has(h)||o.push(h);for(const h of r.get(d)??[])c.has(h)||o.push(h)}}return c}function Da(t,s){return{id:t.id,name:t.title,summary:null,status:t.status,progress:null,initiativeId:s.id,createdAt:t.updatedAt}}function Ma(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}}function Ta(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}}const ts={hidden:{opacity:0},show:{opacity:1}};function hs({label:t,value:s}){return e.jsxs("div",{className:"rounded-lg border border-white/[0.08] bg-white/[0.03] px-2.5 py-2",children:[e.jsx("div",{className:"text-micro text-secondary",children:t}),e.jsx("div",{className:"mt-0.5 text-body font-semibold text-bright",children:s})]})}function $a({initiative:t,selected:s=!1,onSelectionChange:n,isSquished:r=!1,isQueued:c=!1,runtimeActivity:o=null}){var V;const{expandedInitiatives:d,toggleExpanded:x,openModal:h,agentEntityMap:y,authToken:m,embedMode:S,mutations:I}=Tt(),[k,l]=a.useState(!1),[v,g]=a.useState(null),[w,F]=a.useState(null),[_,f]=a.useState(!1),[$,L]=a.useState(!1),[B,G]=a.useState(null),[se,K]=a.useState(!1),J=a.useRef(null),[E,H]=a.useState(52),[z,D]=a.useState(0),W=d.has(t.id),{graph:xe,isLoading:Se,degraded:he,error:ne,refetch:ye}=ca({initiativeId:t.id,authToken:m,embedMode:S,enabled:W}),{details:U,isLoading:M,error:me}=js({initiativeId:t.id,authToken:m,embedMode:S,enabled:W}),te=ls({authToken:m,embedMode:S}),fe=a.useMemo(()=>Aa(t,U),[t,U]),Z=!!(xe&&xe.nodes.length>0),N=fe.nodes.length>0,j=!Z&&N,u=j?fe.nodes:Z?(xe==null?void 0:xe.nodes)??[]:fe.nodes,P=j?fe.edges:Z?(xe==null?void 0:xe.edges)??[]:fe.edges,ie=j?fe.recentTodos:Z?(xe==null?void 0:xe.recentTodos)??[]:fe.recentTodos,ke=he.some(b=>/401|unauthorized/i.test(b))||!!(ne&&/401|unauthorized/i.test(ne))||!!(me&&/401|unauthorized/i.test(me)),be=ne&&/unknown api endpoint/i.test(ne)?"Graph API unavailable. Showing session-derived data.":ne,Pe=me,Ce=[...he,...be?[be]:[],...Pe?[`Entity data partially unavailable: ${Pe}`]:[],...ke?["OrgX auth is missing or expired in this local plugin instance. Reconnect in onboarding to load full workstreams/milestones/tasks."]:[]],le=Ce.filter(b=>/cyclic dependency edge/i.test(b)),Fe=le.reduce((b,O)=>{const $e=/detected\s+(\d+)\s+cyclic dependency edge/i.exec(O);return b+($e&&Number($e[1])||0)},0),ze=le.length>0,Re=async()=>{if(!se){K(!0);try{const b=await fetch("/orgx/api/mission-control/graph/cycles/auto-fix",{method:"POST",headers:Ft({authToken:m,embedMode:S,contentTypeJson:!0}),body:JSON.stringify({initiativeId:t.id})}),O=await b.json().catch(()=>null);if(!b.ok)throw new Error((O==null?void 0:O.error)??(O==null?void 0:O.message)??`Failed to auto-fix dependency cycles (${b.status})`);const $e=typeof(O==null?void 0:O.cycleEdgesDetected)=="number"?O.cycleEdgesDetected:Fe,ge=typeof(O==null?void 0:O.nodesUpdated)=="number"?O.nodesUpdated:0,Ze=typeof(O==null?void 0:O.nodesFailed)=="number"?O.nodesFailed:0;G({tone:Ze>0?"error":"success",message:Ze>0?`Auto-fix removed ${$e} cyclic edge${$e===1?"":"s"} and updated ${ge} nodes (${Ze} failed).`:`Auto-fix removed ${$e} cyclic edge${$e===1?"":"s"} and updated ${ge} nodes.`}),ye()}catch(b){G({tone:"error",message:b instanceof Error?b.message:"Failed to auto-fix dependency cycles."})}finally{K(!1)}}},qe=a.useMemo(()=>new Map(u.map(b=>[b.id,b])),[u]),gt=a.useMemo(()=>Ea(v,u),[v,u]),$t=a.useMemo(()=>ie.some(b=>qe.has(b)),[qe,ie]);a.useEffect(()=>{const b=J.current;if(!b||!W)return;const O=()=>{const ge=Math.max(48,b.offsetHeight);H(Ze=>Ze===ge?Ze:ge)};if(O(),typeof ResizeObserver>"u")return;const $e=new ResizeObserver(()=>O());return $e.observe(b),()=>$e.disconnect()},[W,t.status,t.targetDate,t.name]),a.useEffect(()=>{const b=J.current;if(!b||!W){D(0);return}const O=b.closest('[data-mc-scroll-host="true"]')??b.closest(".h-full.overflow-y-auto.overflow-x-hidden"),$e=O??window;let ge=0;const Ze=()=>{ge=0;const oe=Number.parseFloat(getComputedStyle(b).top||"0"),Q=b.getBoundingClientRect(),_e=(O==null?void 0:O.getBoundingClientRect().top)??0,Ct=1-(Q.top-_e-oe)/56,ft=Math.pow(Math.max(0,Math.min(1,Ct)),1.2);D(Zt=>Math.abs(Zt-ft)<.015?Zt:ft)},Ke=()=>{ge||(ge=window.requestAnimationFrame(Ze))};return Ze(),$e.addEventListener("scroll",Ke,{passive:!0}),window.addEventListener("resize",Ke),()=>{ge&&window.cancelAnimationFrame(ge),$e.removeEventListener("scroll",Ke),window.removeEventListener("resize",Ke)}},[W,t.id]),a.useEffect(()=>{var b;W&&!v&&u.length>0&&g(((b=u[0])==null?void 0:b.id)??null)},[W,u,v]),a.useEffect(()=>{if(!B)return;const b=window.setTimeout(()=>G(null),B.tone==="success"?2800:4200);return()=>window.clearTimeout(b)},[B]);const Ie=((xe==null?void 0:xe.initiative.assignedAgents)??[]).map(b=>({id:b.id,name:b.name,confidence:"high"})),at=y.get(t.id)??[],Ge=Ie.length>0?Ie:at,Le=u.filter(b=>b.type==="task"),ot=Le.filter(b=>Ia(b.status)).length,Nt=Le.filter(b=>Fa(b.status)).length,Ye=Le.filter(b=>rt(b.status)).length,Qe=(o==null?void 0:o.activeCount)??0,We=(o==null?void 0:o.totalCount)??0,zt=ot>0||Qe>0,Je=t.status==="active"&&zt?"in_progress":t.status;Je==="in_progress"||nt(Je);const Xe=is(t.rawStatus??t.status,{hasActiveStreams:ot>0||Qe>0,hasDispatchingStreams:!1,totalTasks:Le.length,completedTasks:Ye,blockedTasks:Le.filter(b=>b.status.toLowerCase()==="blocked").length}),Xt=kt[Xe]??kt.Queued,It=bs[Xe]??bs.Queued,xt=Le.length>0?Le:u.some(b=>b.type==="milestone")?u.filter(b=>b.type==="milestone"):u.filter(b=>b.type==="workstream"),_t=Math.round(xt.reduce((b,O)=>b+(O.expectedDurationHours||0),0)*10)/10,bt=Math.round(xt.reduce((b,O)=>b+(O.expectedBudgetUsd||0),0)*100)/100,St=u.filter(b=>b.type==="milestone"),Ne=u.filter(b=>b.type==="workstream"),lt=te.isPinning||te.isMoving,st=(t.rawStatus??t.status??"").trim().toLowerCase().replace(/[\s-]+/g,"_"),it=new Set(["paused","draft","planned","todo","backlog","queued"]).has(st),yt=st==="paused"?"Resume":"Start",i=!r,A=i||it,C=r,q=a.useMemo(()=>Ne.filter(b=>b.initiativeId===t.id).sort((b,O)=>b.priorityNum-O.priorityNum||b.title.localeCompare(O.title)),[t.id,Ne]),re=W&&(Z||U.workstreams.length>0||U.milestones.length>0||U.tasks.length>0),pe=Le.length>0?Ot(Ye,Le.length):St.length>0?Ot(St.filter(b=>rt(b.status)).length,St.length):re&&Ne.length>0?Ot(Ne.filter(b=>rt(b.status)).length,Ne.length):null,we=Ns(pe===null?t.health:pe),Te=we===0?2:we,Ue=Math.pow(z,.82),de=Math.max(0,Number((16*(1-Ue)).toFixed(2))),De=`0 10px 26px rgba(0,0,0,${(.18+Ue*.24).toFixed(3)}), 0 1px 0 rgba(191,255,0,${(Ue*.09).toFixed(3)})`,Me=async b=>{if(q.length===0){G({tone:"error",message:"No workstreams available to queue for this initiative."});return}const O=b==="top"?[...q].reverse():q;let $e=0,ge=0,Ze=null;for(const Ke of O)try{await te.pin({initiativeId:t.id,workstreamId:Ke.id}),await te.move({initiativeId:t.id,workstreamId:Ke.id,placement:b}),$e+=1}catch(oe){ge+=1,Ze||(Ze=oe instanceof Error?oe.message:"Failed to queue this initiative.")}if(ge>0){G({tone:$e>0?"success":"error",message:$e>0?`Queued ${$e}/${q.length} workstreams (${ge} failed).`:Ze??"Failed to queue initiative workstreams."});return}G({tone:"success",message:`Queued ${$e} workstream${$e===1?"":"s"} to ${b==="top"?"top":"end"}.`})},Ae=b=>{if(b.type==="initiative"){h({type:"initiative",entity:t});return}if(b.type==="workstream"){h({type:"workstream",entity:Da(b,t),initiative:t});return}if(b.type==="milestone"){h({type:"milestone",entity:Ma(b,t),initiative:t});return}h({type:"task",entity:Ta(b,t),initiative:t})},ct=async(b,O)=>{await I.updateEntity.mutateAsync({type:b.type,id:b.id,...O})},ht=b=>O=>{O.stopPropagation(),I.entityAction.mutate({type:"initiative",id:t.id,action:b})},Ve=b=>{b.stopPropagation(),I.updateEntity.mutate({type:"initiative",id:t.id,status:"active"})};return e.jsxs("div",{id:`initiative-${t.id}`,className:`surface-tier-1 overflow-visible rounded-2xl transition-[background-color,border-color,box-shadow] duration-200 ${W?"bg-[--orgx-surface-elevated]":"bg-[--orgx-surface]"} ${s?"ring-1 ring-[#BFFF00]/30 shadow-[0_0_0_1px_rgba(191,255,0,0.12)]":""}`,style:{"--mc-initiative-header-offset":`${E}px`},children:[e.jsxs("div",{ref:J,role:"button",tabIndex:0,"aria-expanded":W,onClick:()=>x(t.id),onKeyDown:b=>{(b.key==="Enter"||b.key===" ")&&(b.preventDefault(),x(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 ${W?"sticky z-30 border-b border-subtle bg-[#0C0E14]/95 shadow-[0_8px_20px_rgba(0,0,0,0.3)] backdrop-blur-xl":""}`,style:W?{top:"var(--mc-toolbar-offset, 88px)",borderTopLeftRadius:`${de}px`,borderTopRightRadius:`${de}px`,boxShadow:De}:void 0,children:[e.jsx(je.div,{animate:{rotate:W?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"})})}),n&&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:b=>{const O=b.nativeEvent.shiftKey??!1;n(t.id,b.currentTarget.checked,O)},onClick:b=>b.stopPropagation(),"aria-label":`Select initiative ${t.name}`,className:"h-3.5 w-3.5 rounded border-white/20 bg-black/40 text-[#BFFF00] focus:ring-[#BFFF00]/35"})}),e.jsx("span",{className:`w-2 h-2 rounded-full flex-shrink-0 ${zt?"status-breathe":""}`,style:{backgroundColor:vn(Je)}}),Vs(t.priority).priorityLabel!=null&&(()=>{const b=Vs(t.priority).priorityLabel,O=b==="urgent"?"P0":b==="high"?"P1":b==="medium"?"P2":"P3",$e=b==="urgent"?"text-red-300 border-red-400/20 bg-red-400/[0.08]":b==="high"?"text-amber-300 border-amber-400/20 bg-amber-400/[0.08]":b==="medium"?"text-secondary border-white/[0.08] bg-white/[0.03]":"text-muted border-white/[0.06] bg-transparent";return e.jsx("span",{className:`hidden sm:block flex-shrink-0 rounded-md border px-1.5 py-0.5 text-micro font-semibold uppercase tracking-wider leading-none ${$e}`,children:O})})(),e.jsx("div",{className:"min-w-0 flex-[1_1_auto] overflow-hidden pr-1.5 sm:pr-2",children:e.jsx("button",{type:"button",onClick:b=>{b.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 items-center gap-1.5 justify-start ${r?"w-[120px] min-w-[120px]":"w-[160px] min-w-[160px] sm:w-[180px] sm:min-w-[180px]"}`,children:[e.jsx("span",{className:`truncate text-center text-micro rounded-full border py-0.5 uppercase tracking-[0.08em] leading-none whitespace-nowrap ${r?"px-1.5":"px-2"} ${Xt}`,children:Xe}),Le.length>0&&e.jsxs("span",{className:"font-mono tabular-nums text-[11px] text-muted whitespace-nowrap",children:[Ye,"/",Le.length]})]}),e.jsx("div",{className:`ml-1.5 flex-shrink-0 ${C?"flex":"lg:hidden"}`,title:`${we}% complete`,children:e.jsxs("svg",{viewBox:"0 0 36 36",className:"h-9 w-9","aria-label":`${we}% complete`,children:[e.jsx("circle",{cx:"18",cy:"18",r:"15",fill:"none",stroke:"rgba(255,255,255,0.06)",strokeWidth:"3"}),e.jsx(je.circle,{cx:"18",cy:"18",r:"15",fill:"none",stroke:vn(Je),strokeWidth:"3",strokeLinecap:"round",initial:!1,animate:{strokeDasharray:`${Te/100*94.25} 94.25`,opacity:we===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:[we,"%"]})]})}),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] ${C?"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(je.div,{className:"h-full rounded-full transition-all",initial:!1,animate:{width:`${Te}%`,opacity:we===0?.45:1},transition:{type:"spring",stiffness:260,damping:34,mass:.75},style:{backgroundColor:It}})})}),e.jsxs("span",{className:"w-[42px] text-right text-micro text-muted xl:w-[48px] xl:text-caption font-mono tabular-nums",children:[we,"%"]})]}),A&&e.jsxs("div",{className:`ml-1 hidden flex-shrink-0 items-center justify-end gap-1.5 lg:flex ${r?"w-[40px] min-w-[40px]":"w-[180px] min-w-[180px]"}`,children:[i&&e.jsx(Ss,{label:c?"Queued":"Queue",size:"sm",busy:lt,disabled:q.length===0,isQueued:c,stopPropagation:!0,title:`Queue initiative: ${t.name}`,onSelectPlacement:Me}),it&&e.jsxs("button",{type:"button",onClick:Ve,disabled:I.updateEntity.isPending,title:`${yt} initiative`,className:`control-pill inline-flex items-center justify-center gap-1.5 text-micro font-semibold text-[#D8FFA1] disabled:opacity-45 ${r?"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"})}),!r&&e.jsx("span",{children:yt})]})]}),e.jsx("div",{className:`ml-2 w-[104px] min-w-[104px] flex-shrink-0 items-center justify-end border-l border-subtle pl-2 lg:w-[116px] lg:min-w-[116px] lg:pl-2.5 xl:w-[132px] xl:min-w-[132px] ${r?"hidden":"hidden md:flex"}`,children:Qe>0?e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border border-[#BFFF00]/30 bg-[#BFFF00]/14 px-2 py-0.5 text-micro font-semibold text-[#D8FFA1]",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-[#BFFF00] status-breathe"}),Qe," live"]}),Ge.length>0&&e.jsx(as,{agents:Ge,max:2})]}):Ge.length>0?e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(as,{agents:Ge,max:3}),We>0&&e.jsx("span",{className:"text-micro text-muted",children:"idle"})]}):We>0?e.jsxs("span",{className:"w-full text-right text-micro text-muted",children:[We," idle"]}):e.jsx("span",{className:"w-full text-right text-micro text-white/28",children:"—"})}),e.jsxs("div",{className:"hidden w-[46px] flex-shrink-0 translate-x-1 items-center justify-end gap-1 opacity-0 transition-all duration-200 group-hover:translate-x-0 group-hover:opacity-100 group-focus-within:translate-x-0 group-focus-within:opacity-100 2xl:flex",children:[t.status==="active"&&e.jsx("button",{type:"button",onClick:ht("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:ht("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:b=>{b.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"})]})})]})]}),B&&e.jsx("div",{role:"status","aria-live":"polite",className:`mx-3 mb-2 rounded-lg border px-2.5 py-1.5 text-micro ${B.tone==="success"?"border-[#BFFF00]/24 bg-[#BFFF00]/[0.1] text-[#D8FFA1]":"border-red-400/24 bg-red-500/[0.1] text-red-100"}`,children:B.message}),e.jsx(mt,{children:W&&e.jsx(je.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:()=>L(!0),onAnimationComplete:()=>L(!1),className:$?"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"}),Se||!Z&&M?e.jsx("div",{className:"space-y-2",children:Array.from({length:3}).map((b,O)=>e.jsx(jt,{className:"h-24 w-full rounded-xl"},`mc-loading-${O}`))}):e.jsxs(je.div,{initial:"hidden",animate:"show",variants:{hidden:{},show:{transition:{staggerChildren:.08}}},className:"space-y-3.5",children:[Ce.length>0&&e.jsxs(je.div,{variants:ts,className:"overflow-hidden rounded-lg border border-amber-300/15 bg-amber-500/[0.06]",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 px-3 py-2",children:[e.jsxs("button",{type:"button",onClick:()=>f(b=>!b),className:"flex min-w-0 flex-1 items-center justify-between text-left transition-colors hover:text-white",children:[e.jsx("span",{className:"truncate text-caption text-amber-100/85",children:ze?`Dependency loop detected (${Fe||le.length} edges)`:`${Ce.length} data source${Ce.length>1?"s":""} unavailable`}),e.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",className:`ml-2 text-amber-100/55 transition-transform ${_?"rotate-180":""}`,children:e.jsx("path",{d:"m6 9 6 6 6-6"})})]}),ze?e.jsx("button",{type:"button",onClick:Re,disabled:se,className:"control-pill h-7 flex-shrink-0 px-2.5 text-micro font-semibold text-[#D8FFA1] disabled:opacity-45",children:se?"Fixing…":"Auto-fix"}):null]}),e.jsx(mt,{children:_&&e.jsx(je.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.15},className:"overflow-hidden",children:e.jsx("div",{className:"space-y-1 px-3 pb-2",children:Ce.map((b,O)=>e.jsx("div",{className:"text-micro text-amber-100/72",children:pt(b)},O))})})})]}),(Nt>0||ot>0||_t>0||bt>0)&&e.jsx(je.div,{variants:ts,children:e.jsx(xs,{title:"Stats",storageKey:`stats.${t.id}`,defaultOpen:!0,children:e.jsxs("div",{className:"grid gap-2 py-0.5 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsx(hs,{label:"Queue",value:`${Nt} todo · ${ot} active`}),e.jsx(hs,{label:"Completed",value:`${Ye}/${Le.length||0}`}),e.jsx(hs,{label:"Duration",value:`${_t}h`}),e.jsx(hs,{label:"Budget",value:`$${bt.toLocaleString()}`})]})})}),w&&e.jsxs("div",{className:"subsection-shell flex items-center justify-between rounded-lg px-3 py-2 text-caption text-[#D8FFA1]",children:[e.jsxs("span",{children:["Focused on workstream ",((V=qe.get(w))==null?void 0:V.title)??w]}),e.jsx("button",{type:"button",onClick:()=>F(null),className:"text-micro underline underline-offset-2",children:"Clear focus"})]}),e.jsx(je.div,{variants:ts,children:e.jsx(xs,{title:"Dependency Map",storageKey:`depmap.${t.id}`,defaultOpen:!0,children:e.jsx(ma,{nodes:u,edges:P,selectedNodeId:v,focusedWorkstreamId:w,onSelectNode:b=>{g(b);const O=qe.get(b);(O==null?void 0:O.type)==="workstream"&&F(O.id)}})})}),$t&&e.jsx(je.div,{variants:ts,children:e.jsx(xs,{title:"Next Up",storageKey:`nextup.${t.id}`,defaultOpen:!0,children:e.jsx(Na,{recentTodoIds:ie,nodesById:qe,selectedNodeId:v,onSelectNode:b=>{g(b);const O=qe.get(b);(O==null?void 0:O.type)==="workstream"&&F(O.id)}})})}),e.jsx(je.div,{variants:ts,children:e.jsx(xs,{title:"Hierarchy",storageKey:`hierarchy.${t.id}`,defaultOpen:!0,contentOverflowVisible:!0,children:e.jsx(ka,{nodes:u,edges:P,selectedNodeId:v,highlightedNodeIds:gt,editMode:k,onSelectNode:g,onFocusWorkstream:F,onOpenNode:Ae,onUpdateNode:ct,onToggleEditMode:()=>l(b=>!b),mutations:I})})})]}),e.jsxs("button",{type:"button",onClick:()=>x(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 qs=20,_a={hidden:{opacity:0},show:{opacity:1,transition:{staggerChildren:.045,delayChildren:.02}}},La={hidden:{opacity:0,y:10,scale:.995},show:{opacity:1,y:0,scale:1,transition:{type:"spring",stiffness:320,damping:28,mass:.7}}},Ba={type:"spring",stiffness:280,damping:32,mass:.75};function In({initiatives:t,selectedInitiativeIds:s,onToggleInitiativeSelection:n,isSquished:r=!1,runtimeActivityByInitiativeId:c,queuedInitiativeIds:o,onPin:d}){const[x,h]=a.useState(null),y=x??t;a.useCallback(async w=>{if(!d)return;const F=x??t,_=F.findIndex(L=>L.id===w);if(_<=0)return;const f=[...F],[$]=f.splice(_,1);f.unshift($),h(f);try{await d(w)===!1&&h(null)}catch{h(null)}},[d,t,x]);const m=a.useRef(t);a.useEffect(()=>{m.current!==t&&(m.current=t,h(null))},[t]);const S=a.useRef(null),[I,k]=a.useState(qs);a.useEffect(()=>{k(qs)},[y.length]),a.useEffect(()=>{const w=S.current;if(!w||I>=y.length)return;const F=new IntersectionObserver(([_])=>{_.isIntersecting&&k(f=>Math.min(f+qs,y.length))},{rootMargin:"200px"});return F.observe(w),()=>F.disconnect()},[I,y.length]);const l=y.slice(0,I),v=I<y.length,g=y.length-I;return e.jsx(er,{children:e.jsxs(je.div,{variants:_a,initial:"hidden",animate:"show",className:"space-y-2",children:[e.jsx(mt,{mode:"popLayout",children:l.map(w=>e.jsx(je.div,{variants:La,layout:!0,transition:Ba,exit:{opacity:0,scale:.98,transition:{duration:.15}},children:e.jsx($a,{initiative:w,selected:(s==null?void 0:s.has(w.id))??!1,onSelectionChange:n,isSquished:r,runtimeActivity:(c==null?void 0:c.get(w.id))??null,isQueued:(o==null?void 0:o.has(w.id))??!1})},w.id))}),v&&e.jsx("div",{ref:S,className:"space-y-2",children:[...Array(Math.min(3,g))].map((w,F)=>e.jsx("div",{className:"h-[72px] rounded-lg bg-white/[0.03] animate-pulse"},`skel-${F}`))})]})})}function Os({mode:t="empty",hasActiveFilters:s=!1,detail:n=null,onClearFilters:r,onCreateInitiative:c,onPlayNextUp:o,onStartAutopilot:d,onRefresh:x,onOpenSettings:h}){const[y,m]=a.useState(null),[S,I]=a.useState(null),k=a.useCallback(async(g,w)=>{if(w){I(null),m(g);try{await w()}catch(F){const _=F instanceof Error?F.message:"";I(_?pt(_):"Action failed")}finally{m(F=>F===g?null:F)}}},[]),l=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(Tr,{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:`${ee.iris}1a`,border:`1px solid ${ee.iris}33`},children:e.jsxs("svg",{width:"22",height:"22",viewBox:"0 0 24 24",fill:"none",stroke:ee.iris,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("circle",{cx:"12",cy:"12",r:"10"}),e.jsx("path",{d:"M12 6v6l4 2"})]})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h3",{className:"text-heading font-semibold text-white",children:l}),e.jsx("p",{className:"mt-1 text-body leading-relaxed text-secondary",children:v})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[t==="filtered"&&r&&e.jsx("button",{type:"button",onClick:r,className:"rounded-full border border-strong bg-white/[0.03] px-3 py-1.5 text-caption font-semibold text-primary transition hover:bg-white/[0.08]",children:"Clear filters"}),t==="degraded"&&h&&e.jsx("button",{type:"button",onClick:h,className:"rounded-full border border-white/[0.12] bg-white/[0.03] px-3 py-1.5 text-caption font-semibold text-primary transition hover:bg-white/[0.08]",children:"Open settings"}),c&&e.jsx("button",{type:"button",onClick:c,className:"rounded-full border border-[#BFFF00]/30 bg-[#BFFF00]/12 px-3 py-1.5 text-caption font-semibold text-[#D8FFA1] transition hover:bg-[#BFFF00]/18",children:"Create initiative"}),o&&e.jsx("button",{type:"button",onClick:()=>void k("play",o),disabled:y!==null,className:"rounded-full border border-white/[0.12] bg-white/[0.03] px-3 py-1.5 text-caption font-semibold text-primary transition hover:bg-white/[0.08] disabled:opacity-45",children:y==="play"?"Dispatching...":"Play Next Up"}),d&&e.jsx("button",{type:"button",onClick:()=>void k("autopilot",d),disabled:y!==null,className:"rounded-full border border-[#0AD4C4]/30 bg-[#0AD4C4]/10 px-3 py-1.5 text-caption font-semibold text-[#98FFF5] transition hover:bg-[#0AD4C4]/16 disabled:opacity-45",children:y==="autopilot"?"Starting...":"Start Autopilot"}),x&&e.jsx("button",{type:"button",onClick:x,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"&&n&&e.jsx("p",{className:"text-caption text-secondary",children:pt(n)}),S&&e.jsx("p",{className:"text-caption text-amber-200/80",children:S})]})})})}function ae({label:t,icon:s,color:n="#BFFF00",variant:r="secondary",size:c="md",className:o="",type:d="button",...x}){const h=c==="sm"?"px-2.5 py-1 text-micro":"px-3 py-1.5 text-caption",y=r==="primary"?{backgroundColor:n,color:"#05060A",borderColor:`${n}CC`}:r==="destructive"?{backgroundColor:`${n}18`,color:n,borderColor:`${n}45`}:r==="ghost"?{backgroundColor:"rgba(255,255,255,0.03)",color:"rgba(255,255,255,0.75)",borderColor:"rgba(255,255,255,0.12)"}:{backgroundColor:`${n}20`,color:n,borderColor:`${n}30`};return e.jsxs("button",{type:d,className:`inline-flex items-center gap-1.5 rounded-lg border transition-colors disabled:cursor-not-allowed disabled:opacity-50 ${h} ${o}`,style:y,...x,children:[s,t&&e.jsx("span",{children:t})]})}const An={draft:ee.textMuted,in_review:ee.amber,approved:ee.lime,changes_requested:ee.red,superseded:ee.textMuted,archived:ee.textMuted};function Pa(t,s){const n=t.toLowerCase(),r=s.toLowerCase();return n.includes("code")||n.includes("script")||n.includes("implementation")||/\.(ts|tsx|js|jsx|py|rb|go|rs|sh)$/i.test(r)?"code":n.includes("schema")||n.includes("config")||n.includes("spec")||/\.(json|yaml|yml|toml)$/i.test(r)?"schema":n.includes("test")||n.includes("spec")||r.includes(".test.")||r.includes(".spec.")||r.includes("_test.")?"test":n.includes("document")||n.includes("report")||n.includes("brief")||n.includes("handbook")||n.includes("copy")||/\.(md|mdx|txt|pdf|doc)$/i.test(r)?"document":"generic"}function Ra({category:t,size:s=16}){const n={width:s,height:s,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};switch(t){case"code":return e.jsxs("svg",{...n,className:"flex-shrink-0 text-[#BFFF00]",children:[e.jsx("polyline",{points:"16 18 22 12 16 6"}),e.jsx("polyline",{points:"8 6 2 12 8 18"})]});case"schema":return e.jsxs("svg",{...n,className:"flex-shrink-0 text-[#F5B700]",children:[e.jsx("path",{d:"M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"}),e.jsx("polyline",{points:"3.27 6.96 12 12.01 20.73 6.96"}),e.jsx("line",{x1:"12",y1:"22.08",x2:"12",y2:"12"})]});case"test":return e.jsxs("svg",{...n,className:"flex-shrink-0 text-[#0AD4C4]",children:[e.jsx("path",{d:"M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"}),e.jsx("polyline",{points:"14 2 14 8 20 8"}),e.jsx("path",{d:"m9 15 2 2 4-4"})]});case"document":return e.jsxs("svg",{...n,className:"flex-shrink-0 text-[#7C7CFF]",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"}),e.jsx("path",{d:"M10 9H8"}),e.jsx("path",{d:"M16 13H8"}),e.jsx("path",{d:"M16 17H8"})]});default:return e.jsxs("svg",{...n,className:"flex-shrink-0 text-white/50",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"})]})}}function qa(t,s){const r=s.toLowerCase().split(".").pop(),c={ts:"TypeScript",tsx:"TypeScript",js:"JavaScript",jsx:"JavaScript",json:"JSON",yaml:"YAML",yml:"YAML",md:"Markdown",mdx:"Markdown",py:"Python",go:"Go",rs:"Rust",sh:"Shell",txt:"Plain Text"};if(r&&c[r])return c[r];const o=t.toLowerCase();return o.includes("json")||o.includes("schema")?"JSON":o.includes("yaml")?"YAML":o.includes("typescript")||o.includes("code")?"TypeScript":o.includes("markdown")?"Markdown":o.includes("document")||o.includes("brief")||o.includes("handbook")?"Document":t.replace(/[._-]/g," ").replace(/\b\w/g,d=>d.toUpperCase())}function Oa(t){if(!t)return null;const s=new Blob([t]).size;return s<1024?`${s} B`:s<1024*1024?`${(s/1024).toFixed(1)} KB`:`${(s/(1024*1024)).toFixed(1)} MB`}function en(t){const s=[t.content,t.body,t.code,t.source,t.text,t.preview_markdown];for(const n of s)if(typeof n=="string"&&n.trim().length>0)return n;return null}function za(t){const s=en(t);return s?s.split(`
|
|
2
|
+
`).length:null}function Ua({metadata:t}){const s=en(t);if(!s)return null;const r=s.split(`
|
|
3
|
+
`).slice(0,3).join(`
|
|
4
|
+
`);return e.jsx("div",{className:"mt-1.5 overflow-hidden rounded-md border border-white/[0.05] bg-white/[0.02]",children:e.jsx("pre",{className:"px-2 py-1.5 font-mono text-[10px] leading-[14px] text-white/40 overflow-hidden whitespace-pre text-ellipsis max-h-[42px]",children:r})})}function Qa(t,s){const n=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",content:`# Q4 Dashboard Polish
|
|
5
|
+
|
|
6
|
+
## Open Items
|
|
7
|
+
- Fix responsive layout on mobile
|
|
8
|
+
- Add loading skeletons
|
|
9
|
+
- Performance audit`},created_at:n,updated_at:n},{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",content:`Variant A: "Ship faster with OrgX"
|
|
10
|
+
Variant B: "Your AI-powered org brain"
|
|
11
|
+
Variant C: "From chaos to clarity"`},created_at:n,updated_at:n}]: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:n,updated_at:n}]:[]}async function En(t,s,n){if(vs())return Qa(t,s);try{const r=Ft(n),c=new URLSearchParams({entity_type:t,entity_id:s,limit:"20"}),o=await fetch(`/orgx/api/work-artifacts/by-entity?${c.toString()}`,{headers:r});if(!o.ok)return[];const d=await o.json();return(d==null?void 0:d.artifacts)??[]}catch{return[]}}function Cs({entityType:t,entityId:s,title:n="Artifacts",authToken:r=null,embedMode:c=!1,finalOnly:o=!1,milestoneIds:d}){const{open:x}=$r(),[h,y]=a.useState(!o),m=!!(d!=null&&d.length),S=rs({queryKey:ws.artifactsByEntity({entityType:t,entityId:s,authToken:r,embedMode:c}),enabled:!m&&!!s,queryFn:()=>En(t,s,{authToken:r,embedMode:c})}),I=rs({queryKey:["artifacts-by-milestones",d,r,c],enabled:m,queryFn:async()=>{if(!(d!=null&&d.length))return[];const g=await Promise.all(d.map(F=>En("milestone",F,{authToken:r,embedMode:c}))),w=new Map;for(const F of g)for(const _ of F)w.has(_.id)||w.set(_.id,_);return[...w.values()].sort((F,_)=>Date.parse(_.updated_at)-Date.parse(F.updated_at))}}),k=m?I:S,l=k.data??[],v=h?l:l.filter(g=>g.status==="approved");return k.isLoading?e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-caption font-medium text-secondary",children:n}),e.jsx("div",{className:"shimmer-skeleton h-10 w-full rounded-lg"})]}):l.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h4",{className:"text-caption font-medium text-secondary",children:[n," (",v.length,")"]}),o&&e.jsx("button",{type:"button",onClick:()=>y(g=>!g),className:"text-micro text-faint transition-colors hover:text-secondary",children:h?"Final only":"Show all"})]}),e.jsxs("div",{className:"space-y-1.5",children:[v.slice(0,10).map((g,w)=>e.jsx(Wa,{artifact:g,index:w,onOpen:()=>x(g.id,{entityType:t,entityId:s})},g.id)),v.length>10&&e.jsxs("p",{className:"text-micro text-faint pl-2",children:["+",v.length-10," more"]})]})]})}function Wa({artifact:t,index:s,onOpen:n}){const r=a.useMemo(()=>Pa(t.artifact_type,t.name),[t.artifact_type,t.name]),c=a.useMemo(()=>qa(t.artifact_type,t.name),[t.artifact_type,t.name]),o=a.useMemo(()=>en(t.metadata),[t.metadata]),d=a.useMemo(()=>za(t.metadata),[t.metadata]),x=a.useMemo(()=>Oa(o),[o]),h=a.useMemo(()=>{const y=[c];return x?y.push(x):d!=null&&y.push(`${d} line${d!==1?"s":""}`),y.join(" · ")},[c,x,d]);return e.jsxs(je.button,{type:"button",onClick:n,className:"flex w-full items-start gap-3 rounded-xl border border-white/[0.06] bg-white/[0.02] px-3 py-2.5 text-left transition-colors hover:bg-white/[0.05] hover:border-white/[0.10]",variants:_r,initial:"hidden",animate:"visible",custom:s,children:[e.jsx("div",{className:"mt-0.5",children:e.jsx(Ra,{category:r,size:16})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-body font-medium text-primary",children:t.name}),e.jsx("span",{className:"text-micro text-faint",children:h}),e.jsx(Ua,{metadata:t.metadata})]}),e.jsx("span",{className:"mt-0.5 flex-shrink-0 rounded-full px-1.5 py-0.5 text-micro font-medium uppercase tracking-wider",style:{color:An[t.status]??ee.textMuted,backgroundColor:`${An[t.status]??ee.textMuted}15`},children:t.status})]})}function Ha({initiative:t}){const{agentEntityMap:s,openModal:n,closeModal:r,authToken:c,embedMode:o,mutations:d}=Tt(),x=s.get(t.id)??[],[h,y]=a.useState(!1),[m,S]=a.useState(""),[I,k]=a.useState(!1),[l,v]=a.useState(!1),[g,w]=a.useState(null),[F,_]=a.useState(t.name),[f,$]=a.useState(t.description??""),[L,B]=a.useState(ss(t.priority)),[G,se]=a.useState(zs(t.targetDate)),[K,J]=a.useState(null),{details:E,isLoading:H}=js({initiativeId:t.id,authToken:c,embedMode:o}),z=ls({authToken:c,embedMode:o}),D=E.tasks.filter(u=>["active","in_progress"].includes(u.status.toLowerCase())).length,W=E.tasks.filter(u=>u.status.toLowerCase()==="blocked").length,xe=E.tasks.filter(u=>rt(u.status)).length;K??t.status;const Se=is(t.rawStatus??t.status,{hasActiveStreams:D>0,totalTasks:E.tasks.length,completedTasks:xe,blockedTasks:W}),he=kt[Se]??kt.Queued,ne=Va(K??t.rawStatus??t.status),ye=["active","in_progress","running","queued"].includes(ne),U=["paused","draft","planned","todo","backlog","pending","not_started"].includes(ne),M=d.entityAction.isPending||d.createEntity.isPending||d.updateEntity.isPending||d.deleteEntity.isPending,me=z.isPinning||z.isMoving,te=a.useMemo(()=>E.workstreams.length>0?E.workstreams.map(u=>({id:u.id,name:u.name})):(t.workstreams??[]).map(u=>({id:u.id,name:u.name})),[E.workstreams,t.workstreams]),fe=(u,P)=>u&&u.trim().length>0?pt(u.trim()):P;a.useEffect(()=>{I||(_(t.name),$(t.description??""),se(zs(t.targetDate)),B(ss(t.priority)))},[I,t.description,t.name,t.priority,t.targetDate]),a.useEffect(()=>{J(null),v(!1)},[t.id,t.status,t.rawStatus]);const Z=(u,P,ie)=>{w(null),d.entityAction.mutate({type:"initiative",id:t.id,action:u},{onSuccess:()=>{J(P),w(ie)},onError:ke=>{w(fe(ke instanceof Error?ke.message:"",`Failed to ${u} initiative.`))}})},N=()=>{const u=F.trim();if(!u){w("Initiative title is required.");return}w(null),d.updateEntity.mutate({type:"initiative",id:t.id,title:u,summary:f.trim()||null,priority:L,target_date:G||null},{onSuccess:()=>{k(!1),w("Initiative updated.")},onError:P=>{w(fe(P instanceof Error?P.message:"","Failed to update initiative."))}})},j=async u=>{if(te.length===0){w("No workstreams available to queue.");return}const P=u==="top"?[...te].reverse():te;let ie=0,ke=0,be=null;for(const Pe of P)try{await z.pin({initiativeId:t.id,workstreamId:Pe.id}),await z.move({initiativeId:t.id,workstreamId:Pe.id,placement:u}),ie+=1}catch(Ce){ke+=1,be||(be=fe(Ce instanceof Error?Ce.message:"","Failed to queue initiative workstream."))}if(ke>0){w(ie>0?`Queued ${ie}/${te.length} workstreams (${ke} failed).`:be??"Failed to queue initiative workstreams.");return}w(`Queued ${ie} workstream${ie===1?"":"s"} to ${u==="top"?"top":"end"}.`)};return e.jsxs("div",{className:"flex h-full w-full min-h-0 flex-col",children:[e.jsxs("div",{className:"min-h-0 flex-1 space-y-5 overflow-y-auto p-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(tt,{type:"initiative",size:16}),e.jsx("h2",{className:"text-title font-semibold text-white",children:t.name}),e.jsx("span",{className:`text-micro px-2.5 py-0.5 rounded-full border uppercase tracking-[0.08em] ${he}`,children:Se}),E.tasks.length>0&&e.jsxs("span",{className:"font-mono tabular-nums text-[11px] text-muted whitespace-nowrap",children:[xe,"/",E.tasks.length," tasks"]}),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:Ka(t.priority)})]}),I?e.jsxs("div",{className:"space-y-2 rounded-xl border border-white/[0.08] bg-white/[0.02] p-3",children:[e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:"Title"}),e.jsx("input",{type:"text",value:F,onChange:u=>_(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:"Summary"}),e.jsx("textarea",{value:f,onChange:u=>$(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("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:G,onChange:u=>se(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:"Priority"}),e.jsxs("select",{value:L,onChange:u=>B(ss(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:[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."}),x.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(as,{agents:x,max:6})]}),g&&e.jsx("div",{className:"text-caption text-secondary",children:g})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 sm:grid-cols-4",children:[e.jsx(fs,{label:"Workstreams",value:`${E.workstreams.length}`}),e.jsx(fs,{label:"Milestones",value:`${E.milestones.length}`}),e.jsx(fs,{label:"Active Tasks",value:`${D}`,accent:D>0?ee.lime:void 0}),e.jsx(fs,{label:"Blocked",value:`${W}`,accent:W>0?ee.red:void 0})]}),H?e.jsx("div",{className:"space-y-2",children:Array.from({length:3}).map((u,P)=>e.jsx(jt,{className:"h-14 w-full rounded-lg"},`init-detail-${P}`))}):e.jsxs(e.Fragment,{children:[E.workstreams.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(Dn,{title:"Workstreams",count:E.workstreams.length}),E.workstreams.map(u=>{const P=E.tasks.filter(Fe=>Fe.workstreamId===u.id),ie=P.filter(Fe=>rt(Fe.status)).length,ke=P.filter(Fe=>["active","in_progress"].includes(Fe.status.toLowerCase())).length,be=P.filter(Fe=>Fe.status.toLowerCase()==="blocked").length,Pe=P.length>0?Ot(ie,P.length):typeof u.progress=="number"?Ns(u.progress<=1?u.progress*100:u.progress):rt(u.status)?100:null,Ce=is(u.status,{hasActiveStreams:ke>0,totalTasks:P.length,completedTasks:ie,blockedTasks:be}),le=kt[Ce]??kt.Queued;return e.jsxs("button",{onClick:()=>n({type:"workstream",entity:u,initiative:t}),className:"w-full text-left rounded-xl border border-white/[0.08] bg-white/[0.03] p-3.5 transition-colors hover:bg-white/[0.06]",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-body text-bright break-words",children:u.name}),e.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[e.jsx("span",{className:`text-micro px-1.5 py-0.5 rounded-full border uppercase tracking-[0.08em] ${le}`,children:Ce}),P.length>0&&e.jsxs("span",{className:"font-mono tabular-nums text-[11px] text-muted whitespace-nowrap",children:[ie,"/",P.length]})]})]}),e.jsxs("div",{className:"mt-1.5 flex items-center gap-3 text-micro text-muted uppercase tracking-[0.08em]",children:[e.jsxs("span",{children:[P.length," tasks"]}),Pe!==null&&e.jsxs("span",{className:"font-mono tabular-nums",children:[Pe,"%"]})]})]},u.id)})]}),E.milestones.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(Dn,{title:"Milestones",count:E.milestones.length}),E.milestones.map(u=>e.jsxs("button",{onClick:()=>n({type:"milestone",entity:u,initiative:t}),className:"w-full text-left rounded-xl border border-white/[0.08] bg-white/[0.03] p-3 transition-colors hover:bg-white/[0.06]",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-body text-bright break-words",children:u.title}),e.jsx("span",{className:"text-micro text-muted uppercase tracking-[0.08em]",children:nt(u.status)})]}),u.dueDate&&e.jsxs("span",{className:"text-micro text-muted mt-0.5 block",children:["Due: ",new Date(u.dueDate).toLocaleDateString()]})]},u.id))]}),e.jsxs("div",{className:"text-micro uppercase tracking-[0.08em] text-muted pt-2 border-t border-subtle",children:[E.tasks.length," total tasks · ",xe," done"]}),e.jsx(Cs,{entityType:"initiative",entityId:t.id,authToken:c,embedMode:o}),e.jsxs("div",{className:"mt-4 pt-4 border-t border-subtle",children:[e.jsx("p",{className:"text-micro font-semibold uppercase tracking-[0.08em] text-muted mb-2",children:"Notes"}),e.jsx(ks,{entityType:"initiative",entityId:t.id,authToken:c,embedMode:o,variant:"inline"})]})]})]}),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:[ye&&e.jsx(ae,{label:"Pause",color:ee.amber,onClick:()=>Z("pause","paused","Initiative paused."),disabled:M}),U&&e.jsx(ae,{label:ne==="paused"?"Resume":"Start",color:ee.lime,variant:"primary",onClick:()=>Z("resume","active",ne==="paused"?"Initiative resumed.":"Initiative started."),disabled:M}),e.jsx(Ss,{label:"Queue",size:"md",busy:me,disabled:M||te.length===0,title:`Queue initiative: ${t.name}`,onSelectPlacement:j}),I?e.jsxs(e.Fragment,{children:[e.jsx(ae,{label:"Save",color:ee.teal,variant:"primary",onClick:N,disabled:M||!F.trim()}),e.jsx(ae,{label:"Cancel",variant:"ghost",onClick:()=>{k(!1),_(t.name),$(t.description??""),B(ss(t.priority)),se(zs(t.targetDate)),w(null)},disabled:M})]}):e.jsx(ae,{label:"Edit",variant:"ghost",onClick:()=>{k(!0),w(null)},disabled:M}),e.jsx("div",{className:"flex-1"}),l?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-caption text-secondary",children:"Delete initiative?"}),e.jsx(ae,{label:"Delete",color:ee.red,variant:"destructive",onClick:()=>d.deleteEntity.mutate({type:"initiative",id:t.id},{onSuccess:()=>r(),onError:u=>w(u instanceof Error?u.message:"Failed to delete initiative.")}),disabled:M}),e.jsx(ae,{label:"Keep",variant:"ghost",onClick:()=>v(!1),disabled:M})]}):e.jsx(ae,{label:"Delete",color:ee.red,variant:"destructive",onClick:()=>v(!0),disabled:M}),h?e.jsxs("form",{className:"flex flex-wrap items-center gap-2",onSubmit:u=>{u.preventDefault(),m.trim()&&d.createEntity.mutate({type:"workstream",title:m.trim(),initiative_id:t.id,status:"not_started"},{onSuccess:()=>{S(""),y(!1)}})},children:[e.jsx("input",{type:"text",value:m,onChange:u=>S(u.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(ae,{type:"submit",label:"Add",color:ee.lime,disabled:!m.trim()||d.createEntity.isPending,size:"sm"}),e.jsx(ae,{label:"Cancel",variant:"ghost",onClick:()=>{y(!1),S("")},size:"sm"})]}):e.jsx(ae,{label:"+ Workstream",variant:"ghost",onClick:()=>y(!0),disabled:M})]})})]})}function zs(t){if(!t)return"";const s=Date.parse(t);return Number.isFinite(s)?new Date(s).toISOString().slice(0,10):""}function Va(t){return(t??"").trim().toLowerCase().replace(/[\s-]+/g,"_")}function ss(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 Ka(t){const s=ss(t);return s==="critical"?"Priority: Critical":s==="high"?"Priority: High":s==="low"?"Priority: Low":"Priority: Medium"}function fs({label:t,value:s,accent:n}){return e.jsxs("div",{className:"rounded-xl border border-white/[0.08] bg-white/[0.03] px-3 py-2.5",style:n?{borderTopColor:`${n}50`,borderTopWidth:2}:void 0,children:[e.jsx("div",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:t}),e.jsx("div",{className:"text-heading font-medium mt-0.5",style:{color:n??"rgba(255,255,255,0.8)"},children:s})]})}function Dn({title:t,count:s}){return e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-caption uppercase tracking-[0.08em] text-muted",children:t}),e.jsx("span",{className:"text-micro text-muted",children:s})]})}function Ga({workstream:t,initiative:s}){const{agentEntityMap:n,openModal:r,closeModal:c,authToken:o,embedMode:d,mutations:x}=Tt(),h=n.get(t.id)??n.get(s.id)??[],[y,m]=a.useState(!1),[S,I]=a.useState(""),[k,l]=a.useState(!1),[v,g]=a.useState(!1),[w,F]=a.useState(null),[_,f]=a.useState(t.name),[$,L]=a.useState(t.summary??""),[B,G]=a.useState(t.status),{details:se,isLoading:K}=js({initiativeId:s.id,authToken:o,embedMode:d}),J=ls({authToken:o,embedMode:d}),E=a.useMemo(()=>se.milestones.filter(N=>N.workstreamId===t.id),[se.milestones,t.id]),H=a.useMemo(()=>new Set(E.map(N=>N.id)),[E]),z=a.useMemo(()=>se.tasks.filter(N=>N.workstreamId===t.id||N.milestoneId!==null&&H.has(N.milestoneId)).sort((N,j)=>{const u=gs(N.status)-gs(j.status);if(u!==0)return u;const P=N.createdAt?Date.parse(N.createdAt):0;return(j.createdAt?Date.parse(j.createdAt):0)-P}),[se.tasks,H,t.id]),D=z.filter(N=>rt(N.status)).length,W=z.filter(N=>["active","in_progress"].includes(N.status.toLowerCase())).length,xe=z.filter(N=>N.status.toLowerCase()==="blocked").length,Se=z.length>0?Ot(D,z.length):typeof t.progress=="number"?Ns(t.progress<=1?t.progress*100:t.progress):rt(t.status)?100:null,he=is(t.status,{hasActiveStreams:W>0,totalTasks:z.length,completedTasks:D,blockedTasks:xe}),ne=kt[he]??kt.Queued,ye=bs[he]??"#14B8A6",U=t.status.toLowerCase(),M=x.entityAction.isPending||x.createEntity.isPending||x.updateEntity.isPending||x.deleteEntity.isPending,me=J.isPinning||J.isMoving,te=(N,j)=>N&&N.trim().length>0?pt(N.trim()):j,fe=()=>{const N=_.trim();if(!N){F("Workstream name is required.");return}F(null),x.updateEntity.mutate({type:"workstream",id:t.id,title:N,summary:$.trim()||null,status:B},{onSuccess:()=>{l(!1),F("Workstream updated.")},onError:j=>{F(te(j instanceof Error?j.message:"","Failed to update workstream."))}})},Z=async N=>{F(null);try{await J.pin({initiativeId:s.id,workstreamId:t.id}),await J.move({initiativeId:s.id,workstreamId:t.id,placement:N}),F(`Queued workstream to ${N==="top"?"top":"end"}.`)}catch(j){F(te(j instanceof Error?j.message:"","Failed to queue workstream."))}};return e.jsxs("div",{className:"flex h-full w-full min-h-0 flex-col",children:[e.jsxs("div",{className:"min-h-0 flex-1 space-y-5 overflow-y-auto p-6",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-caption",children:[e.jsx(tt,{type:"initiative",size:12,className:"flex-shrink-0 opacity-80"}),e.jsx("button",{onClick:()=>r({type:"initiative",entity:s}),className:"break-words text-secondary transition-colors hover:text-white",children:s.name}),e.jsx("svg",{width:"8",height:"8",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"text-faint",children:e.jsx("path",{d:"m9 18 6-6-6-6"})}),e.jsx(tt,{type:"workstream",size:12,className:"flex-shrink-0 opacity-95"}),e.jsx("span",{className:"break-words font-medium text-primary",children:t.name})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(tt,{type:"workstream",size:16}),e.jsx("h2",{className:"text-title font-semibold text-white",children:t.name}),e.jsx("span",{className:`text-micro px-2.5 py-0.5 rounded-full border uppercase tracking-[0.08em] ${ne}`,children:he}),z.length>0&&e.jsxs("span",{className:"font-mono tabular-nums text-[11px] text-muted whitespace-nowrap",children:[D,"/",z.length," tasks"]})]}),k?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:_,onChange:N=>f(N.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:N=>L(N.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:B,onChange:N=>G(N.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(N=>e.jsx("option",{value:N,children:nt(N)},N))})]})]}):t.summary?e.jsx("p",{className:"text-body text-secondary leading-relaxed",children:t.summary}):e.jsx("p",{className:"text-body text-muted",children:"No summary yet."}),h.length>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-micro text-muted uppercase tracking-wider",children:"Agents"}),e.jsx(as,{agents:h,max:6})]}),w&&e.jsx("div",{className:"text-caption text-secondary",children:w})]}),Se!==null&&e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("span",{className:"text-micro text-muted uppercase tracking-wider",children:"Progress"}),e.jsxs("span",{className:"text-body text-secondary font-mono tabular-nums",children:[Se,"%"]})]}),e.jsx("div",{className:"h-1.5 w-full rounded-full bg-white/[0.06] overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${Se}%`,backgroundColor:ye}})})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-3",children:[e.jsxs("div",{className:"rounded-xl border border-white/[0.08] bg-white/[0.03] px-3 py-2.5",children:[e.jsx("div",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:"Tasks"}),e.jsx("div",{className:"text-heading font-medium text-primary mt-0.5",children:z.length})]}),e.jsxs("div",{className:"rounded-xl border border-white/[0.08] bg-white/[0.03] px-3 py-2.5",children:[e.jsx("div",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:"Milestones"}),e.jsx("div",{className:"text-heading font-medium text-primary mt-0.5",children:E.length})]}),e.jsxs("div",{className:"rounded-xl border border-white/[0.08] bg-white/[0.03] px-3 py-2.5",children:[e.jsx("div",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:"Progress"}),e.jsx("div",{className:"text-heading font-medium text-primary mt-0.5 font-mono tabular-nums",children:Se!==null?`${Se}%`:"-"}),z.length>0&&e.jsxs("div",{className:"text-micro text-muted mt-0.5 font-mono tabular-nums",children:[D,"/",z.length," done"]})]})]}),K?e.jsx("div",{className:"space-y-2",children:Array.from({length:3}).map((N,j)=>e.jsx(jt,{className:"h-12 w-full rounded-lg"},`ws-detail-${j}`))}):e.jsxs(e.Fragment,{children:[E.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("span",{className:"text-caption uppercase tracking-[0.08em] text-muted",children:"Milestones"}),E.map(N=>e.jsx("button",{onClick:()=>r({type:"milestone",entity:N,initiative:s}),className:"w-full text-left rounded-xl border border-white/[0.08] bg-white/[0.03] p-3 transition-colors hover:bg-white/[0.06]",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-body text-bright",children:N.title}),e.jsx("span",{className:`text-micro px-1.5 py-0.5 rounded-full border uppercase tracking-[0.08em] ${Lr(N.status)}`,children:nt(N.status)})]})},N.id))]}),z.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("span",{className:"text-caption uppercase tracking-[0.08em] text-muted",children:["Tasks (",z.length,")"]}),z.map(N=>e.jsxs("button",{onClick:()=>r({type:"task",entity:N,initiative:s}),className:"w-full text-left rounded-xl border border-white/[0.08] bg-white/[0.03] p-3 transition-colors hover:bg-white/[0.06]",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-body text-bright",children:N.title}),e.jsx("span",{className:`text-micro px-1.5 py-0.5 rounded-full border uppercase tracking-[0.08em] flex-shrink-0 ${Ys(N.status)}`,children:nt(N.status)})]}),N.priority&&e.jsxs("span",{className:"text-micro text-muted mt-0.5 block uppercase tracking-wider",children:["Priority: ",N.priority]})]},N.id))]}),e.jsx(Cs,{entityType:"workstream",entityId:t.id,title:"Artifacts (from milestones)",authToken:o,embedMode:d,finalOnly:!0,milestoneIds:E.map(N=>N.id)}),e.jsxs("div",{className:"mt-2 pt-4 border-t border-subtle",children:[e.jsx("p",{className:"text-micro font-semibold uppercase tracking-[0.08em] text-muted mb-2",children:"Notes"}),e.jsx(ks,{entityType:"workstream",entityId:t.id,authToken:o,embedMode:d,variant:"inline"})]})]})]}),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(ae,{label:"Start",color:ee.lime,variant:"primary",onClick:()=>x.entityAction.mutate({type:"workstream",id:t.id,action:"start"}),disabled:M}),["active","in_progress"].includes(U)&&e.jsxs(e.Fragment,{children:[e.jsx(ae,{label:"Complete",color:ee.teal,variant:"primary",onClick:()=>x.entityAction.mutate({type:"workstream",id:t.id,action:"complete"}),disabled:M}),e.jsx(ae,{label:"Pause",color:ee.amber,onClick:()=>x.entityAction.mutate({type:"workstream",id:t.id,action:"pause"}),disabled:M}),e.jsx(ae,{label:"Block",color:ee.red,variant:"destructive",onClick:()=>x.entityAction.mutate({type:"workstream",id:t.id,action:"block"}),disabled:M})]}),["paused","blocked"].includes(U)&&e.jsx(ae,{label:"Resume",color:ee.lime,variant:"primary",onClick:()=>x.entityAction.mutate({type:"workstream",id:t.id,action:"resume"}),disabled:M}),e.jsx(Ss,{label:"Queue",size:"md",busy:me,disabled:M,title:`Queue workstream: ${t.name}`,onSelectPlacement:Z}),k?e.jsxs(e.Fragment,{children:[e.jsx(ae,{label:"Save",color:ee.teal,variant:"primary",onClick:fe,disabled:M||!_.trim()}),e.jsx(ae,{label:"Cancel",variant:"ghost",onClick:()=>{l(!1),f(t.name),L(t.summary??""),G(t.status),F(null)},disabled:M})]}):e.jsx(ae,{label:"Edit",variant:"ghost",onClick:()=>{l(!0),F(null)},disabled:M}),e.jsx("div",{className:"flex-1"}),v?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-caption text-secondary",children:"Delete workstream?"}),e.jsx(ae,{label:"Delete",color:ee.red,variant:"destructive",onClick:()=>x.deleteEntity.mutate({type:"workstream",id:t.id},{onSuccess:()=>c(),onError:N=>F(te(N instanceof Error?N.message:"","Failed to delete workstream."))}),disabled:M}),e.jsx(ae,{label:"Keep",variant:"ghost",onClick:()=>g(!1),disabled:M})]}):e.jsx(ae,{label:"Delete",color:ee.red,variant:"destructive",onClick:()=>g(!0),disabled:M}),y?e.jsxs("form",{className:"flex flex-wrap items-center gap-2",onSubmit:N=>{N.preventDefault(),S.trim()&&x.createEntity.mutate({type:"task",title:S.trim(),workstream_id:t.id,initiative_id:s.id,status:"todo"},{onSuccess:()=>{I(""),m(!1)},onError:j=>{F(te(j instanceof Error?j.message:"","Failed to create task."))}})},children:[e.jsx("input",{type:"text",value:S,onChange:N=>I(N.target.value),placeholder:"Task title...",autoFocus:!0,className:"text-body bg-white/5 border border-white/10 rounded-lg px-2.5 py-1.5 text-primary placeholder-white/30 w-[160px] outline-none focus:border-white/25"}),e.jsx(ae,{label:"Add",color:ee.lime,type:"submit",size:"sm",disabled:!S.trim()||x.createEntity.isPending}),e.jsx(ae,{label:"Cancel",variant:"ghost",size:"sm",onClick:()=>{m(!1),I("")}})]}):e.jsx(ae,{label:"+ Task",variant:"ghost",onClick:()=>m(!0),disabled:M})]})})]})}function Ja({milestone:t,initiative:s}){const{openModal:n,closeModal:r,authToken:c,embedMode:o,mutations:d}=Tt(),[x,h]=a.useState(!1),[y,m]=a.useState(!1),[S,I]=a.useState(!1),[k,l]=a.useState(""),[v,g]=a.useState(null),[w,F]=a.useState(t.title),[_,f]=a.useState(t.description??""),[$,L]=a.useState(Mn(t.dueDate)),[B,G]=a.useState(t.status),{details:se}=js({initiativeId:s.id,authToken:c,embedMode:o}),K=se.tasks.filter(U=>U.milestoneId===t.id),J=t.status.toLowerCase()==="done"||t.status.toLowerCase()==="completed",E=K.filter(U=>rt(U.status)).length,H=K.filter(U=>["active","in_progress"].includes(U.status.toLowerCase())).length,z=K.filter(U=>U.status.toLowerCase()==="blocked").length,D=K.length>0?Ot(E,K.length):J?100:0,W=is(t.status,{hasActiveStreams:H>0,totalTasks:K.length,completedTasks:E,blockedTasks:z}),xe=kt[W]??kt.Queued,Se=bs[W]??"#14B8A6",he=d.entityAction.isPending||d.createEntity.isPending||d.updateEntity.isPending||d.deleteEntity.isPending,ne=(U,M)=>U&&U.trim().length>0?pt(U.trim()):M,ye=()=>{const U=w.trim();if(!U){g("Milestone title is required.");return}g(null),d.updateEntity.mutate({type:"milestone",id:t.id,title:U,description:_.trim()||null,due_date:$||null,status:B},{onSuccess:()=>{h(!1),g("Milestone updated.")},onError:M=>{g(ne(M instanceof Error?M.message:"","Failed to update milestone."))}})};return e.jsxs("div",{className:"flex h-full w-full min-h-0 flex-col",children:[e.jsxs("div",{className:"min-h-0 flex-1 space-y-5 overflow-y-auto p-6",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-caption",children:[e.jsx(tt,{type:"initiative",size:12,className:"flex-shrink-0 opacity-80"}),e.jsx("button",{onClick:()=>n({type:"initiative",entity:s}),className:"break-words text-secondary transition-colors hover:text-white",children:s.name}),e.jsx("svg",{width:"8",height:"8",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"text-faint",children:e.jsx("path",{d:"m9 18 6-6-6-6"})}),e.jsx(tt,{type:"milestone",size:12,className:"flex-shrink-0 opacity-95"}),e.jsx("span",{className:"break-words font-medium text-primary",children:t.title})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(tt,{type:"milestone",size:16}),e.jsx("h2",{className:"text-title font-semibold text-white",children:t.title}),e.jsx("span",{className:`text-micro px-2.5 py-0.5 rounded-full border uppercase tracking-[0.08em] ${xe}`,children:W}),K.length>0&&e.jsxs("span",{className:"font-mono tabular-nums text-[11px] text-muted whitespace-nowrap",children:[E,"/",K.length," tasks"]})]}),x?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:w,onChange:U=>F(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:_,onChange:U=>f(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-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:$,onChange:U=>L(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:B,onChange:U=>G(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:["planned","active","in_progress","at_risk","blocked","done"].map(U=>e.jsx("option",{value:U,children:nt(U)},U))})]})]})]}):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."}),v&&e.jsx("div",{className:"text-caption text-secondary",children:v})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-3",children:[t.dueDate&&e.jsxs("div",{className:"rounded-xl border border-white/[0.08] bg-white/[0.03] px-3 py-2.5",children:[e.jsx("div",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:"Due Date"}),e.jsx("div",{className:"text-body text-primary mt-0.5",children:new Date(t.dueDate).toLocaleDateString()})]}),e.jsxs("div",{className:"rounded-xl border border-white/[0.08] bg-white/[0.03] px-3 py-2.5",children:[e.jsx("div",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:"Associated Tasks"}),e.jsx("div",{className:"text-heading font-medium text-primary mt-0.5",children:K.length})]}),e.jsxs("div",{className:"rounded-xl border border-white/[0.08] bg-white/[0.03] px-3 py-2.5",children:[e.jsx("div",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:"Completion"}),e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[e.jsx("div",{className:"h-1.5 flex-1 rounded-full bg-white/[0.06] overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${D}%`,backgroundColor:Se}})}),e.jsxs("div",{className:"text-body text-primary font-mono tabular-nums",children:[D,"%"]})]}),e.jsxs("div",{className:"mt-1 text-micro text-muted font-mono tabular-nums",children:[E,"/",K.length," done"]})]})]}),K.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("span",{className:"text-caption uppercase tracking-[0.08em] text-muted",children:"Tasks"}),K.map(U=>e.jsx("button",{onClick:()=>n({type:"task",entity:U,initiative:s}),className:"w-full text-left rounded-xl border border-white/[0.08] bg-white/[0.03] p-3 transition-colors hover:bg-white/[0.06]",children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-body text-bright",children:U.title}),e.jsx("span",{className:`text-micro px-1.5 py-0.5 rounded-full border uppercase tracking-[0.08em] flex-shrink-0 ${Ys(U.status)}`,children:nt(U.status)})]})},U.id))]}),e.jsx(Cs,{entityType:"milestone",entityId:t.id,authToken:c,embedMode:o}),e.jsxs("div",{className:"mt-2 pt-4 border-t border-subtle",children:[e.jsx("p",{className:"text-micro font-semibold uppercase tracking-[0.08em] text-muted mb-2",children:"Notes"}),e.jsx(ks,{entityType:"milestone",entityId:t.id,authToken:c,embedMode:o,variant:"inline"})]})]}),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:[!J&&t.status.toLowerCase()==="planned"&&e.jsx(ae,{label:"Start",color:ee.lime,variant:"primary",onClick:()=>d.entityAction.mutate({type:"milestone",id:t.id,action:"start"}),disabled:he}),!J&&(t.status.toLowerCase()==="in_progress"||t.status.toLowerCase()==="at_risk")&&e.jsx(ae,{label:K.length>0&&!K.every(U=>rt(U.status))?"Complete (force)":"Complete",color:ee.teal,variant:"primary",onClick:()=>{const U=K.length===0||K.every(M=>rt(M.status));d.entityAction.mutate({type:"milestone",id:t.id,action:"complete",force:!U})},disabled:he}),x?e.jsxs(e.Fragment,{children:[e.jsx(ae,{label:"Save",color:ee.teal,variant:"primary",onClick:ye,disabled:he||!w.trim()}),e.jsx(ae,{label:"Cancel",variant:"ghost",onClick:()=>{h(!1),F(t.title),f(t.description??""),L(Mn(t.dueDate)),G(t.status),g(null)},disabled:he})]}):e.jsx(ae,{label:"Edit",variant:"ghost",onClick:()=>{h(!0),g(null)},disabled:he}),e.jsx("div",{className:"flex-1"}),y?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-caption text-secondary",children:"Delete milestone?"}),e.jsx(ae,{label:"Delete",color:ee.red,variant:"destructive",onClick:()=>d.deleteEntity.mutate({type:"milestone",id:t.id},{onSuccess:()=>r(),onError:U=>g(ne(U instanceof Error?U.message:"","Failed to delete milestone."))}),disabled:he}),e.jsx(ae,{label:"Keep",variant:"ghost",onClick:()=>m(!1),disabled:he})]}):e.jsx(ae,{label:"Delete",color:ee.red,variant:"destructive",onClick:()=>m(!0),disabled:he}),S?e.jsxs("form",{className:"flex flex-wrap items-center gap-2",onSubmit:U=>{U.preventDefault(),k.trim()&&d.createEntity.mutate({type:"task",title:k.trim(),milestone_id:t.id,workstream_id:t.workstreamId??void 0,initiative_id:s.id,status:"todo"},{onSuccess:()=>{l(""),I(!1)},onError:M=>{g(ne(M instanceof Error?M.message:"","Failed to create task."))}})},children:[e.jsx("input",{type:"text",value:k,onChange:U=>l(U.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(ae,{label:"Add",color:ee.lime,type:"submit",size:"sm",disabled:!k.trim()||d.createEntity.isPending}),e.jsx(ae,{label:"Cancel",variant:"ghost",size:"sm",onClick:()=>{I(!1),l("")}})]}):e.jsx(ae,{label:"+ Task",variant:"ghost",onClick:()=>I(!0),disabled:he})]})})]})}function Mn(t){if(!t)return"";const s=Date.parse(t);return Number.isFinite(s)?new Date(s).toISOString().slice(0,10):""}function Ya({task:t,initiative:s}){const{agentEntityMap:n,openModal:r,mutations:c,closeModal:o,authToken:d,embedMode:x}=Tt(),h=n.get(t.id)??n.get(s.id)??[],[y,m]=a.useState(!1),[S,I]=a.useState(!1),[k,l]=a.useState(null),[v,g]=a.useState(t.title),[w,F]=a.useState(t.description??""),[_,f]=a.useState(t.priority??""),[$,L]=a.useState(Tn(t.dueDate)),[B,G]=a.useState(t.status),se=t.status.toLowerCase(),K=(D,W)=>D&&D.trim().length>0?pt(D.trim()):W,J=c.entityAction.isPending||c.updateEntity.isPending||c.deleteEntity.isPending,E=D=>{l(null),c.entityAction.mutate({type:"task",id:t.id,action:D},{onError:W=>{l(K(W instanceof Error?W.message:"","Task action failed."))}})},H=()=>{const D=v.trim();if(!D){l("Task title is required.");return}l(null),c.updateEntity.mutate({type:"task",id:t.id,title:D,description:w.trim()||null,priority:_.trim()||null,due_date:$||null,status:B},{onSuccess:()=>{I(!1),l("Task updated.")},onError:W=>{l(K(W instanceof Error?W.message:"","Failed to update task."))}})},z=()=>{l(null),c.deleteEntity.mutate({type:"task",id:t.id},{onSuccess:()=>o(),onError:D=>{l(K(D instanceof Error?D.message:"","Failed to delete task."))}})};return e.jsxs("div",{className:"flex h-full w-full min-h-0 flex-col",children:[e.jsxs("div",{className:"min-h-0 flex-1 space-y-5 overflow-y-auto p-6",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-caption",children:[e.jsx(tt,{type:"initiative",size:12,className:"flex-shrink-0 opacity-80"}),e.jsx("button",{onClick:()=>r({type:"initiative",entity:s}),className:"break-words text-secondary transition-colors hover:text-white",children:s.name}),e.jsx("svg",{width:"8",height:"8",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"text-faint",children:e.jsx("path",{d:"m9 18 6-6-6-6"})}),e.jsx(tt,{type:"task",size:12,className:"flex-shrink-0 opacity-95"}),e.jsx("span",{className:"break-words font-medium text-primary",children:t.title})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(tt,{type:"task",size:16}),e.jsx("h2",{className:"break-words text-title font-semibold text-white",children:t.title}),e.jsx("span",{className:`text-micro px-2.5 py-0.5 rounded-full border uppercase tracking-[0.08em] ${Ys(t.status)}`,children:nt(t.status)})]}),S?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:v,onChange:D=>g(D.target.value),className:"mt-1 w-full rounded-lg border border-white/15 bg-white/[0.06] px-3 py-2 text-body text-bright outline-none focus:border-white/30"})]}),e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:"Description"}),e.jsx("textarea",{value:w,onChange:D=>F(D.target.value),rows:3,className:"mt-1 w-full resize-y rounded-lg border border-white/15 bg-white/[0.06] px-3 py-2 text-body text-bright outline-none focus:border-white/30"})]}),e.jsxs("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:D=>f(D.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:$,onChange:D=>L(D.target.value),className:"mt-1 w-full rounded-lg border border-white/15 bg-white/[0.06] px-3 py-2 text-body text-bright outline-none focus:border-white/30"})]}),e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:"Status"}),e.jsx("select",{value:B,onChange:D=>G(D.target.value),className:"mt-1 w-full rounded-lg border border-white/15 bg-white/[0.06] px-3 py-2 text-body text-bright outline-none focus:border-white/30",children:["not_started","planned","todo","in_progress","active","blocked","done"].map(D=>e.jsx("option",{value:D,children:nt(D)},D))})]})]})]}):t.description?e.jsx(Br,{text:t.description,mode:"block",className:"text-body text-secondary leading-relaxed"}):e.jsx("p",{className:"text-body text-muted",children:"No description yet."}),h.length>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-micro text-muted uppercase tracking-wider",children:"Agents"}),e.jsx(as,{agents:h,max:4})]})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-3",children:[e.jsxs("div",{className:"rounded-xl border border-white/[0.08] bg-white/[0.03] px-3 py-2.5",children:[e.jsx("div",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:"Status"}),e.jsx("div",{className:"text-body text-primary mt-0.5",children:nt(t.status)})]}),e.jsxs("div",{className:"rounded-xl border border-white/[0.08] bg-white/[0.03] px-3 py-2.5",children:[e.jsx("div",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:"Priority"}),e.jsx("div",{className:"text-body text-primary mt-0.5",children:t.priority??"-"})]}),e.jsxs("div",{className:"rounded-xl border border-white/[0.08] bg-white/[0.03] px-3 py-2.5",children:[e.jsx("div",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:"Due Date"}),e.jsx("div",{className:"text-body text-primary mt-0.5",children:t.dueDate?new Date(t.dueDate).toLocaleDateString():"-"})]})]}),k&&e.jsx("div",{className:"text-caption px-1",style:{color:`${ee.red}b3`},children:k}),e.jsx(Cs,{entityType:"task",entityId:t.id,authToken:d,embedMode:x}),e.jsxs("div",{className:"mt-4 pt-4 border-t border-subtle",children:[e.jsx("p",{className:"text-micro font-semibold uppercase tracking-[0.08em] text-muted mb-2",children:"Notes"}),e.jsx(ks,{entityType:"task",entityId:t.id,authToken:d,embedMode:x,variant:"inline"})]})]}),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:[se==="todo"&&e.jsx(ae,{label:"Start",color:ee.lime,variant:"primary",onClick:()=>E("start"),disabled:J}),(se==="in_progress"||se==="active")&&e.jsx(ae,{label:"Complete",color:ee.teal,variant:"primary",onClick:()=>E("complete"),disabled:J}),(se==="todo"||se==="in_progress"||se==="active")&&e.jsx(ae,{label:"Block",color:ee.red,variant:"destructive",onClick:()=>E("block"),disabled:J}),se==="blocked"&&e.jsx(ae,{label:"Unblock",color:ee.amber,onClick:()=>E("unblock"),disabled:J}),S?e.jsxs(e.Fragment,{children:[e.jsx(ae,{label:"Save",color:ee.teal,variant:"primary",onClick:H,disabled:J||!v.trim()}),e.jsx(ae,{label:"Cancel",variant:"ghost",onClick:()=>{I(!1),l(null),g(t.title),F(t.description??""),f(t.priority??""),L(Tn(t.dueDate)),G(t.status)},disabled:J})]}):e.jsx(ae,{label:"Edit",variant:"ghost",onClick:()=>{I(!0),l(null)},disabled:J}),e.jsx("div",{className:"flex-1"}),y?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-caption",style:{color:`${ee.red}b3`},children:"Delete?"}),e.jsx(ae,{label:"Delete",color:ee.red,variant:"destructive",onClick:z,disabled:J}),e.jsx(ae,{label:"Keep",variant:"ghost",onClick:()=>m(!1),disabled:J})]}):e.jsx(ae,{label:"Delete",color:ee.red,variant:"destructive",onClick:()=>m(!0),disabled:J})]})})]})}function Tn(t){if(!t)return"";const s=Date.parse(t);return Number.isFinite(s)?new Date(s).toISOString().slice(0,10):""}function Xa(t){const s=[];return t.type!=="initiative"&&t.initiative&&s.push(t.initiative.name),t.type==="initiative"||t.type==="workstream"?s.push(t.entity.name):(t.type==="milestone"||t.type==="task")&&s.push(t.entity.title),s}function Za({target:t,onClose:s}){return e.jsx(Pr,{open:t!==null,onClose:s,maxWidth:"max-w-5xl",children:t&&e.jsxs("div",{className:"flex h-full w-full min-h-0 flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 border-b border-subtle px-5 py-3 sm:px-6",children:[e.jsxs("div",{className:"flex items-center gap-1.5 min-w-0 text-body text-secondary",children:[Xa(t).map((n,r,c)=>e.jsxs("span",{className:"flex items-center gap-1.5 min-w-0",children:[r>0&&e.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",className:"flex-shrink-0 text-faint",children:e.jsx("path",{d:"m9 18 6-6-6-6"})}),e.jsx("span",{className:`truncate ${r===c.length-1?"text-primary font-medium":""}`,children:n})]},r)),e.jsxs("span",{className:"ml-1 inline-flex items-center gap-1 rounded-full border border-white/[0.1] bg-white/[0.04] px-2 py-0.5 text-micro uppercase tracking-[0.06em] text-secondary",children:[e.jsx(tt,{type:t.type,size:11,className:"opacity-90"}),t.type]})]}),e.jsx("button",{type:"button",onClick:s,"aria-label":"Close detail",className:"inline-flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-full border border-strong bg-white/[0.03] text-primary transition-colors hover:bg-white/[0.08] hover:text-white",children:e.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M18 6L6 18"}),e.jsx("path",{d:"M6 6l12 12"})]})})]}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto",children:[t.type==="initiative"&&e.jsx(Ha,{initiative:t.entity}),t.type==="workstream"&&e.jsx(Ga,{workstream:t.entity,initiative:t.initiative}),t.type==="milestone"&&e.jsx(Ja,{milestone:t.entity,initiative:t.initiative}),t.type==="task"&&e.jsx(Ya,{task:t.entity,initiative:t.initiative})]})]})})}function $n(t){return(t??"").trim().toLowerCase().replace(/[\s-]+/g,"_")}function ei(t){return t.split("_").map(s=>s.slice(0,1).toUpperCase()+s.slice(1)).join(" ")}const Us=["active","in_progress","not_started","planned","blocked","at_risk","paused","completed","done","backlog","todo","pending","draft"],ti=[{value:"target",label:"Target date"},{value:"created",label:"Created at"},{value:"updated",label:"Updated at"}],si=[{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"}],ni=[{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 ri({initiatives:t,visibleCount:s}){const{statusFilters:n,dateField:r,datePreset:c,dateStart:o,dateEnd:d,activeFilterCount:x,groupBy:h,setGroupBy:y,sortBy:m,setSortBy:S,zoomLevel:I,setZoomLevel:k,noiseThreshold:l,setNoiseThreshold:v,setStatusFilters:g,toggleStatusFilter:w,setDateField:F,setDatePreset:_,setDateStart:f,setDateEnd:$,clearFilters:L}=Tt(),[B,G]=a.useState(!1),[se,K]=a.useState(!1),J=a.useRef(null);a.useEffect(()=>{if(!B)return;const M=te=>{var Z;const fe=te.target;fe&&((Z=J.current)!=null&&Z.contains(fe)||G(!1))},me=te=>{te.key==="Escape"&&G(!1)};return document.addEventListener("mousedown",M),document.addEventListener("keydown",me),()=>{document.removeEventListener("mousedown",M),document.removeEventListener("keydown",me)}},[B]);const E=a.useMemo(()=>{const M=new Map;for(const te of t){const fe=new Set([$n(te.status),$n(te.rawStatus)]);for(const Z of fe)Z&&M.set(Z,(M.get(Z)??0)+1)}for(const te of Us)M.has(te)||M.set(te,0);return Array.from(M.entries()).sort((te,fe)=>{const Z=Us.indexOf(te[0]),N=Us.indexOf(fe[0]);return Z>=0&&N>=0?Z-N:Z>=0?-1:N>=0?1:te[0].localeCompare(fe[0])}).map(([te,fe])=>({key:te,count:fe}))},[t]),H=n.length,z=a.useMemo(()=>E.filter(M=>se||M.count>0||n.includes(M.key)),[se,n,E]),D=E.length-z.length,W=a.useMemo(()=>r==="target"?si:ni,[r]);a.useEffect(()=>{W.some(M=>M.value===c)||_("any")},[c,W,_]);const xe=[{value:"none",label:"None"},{value:"status",label:"Status"},{value:"date",label:"Date"},{value:"category",label:"Category"}],Se=[{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)"}],he=h!=="status"||m!=="default",ne=x>0,ye=x,U=ne||he;return e.jsxs("div",{ref:J,className:"relative flex items-center gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>{G(M=>{const me=!M;return me||K(!1),me})},"data-state":B||ye>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"}),ye>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:ye})]}),s<t.length&&e.jsxs("span",{className:"text-micro text-muted whitespace-nowrap",children:[s,"/",t.length]}),e.jsx(mt,{initial:!1,children:ne&&e.jsx(je.button,{type:"button",onClick:L,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(mt,{children:B&&e.jsxs(je.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"})]}),ne?e.jsxs("span",{className:"rounded-full border border-strong bg-white/[0.04] px-2 py-0.5 text-micro text-primary",children:[ye," active"]}):he?e.jsx("span",{className:"rounded-full border border-strong bg-white/[0.04] px-2 py-0.5 text-micro text-secondary",children:"view modified"}):null]}),e.jsxs("div",{className:"subsection-shell p-2.5",children:[e.jsx("div",{className:"section-kicker mb-2",children:"Layout"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("label",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:"Group"}),e.jsx("select",{value:h,onChange:M=>y(M.target.value),className:"h-9 rounded-lg border border-white/[0.08] bg-black/30 px-2 text-caption text-primary focus:border-[#BFFF00]/40 focus:outline-none",children:xe.map(M=>e.jsx("option",{value:M.value,children:M.label},M.value))})]}),e.jsxs("label",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:"Sort"}),e.jsx("select",{value:m,onChange:M=>S(M.target.value),className:"h-9 rounded-lg border border-white/[0.08] bg-black/30 px-2 text-caption text-primary focus:border-[#BFFF00]/40 focus:outline-none",children:Se.map(M=>e.jsx("option",{value:M.value,children:M.label},M.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"}),D>0&&e.jsx("button",{type:"button",onClick:()=>K(M=>!M),className:"text-micro text-muted transition-colors hover:text-white/72",children:se?"Hide empty":`Show empty (${D})`})]}),e.jsx("div",{className:"max-h-40 space-y-1 overflow-auto pr-1",children:z.map(M=>{const me=n.includes(M.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 ${me?"border-[#BFFF00]/30 bg-[#BFFF00]/10 text-bright":"border-white/[0.08] bg-white/[0.02] text-primary hover:border-white/[0.15]"}`,children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"checkbox",checked:me,onChange:()=>w(M.key),className:"h-3.5 w-3.5 accent-[#BFFF00]"}),e.jsx("span",{children:ei(M.key)})]}),e.jsx("span",{className:"text-micro text-secondary",children:M.count})]},M.key)})}),e.jsxs("div",{className:"mt-2 flex items-center justify-between",children:[e.jsx("button",{type:"button",onClick:()=>g([]),className:`text-micro uppercase tracking-[0.08em] ${H>0?"text-primary hover:text-white":"text-muted"}`,disabled:H===0,children:"Clear status"}),e.jsxs("div",{className:"text-micro text-secondary",children:[H," 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:r,onChange:M=>F(M.target.value),className:"h-9 rounded-lg border border-strong bg-black/30 px-2 text-caption text-white focus:border-[#BFFF00]/40 focus:outline-none",children:ti.map(M=>e.jsx("option",{value:M.value,children:M.label},M.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:c,onChange:M=>_(M.target.value),className:"h-9 rounded-lg border border-strong bg-black/30 px-2 text-caption text-white focus:border-[#BFFF00]/40 focus:outline-none",children:W.map(M=>e.jsx("option",{value:M.value,children:M.label},M.value))})]})]}),c==="custom_range"&&e.jsxs("div",{className:"mt-2 grid grid-cols-2 gap-2",children:[e.jsxs("label",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-secondary",children:"Start"}),e.jsx("input",{type:"date",value:o,onChange:M=>f(M.target.value),className:"h-9 rounded-lg border border-strong bg-black/30 px-2 text-caption text-white focus:border-[#BFFF00]/40 focus:outline-none"})]}),e.jsxs("label",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-secondary",children:"End"}),e.jsx("input",{type:"date",value:d,onChange:M=>$(M.target.value),className:"h-9 rounded-lg border border-strong bg-black/30 px-2 text-caption text-white focus:border-[#BFFF00]/40 focus:outline-none"})]})]})]}),U&&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:[he&&e.jsx("button",{type:"button",onClick:()=>{y("status"),S("default")},className:"text-micro uppercase tracking-[0.09em] text-secondary transition-colors hover:text-bright",children:"Reset layout"}),ne&&e.jsx("button",{type:"button",onClick:L,className:"text-micro uppercase tracking-[0.09em] text-secondary transition-colors hover:text-bright",children:"Clear filters"})]})]})]})})]})}function vt(t){return!t||typeof t!="object"||Array.isArray(t)?null:t}function ue(t){if(typeof t!="string")return null;const s=t.trim();return s.length>0?s:null}function Ee(t){if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"&&t.trim().length>0){const s=Number(t);if(Number.isFinite(s))return s}return null}function ai(t){const s=(ue(t)??"").toLowerCase();return s==="assigned"||s==="inferred"||s==="fallback"?s:null}function os(t){const s=ue(t);if(!s)return null;const n=s.toLowerCase();return n==="undefined"||n==="null"||n==="main"||n==="unassigned"?null:s}function rr(t){return os(t)}function ii(t,s,n){if(!Array.isArray(t)){if(s||n){const o=s??n??"",d=n??s??"";if(o.trim().length>0&&d.trim().length>0)return[{id:o,name:d}]}return[]}const r=[],c=new Set;for(const o of t){const d=vt(o);if(!d)continue;const x=rr(d.id)??os(d.name),h=os(d.name)??x;if(!x||!h)continue;const y=x.toLowerCase();c.has(y)||(c.add(y),r.push({id:x,name:h}))}if(r.length===0&&(s||n)){const o=s??n??"",d=n??s??"";if(o.trim().length>0&&d.trim().length>0)return[{id:o,name:d}]}return r}function Ks(t,s){const n=(ue(t)??"").toLowerCase();return n==="initiative"?"initiative":n==="milestone"?"milestone":n==="task"?"task":n==="workstream"?"workstream":s}function oi(t){return(ue(t)??"").toLowerCase()==="algorithmic"?"algorithmic":"manual"}function Rt(t){return Array.isArray(t)?t.map(s=>ue(s)).filter(s=>!!s):[]}function li(t,s,n){const r=vt(t);if(!r)return null;const c=ue(r.sliceId)??ue(r.id);if(!c)return null;const o=Ks(r.level??r.scope,s),d=ue(r.title)??ue(r.workstreamTitle)??ue(r.milestoneTitle)??ue(r.taskTitle)??ue(r.initiativeTitle)??c,x=vt(r.order),h=vt(r.dispatch),y=vt(r.objectiveSnapshot??r.objective??r.ranking),m=vt(r.factors),S=vt(r.iwmt),I=vt(r.lineage),k=rr(r.runnerAgentId??r.agentId),l=os(r.runnerAgentName??r.agentName)??os(r.runner),v=ii(r.runnerAgents,k,l??k),g=v[0]??null;return{sliceId:c,level:o,title:d,initiativeId:ue(r.initiativeId),initiativeTitle:ue(r.initiativeTitle),workstreamId:ue(r.workstreamId),workstreamTitle:ue(r.workstreamTitle),milestoneId:ue(r.milestoneId),milestoneTitle:ue(r.milestoneTitle),taskId:ue(r.taskId),taskTitle:ue(r.taskTitle),status:ue(r.status)??ue(r.queueState)??(h&&h.runnable===!1?"blocked":"queued"),priorityNum:Ee(r.priorityNum??r.nextTaskPriority),dueAt:ue(r.dueAt??r.nextTaskDueAt),dependencyState:ue(r.dependencyState),objectiveScore:Ee(r.objectiveScore)??Ee(y==null?void 0:y.objectiveScore)??Ee(r.mixScore),roiPerToken:Ee(r.roiPerToken)??Ee(y==null?void 0:y.roiPerToken),expectedTokens:Ee(r.expectedTokens)??Ee(y==null?void 0:y.expectedTokens),expectedValueUsd:Ee(r.expectedValueUsd)??Ee(y==null?void 0:y.expectedValueUsd),goalAlignment:Ee(r.goalAlignment)??Ee(m==null?void 0:m.goalAlignment),riskPenalty:Ee(r.riskPenalty)??Ee(m==null?void 0:m.riskPenalty),runnable:typeof(h==null?void 0:h.runnable)=="boolean"?h.runnable:void 0,blockReason:ue((h==null?void 0:h.blockReason)??r.blockReason),suggestedScope:h&&h.suggestedScope?Ks(h.suggestedScope,o):null,manualRank:Ee(r.manualRank)??Ee(x==null?void 0:x.manualRank),algorithmRank:Ee(r.algorithmRank)??Ee(x==null?void 0:x.algorithmRank)??n,finalRank:Ee(r.finalRank)??Ee(x==null?void 0:x.finalRank)??n,iwmt:S?{laneId:ue(S.laneId),mixScore:Ee(S.mixScore),factors:Array.isArray(S.factors)?S.factors.map(w=>{const F=vt(w);return F?{key:ue(F.key)??void 0,label:ue(F.label)??ue(F.key)??void 0,value:Ee(F.value)??void 0,weight:Ee(F.weight)??void 0}:null}).filter(w=>!!w):void 0}:null,lineage:I?{initiativeIds:Rt(I.initiativeIds),workstreamIds:Rt(I.workstreamIds),milestoneIds:Rt(I.milestoneIds),taskIds:Rt(I.taskIds),iwmtIds:Rt(I.iwmtIds)}:null,sourceWorkstreamIds:Rt(r.sourceWorkstreamIds),queueState:ue(r.queueState),sliceTaskIds:Rt(r.sliceTaskIds),sliceTaskCount:Ee(r.sliceTaskCount),sliceMilestoneId:ue(r.sliceMilestoneId),runnerAgentId:(g==null?void 0:g.id)??k,runnerAgentName:(g==null?void 0:g.name)??l,runnerAgents:v,runnerSource:ai(r.runnerSource)??((g==null?void 0:g.id)??k?"inferred":"fallback"),updatedAt:ue(r.updatedAt)}}function ci(t,s,n,r){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:n,limit:r,total:0,nextCursor:null,hasMore:!1}}}function di(t){const s=t.offset+t.limit,n=s<t.total;return{offset:t.offset,limit:t.limit,total:t.total,nextCursor:n?String(s):null,hasMore:n}}function ui({workspaceId:t=null,initiativeId:s=null,level:n,orderMode:r=null,includeCompleted:c=!1,search:o="",offset:d=0,limit:x=24,cursor:h,authToken:y=null,embedMode:m=!1,enabled:S=!0}){var z,D,W,xe,Se,he,ne,ye,U,M,me,te,fe,Z;const I=vs(),k=Math.max(0,d),l=Math.max(1,Math.min(300,x)),v=o.trim(),[g,w]=a.useState(null),[F,_]=a.useState([]),f=a.useRef({level:n,orderMode:r,normalizedSearch:v,includeCompleted:c,workspaceId:t,initiativeId:s,externalCursor:h});a.useEffect(()=>{const N=f.current;(N.level!==n||N.orderMode!==r||N.normalizedSearch!==v||N.includeCompleted!==c||N.workspaceId!==t||N.initiativeId!==s||N.externalCursor!==h)&&(f.current={level:n,orderMode:r,normalizedSearch:v,includeCompleted:c,workspaceId:t,initiativeId:s,externalCursor:h},w(null),_([]))},[n,r,v,c,t,s,h]);const $=g??h,L=a.useMemo(()=>[...ws.missionControlSlices({workspaceId:t,initiativeId:s,level:n,orderMode:r,includeCompleted:c,search:v,offset:k,limit:l,authToken:y,embedMode:m}),{cursor:$??null}],[y,$,m,c,s,n,l,k,v,r,t]),B=rs({queryKey:L,enabled:S,queryFn:async()=>{if(I)return ci(n,r??"manual",k,l);const N=new URLSearchParams;jn(N,t,{allTokenWhenMissing:!0}),s&&N.set("initiative_id",s),N.set("level",n),N.set("include_completed",c?"1":"0"),$?N.set("cursor",$):N.set("offset",String(k)),N.set("limit",String(l)),N.set("mix_policy","iwmt_v1"),r&&N.set("order_mode",r),v.length>0&&N.set("q",v);const j=await fetch(`/orgx/api/mission-control/slices?${N.toString()}`,{headers:Ft({authToken:y,embedMode:m})}),u=await j.json().catch(()=>null);if(!j.ok){const le=u&&typeof u.error=="string"&&u.error||u&&typeof u.message=="string"&&u.message||`Failed to fetch mission-control slices (${j.status})`;throw new Error(le)}const P=Array.isArray(u==null?void 0:u.items)?u.items:[],ie=Ks((u==null?void 0:u.level)??(u==null?void 0:u.scope),n),ke=P.map((le,Fe)=>li(le,ie,Fe+1)).filter(le=>!!le),be=vt(u==null?void 0:u.pagination),Pe=Ee(u==null?void 0:u.total)??Ee(be==null?void 0:be.total)??ke.length,Ce=be?{offset:Ee(be.offset)??k,limit:Ee(be.limit)??l,total:Pe,nextCursor:ue(be.nextCursor),hasMore:typeof be.hasMore=="boolean"?be.hasMore:!1}:di({offset:k,limit:l,total:Pe});return{ok:!0,generatedAt:ue(u==null?void 0:u.generatedAt)??new Date().toISOString(),workspaceId:ue((u==null?void 0:u.workspaceId)??(u==null?void 0:u.workspace_id)),initiativeId:ue((u==null?void 0:u.initiativeId)??(u==null?void 0:u.initiative_id)??s),level:ie,mixPolicy:ue((u==null?void 0:u.mixPolicy)??(u==null?void 0:u.mix_policy))??"iwmt_v1",orderMode:oi((u==null?void 0:u.orderMode)??(u==null?void 0:u.order_mode)??(u==null?void 0:u.order)),total:Pe,items:ke,degraded:Array.isArray(u==null?void 0:u.degraded)?u.degraded.map(le=>ue(le)).filter(le=>!!le):void 0,source:ue(u==null?void 0:u.source)==="canonical"?"canonical":ue(u==null?void 0:u.source)==="local_fallback"?"local_fallback":"local",pagination:Ce}}}),G=a.useRef(null);a.useEffect(()=>{var P;const N=(P=B.data)==null?void 0:P.pagination;if(!S||!(N!=null&&N.hasMore)||!N.nextCursor||G.current===N.nextCursor)return;const j=Number.parseInt(N.nextCursor,10);if(!Number.isFinite(j))return;G.current=N.nextCursor;const u=new URLSearchParams;jn(u,t,{allTokenWhenMissing:!0}),s&&u.set("initiative_id",s),u.set("level",n),u.set("include_completed",c?"1":"0"),u.set("offset",String(j)),u.set("limit",String(l)),u.set("mix_policy","iwmt_v1"),r&&u.set("order_mode",r),v.length>0&&u.set("q",v),fetch(`/orgx/api/mission-control/slices?${u.toString()}`,{headers:Ft({authToken:y,embedMode:m})}).catch(()=>{})},[S,(D=(z=B.data)==null?void 0:z.pagination)==null?void 0:D.hasMore,(xe=(W=B.data)==null?void 0:W.pagination)==null?void 0:xe.nextCursor,t,s,n,r,c,v,l,y,m]);const se=((he=(Se=B.data)==null?void 0:Se.pagination)==null?void 0:he.nextCursor)??null,K=((ye=(ne=B.data)==null?void 0:ne.pagination)==null?void 0:ye.hasMore)??!1,J=a.useRef(B.data);a.useEffect(()=>{B.data&&B.data!==J.current&&g&&_(N=>{var P;const j=new Set(N.map(ie=>ie.sliceId)),u=(((P=B.data)==null?void 0:P.items)??[]).filter(ie=>!j.has(ie.sliceId));return[...N,...u]}),J.current=B.data},[B.data,g]);const E=a.useCallback(()=>{var j;if(!se||!K)return;const N=((j=B.data)==null?void 0:j.items)??[];_(u=>{if(u.length===0)return N;const P=new Set(u.map(ke=>ke.sliceId)),ie=N.filter(ke=>!P.has(ke.sliceId));return[...u,...ie]}),w(se)},[se,K,(U=B.data)==null?void 0:U.items]),H=F.length>0?(()=>{var u;const N=new Set(F.map(P=>P.sliceId)),j=(((u=B.data)==null?void 0:u.items)??[]).filter(P=>!N.has(P.sliceId));return[...F,...j]})():((M=B.data)==null?void 0:M.items)??[];return{...B,slices:H,orderMode:((me=B.data)==null?void 0:me.orderMode)??r??"manual",degraded:((te=B.data)==null?void 0:te.degraded)??[],source:((fe=B.data)==null?void 0:fe.source)??null,pagination:((Z=B.data)==null?void 0:Z.pagination)??null,nextCursor:se,hasMore:K,fetchNextPage:E}}function Qs(t,s){if(!s||s.trim().length===0)return;const n=s.trim();t.workspace_id=n}async function Ws(t){const s=await t.json().catch(()=>null);if(!t.ok){const n=s&&typeof s.error=="string"&&s.error||s&&typeof s.message=="string"&&s.message||`Request failed (${t.status})`;throw new Error(n)}return s??{}}function mi({workspaceId:t=null,initiativeId:s=null,level:n,authToken:r=null,embedMode:c=!1}){const o=Gn(),d=Mt({mutationFn:async y=>{const m={level:n,order:y.map(I=>({sliceId:I}))};Qs(m,t),s&&(m.initiative_id=s);const S=await fetch("/orgx/api/mission-control/slices/reorder",{method:"POST",headers:Ft({authToken:r,embedMode:c,contentTypeJson:!0,workspaceId:t}),body:JSON.stringify(m)});return Ws(S)},onMutate:async y=>{const m=o.getQueriesData({queryKey:["mission-control-slices"]});for(const[S,I]of m){if(!I||I.level!==n||s&&I.initiativeId&&I.initiativeId!==s)continue;const k=new Map(I.items.map(g=>[g.sliceId,g])),l=y.map(g=>k.get(g)??null).filter(g=>!!g);if(l.length===0)continue;const v=new Set(l.map(g=>g.sliceId));for(const g of I.items)v.has(g.sliceId)||l.push(g);o.setQueryData(S,{...I,items:l.map((g,w)=>({...g,manualRank:w+1,finalRank:w+1})),orderMode:"manual"})}return{snapshots:m}},onError:(y,m,S)=>{for(const[I,k]of(S==null?void 0:S.snapshots)??[])o.setQueryData(I,k)},onSettled:()=>{o.invalidateQueries({queryKey:["mission-control-slices"]})}}),x=Mt({mutationFn:async y=>{const m={level:n,order_mode:y};Qs(m,t),s&&(m.initiative_id=s);const S=await fetch("/orgx/api/mission-control/slices/order-mode",{method:"POST",headers:Ft({authToken:r,embedMode:c,contentTypeJson:!0,workspaceId:t}),body:JSON.stringify(m)});return Ws(S)},onMutate:async y=>{const m=o.getQueriesData({queryKey:["mission-control-slices"]});for(const[S,I]of m)!I||I.level!==n||s&&I.initiativeId&&I.initiativeId!==s||o.setQueryData(S,{...I,orderMode:y});return{snapshots:m}},onError:(y,m,S)=>{for(const[I,k]of(S==null?void 0:S.snapshots)??[])o.setQueryData(I,k)},onSettled:()=>{o.invalidateQueries({queryKey:["mission-control-slices"]})}}),h=Mt({mutationFn:async y=>{const m=o.getQueriesData({queryKey:["mission-control-slices"]});let S=null;for(const[,l]of m){if(!l||l.level!==n||s&&l.initiativeId&&l.initiativeId!==s)continue;const v=l.items.map(w=>w.sliceId);if(!(v.indexOf(y)<=0)){S=[y,...v.filter(w=>w!==y)];break}}if(!S)throw new Error("Item not found in current slice data");const I={level:n,order:S.map(l=>({sliceId:l}))};Qs(I,t),s&&(I.initiative_id=s);const k=await fetch("/orgx/api/mission-control/slices/reorder",{method:"POST",headers:Ft({authToken:r,embedMode:c,contentTypeJson:!0,workspaceId:t}),body:JSON.stringify(I)});return Ws(k)},onMutate:async y=>{const m=o.getQueriesData({queryKey:["mission-control-slices"]});for(const[S,I]of m){if(!I||I.level!==n||s&&I.initiativeId&&I.initiativeId!==s)continue;const k=I.items.findIndex(g=>g.sliceId===y);if(k<=0)continue;const l=[...I.items],[v]=l.splice(k,1);l.unshift(v),o.setQueryData(S,{...I,items:l.map((g,w)=>({...g,manualRank:w+1,finalRank:w+1})),orderMode:"manual"})}return{snapshots:m}},onError:(y,m,S)=>{for(const[I,k]of(S==null?void 0:S.snapshots)??[])o.setQueryData(I,k)},onSettled:()=>{o.invalidateQueries({queryKey:["mission-control-slices"]})}});return{reorder:d.mutateAsync,setOrderMode:x.mutateAsync,pin:async y=>{try{return await h.mutateAsync(y),!0}catch{return!1}},isReordering:d.isPending,isPinning:h.isPending,isSettingOrderMode:x.isPending,error:(d.error instanceof Error?d.error.message:null)??(h.error instanceof Error?h.error.message:null)??(x.error instanceof Error?x.error.message:null)}}const Gs=[{value:"initiative",label:"Initiative"},{value:"workstream",label:"Workstream"},{value:"milestone",label:"Milestone"},{value:"task",label:"Task"}];function _n(t){var s;return((s=Gs.find(n=>n.value===t))==null?void 0:s.label)??"Workstream"}function Ln(t){const s=t.trim().toLowerCase();return s==="running"||s==="active"||s==="in_progress"?"border-teal-300/28 bg-teal-400/[0.09] text-teal-100/90":s==="blocked"||s==="failed"||s==="error"?"border-red-400/26 bg-red-500/[0.08] text-red-100/90":s==="completed"||s==="done"||s==="resolved"?"border-strong bg-white/[0.05] text-secondary":"border-[#BFFF00]/24 bg-[#BFFF00]/[0.08] text-[#E8FFD0]/92"}function Bn(t){const s=t.trim().toLowerCase();return s==="running"||s==="active"||s==="in_progress"?"from-teal-300/0 via-teal-300/65 to-teal-300/0":s==="blocked"||s==="failed"||s==="error"?"from-red-300/0 via-red-300/65 to-red-300/0":s==="completed"||s==="done"||s==="resolved"?"from-white/0 via-white/45 to-white/0":"from-[#BFFF00]/0 via-[#BFFF00]/70 to-[#BFFF00]/0"}function Gt(t,s=2){return typeof t!="number"||!Number.isFinite(t)?"—":t.toFixed(s)}function ns(t,s){if(!t)return s;const n=t.trim();return n?Xs(n)?`${s} ${Zn(n)}`:n:s}function Pn(t){var n,r,c,o;const s=t.title.trim()||((n=t.taskTitle)==null?void 0:n.trim())||((r=t.milestoneTitle)==null?void 0:r.trim())||((c=t.workstreamTitle)==null?void 0:c.trim())||((o=t.initiativeTitle)==null?void 0:o.trim())||"";return s&&!Xs(s)?Yt(s):t.level==="task"?ns(t.taskId??t.sliceId,"Task"):t.level==="milestone"?ns(t.milestoneId??t.sliceId,"Milestone"):t.level==="initiative"?ns(t.initiativeId??t.sliceId,"Initiative"):ns(t.workstreamId??t.sliceId,"Workstream")}function Rn(t){const s=[t.initiativeTitle,t.workstreamTitle,t.milestoneTitle,t.taskTitle].filter(r=>!!(r&&r.trim().length>0));return s.length===0?Yt(ns(t.sliceId,"Slice")):s.map(r=>Yt(r)).filter(r=>r.length>0).join(" / ")}function qn(t){var c,o;const s=((c=t.runnerAgentName)==null?void 0:c.trim())??"",n=((o=t.runnerAgentId)==null?void 0:o.trim().toLowerCase())??"";if(!s)return n&&n!=="main"?Yt(n):"Unassigned";const r=s.toLowerCase();return r==="undefined"||r==="null"||r==="main"&&(n==="main"||t.runnerSource==="fallback")?"Unassigned":Yt(s)}function On(t){const s=typeof t.sliceTaskCount=="number"&&Number.isFinite(t.sliceTaskCount)?Math.max(0,Math.floor(t.sliceTaskCount)):0;return s<=0?"No task":s===1?"1 task":`${s} tasks`}function zn(t,s){return!t||t.trim().length===0?s:pt(t.trim())||s}function Un({workspaceId:t=null,initiativeId:s=null,authToken:n=null,embedMode:r=!1,className:c="",title:o="Slice Explorer",compact:d=!1,onOpenInitiative:x}){var Z,N;const[h,y]=a.useState("workstream"),[m,S]=a.useState(""),[I,k]=a.useState(0),[l]=a.useState(d?18:28),[v,g]=a.useState(null),[w,F]=a.useState([]),[_,f]=a.useState(!1),[$,L]=a.useState(null),[B,G]=a.useState(!1),se=a.useRef(null),K=ui({workspaceId:t,initiativeId:s,level:h,orderMode:$,includeCompleted:!1,search:m,offset:I,limit:l,authToken:n,embedMode:r,enabled:!!(t||s)}),J=mi({workspaceId:t,initiativeId:s,level:h,authToken:n,embedMode:r}),E=K.slices,H=K.source,z=K.pagination,D=K.orderMode??"manual",W=(z==null?void 0:z.offset)??I,xe=(z==null?void 0:z.total)??((Z=K.data)==null?void 0:Z.total)??E.length,Se=E.length===0?0:W+1,he=E.length===0?0:W+E.length;a.useEffect(()=>{if(!v)return;const j=window.setTimeout(()=>g(null),5e3);return()=>window.clearTimeout(j)},[v]),a.useEffect(()=>{if(!B)return;const j=P=>{var ke;const ie=P.target;ie&&((ke=se.current)!=null&&ke.contains(ie)||G(!1))},u=P=>{P.key==="Escape"&&G(!1)};return document.addEventListener("mousedown",j),document.addEventListener("touchstart",j),document.addEventListener("keydown",u),()=>{document.removeEventListener("mousedown",j),document.removeEventListener("touchstart",j),document.removeEventListener("keydown",u)}},[B]),a.useEffect(()=>{k(0)},[h,m]);const ne=a.useMemo(()=>E.map(j=>j.sliceId).join("|"),[E]);a.useEffect(()=>{F(E.map(j=>j.sliceId)),f(!1)},[ne,D]);const ye=a.useMemo(()=>new Map(E.map(j=>[j.sliceId,j])),[E]),U=a.useMemo(()=>{if(!_||w.length!==E.length)return E;const j=w.map(u=>ye.get(u)??null).filter(u=>!!u);return j.length!==E.length?E:j},[_,w,E,ye]),M=D==="manual"&&E.length>1&&!J.isReordering&&W===0&&!((z==null?void 0:z.hasMore)??!1),me=async()=>{if(!(!M||!_))try{await J.reorder(w),f(!1),g({tone:"success",message:`Saved ${w.length} slice positions.`})}catch(j){g({tone:"error",message:zn(j instanceof Error?j.message:"","Failed to save slice order.")})}},te=async j=>{if(!(j===D&&$===null)){L(j);try{await J.setOrderMode(j),g({tone:"success",message:`Slice ordering set to ${j}.`})}catch(u){g({tone:"error",message:zn(u instanceof Error?u.message:"",`Failed to set ${j} ordering.`)})}finally{L(null)}}},fe=j=>{!x||!j.initiativeId||x(j.initiativeId,j.initiativeTitle??void 0)};return e.jsxs("section",{className:Kt("flex min-h-0 flex-col rounded-2xl border border-strong bg-[#070b12]/88",c),children:[e.jsxs("div",{className:"flex flex-col gap-2 border-b border-strong px-3 py-3",children:[e.jsxs("div",{className:"flex min-h-[34px] items-center gap-2",children:[e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-[#BFFF00]/70"}),e.jsx("h3",{className:"text-caption font-semibold uppercase tracking-[0.1em] text-secondary",children:o}),e.jsx("span",{className:"rounded-full border border-strong bg-white/[0.04] px-2 py-0.5 text-micro text-secondary",children:xe}),e.jsxs("div",{className:"ml-auto flex items-center gap-1.5",children:[e.jsxs("div",{ref:se,className:"relative",children:[e.jsxs("button",{type:"button",onClick:()=>G(j=>!j),className:"control-pill h-8 px-2.5 text-micro font-semibold","aria-haspopup":"menu","aria-expanded":B,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"})]}),B?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:Gs.map(j=>e.jsxs("button",{type:"button",onClick:()=>{y(j.value),G(!1)},className:Kt("control-pill flex h-8 items-center gap-1.5 px-2 text-micro font-semibold",h===j.value?"border-[#BFFF00]/34 bg-[#BFFF00]/[0.12] text-[#E8FFD0]":"text-secondary"),children:[e.jsx(tt,{type:j.value,size:10,className:"opacity-80"}),e.jsx("span",{children:j.label})]},j.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:Kt("control-pill h-8 px-2.5 text-micro font-semibold",D==="manual"?"border-[#BFFF00]/34 bg-[#BFFF00]/[0.12] text-[#E8FFD0]":"text-secondary"),disabled:J.isSettingOrderMode,onClick:()=>void te("manual"),children:"Manual"}),e.jsx("button",{type:"button",className:Kt("control-pill h-8 px-2.5 text-micro font-semibold",D==="algorithmic"?"border-teal-300/34 bg-teal-400/[0.13] text-teal-100":"text-secondary"),disabled:J.isSettingOrderMode,onClick:()=>void te("algorithmic"),children:"Algorithmic"})]})]})]})}):null]}),D==="manual"&&e.jsx("button",{type:"button",className:"control-pill h-8 px-2.5 text-micro font-semibold disabled:opacity-45",disabled:!_||!M,onClick:()=>void me(),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(Zs,{value:m,onChange:S,placeholder:"Search slices, entities, or IDs..."})}),e.jsx("span",{className:"chip whitespace-nowrap text-micro",children:((N=Gs.find(j=>j.value===h))==null?void 0:N.label)??"Workstream"})]}),(H==="local_fallback"||K.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:H==="local_fallback"?"Canonical slices unavailable; showing local fallback.":K.degraded[0]})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-2 pb-2 pt-2",children:K.isLoading?e.jsx("div",{className:"space-y-2 px-1",children:Array.from({length:d?4:7}).map((j,u)=>e.jsxs("div",{className:"rounded-xl border border-strong bg-white/[0.02] px-3 py-2",children:[e.jsx(jt,{className:"h-3.5 w-1/2 rounded-full"}),e.jsx(jt,{className:"mt-2 h-3 w-4/5 rounded-full"})]},`slice-loading-${u}`))}):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."}):M?e.jsx(zr,{axis:"y",values:w,onReorder:j=>{F(j),f(!0)},className:"space-y-2",children:w.map((j,u)=>{var ze;const P=ye.get(j);if(!P)return null;const ie=P.finalRank??P.manualRank??P.algorithmRank??u+1,be=(((ze=P.iwmt)==null?void 0:ze.factors)??[]).filter(Re=>typeof Re.value=="number"&&Number.isFinite(Re.value)),Pe=typeof P.roiPerToken=="number"&&Number.isFinite(P.roiPerToken),Ce=typeof P.objectiveScore=="number"&&Number.isFinite(P.objectiveScore),le=qn(P),Fe=Rn(P);return e.jsxs(Ur,{value:P.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 ${Bn(P.status)}`,"aria-hidden":!0}),e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("button",{type:"button",className:"mt-0.5 inline-flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-md border border-strong bg-white/[0.04] text-caption text-secondary","aria-label":"Drag to reorder",title:"Drag to reorder",children:"⋮⋮"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsxs("span",{className:"rounded-md border border-[#BFFF00]/22 bg-[#BFFF00]/[0.08] px-1.5 py-0.5 text-micro font-semibold text-[#DFFFB5]",children:["#",ie]}),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(tt,{type:P.level,size:11,className:"mt-0.5 flex-shrink-0 opacity-80"}),e.jsx("p",{className:"min-w-0 flex-1 line-clamp-2 text-caption font-semibold leading-snug text-primary",children:Pn(P)})]})}),e.jsxs("div",{className:"ml-auto flex flex-shrink-0 items-center gap-1.5",children:[e.jsx("span",{className:Kt("rounded-full border px-2 py-0.5 text-micro uppercase tracking-[0.08em]",Ln(P.status)),children:P.status.replace(/_/g," ")}),P.initiativeId&&x?e.jsx("button",{type:"button",className:"control-pill h-6 px-2 text-micro font-semibold",onClick:()=>fe(P),children:"Open"}):null]})]}),e.jsx("p",{className:"mt-1 inline-flex min-w-0 items-center gap-1 truncate text-micro text-secondary",title:Fe,children:e.jsx("span",{className:"truncate",children:Fe})}),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:_n(P.level)}),e.jsx("span",{className:"chip text-micro",children:On(P)}),e.jsxs("span",{className:"chip text-micro",children:["Agent ",le]}),Pe?e.jsxs("span",{className:"chip text-micro",children:["ROI/token ",Gt(P.roiPerToken,3)]}):null,Ce?e.jsxs("span",{className:"chip text-micro",children:["Obj ",Gt(P.objectiveScore,2)]}):null]}),be.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:be.slice(0,3).map((Re,qe)=>e.jsxs("p",{children:[(Re.label??Re.key??"factor").replace(/_/g," "),":"," ",Gt(Re.value,2)]},`${P.sliceId}-factor-${qe}`))})]})]})]})]},P.sliceId)})}):e.jsx("div",{className:"space-y-2",children:U.map((j,u)=>{var Fe;const P=j.finalRank??j.manualRank??j.algorithmRank??u+1,ke=(((Fe=j.iwmt)==null?void 0:Fe.factors)??[]).filter(ze=>typeof ze.value=="number"&&Number.isFinite(ze.value)),be=typeof j.roiPerToken=="number"&&Number.isFinite(j.roiPerToken),Pe=typeof j.objectiveScore=="number"&&Number.isFinite(j.objectiveScore),Ce=qn(j),le=Rn(j);return e.jsxs(je.article,{initial:{opacity:0,y:10,scale:.985},animate:{opacity:1,y:0,scale:1},transition:{duration:.22,delay:Math.min(u,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 ${Bn(j.status)}`,"aria-hidden":!0}),e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsxs("span",{className:"rounded-md border border-[#BFFF00]/22 bg-[#BFFF00]/[0.08] px-1.5 py-0.5 text-micro font-semibold text-[#DFFFB5]",children:["#",P]}),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(tt,{type:j.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:Pn(j)})]}),e.jsx("p",{className:"mt-1 inline-flex min-w-0 items-center gap-1 truncate text-micro text-secondary",title:le,children:e.jsx("span",{className:"truncate",children:le})}),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:_n(j.level)}),e.jsx("span",{className:"chip text-micro",children:On(j)}),e.jsxs("span",{className:"chip text-micro",children:["Agent ",Ce]}),be?e.jsxs("span",{className:"chip text-micro",children:["ROI/token ",Gt(j.roiPerToken,3)]}):null,Pe?e.jsxs("span",{className:"chip text-micro",children:["Obj ",Gt(j.objectiveScore,2)]}):null,e.jsx("span",{className:Kt("rounded-full border px-2 py-0.5 uppercase tracking-[0.08em]",Ln(j.status)),children:j.status.replace(/_/g," ")})]}),ke.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:ke.slice(0,3).map((ze,Re)=>e.jsxs("p",{children:[(ze.label??ze.key??"factor").replace(/_/g," "),":"," ",Gt(ze.value,2)]},`${j.sliceId}-factor-static-${Re}`))})]})]}),j.initiativeId&&x?e.jsx("button",{type:"button",className:"control-pill h-7 px-2 text-micro font-semibold",onClick:()=>fe(j),children:"Open"}):null]})]},j.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:[Se,"-",he," of ",xe]}),e.jsx("button",{type:"button",className:"control-pill ml-auto h-7 px-2 text-micro font-semibold disabled:opacity-40",disabled:W===0,onClick:()=>k(Math.max(0,W-l)),children:"Prev"}),e.jsx("button",{type:"button",className:"control-pill h-7 px-2 text-micro font-semibold disabled:opacity-40",disabled:!((z==null?void 0:z.hasMore)??!1),onClick:()=>k(W+l),children:"Next"})]}),v&&e.jsx("div",{className:"border-t border-strong px-3 py-2",children:e.jsx(Jn,{open:!0,tone:v.tone==="error"?"error":"success",title:v.tone==="error"?"Slice explorer error":"Slice explorer updated",message:v.message,onDismiss:()=>g(null),autoDismissMs:4200})})]})}function Hs(t){return(t??"").trim().toLowerCase().replace(/[\s-]+/g,"_")}function Js(t){return new Date(t.getFullYear(),t.getMonth(),t.getDate()).getTime()}function Qn(t){if(!t)return null;const s=Date.parse(`${t}T00:00:00`);return Number.isFinite(s)?s:null}function pi(t,s){return s==="target"?t.targetDate??null:s==="created"?t.createdAt??null:t.updatedAt??t.createdAt??null}function Wn(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 Hn(t){return t==="active"?0:t==="blocked"?1:t==="paused"?2:3}function Vn(t,s){if(s==="status"){const n=new Map,r=["active","blocked","paused","completed"];for(const c of t){const o=c.status??"active",d=n.get(o)??[];d.push(c),n.set(o,d)}return r.filter(c=>n.has(c)).concat(Array.from(n.keys()).filter(c=>!r.includes(c))).map(c=>{var o;return{key:c,label:c.charAt(0).toUpperCase()+c.slice(1),count:((o=n.get(c))==null?void 0:o.length)??0,initiatives:n.get(c)??[]}})}if(s==="category"){const n=new Map;for(const r of t){const c=r.category??"Uncategorized",o=n.get(c)??[];o.push(r),n.set(c,o)}return Array.from(n.entries()).sort((r,c)=>r[0].localeCompare(c[0])).map(([r,c])=>({key:r,label:r,count:c.length,initiatives:c}))}if(s==="date"){const r=Js(new Date),c=r+7*864e5,o=r+30*864e5,d={overdue:[],this_week:[],this_month:[],later:[],no_date:[]};for(const h of t){const y=h.targetDate?Date.parse(h.targetDate):null;y===null||!Number.isFinite(y)?d.no_date.push(h):y<r?d.overdue.push(h):y<c?d.this_week.push(h):y<o?d.this_month.push(h):d.later.push(h)}const x={overdue:"Overdue",this_week:"This Week",this_month:"This Month",later:"Later",no_date:"No Date"};return["overdue","this_week","this_month","later","no_date"].filter(h=>d[h].length>0).map(h=>({key:h,label:x[h],count:d[h].length,initiatives:d[h]}))}return[]}function qt(t,s){return`${t}:${s}`}function xi(t){return`mc-group-${t}`.toLowerCase().replace(/[^a-z0-9_-]+/g,"-")}function Kn(t,s){if(t.size!==s.size)return!1;for(const n of t)if(!s.has(n))return!1;return!0}function hi(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 fi(t){return t==="running"?"border-teal-300/24 bg-teal-400/[0.08] text-teal-100/90":t==="blocked"?"border-red-400/24 bg-red-500/[0.08] text-red-100/90":t==="queued"||t==="startable"?"border-[#BFFF00]/18 bg-[#BFFF00]/[0.06] text-[#E8FFD0]/95":t==="completed"?"border-strong bg-white/[0.05] text-secondary":"border-strong bg-white/[0.04] text-white/68"}function gi(t){const s=t.trim().toLowerCase();if(s.includes("timed out")||s.includes("timeout")||s.includes("request cancelled")||s.includes("signal is aborted"))return"Live sync is taking longer than expected. Initiatives and Next Up will repopulate as soon as sync completes.";if(s.includes("unauthorized")||s.includes("forbidden")||s.includes("api key")||s.includes("auth"))return"OrgX authentication needs attention. Reconnect your API key in Settings.";if(s.includes("unknown api endpoint")||s.includes("missing required live routes"))return"This runtime is missing required live routes. Restart and update the plugin build.";const n=t.split("|").map(r=>r.trim()).filter(Boolean).map(r=>r.replace(/^[^:]+:\s*/,"").trim()).filter(Boolean).slice(0,2).join(" ");return pt(n||t)||"Live data is temporarily unavailable."}function Jt(t,s){return!t||t.trim().length===0?s:pt(t.trim())||s}const bi=[12,24,36,48,72];function Ei({initiatives:t,activities:s,agents:n,runtimeInstances:r=[],workspaceInitiativeId:c=null,isLoading:o,authToken:d,embedMode:x,initialInitiativeId:h,connection:y,lastSnapshotAt:m,error:S,hasApiKey:I,onOpenSettings:k,onRefresh:l,onCreateInitiative:v,onPlayNextUp:g,onStartAutopilot:w,nextUpQueueModel:F,nextUpActionsModel:_,snapshotVersion:f=null}){const $=Kr({activities:s,agents:n,initiatives:t});return e.jsx(oa,{agentEntityMap:$,authToken:d,embedMode:x,children:e.jsx(vi,{initiatives:t,runtimeInstances:r,workspaceInitiativeId:c,isLoading:o,initialInitiativeId:h,connection:y,lastSnapshotAt:m,error:S,hasApiKey:I,onOpenSettings:k,onRefresh:l,onCreateInitiative:v,onPlayNextUp:g,onStartAutopilot:w,nextUpQueueModel:F,nextUpActionsModel:_,snapshotVersion:f})})}function yi(t){if(!t)return"unknown";const s=Date.parse(t);if(!Number.isFinite(s))return"unknown";try{return new Date(s).toLocaleString()}catch{return"unknown"}}function wi(t,s){var n,r;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:(n=t.avatars)!=null&&n.length?t.avatars:s.avatars,workstreams:(r=t.workstreams)!=null&&r.length?t.workstreams:s.workstreams,health:t.health>0?t.health:s.health}}function vi({initiatives:t,runtimeInstances:s,workspaceInitiativeId:n=null,isLoading:r,initialInitiativeId:c,connection:o,lastSnapshotAt:d,error:x,hasApiKey:h,onOpenSettings:y,onRefresh:m,onCreateInitiative:S,onPlayNextUp:I,onStartAutopilot:k,nextUpQueueModel:l,nextUpActionsModel:v,snapshotVersion:g=null}){var xn,hn,fn,gn,bn;const{searchQuery:w,setSearchQuery:F,statusFilters:_,setStatusFilters:f,dateField:$,setDateField:L,datePreset:B,setDatePreset:G,dateStart:se,setDateStart:K,dateEnd:J,setDateEnd:E,clearFilters:H,hasActiveFilters:z,groupBy:D,sortBy:W,expandedInitiatives:xe,expandAll:Se,collapseAll:he,modalTarget:ne,closeModal:ye,expandInitiative:U,authToken:M,embedMode:me,mutations:te}=Tt(),fe=a.useRef(!1),Z=a.useRef(null),N=a.useRef(0),[j,u]=a.useState(0),[P,ie]=a.useState(new Set),[ke,be]=a.useState(!1),[Pe,Ce]=a.useState(!1),[le,Fe]=a.useState(!1),[ze,Re]=a.useState(!1),[qe,gt]=a.useState("next-up"),[$t,Ie]=a.useState(null),[at,Ge]=a.useState(null),[Le,ot]=a.useState(new Set),[Nt,Ye]=a.useState(!1),[Qe,We]=a.useState(null),[zt,Je]=a.useState(0),[Xe,Xt]=a.useState(24),It=w.trim(),xt=na(It,It.length>=2,n),_t=a.useMemo(()=>{var T;if(It.length<2||!((T=xt.data)!=null&&T.length))return t;const p=new Map;for(const R of t)p.set(R.id,R);for(const R of xt.data){const Y=p.get(R.id);p.set(R.id,Y?wi(Y,R):R)}return Array.from(p.values())},[xt.data,t,It.length]),bt=a.useMemo(()=>new Set((xt.data??[]).map(p=>p.id)),[xt.data]);a.useEffect(()=>{if(!Qe)return;const p=Qe.tone==="success"?6500:9e3,T=window.setTimeout(()=>We(null),p);return()=>window.clearTimeout(T)},[Qe==null?void 0:Qe.message,Qe==null?void 0:Qe.tone]);const St=a.useMemo(()=>{const T=Js(new Date),R=w.toLowerCase().trim().split(/\s+/).filter(Boolean);return _t.filter(Y=>{if(_.length>0&&![Hs(Y.status),Hs(Y.rawStatus)].filter(Boolean).some(ut=>_.includes(ut)))return!1;const ve=pi(Y,$),Oe=ve?Date.parse(ve):Number.NaN,He=Number.isFinite(Oe)?Js(new Date(Oe)):null,ce=He===null?null:Math.round((He-T)/864e5);if(B==="missing"&&He!==null||B==="overdue"&&!(ce!==null&&ce<0)||B==="today"&&ce!==0||B==="next_7_days"&&!(ce!==null&&ce>=0&&ce<=7)||B==="next_30_days"&&!(ce!==null&&ce>=0&&ce<=30)||B==="past_7_days"&&!(ce!==null&&ce<=0&&ce>=-7)||B==="past_30_days"&&!(ce!==null&&ce<=0&&ce>=-30))return!1;if(B==="custom_range"){const wt=Qn(se),ut=Qn(J);if(He===null||wt!==null&&He<wt||ut!==null&&He>ut)return!1}if(R.length===0||bt.has(Y.id))return!0;const Dt=[Y.name,Y.description??"",Y.status,Y.rawStatus??"",Y.category??""].join(" ").toLowerCase();return R.every(wt=>Dt.includes(wt))})},[_t,w,bt,_,$,B,se,J]),Ne=a.useMemo(()=>{const p=(T,R,Y)=>{const ve=T.targetDate?Date.parse(T.targetDate):Number.NaN,Oe=R.targetDate?Date.parse(R.targetDate):Number.NaN,He=Number.isFinite(ve),ce=Number.isFinite(Oe);return!He&&!ce?0:He?ce?Y==="asc"?ve-Oe:Oe-ve:-1:1};return[...St].sort((T,R)=>{if(W==="date_asc")return p(T,R,"asc");if(W==="date_desc")return p(T,R,"desc");const Y=Wn(T.priority),ve=Wn(R.priority);if(W==="priority_high"&&Y!==ve)return Y-ve;if(W==="priority_low"&&Y!==ve)return ve-Y;if(W==="default"){const ce=Hn(T.status)-Hn(R.status);if(ce!==0)return ce;if(Y!==ve)return Y-ve}const Oe=T.updatedAt?Date.parse(T.updatedAt):0,He=R.updatedAt?Date.parse(R.updatedAt):0;return Oe!==He?He-Oe:T.name.localeCompare(R.name)})},[St,W]),lt=Ne.length,st=Math.max(1,Math.ceil(lt/Xe)),it=lt===0?0:Math.min(zt,st-1),yt=it*Xe,i=Math.min(lt,yt+Xe),A=lt===0?0:yt+1,C=lt===0?0:i,q=a.useMemo(()=>Ne.slice(yt,i),[i,yt,Ne]),re=a.useMemo(()=>new Set(Ne.map(p=>p.id)),[Ne]),pe=a.useMemo(()=>Ne.filter(p=>Le.has(p.id)),[Le,Ne]),we=a.useMemo(()=>q.filter(p=>Le.has(p.id)),[q,Le]),Te=pe.length,Ue=we.length,de=q.length>0&&Ue===q.length,De=te.bulkEntityMutation.isPending,Me=a.useMemo(()=>{var R;const p=new Map;for(const Y of s){const ve=(R=Y.initiativeId)==null?void 0:R.trim();if(!ve)continue;const Oe=p.get(ve)??{activeCount:0,totalCount:0,lastHeartbeatAt:null,lastHeartbeatMs:0};Oe.totalCount+=1,Y.state==="active"&&(Oe.activeCount+=1);const He=Y.lastHeartbeatAt??Y.lastEventAt??null,ce=He?Date.parse(He):Number.NaN;Number.isFinite(ce)&&ce>Oe.lastHeartbeatMs&&(Oe.lastHeartbeatMs=ce,Oe.lastHeartbeatAt=new Date(ce).toISOString()),p.set(ve,Oe)}const T=new Map;for(const[Y,ve]of p.entries())T.set(Y,{activeCount:ve.activeCount,totalCount:ve.totalCount,lastHeartbeatAt:ve.lastHeartbeatAt});return T},[s]),Ae=a.useMemo(()=>D!=="none"?Vn(q,D):null,[D,q]),ct=a.useMemo(()=>(Ae==null?void 0:Ae.map(p=>qt(D,p.key)))??[],[D,Ae]),ht=a.useMemo(()=>{if(!Ae)return q.map(T=>T.id);const p=[];for(const T of Ae){const R=qt(D,T.key);if(P.has(R))for(const Y of T.initiatives)p.push(Y.id)}return p},[P,D,Ae,q]),{handleSelect:Ve}=sr(ht),V=a.useCallback(p=>{ie(T=>{const R=new Set(T);return R.has(p)?R.delete(p):R.add(p),R})},[]);a.useEffect(()=>{if(!Ae||Ae.length===0){ie(T=>T.size===0?T:new Set);return}const p=new Set(Ae.map(T=>qt(D,T.key)));ie(T=>{const R=new Set(Array.from(T).filter(Y=>p.has(Y)));return R.size===0&&R.add(qt(D,Ae[0].key)),Kn(R,T)?T:R})},[D,Ae]),a.useEffect(()=>{ot(p=>{if(p.size===0)return p;const T=new Set(Array.from(p).filter(R=>re.has(R)));return Kn(T,p)?p:T})},[re]),a.useEffect(()=>{if(c&&!fe.current&&!r&&t.length>0){const p=Ne.findIndex(T=>T.id===c);if(p>=0&&Je(Math.floor(p/Xe)),U(c),Ae){const T=Ae.find(R=>R.initiatives.some(Y=>Y.id===c));if(T){const R=qt(D,T.key);ie(Y=>{if(Y.has(R))return Y;const ve=new Set(Y);return ve.add(R),ve})}}fe.current=!0,requestAnimationFrame(()=>{const T=document.getElementById(`initiative-${c}`);T==null||T.scrollIntoView({behavior:"smooth",block:"start"})})}},[c,r,t.length,U,Xe,D,Ae,Ne]),a.useEffect(()=>{Te===0&&Nt&&Ye(!1)},[Nt,Te]),a.useEffect(()=>{Je(p=>Math.min(p,Math.max(st-1,0)))},[st]),a.useEffect(()=>{Je(0)},[w,_,$,B,se,J,D,W,Xe]);const b=q.length>0&&q.every(p=>xe.has(p.id)),O=a.useMemo(()=>Ne.find(p=>p.status!=="completed")??Ne[0]??null,[Ne]),$e=Rr({projectId:n,authToken:M,embedMode:me,enabled:l?!1:t.length>0,snapshotVersion:g}),ge=l??$e,Ze=ls({authToken:M,embedMode:me}),Ke=v??Ze,oe=ge.items[0]??null,Q=a.useMemo(()=>ge.items.find(p=>p.playbackState==="running"||p.playbackState==="blocked")??ge.items.find(p=>p.queueState==="running"||p.queueState==="blocked")??null,[ge.items]),_e=a.useMemo(()=>ge.items.find(p=>Q&&p.initiativeId===Q.initiativeId&&p.workstreamId===Q.workstreamId?!1:p.playbackState==="queued"||p.playbackState==="idle"||p.queueState==="queued"||p.queueState==="idle")??null,[ge.items,Q]),X=a.useMemo(()=>oe?t.find(p=>p.id===oe.initiativeId)??O:O,[O,t,oe]),Ct=Q??_e??oe??null,ft=(Ct==null?void 0:Ct.initiativeId)??(X==null?void 0:X.id)??null,Zt=a.useMemo(()=>new Set(ge.items.map(p=>p.initiativeId)),[ge.items]),tn=a.useCallback((p,T,R)=>{We(null),Ye(!1),Ve(p,T,R,ot)},[Ve]),ar=a.useCallback(()=>{We(null),Ye(!1),ot(p=>{if(q.length===0)return p;const T=new Set(p);if(de)for(const R of q)T.delete(R.id);else for(const R of q)T.add(R.id);return T})},[de,q]),ir=a.useCallback(()=>{Ye(!1),ot(new Set)},[]),sn=it>0,nn=it<st-1,At=a.useCallback(p=>{Je(Math.max(0,Math.min(p,st-1)))},[st]),or=a.useCallback(()=>{At(0)},[At]),lr=a.useCallback(()=>{At(it-1)},[it,At]),cr=a.useCallback(()=>{At(it+1)},[it,At]),dr=a.useCallback(()=>{At(st-1)},[At,st]),cs=a.useCallback(async p=>{if(pe.length!==0){Ye(!1),We(null);try{const T=await te.bulkEntityMutation.mutateAsync({items:pe.map(R=>({type:"initiative",id:R.id})),mode:"update",updates:{status:p}});T.failed>0?We({tone:"error",message:`Updated ${T.updated}, failed ${T.failed}.`}):We({tone:"success",message:`Updated ${T.updated} initiative${T.updated===1?"":"s"} to ${p}.`})}catch(T){We({tone:"error",message:Jt(T instanceof Error?T.message:"","Bulk initiative update failed.")})}}},[te.bulkEntityMutation,pe]),ur=a.useCallback(async()=>{if(pe.length!==0){We(null);try{const p=await te.bulkEntityMutation.mutateAsync({items:pe.map(T=>({type:"initiative",id:T.id})),mode:"delete"});p.failed>0?We({tone:"error",message:`Deleted ${p.updated}, failed ${p.failed}.`}):(We({tone:"success",message:`Deleted ${p.updated} initiative${p.updated===1?"":"s"}.`}),ot(new Set),Ye(!1))}catch(p){We({tone:"error",message:Jt(p instanceof Error?p.message:"","Bulk initiative delete failed.")})}}},[te.bulkEntityMutation,pe]),Fs=a.useCallback(()=>{N.current+=1,be(!1)},[]),mr=a.useCallback(p=>{if(p.length===0){Fs();return}const T=1,R=N.current+1;N.current=R,be(!0);const Y=ve=>{if(N.current===R){if(Se(p.slice(0,ve)),ve>=p.length){be(!1);return}requestAnimationFrame(()=>Y(Math.min(p.length,ve+T)))}};Y(Math.min(T,p.length))},[Fs,Se]),Be=Ir({initiativeId:ft,authToken:M,embedMode:me,enabled:!!ft}),[Lt,Ut]=a.useState(null),ds=Be.run,Is=((xn=Be.error)==null?void 0:xn.toLowerCase())??"",As=!ft||Is.includes("404")||Is.includes("400")||Is.includes("not found"),dt=ft?Me.get(ft)??null:null,Es=((dt==null?void 0:dt.activeCount)??0)>0,pr=((dt==null?void 0:dt.totalCount)??0)>0,rn=Lt?`Upgrade required · ${kn(Lt.currentPlan)} → ${kn(Lt.requiredPlan)}`:ft?Be.isRunning?Es?`Running · ${(dt==null?void 0:dt.activeCount)??0} live`:pr?`Enabled · ${(dt==null?void 0:dt.totalCount)??0} idle`:"Enabled · waiting":ds!=null&&ds.stopReason?`Idle · ${ds.stopReason.replace(/_/g," ")}`:"Idle":"No target",Qt=!!Lt&&!Be.isRunning,xr=Qt?"amber":"teal",hr=a.useMemo(()=>{const p=new URL("https://www.useorgx.com/integrations/openclaw");return p.searchParams.set("utm_source",me?"live_share":"orgx_openclaw_plugin"),p.searchParams.set("utm_medium","mission_control"),p.searchParams.set("utm_campaign","live_link_dashboard"),p.searchParams.set("utm_content","install_cta"),p.toString()},[me]);a.useEffect(()=>{Ut(null)},[ft]),a.useEffect(()=>{const p=Z.current;if(!p)return;const T=()=>{u(Math.max(64,p.offsetHeight))};if(T(),typeof ResizeObserver>"u")return;const R=new ResizeObserver(()=>T());return R.observe(p),()=>R.disconnect()},[rn,o,x,r,Ne.length]);const Ds=!!(!r&&h&&(o==="disconnected"||x)),fr=o==="disconnected"||x?"critical":"info",gr=o==="disconnected"?"Offline":x?"Live degraded":"Connected",an=x?gi(x):o==="disconnected"?"Live updates are offline. Data may be stale until reconnect.":`Last snapshot ${yi(d)}`;a.useEffect(()=>{Ds||Ce(!1)},[Ds]);const Et=a.useCallback((p,T)=>{if(!t.find(ce=>ce.id===p)){const ce=(T??"").trim(),Dt=ce?Xs(ce)?`Initiative ${Zn(ce)}`:Yt(ce):"This initiative";return Ie({tone:"error",message:`${Dt} is not in this workspace view. Switch workspace or clear filters to find it.`}),!1}Ie(null);const Y=Ne.findIndex(ce=>ce.id===p),ve=Y<0;if(Y>=0&&Je(Math.floor(Y/Xe)),ve&&(F(""),f([]),L("target"),G("any"),K(""),E("")),U(p),D!=="none"){const ce=Y>=0?Ne:t,wt=Vn(ce,D).find(ut=>ut.initiatives.some(Vt=>Vt.id===p));if(wt){const ut=qt(D,wt.key);ie(Vt=>{if(Vt.has(ut))return Vt;const yn=new Set(Vt);return yn.add(ut),yn})}}const Oe=(ce=0)=>{const Dt=document.getElementById(`initiative-${p}`);if(Dt){Dt.scrollIntoView({behavior:ce===0?"smooth":"auto",block:"start"});const wt=Math.max(72,j)+8,ut=Dt.getBoundingClientRect();!(ut.top>=wt&&ut.top<=window.innerHeight-72)&&ce<18&&window.setTimeout(()=>Oe(ce+1),90);return}ce>=60||requestAnimationFrame(()=>Oe(ce+1))},He=()=>requestAnimationFrame(()=>Oe());return ve?window.setTimeout(He,90):He(),!0},[t,Xe,Ie,Je,F,f,L,G,K,E,U,D,Ne,j]),br=a.useCallback(()=>{X&&(Ie(null),te.updateEntity.mutateAsync({type:"initiative",id:X.id,status:"active"}).then(()=>{Ie({tone:"success",message:`Started ${X.name}.`}),Et(X.id,X.name)}).catch(p=>{Ie({tone:"error",message:Jt(p instanceof Error?p.message:"","Failed to start initiative.")})}))},[te.updateEntity,X,Et]),Bt=a.useCallback(async(p,T,R)=>{Ge(p),Ie(null);try{await T(),Ie({tone:"success",message:R})}catch(Y){Ie({tone:"error",message:Jt(Y instanceof Error?Y.message:"","Action failed.")})}finally{Ge(null)}},[]),yr=a.useCallback(()=>Q?Bt("pause",()=>Ke.stopTriage({initiativeId:Q.initiativeId,workstreamId:Q.workstreamId,placement:"bottom",resetToTodo:!1}),`Paused ${Q.workstreamTitle} and moved it to bottom of queue.`):Promise.resolve(),[Ke,Q,Bt]),wr=a.useCallback(()=>{if(!Q)return Promise.resolve();const p=Q.playbackState==="running"||Q.playbackState==="blocked"||Q.queueState==="running"||Q.queueState==="blocked";return Bt("defer",()=>p?Ke.stopTriage({initiativeId:Q.initiativeId,workstreamId:Q.workstreamId,placement:"bottom",resetToTodo:!1}):Ke.move({initiativeId:Q.initiativeId,workstreamId:Q.workstreamId,placement:"bottom"}),`Deferred ${Q.workstreamTitle} to bottom of queue.`)},[Ke,Q,Bt]),vr=a.useCallback(()=>{const p=Q??_e??oe;if(!p)return Promise.resolve();const T=p.autoIntentEnabled===!0&&(p.autoRuntimeState==="running"||p.autoRuntimeState==="stopping");return Bt("auto",()=>T?ge.stopInitiativeAutoContinue({initiativeId:p.initiativeId}):(async()=>(await Ke.move({initiativeId:p.initiativeId,workstreamId:p.workstreamId,placement:"top"}),ge.startWorkstreamAutoContinue({initiativeId:p.initiativeId,workstreamId:p.workstreamId,agentId:p.runnerAgentId,scope:"initiative"})))(),T?`Stopped auto-continue for ${p.initiativeTitle}.`:`Auto-continue enabled for ${p.initiativeTitle}; starting with ${p.workstreamTitle}.`)},[ge,oe,_e,Ke,Q,Bt]),on=a.useCallback(()=>{X&&(Et(X.id,X.name),typeof window<"u"&&window.innerWidth>=1280&&Fe(!0))},[X,Et]),Ms=a.useCallback(()=>{if(typeof window>"u")return;if(window.innerWidth>=1280){const T=!le;Re(!1),Fe(T),Ie({tone:"success",message:T?"Opened queue rail.":"Closed queue rail."});return}const p=!ze;Fe(!1),Re(p),Ie({tone:"success",message:p?"Opened queue panel.":"Closed queue panel."})},[ze,le]),Wt=Hs((X==null?void 0:X.rawStatus)??(X==null?void 0:X.status)??null),ln=a.useMemo(()=>new Set(["paused","draft","planned","todo","backlog","queued"]),[]),et=a.useMemo(()=>X?(Q==null?void 0:Q.queueState)==="running"||(Q==null?void 0:Q.playbackState)==="running"||(oe==null?void 0:oe.autoIntentEnabled)===!0&&(oe.autoRuntimeState==="running"||oe.autoRuntimeState==="stopping")?"running":(oe==null?void 0:oe.queueState)==="blocked"||X.status==="blocked"?"blocked":oe?"queued":ln.has(Wt)?"startable":Wt==="completed"||Wt==="done"?"completed":"active_no_queue":"none",[X,oe,ln,Wt,Q]),Ts=a.useMemo(()=>X?et==="running"&&oe?{headline:`${oe.workstreamTitle} is running`,detail:`Runner: ${oe.runnerAgentName}. Follow live updates in Activity.`}:et==="queued"&&oe?{headline:oe.workstreamTitle,detail:`Ready to dispatch${oe.nextTaskTitle?` · ${oe.nextTaskTitle}`:""}.`}:et==="startable"?{headline:Wt==="paused"?`${X.name} is paused`:`${X.name} is ready to start`,detail:"Start initiative to queue and dispatch the next workstream."}:et==="blocked"?{headline:(oe==null?void 0:oe.queueState)==="blocked"?`${oe.workstreamTitle} is blocked`:`${X.name} is blocked`,detail:(oe==null?void 0:oe.blockReason)??"Resolve blockers or approvals before dispatching more work."}:et==="completed"?{headline:`${X.name} is complete`,detail:"Choose another active initiative or queue new workstreams."}:{headline:X.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."},[X,et,oe,Wt]),us=ge.isPlaying||ge.isStartingAutoContinue||ge.isStoppingAutoContinue||te.updateEntity.isPending,jr=a.useMemo(()=>et==="blocked"?"Review blockers":et==="active_no_queue"?"Open and queue work":et==="completed"?"Review initiative":"Open initiative",[et]),cn=a.useMemo(()=>(Q==null?void 0:Q.playbackState)==="running"||(Q==null?void 0:Q.queueState)==="running"?"running":(Q==null?void 0:Q.playbackState)==="blocked"||(Q==null?void 0:Q.queueState)==="blocked"?"blocked":_e?"queued":et==="startable"?"startable":et==="completed"?"completed":X?"active_no_queue":"none",[X,et,_e,Q]),dn=(Q==null?void 0:Q.workstreamTitle)??"No active workstream",kr=(Q==null?void 0:Q.initiativeTitle)??(X==null?void 0:X.name)??"No initiative selected",$s=Q?[Q.nextTaskTitle?`Next: ${Q.nextTaskTitle}`:null,Q.blockReason?`Blocked: ${Q.blockReason}`:null].filter(Boolean).join(" · "):_e?`Next up: ${_e.workstreamTitle}`:Ts.detail,un=(_e==null?void 0:_e.workstreamTitle)??"Queue is empty",mn=_e!=null&&_e.nextTaskTitle?`Next task: ${_e.nextTaskTitle}`:"Add or reorder workstreams in queue.",Nr=hi(cn),Sr=fi(cn),Ht=Q??_e??oe,_s=(Ht==null?void 0:Ht.autoIntentEnabled)===!0&&(Ht.autoRuntimeState==="running"||Ht.autoRuntimeState==="stopping"),Ls="next-up-surface",Bs=a.useMemo(()=>({type:"spring",stiffness:340,damping:38,mass:.72}),[]),Cr=a.useMemo(()=>({backgroundColor:"rgba(10, 14, 21, 0.66)",borderColor:"rgba(255, 255, 255, 0.10)"}),[]),pn=a.useMemo(()=>({backgroundColor:"rgba(10, 14, 21, 0.95)",borderColor:"rgba(255, 255, 255, 0.11)"}),[]),Fr=a.useMemo(()=>{if(!ne)return null;const p=R=>t.find(Y=>Y.id===R)??null;if(ne.type==="initiative"){const R=p(ne.entity.id);return R?{...ne,entity:R}:ne}const T=p(ne.initiative.id);return T?{...ne,initiative:T}:ne},[t,ne]);return a.useEffect(()=>{Ie(null)},[X==null?void 0:X.id,oe==null?void 0:oe.initiativeId,oe==null?void 0:oe.workstreamId,Q==null?void 0:Q.initiativeId,Q==null?void 0:Q.workstreamId,_e==null?void 0:_e.initiativeId,_e==null?void 0:_e.workstreamId]),a.useEffect(()=>{if(!ne)return;const p=ne.type==="initiative"?ne.entity.id:ne.initiative.id;t.some(R=>R.id===p)||ye()},[ye,t,ne]),a.useEffect(()=>{if(typeof window>"u")return;const p=()=>{window.innerWidth>=1280?Re(!1):Fe(!1)};return p(),window.addEventListener("resize",p),()=>window.removeEventListener("resize",p)},[]),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":`${j}px`},children:[e.jsxs(er,{id:"next-up-morph",children:[e.jsxs("div",{ref:Z,className:"sticky top-0 z-40 relative -mx-4 border-b border-subtle bg-[#02040A]/78 px-4 pb-2.5 pt-3.5 backdrop-blur-xl sm:-mx-6 sm:px-6",children:[e.jsx("div",{className:"pointer-events-none absolute right-4 top-2.5 z-50 sm:right-6",children:e.jsx(Jn,{open:Ds&&!Pe,tone:fr==="critical"?"error":"warning",title:gr,message:an,onDismiss:()=>Ce(!0),primaryAction:m?{label:"Refresh",onClick:m}:null,secondaryAction:y?{label:"Settings",onClick:y}:null})}),e.jsxs("div",{className:"toolbar-shell flex flex-col gap-2.5 md:flex-row md:items-center",children:[e.jsx("div",{className:"min-w-0 flex-1",children:e.jsx(Zs,{value:w,onChange:F,placeholder:"Search initiatives..."})}),e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-2.5 md:ml-auto md:flex-nowrap",children:[e.jsx(ri,{initiatives:t,visibleCount:St.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:(X==null?void 0:X.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:rn}),X&&e.jsx("div",{className:"truncate text-micro text-white/44",children:X.name})]})]}),e.jsxs("button",{type:"button",onClick:()=>{if(As||!ft)return;if(Qt&&Lt){Ar({actions:Lt.actions,requiredPlan:Lt.requiredPlan}).catch(R=>{Ie({tone:"error",message:Jt(R instanceof Error?R.message:"","Unable to open checkout right now.")})});return}const p=Be.isRunning;(p?Be.stop:Be.start)().then(()=>{Ut(null);const R=(X==null?void 0:X.name)??"selected initiative";Ie({tone:"success",message:p?`Stopped Autopilot for ${R}.`:`Started Autopilot for ${R}.`})}).catch(R=>{R instanceof qr?Ut(R):(Ut(null),Ie({tone:"error",message:Jt(R instanceof Error?R.message:"","Autopilot action failed.")}))})},disabled:As||Be.isStarting||Be.isStopping,title:As?"Select an initiative to run Autopilot":Qt?"Upgrade to enable auto-continue for BYOK agents":Be.isRunning?"Stop Autopilot":`Start Autopilot${X?` for ${X.name}`:""}`,"data-state":Be.isRunning||Qt?"active":"idle","data-tone":xr,className:"control-pill flex items-center gap-1.5 px-3 text-caption font-semibold disabled:opacity-40",children:[Qt?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"})]}):Be.isRunning?Es?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:Qt?"Upgrade Autopilot":`${Be.isRunning?"Stop":"Start"} Autopilot`}),Be.isRunning&&Es&&e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-[#0AD4C4] status-breathe"})]}),Be.isRunning&&e.jsxs("div",{className:"autopilot-rail autopilot-rail-pulse flex items-center gap-2 rounded-lg px-3 py-1.5 mt-1.5","data-state":(hn=Be.run)!=null&&hn.lastError?"error":((fn=Be.run)==null?void 0:fn.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"}),((gn=Be.run)==null?void 0:gn.tokensUsed)!=null&&((bn=Be.run)==null?void 0:bn.tokenBudget)!=null&&Be.run.tokenBudget>0&&e.jsxs("span",{className:"text-micro text-[#7AEDE5]/60 tabular-nums",children:[Math.round(Be.run.tokensUsed/Be.run.tokenBudget*100),"% budget"]})]}),me&&e.jsxs("a",{href:hr,target:"_blank",rel:"noreferrer noopener",onClick:()=>{try{Or("live_install_cta_click",{surface:"mission_control",embedMode:!0,initiativeId:(X==null?void 0:X.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"})]}),q.length>0&&e.jsx("button",{type:"button",onClick:()=>{b?(Fs(),he(),Ae&&ct.length>0&&ie(new Set)):(mr(q.map(p=>p.id)),Ae&&ct.length>0&&ie(new Set(ct)))},title:b?"Collapse all":"Expand all","aria-busy":ke&&!b,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:b?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"})]})})})]})]})]}),Ne.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 ${Te>0?"border-[#BFFF00]/14 bg-[#0A0E15]/72":"border-white/[0.10] bg-[#0A0E15]/66"}`,children:[Te>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 ${Te>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:de,onChange:ar,className:"h-3.5 w-3.5 rounded border-white/20 bg-black/40 text-[#BFFF00] focus:ring-[#BFFF00]/35"}),"Select page"]}),e.jsx("span",{className:"flex-shrink-0 text-caption text-white/58",children:Te>0?`${Te} selected`:lt===0?"0 visible":`${A}-${C} of ${lt}`}),Te>0&&e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("button",{type:"button",onClick:()=>{cs("active")},disabled:De,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:De,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:De,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:De,className:"control-pill h-8 flex-shrink-0 px-3 text-caption font-semibold disabled:opacity-45",children:"Complete"}),Nt?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:()=>{ur()},disabled:De,className:"control-pill h-8 flex-shrink-0 border-red-400/35 bg-red-500/14 px-3 text-caption font-semibold text-red-100 disabled:opacity-45",children:"Delete"}),e.jsx("button",{type:"button",onClick:()=>Ye(!1),disabled:De,className:"control-pill h-8 flex-shrink-0 px-2.5 text-caption disabled:opacity-45",children:"Keep"})]}):e.jsx("button",{type:"button",onClick:()=>Ye(!0),disabled:De,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:ir,disabled:De,className:"text-caption text-secondary transition-colors hover:text-primary disabled:opacity-45",children:"Clear"})]})]})}),e.jsx(mt,{initial:!1,mode:"popLayout",children:!le&&!ze&&e.jsxs(je.div,{layout:"position",layoutId:Ls,initial:{opacity:0,y:4},animate:{opacity:1,y:0,...Cr},exit:{opacity:0,y:-4},transition:{layout:Bs,duration:.2,ease:[.22,1,.36,1]},className:"flex w-full min-w-0 flex-col gap-2 overflow-hidden rounded-xl border border-strong px-2.5 py-2 shadow-[0_10px_24px_rgba(0,0,0,0.22)] backdrop-blur-[10px] sm:flex-row sm:items-center xl:h-full xl:rounded-none xl:border-b-0 xl:border-l xl:border-r-0 xl:border-t-0 xl:border-white/[0.10] xl:bg-transparent xl:px-3 xl:py-2 xl:shadow-none xl:backdrop-blur-none",children:[e.jsxs("div",{className:"flex min-w-0 w-full flex-1 items-center gap-2.5",children:[ge.isLoading?e.jsx(jt,{className:"h-6 w-6 rounded-full"}):Ct?e.jsx(Xn,{name:Ct.runnerAgentName,hint:`${Ct.runnerAgentId} ${Ct.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"}),ge.isLoading?e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full border border-strong bg-white/[0.04] px-1.5 py-[1px] text-micro uppercase tracking-[0.07em] text-secondary",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-[#BFFF00]/70 status-breathe"}),"Syncing"]}):e.jsx("span",{className:`rounded-full border px-1.5 py-[1px] text-micro uppercase tracking-[0.07em] ${Sr}`,children:Nr})]}),ge.isLoading?e.jsxs("div",{className:"mt-1.5 space-y-1",children:[e.jsx(jt,{className:"h-3 w-56 rounded"}),e.jsx(jt,{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:dn,children:dn}),e.jsxs("p",{className:"truncate text-caption leading-snug text-secondary",title:$s,children:[kr,$s?` · ${$s}`:""]}),e.jsxs("p",{className:"hidden truncate text-micro leading-snug text-secondary/85 sm:block",title:un,children:["Up next: ",un,mn?` · ${mn}`:""]})]})]})]}),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 p=_e??oe;if(Q){yr();return}if(p){Bt("start",()=>ge.playWorkstream({initiativeId:p.initiativeId,workstreamId:p.workstreamId,agentId:p.runnerAgentId}),`Started ${p.workstreamTitle}.`);return}on()},disabled:us||at==="start"||at==="pause",className:"control-pill h-8 flex-shrink-0 px-3 text-caption font-semibold disabled:opacity-45",title:Q?`Pause ${Q.workstreamTitle}`:"Start next workstream",children:Q?"Pause":"Start"}),e.jsx("button",{type:"button",onClick:()=>void wr(),disabled:!Q||at==="defer"||us,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 vr(),disabled:!Ht||at==="auto"||us,className:"control-pill h-8 flex-shrink-0 px-3 text-caption font-semibold disabled:opacity-45","data-state":_s?"active":"idle","data-tone":"teal",title:_s?"Stop automatic continuation":"Continue automatically for this initiative",children:_s?"Auto on":"Auto"}),e.jsx("button",{type:"button",onClick:Ms,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:()=>We(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(je.div,{layout:!0,transition:{type:"spring",stiffness:260,damping:30},className:`mt-3 grid gap-4 pb-8 ${le?"xl:grid-cols-[minmax(0,1fr)_320px] xl:gap-0":"grid-cols-1"}`,children:[e.jsxs(je.div,{layout:!0,className:`min-w-0 ${le?"xl:pr-4":""}`,children:[!r&&X&&e.jsxs(je.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:Ts.headline}),e.jsx("p",{className:"mt-1 text-body leading-relaxed text-secondary",children:Ts.detail}),$t&&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 ${$t.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:$t.message})]}),e.jsxs("div",{className:"ml-auto flex flex-wrap items-center gap-2.5 xl:self-end",children:[et==="startable"?e.jsx("button",{type:"button",onClick:br,disabled:us,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:on,className:"control-pill h-9 px-4 text-body font-semibold","data-state":et==="blocked"?"active":"idle",children:jr}),e.jsx("button",{type:"button",onClick:Ms,className:"control-pill h-9 px-4 text-body font-semibold",children:le?"Hide Queue":"Open Queue"})]})]})]}),r?e.jsx("div",{className:"space-y-3 pb-8",children:Array.from({length:4}).map((p,T)=>e.jsxs("div",{className:"bg-[--orgx-surface] border border-[--orgx-border] soft-shadow rounded-2xl p-4",children:[e.jsx(jt,{className:"h-4 w-2/5 rounded"}),e.jsx(jt,{className:"h-1 w-full rounded mt-3"})]},`mc-skeleton-${T}`))}):t.length===0?h?o==="disconnected"||x?e.jsx("div",{className:"pb-8",children:e.jsx(Os,{mode:"degraded",detail:an,onCreateInitiative:S,onPlayNextUp:I,onStartAutopilot:k,onRefresh:m,onOpenSettings:y})}):e.jsx("div",{className:"pb-8",children:e.jsx(Os,{mode:"empty",onCreateInitiative:S,onPlayNextUp:I,onStartAutopilot:k,onRefresh:m})}):e.jsx("div",{className:"pb-8",children:e.jsxs("div",{className:"rounded-2xl border border-white/[0.08] bg-white/[0.02] px-6 py-8 text-center",children:[e.jsx("div",{className:"text-heading font-semibold text-bright",children:"Connect OrgX to get started"}),e.jsx("div",{className:"mt-1 text-body text-secondary",children:"Mission Control shows your initiative hierarchy once a user-scoped API key is configured."}),y&&e.jsx("div",{className:"mt-4 flex items-center justify-center",children:e.jsx("button",{type:"button",onClick:y,className:"h-10 rounded-full border border-[#BFFF00]/30 bg-[#BFFF00]/15 px-4 text-body font-semibold text-[#D8FFA1] transition-colors hover:bg-[#BFFF00]/20",children:"Open settings"})})]})}):Ne.length===0?e.jsx("div",{className:"pb-8",children:e.jsx(Os,{mode:"filtered",hasActiveFilters:z,onClearFilters:z?H:void 0,onCreateInitiative:S,onPlayNextUp:I,onStartAutopilot:k,onRefresh:m})}):Ae?e.jsx("div",{className:"space-y-4 pb-8",children:Ae.map(p=>{const T=qt(D,p.key),R=xi(T),Y=P.has(T);return e.jsxs(je.div,{layout:!0,transition:{type:"spring",stiffness:260,damping:30},children:[e.jsxs("button",{type:"button","aria-expanded":Y,"aria-controls":R,onClick:()=>V(T),className:"mb-2 flex w-full items-center gap-2 rounded-xl border border-white/[0.075] bg-white/[0.016] px-3 py-2.5 text-left transition-colors hover:border-strong hover:bg-white/[0.04]",children:[e.jsx("span",{"aria-hidden":!0,className:`inline-flex h-5 w-5 items-center justify-center rounded-md border border-strong bg-white/[0.04] text-caption text-secondary transition-transform ${Y?"rotate-90":""}`,children:"▶"}),e.jsx("span",{className:"text-body font-semibold text-primary",children:p.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:p.count}),e.jsx("span",{className:"ml-auto text-micro uppercase tracking-[0.08em] text-secondary",children:Y?"Hide":"Show"})]}),e.jsx(mt,{initial:!1,children:Y&&e.jsx(je.div,{id:R,initial:{opacity:0,y:-4},animate:{opacity:1,y:0},exit:{opacity:0,y:-4},transition:{duration:.2,ease:[.22,1,.36,1]},children:e.jsx("div",{className:"pt-0.5",children:e.jsx(In,{initiatives:p.initiatives,selectedInitiativeIds:Le,onToggleInitiativeSelection:tn,isSquished:le,runtimeActivityByInitiativeId:Me,queuedInitiativeIds:Zt})})})})]},p.key)})}):e.jsx("div",{className:"pb-8",children:e.jsx(In,{initiatives:q,selectedInitiativeIds:Le,onToggleInitiativeSelection:tn,isSquished:le,runtimeActivityByInitiativeId:Me,queuedInitiativeIds:Zt})}),Ne.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 ",A,"-",C]}),e.jsx("span",{className:"text-white/50",children:"of"}),e.jsx("span",{className:"font-medium text-white/80",children:lt}),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:Xe,onChange:p=>{const T=Number.parseInt(p.target.value,10);Number.isFinite(T)&&Xt(T)},className:"h-6 rounded-md border border-transparent bg-transparent px-1 text-caption text-white/90 outline-none",children:bi.map(p=>e.jsx("option",{value:p,children:p},p))})]}),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:!sn,className:"control-pill h-7 px-2 text-micro font-semibold disabled:opacity-40",title:"First page",children:"«"}),e.jsx("button",{type:"button",onClick:lr,disabled:!sn,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 ",it+1," / ",st]}),e.jsx("button",{type:"button",onClick:cr,disabled:!nn,className:"control-pill h-7 px-2 text-micro font-semibold disabled:opacity-40",title:"Next page",children:"›"}),e.jsx("button",{type:"button",onClick:dr,disabled:!nn,className:"control-pill h-7 px-2 text-micro font-semibold disabled:opacity-40",title:"Last page",children:"»"})]})]})]})]}),e.jsx(mt,{initial:!1,children:le&&e.jsx(je.aside,{layout:!0,initial:{opacity:0,x:14},animate:{opacity:1,x:0},exit:{opacity:0,x:14},transition:{duration:.2,ease:[.22,1,.36,1]},className:"hidden xl:block",children:e.jsx("div",{className:"sticky",style:{top:"calc(var(--mc-toolbar-offset) + 12px)"},children:e.jsx(je.div,{layout:"position",layoutId:Ls,initial:{borderRadius:12},animate:{borderRadius:16,...pn},transition:{layout:Bs,type:"spring",stiffness:340,damping:38,mass:.72},className:"origin-top-right flex h-[calc(100vh-var(--mc-toolbar-offset)-24px)] min-h-0 flex-col overflow-hidden rounded-2xl border shadow-[0_18px_40px_rgba(0,0,0,0.42)] backdrop-blur-[12px] xl:rounded-l-none",children:e.jsxs("div",{className:"relative flex h-full min-h-0 flex-col",children:[e.jsxs("div",{className:"flex items-center gap-1 border-b border-strong px-3 py-2",children:[e.jsx("button",{type:"button",onClick:()=>gt("next-up"),className:`control-pill h-7 px-2 text-micro font-semibold ${qe==="next-up"?"border-[#BFFF00]/34 bg-[#BFFF00]/[0.12] text-[#E8FFD0]":"text-secondary"}`,children:"Next Up"}),e.jsx("button",{type:"button",onClick:()=>gt("slices"),className:`control-pill h-7 px-2 text-micro font-semibold ${qe==="slices"?"border-teal-300/34 bg-teal-400/[0.12] text-teal-100":"text-secondary"}`,children:"Slices"})]}),e.jsx("div",{className:"min-h-0 flex-1",children:qe==="next-up"?e.jsx(wn,{title:"Next Up",panelStyle:"flat",className:"!bg-transparent !shadow-none !border-transparent",disableEnterAnimation:!0,projectId:n,authToken:M,embedMode:me,queueModel:ge,queueActions:Ke,snapshotVersion:g,onOpenInitiative:Et,onOpenSettings:y,onUpgradeGate:Ut}):e.jsx(Un,{title:"Slice Explorer",className:"h-full !rounded-none !border-0 !bg-transparent",workspaceId:n,authToken:M,embedMode:me,compact:!0,onOpenInitiative:(p,T)=>{Et(p,T)}})}),e.jsx("button",{type:"button",onClick:Ms,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(mt,{children:ze&&e.jsxs(e.Fragment,{children:[e.jsx(je.button,{type:"button","aria-label":"Close next up panel",onClick:()=>Re(!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(je.aside,{initial:{x:"100%",opacity:.85},animate:{x:0,opacity:1},exit:{x:"100%",opacity:.9},transition:{type:"spring",stiffness:320,damping:34},className:"fixed inset-x-0 bottom-0 top-[60vh] z-[250] p-2 sm:top-[64px] sm:left-auto sm:right-0 sm:w-[min(84vw,360px)] sm:p-3 lg:w-[360px] lg:max-w-[94vw] xl:hidden",children:e.jsxs("div",{className:"relative flex h-full flex-col",children:[e.jsx("button",{type:"button",onClick:()=>Re(!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(je.div,{layout:"position",layoutId:Ls,initial:{borderRadius:12},animate:{borderRadius:16,...pn},transition:{layout:Bs,type:"spring",stiffness:340,damping:38,mass:.72},className:"h-full overflow-hidden rounded-2xl border shadow-[0_18px_40px_rgba(0,0,0,0.42)] backdrop-blur-[12px]",children:e.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[e.jsxs("div",{className:"flex items-center gap-1 border-b border-strong px-3 py-2",children:[e.jsx("button",{type:"button",onClick:()=>gt("next-up"),className:`control-pill h-7 px-2 text-micro font-semibold ${qe==="next-up"?"border-[#BFFF00]/34 bg-[#BFFF00]/[0.12] text-[#E8FFD0]":"text-secondary"}`,children:"Next Up"}),e.jsx("button",{type:"button",onClick:()=>gt("slices"),className:`control-pill h-7 px-2 text-micro font-semibold ${qe==="slices"?"border-teal-300/34 bg-teal-400/[0.12] text-teal-100":"text-secondary"}`,children:"Slices"})]}),e.jsx("div",{className:"min-h-0 flex-1",children:qe==="next-up"?e.jsx(wn,{title:"Next Up",panelStyle:"flat",className:"!bg-transparent !shadow-none !border-transparent",disableEnterAnimation:!0,projectId:n,authToken:M,embedMode:me,queueModel:ge,queueActions:Ke,snapshotVersion:g,onOpenInitiative:(p,T)=>{Et(p,T),Re(!1)},onOpenSettings:y,onUpgradeGate:Ut}):e.jsx(Un,{title:"Slice Explorer",className:"h-full !rounded-none !border-0 !bg-transparent",workspaceId:n,authToken:M,embedMode:me,compact:!0,onOpenInitiative:(p,T)=>{Et(p,T),Re(!1)}})})]})})]})},"next-up-drawer")]})})]})})]}),e.jsx(Za,{target:Fr,onClose:ye})]})}export{Ei as MissionControlView};
|