@taskforcehq/taskforce 0.3.301 → 0.3.302

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (147) hide show
  1. package/dist/Taskforce.module.css +26 -2
  2. package/dist/TaskforceCore.filter-persistence.test.js +1 -1
  3. package/dist/TaskforceCore.js +13 -24
  4. package/dist/TaskforceCore.test.js +167 -152
  5. package/dist/components/features/TaskSettings.js +14 -82
  6. package/dist/components/features/TaskSettings.test.js +33 -70
  7. package/dist/components/features/settings/TaxonomyLibraryManager.js +8 -2
  8. package/dist/components/features/settings/TaxonomyLibraryManager.test.js +1 -1
  9. package/dist/components/task/TaskActionHeader.js +6 -3
  10. package/dist/components/task/TaskCard.js +6 -3
  11. package/dist/components/task/TaskForm.js +2 -2
  12. package/dist/components/task/TaskForm.test.js +41 -2
  13. package/dist/components/ui/ReferenceBadgeButton.js +1 -1
  14. package/dist/components/views/PlansPage.js +9 -8
  15. package/dist/components/views/StandaloneLayout.js +466 -204
  16. package/dist/components/views/panels/PlanningDrawer.js +18 -1
  17. package/dist/components/views/standalone/modals/AccountHubModal.d.ts +43 -0
  18. package/dist/components/views/standalone/modals/AccountHubModal.js +22 -0
  19. package/dist/components/views/standalone/modals/CreateWorkspaceConfirmModal.d.ts +9 -0
  20. package/dist/components/views/standalone/modals/CreateWorkspaceConfirmModal.js +8 -0
  21. package/dist/components/views/standalone/modals/EditProfileModal.d.ts +26 -0
  22. package/dist/components/views/standalone/modals/EditProfileModal.js +10 -0
  23. package/dist/components/views/standalone/modals/HelpModal.d.ts +9 -0
  24. package/dist/components/views/standalone/modals/HelpModal.js +8 -0
  25. package/dist/components/views/standalone/modals/ScheduleWarningModal.d.ts +13 -0
  26. package/dist/components/views/standalone/modals/ScheduleWarningModal.js +6 -0
  27. package/dist/components/views/standalone/modals/SyncStatusModal.d.ts +61 -0
  28. package/dist/components/views/standalone/modals/SyncStatusModal.js +38 -0
  29. package/dist/components/views/standalone/modals/TeamManagementModal.d.ts +64 -0
  30. package/dist/components/views/standalone/modals/TeamManagementModal.js +10 -0
  31. package/dist/components/views/standalone/modals/types.d.ts +2 -0
  32. package/dist/components/views/standalone/modals/types.js +1 -0
  33. package/dist/components/views/teamManagementAccess.d.ts +1 -1
  34. package/dist/components/views/teamManagementAccess.js +2 -2
  35. package/dist/components/views/teamManagementAccess.test.js +3 -3
  36. package/dist/config/deployment.js +2 -2
  37. package/dist/config/deployment.test.js +5 -3
  38. package/dist/core/AiProfileService.js +7 -2
  39. package/dist/core/AiProfiles.test.js +19 -0
  40. package/dist/core/SyncReconciliationService.d.ts +2 -0
  41. package/dist/core/SyncReconciliationService.js +3 -0
  42. package/dist/core/TaskAuditTimeline.test.js +40 -0
  43. package/dist/core/Taskforce.d.ts +49 -0
  44. package/dist/core/Taskforce.ids.test.js +133 -0
  45. package/dist/core/Taskforce.js +241 -78
  46. package/dist/core/UserProfileAvatarDrafts.test.d.ts +1 -0
  47. package/dist/core/UserProfileAvatarDrafts.test.js +102 -0
  48. package/dist/core/taskReferencePolicy.d.ts +28 -0
  49. package/dist/core/taskReferencePolicy.js +189 -0
  50. package/dist/core/types.d.ts +2 -0
  51. package/dist/hooks/tasks/useTaskFormActions.js +3 -0
  52. package/dist/hooks/useTaskData.js +3 -2
  53. package/dist/hooks/useTaskData.test.js +66 -0
  54. package/dist/hooks/useTaskforce.d.ts +5 -0
  55. package/dist/hooks/useTaskforce.js +63 -15
  56. package/dist/hooks/useTaskforce.sync-behavior.test.js +185 -6
  57. package/dist/mcp/aiProfileBootstrap.d.ts +29 -0
  58. package/dist/mcp/aiProfileBootstrap.js +80 -0
  59. package/dist/mcp/aiProfileBootstrap.test.d.ts +1 -0
  60. package/dist/mcp/aiProfileBootstrap.test.js +68 -0
  61. package/dist/mcp/clientIntegrations.d.ts +2 -8
  62. package/dist/mcp/clientIntegrations.js +21 -40
  63. package/dist/mcp/clientIntegrations.test.js +28 -2
  64. package/dist/mcp/clientProfileDefaults.d.ts +12 -0
  65. package/dist/mcp/clientProfileDefaults.js +37 -0
  66. package/dist/mcp/runtime.d.ts +10 -7
  67. package/dist/mcp/runtime.js +41 -19
  68. package/dist/mcp/runtime.test.js +49 -2
  69. package/dist/migrations/taskSchemaMigrations.js +53 -1
  70. package/dist/qaOpen.test.d.ts +1 -0
  71. package/dist/qaOpen.test.js +56 -0
  72. package/dist/server/index.cookieProxy.test.js +1 -0
  73. package/dist/server/index.d.ts +1 -0
  74. package/dist/server/index.js +15 -1
  75. package/dist/server/index.test.js +14 -1
  76. package/dist/server/routes/admin.js +25 -22
  77. package/dist/server/routes/auth.d.ts +5 -0
  78. package/dist/server/routes/auth.js +350 -16
  79. package/dist/server/routes/billing.js +11 -1
  80. package/dist/server/routes/billing.test.js +32 -2
  81. package/dist/server/routes/documents.js +6 -1
  82. package/dist/server/routes/shared.d.ts +1 -1
  83. package/dist/server/routes/shared.js +11 -3
  84. package/dist/server/routes/sync.integration.test.js +130 -0
  85. package/dist/server/routes/sync.js +226 -1924
  86. package/dist/server/routes/tasks.js +18 -4
  87. package/dist/server/routes.js +26 -19
  88. package/dist/server/routes.test.js +352 -6
  89. package/dist/shared/runtimeContract.d.ts +1 -1
  90. package/dist/sync/collaborationSyncPayload.d.ts +17 -0
  91. package/dist/sync/collaborationSyncPayload.js +131 -0
  92. package/dist/sync/collaborationSyncPayload.test.d.ts +1 -0
  93. package/dist/sync/collaborationSyncPayload.test.js +104 -0
  94. package/dist/sync/collaborationSyncState.d.ts +15 -0
  95. package/dist/sync/collaborationSyncState.js +60 -0
  96. package/dist/sync/contentSyncPayload.d.ts +45 -0
  97. package/dist/sync/contentSyncPayload.js +104 -0
  98. package/dist/sync/contentSyncPayload.test.d.ts +1 -0
  99. package/dist/sync/contentSyncPayload.test.js +104 -0
  100. package/dist/sync/contentSyncState.d.ts +88 -0
  101. package/dist/sync/contentSyncState.js +743 -0
  102. package/dist/sync/planningSyncPayload.d.ts +9 -0
  103. package/dist/sync/planningSyncPayload.js +82 -0
  104. package/dist/sync/planningSyncPayload.test.d.ts +1 -0
  105. package/dist/sync/planningSyncPayload.test.js +68 -0
  106. package/dist/sync/syncApplyHandlers.d.ts +83 -0
  107. package/dist/sync/syncApplyHandlers.js +445 -0
  108. package/dist/sync/taskSyncPayload.d.ts +33 -0
  109. package/dist/sync/taskSyncPayload.js +126 -0
  110. package/dist/sync/taskSyncPayload.test.d.ts +1 -0
  111. package/dist/sync/taskSyncPayload.test.js +54 -0
  112. package/dist/sync/workspacePullFeed.d.ts +28 -0
  113. package/dist/sync/workspacePullFeed.js +301 -0
  114. package/dist/sync/workspacePullFeed.test.d.ts +1 -0
  115. package/dist/sync/workspacePullFeed.test.js +166 -0
  116. package/dist/sync/workspaceSyncModel.d.ts +4 -1
  117. package/dist/sync/workspaceSyncModel.js +9 -2
  118. package/dist/sync/workspaceSyncModel.test.js +29 -0
  119. package/dist/test/setup.js +1 -1
  120. package/dist/types.d.ts +1 -0
  121. package/dist/ui/assets/{AgentsModule-Bdq3T1Ts.js → AgentsModule-JG5jc3he.js} +1 -1
  122. package/dist/ui/assets/{AnnotatedAttachmentWorkspace-jKUVo-PJ.js → AnnotatedAttachmentWorkspace-Dvi02Y7q.js} +1 -1
  123. package/dist/ui/assets/{DocumentWorkspace-DuQa-uIC.js → DocumentWorkspace-iys3zfca.js} +2 -2
  124. package/dist/ui/assets/{InitiativesModule-C8Pi2VTk.js → InitiativesModule-DJvLJI3A.js} +1 -1
  125. package/dist/ui/assets/PlansPage-BMPlpFpw.js +1 -0
  126. package/dist/ui/assets/TaskSettings-Bqd4cCzW.js +8 -0
  127. package/dist/ui/assets/{TaskSettings-BwB9NtmJ.css → TaskSettings-CnIBL_Eb.css} +1 -1
  128. package/dist/ui/assets/{WorkflowsModule-b6TLuHwJ.js → WorkflowsModule-BguHeQaV.js} +1 -1
  129. package/dist/ui/assets/index-MXeWoebC.css +1 -0
  130. package/dist/ui/assets/index-YJ4k5QNa.js +6 -0
  131. package/dist/ui/assets/{vendor-icons-QZyhEwgT.js → vendor-icons-C8EED3Oh.js} +1 -1
  132. package/dist/ui/index.html +3 -3
  133. package/dist/utils/billingStatusCache.d.ts +21 -0
  134. package/dist/utils/billingStatusCache.js +70 -0
  135. package/dist/utils/taskActivity.js +17 -4
  136. package/dist/utils/taskActivity.test.js +27 -0
  137. package/dist/utils/taskNormalization.js +10 -2
  138. package/dist/utils/taskReferences.d.ts +11 -1
  139. package/dist/utils/taskReferences.js +33 -1
  140. package/package.json +2 -1
  141. package/scripts/qa-open-lib.mjs +175 -0
  142. package/scripts/qa-open-lib.mjs.d.ts +49 -0
  143. package/scripts/qa-open.mjs +352 -0
  144. package/dist/ui/assets/PlansPage-B6BDECSi.js +0 -1
  145. package/dist/ui/assets/TaskSettings-DUJgRTPU.js +0 -8
  146. package/dist/ui/assets/index-BiiF1cLQ.css +0 -1
  147. package/dist/ui/assets/index-xBWLPOEb.js +0 -6
@@ -0,0 +1,6 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/TaskSettings-Bqd4cCzW.js","assets/vendor-react-CKJs5o3c.js","assets/vendor-icons-C8EED3Oh.js","assets/vendor-markdown-BUxTU7dS.js","assets/vendor-dnd-DRzYolkg.js","assets/vendor-router-BbWMxlnO.js","assets/TaskSettings-CnIBL_Eb.css","assets/AnnotatedAttachmentWorkspace-Dvi02Y7q.js","assets/AnnotatedAttachmentWorkspace-BaS2VwIr.css","assets/DocumentWorkspace-iys3zfca.js","assets/DocumentWorkspace-C_8T8oz-.css","assets/WorkflowsModule-BguHeQaV.js","assets/AgentsModule-JG5jc3he.js","assets/InitiativesModule-DJvLJI3A.js","assets/PlansPage-BMPlpFpw.js","assets/PlansPage-BlVC_lRq.css"])))=>i.map(i=>d[i]);
2
+ import{r as a,j as t,R as pt,a as Ci,b as Gh}from"./vendor-react-CKJs5o3c.js";import{I as $s,C as xi,a as jc,b as so,c as Ll,F as Vh,A as Zh,R as wp,T as Fl,L as bp,d as Ai,e as Kh,X as ji,f as tf,g as nf,h as Fa,i as Ii,j as np,k as Rc,P as Yh,D as dm,l as Jh,B as Xd,U as Ac,m as sr,n as Xh,S as Qh,G as eg,o as tg,p as af,q as ng,r as _p,s as sf,t as ag,u as sg,v as Tc,w as rf,x as rg,y as of,z as og,E as ig,H as cg,M as um,J as pm,K as lg,N as dg,Z as ug,O as pg,Q as mg,V as fg,W as hg,Y as gg,_ as yg,$ as kg}from"./vendor-icons-C8EED3Oh.js";import{M as Sg,r as vg,a as wg}from"./vendor-markdown-BUxTU7dS.js";import{u as cf,a as Cp,b as bg,D as lf,c as _g,S as df,v as uf,P as pf,d as mf,C as Lp,e as Cg,p as xg,f as mm,s as Ag,K as Tg,g as ql,h as Ig,i as gu,j as Ng}from"./vendor-dnd-DRzYolkg.js";import{u as ff,a as hf,b as jg,M as Rg,N as fm,B as Dg}from"./vendor-router-BbWMxlnO.js";(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const l of o)if(l.type==="childList")for(const c of l.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&r(c)}).observe(document,{childList:!0,subtree:!0});function s(o){const l={};return o.integrity&&(l.integrity=o.integrity),o.referrerPolicy&&(l.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?l.credentials="include":o.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function r(o){if(o.ep)return;o.ep=!0;const l=s(o);fetch(o.href,l)}})();const Ic="default",yu="General",ms="task",Pg=2,Eg=[{value:Ic,label:yu,icon:"Inbox"}],gf=[{value:ms,label:"Task",icon:"CheckSquare",color:"blue-500"}],Lg=[{value:Pg,label:"Medium",color:"blue-500",icon:"Minus"}];function Mg(){return Eg.map(e=>({...e}))}function Bg(){return gf.map(e=>({...e}))}function Wg(e){const n=String(e||"").trim().toLowerCase();return gf.find(s=>s.value===n)}function yf(){return Lg.map(e=>({...e}))}const Fg="default",zg=[{value:Fg,label:"Default",color:"slate-500",icon:"Circle"},{value:"evaluate",label:"Evaluate",color:"amber-500",icon:"Search"},{value:"collaborate",label:"Collaborate",color:"blue-500",icon:"Users"},{value:"plan",label:"Plan",color:"teal-500",icon:"FileText"},{value:"review",label:"Review",color:"violet-500",icon:"Microscope"}];function kf(){return zg.map(e=>({...e}))}const Og={categories:Mg(),types:Bg(),priorities:yf(),approaches:kf(),taxonomies:[],apiEndpoint:"/api/taskforce/task",apiBaseUrl:void 0,cloudAuthBaseUrl:void 0,cloudMcpBaseUrl:void 0,wsBaseUrl:void 0,position:"bottom-right",offsetY:70,theme:"dark",shortcut:"Alt+T",manualComplexityEnabled:!1,checklistDropdownEnabled:!0,showTaskCardStatusLabel:!0},$g=["light","dawn","dark","midnight"],ru="dark",Ug=[{id:"light",label:"Light",family:"light",icon:"sun"},{id:"dawn",label:"Dawn",family:"light",icon:"wind"},{id:"dark",label:"Dark",family:"dark",icon:"moon"},{id:"midnight",label:"Midnight",family:"dark",icon:"sparkles"}],qg=new Set($g),Hg=new Set(Ug.filter(e=>e.family==="light").map(e=>e.id));function Gg(e){return typeof e=="string"&&qg.has(e)}function bc(e){if(typeof e!="string")return null;const n=e.trim().toLowerCase();return Gg(n)?n:null}function Sf(e){const n=bc(e);return n!==null&&Hg.has(n)}function xp(e){const n=typeof e=="number"?e:Number(e);if(!Number.isFinite(n))return null;const s=Math.floor(n);return s>0?s:null}function Dc(e,n){const s=xp(typeof n=="object"&&n!==null?n.referenceNumber:n);return s?`${e}${s}`:""}function Mp(e,n){const s=String(e||"").trim(),r=String(n||"").trim();if(!s||!r)return null;const o=s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),l=r.match(new RegExp(`^${o}(\\d+)$`,"i"));return l?xp(l[1]):null}function Hl(e,n){return n?typeof n.referenceLabel=="string"&&n.referenceLabel.trim().length>0?n.referenceLabel.trim():Dc(e,n.referenceNumber):""}const Bp="T-",hm="LT-";function Vg(e){return Dc(Bp,e)}function vf(e){return typeof e=="number"||e===null||e===void 0?Dc(hm,e):Dc(hm,{referenceNumber:e.localReferenceNumber??null})}function wf(e){return Mp(Bp,e)}function Rr(e){if(!e)return"";if(typeof e.referenceLabel=="string"&&e.referenceLabel.trim().length>0)return e.referenceLabel.trim();const n=Hl(Bp,e);return n||vf(e.localReferenceNumber)}function Zg(e){return!e?.referenceNumber&&!!e?.localReferenceNumber}function bf(e){return{label:Rr(e),isProvisional:Zg(e)}}yf();const Kg={low:1,medium:2,high:3,critical:4,"on-hold":1},Yg={1:"low",2:"medium",3:"high",4:"critical",5:"critical"};function Jg(e){const n=String(e||"").trim().toLowerCase();return n==="blocked"||n==="on hold"||n==="on-hold"?"on-hold":n==="task"||n==="on-hold"||n==="in-progress"||n==="review"||n==="done"||n==="cancelled"?n:"task"}function ou(e){if(typeof e=="number"&&Number.isFinite(e))return Math.max(1,Math.round(e));const n=Number(e);return Number.isFinite(n)?Math.max(1,Math.round(n)):Kg[String(e||"").trim().toLowerCase()]??2}function Xg(e,n){return Yg[String(e)]||n}function ro(e){const n=typeof e.referenceNumber=="number"?e.referenceNumber:Number.isFinite(Number(e.referenceNumber))?Number(e.referenceNumber):null,s=typeof e.localReferenceNumber=="number"?e.localReferenceNumber:Number.isFinite(Number(e.localReferenceNumber))?Number(e.localReferenceNumber):null;return{...e,referenceNumber:n&&n>0?Math.floor(n):null,localReferenceNumber:s&&s>0?Math.floor(s):null,referenceLabel:typeof e.referenceLabel=="string"&&e.referenceLabel.trim().length>0?e.referenceLabel.trim():n?Vg(n):vf(s),assignee:(()=>{const r=String(e.assignee||"").trim(),o=r.toLowerCase();return o==="agent"||o==="ai"?"agent":!r||o==="user"||o==="human"||o==="unassigned"||o==="none"||o==="null"?"unassigned":r})(),category:typeof e.category=="string"?e.category:e.category?.value||"default",type:(typeof e.type=="string"?e.type:e.type?.label||"task").toLowerCase(),priority:ou(e.priority),complexity:typeof e.complexity=="number"?e.complexity:3,status:Jg(e.status)}}function Qg(e,n,s){if(!e||typeof e!="object")return{tasks:n,archivedTasks:s};const r=ro(e),o=String(r.id||"").trim();if(!o)return{tasks:n,archivedTasks:s};const l=!!r.isArchived,c=l?{...r,isArchived:!0}:{...r,isArchived:!1},p=C=>[...C].sort((_,y)=>{const k=Date.parse(String(_.updatedAt||_.createdAt||"")),b=Date.parse(String(y.updatedAt||y.createdAt||""));if(Number.isFinite(k)&&Number.isFinite(b)&&k!==b)return b-k;if(Number.isFinite(k)!==Number.isFinite(b))return Number.isFinite(b)?1:-1;const E=Date.parse(String(y.createdAt||""))-Date.parse(String(_.createdAt||""));return Number.isFinite(E)&&E!==0?E:String(_.id).localeCompare(String(y.id))}),g=n.filter(C=>C.id!==o),w=s.filter(C=>C.id!==o);return l?w.push(c):g.push(c),{tasks:p(g),archivedTasks:p(w)}}function ey(e,n){if(!n.length||!e.length)return[];const s=new Set(n.map(o=>Number(o.value))),r=Array.from(new Set(e.map(o=>Number(o)).filter(o=>Number.isFinite(o)&&s.has(o))));return r.length>0?r:n.map(o=>Number(o.value))}function ap(e,n){return n.some(s=>String(s)===String(e))}function ty(e,n){if(!e.length||!n.length)return e;const s=new Set(n.map(o=>o.value)),r=Array.from(new Set(e.filter(o=>s.has(o))));return r.length>0?r:n.map(o=>o.value)}const ny={taskForm:{commentsSectionTitle:"Activity & Comments",hideComments:"Hide Comments",showComments:"Show Comments",noComments:"No comments yet. Start the conversation!",you:"You",commentPlaceholder:"Type a comment...",scheduledLabel:"Scheduled:",dueLabel:"Due:",createdLabel:"Created:",updatedLabel:"Updated:",completedLabel:"Completed:",emptyValue:"—",parentCannotSchedule:"Parent tasks cannot be scheduled. Schedule leaf tasks instead.",dueBeforeScheduled:"Due date is before scheduled date.",overdue:"This task is overdue."},schedule:{},taskList:{searchPlaceholder:"Search tasks...",clearSearchTitle:"Clear search",categoryLabel:"Category",typeLabel:"Type",priorityLabel:"Priority",statusLabel:"Status",assigneeLabel:"Assignee",sortByLabel:"Sort By:",sortCreated:"Created",sortUpdated:"Updated",sortPriority:"Priority",sortDirectionDescTitle:"Sort: Last First",sortDirectionAscTitle:"Sort: First First",resetFiltersTitle:"Reset all filters",archiveAllTitle:"Archive all completed and cancelled tasks",noTasksToArchiveTitle:"No tasks to archive",archiveFinished:"Archive Finished",linksLabel:"Links",linksAll:"All",linksParents:"Parents",linksLinked:"Linked",linksUnlinked:"Unlinked",includeArchive:"Archived",noMatchingTasks:"No matching tasks",noActiveTasks:"No active tasks",addTaskToCategoryTitle:"Add task to {category}"},actionHeader:{saveChangesTitle:"Save Changes",update:"Update",copyTaskIdTitle:"Click to copy Task ID",startWorking:"Start Working",stopWorking:"Stop Working",unlockAndContinue:"Unlock & Continue Work",readyForReview:"Ready for Review",markComplete:"Mark Complete",unmarkComplete:"Unmark Complete",cancelTask:"Cancel Task",unmarkCancelled:"Unmark Cancelled",archiveNow:"Archive Now",completeTaskToArchive:"Complete task to archive",clearFormTitle:"Clear Form",clear:"Clear",addTaskTitle:"Add Task",addTask:"Add Task"},standalone:{searchPlaceholder:"Search tasks...",clearSearchTitle:"Clear search",sortLabel:"Sort:",sortCreated:"Created",sortUpdated:"Updated",sortPriority:"Priority",sortComplexity:"Complexity",sortDirectionDescTitle:"Sort: Last First",sortDirectionAscTitle:"Sort: First First",groupLabel:"Group:",groupCategory:"Category",groupType:"Type",groupPriority:"Priority",groupComplexity:"Complexity",groupApproach:"Workflow",groupAssignee:"Assignee",groupStatus:"Status",groupHierarchy:"Hierarchy",groupSchedule:"Schedule",showEmptyColumns:"Show Empty Columns",compressEmptyColumns:"Compress Empty Columns",hideEmptyColumns:"Hide Empty Columns",expandCards:"Expand Cards",compressCards:"Compress Cards",exitZenMode:"Exit Zen Mode",enterZenMode:"Enter Zen Mode",toggleFilters:"Toggle Filters",addTask:"Add Task",helpTutorial:"Help / Tutorial",settings:"Settings",filtersCaps:"FILTERS:",categoryLabel:"Category",typeLabel:"Type",priorityLabel:"Priority",statusLabel:"Status",assigneeLabel:"Assignee",linksLabel:"Links:",chooseLinksTitle:"Choose which linked tasks are shown",linksAll:"All",linksParents:"Parents",linksLinked:"Linked",linksUnlinked:"Unlinked",includeArchiveTitle:"Include archived tasks",includeArchive:"Archived",clearFilters:"Clear Filters",noTasksMatchFilters:"No tasks match current filters.",showingWithLinksHint:"Showing: {parentFilterLabel}. Switch Links to All or clear filters.",visibleActiveTasksTitle:"Visible active tasks / total active tasks",totalActiveTasksTitle:"Total active tasks"},setup:{headingCheckFailed:"Setup Check Failed",headingGlobalRequired:"Global Setup Required",headingWorkspaceRequired:"Workspace Setup Required",subtitleUnreadable:"Taskforce could not read setup state. Retry to continue.",subtitleGlobalRequired:"Choose your default operating mode to continue.",subtitleWorkspaceRequired:"Set up your workspace profile to continue.",runtimeLabel:"Runtime",workspaceTermProject:"Project",workspaceTermMission:"Mission",coreModeOption:"Core Mode: {workspaceLabel} planning defaults",operationsModeOption:"Operations Mode: Mission-first terminology and flows",workspaceNamePlaceholder:"{workspaceLabel} name",workspaceDescriptionPlaceholder:"{workspaceLabel} description (optional)",saving:"Saving...",saveGlobalSetup:"Save Global Setup",saveWorkspaceSetup:"Save {workspaceLabel} Setup",globalSetupSaved:"Global setup saved.",workspaceSetupSaved:"{workspaceLabel} setup saved.",saveFailedWithStatus:"Failed to save setup ({status})",saveFailed:"Failed to save setup.",saveWorkspaceFailed:"Failed to save workspace profile.",retrySetupCheck:"Retry Setup Check",signOut:"Sign Out"}},ay={taskForm:{commentsSectionTitle:"Actividad y comentarios",hideComments:"Ocultar comentarios",showComments:"Mostrar comentarios",noComments:"Aun no hay comentarios. Inicia la conversacion.",you:"Tu",commentPlaceholder:"Escribe un comentario...",scheduledLabel:"Programado:",dueLabel:"Vence:",createdLabel:"Creado:",updatedLabel:"Actualizado:",completedLabel:"Completado:",emptyValue:"—",parentCannotSchedule:"Las tareas padre no se pueden programar. Programa tareas hoja en su lugar.",dueBeforeScheduled:"La fecha de vencimiento es anterior a la fecha programada.",overdue:"Esta tarea esta vencida."},schedule:{},taskList:{searchPlaceholder:"Buscar tareas...",clearSearchTitle:"Limpiar busqueda",categoryLabel:"Categoria",typeLabel:"Tipo",priorityLabel:"Prioridad",statusLabel:"Estado",assigneeLabel:"Asignado a",sortByLabel:"Ordenar por:",sortCreated:"Creado",sortUpdated:"Actualizado",sortPriority:"Prioridad",sortDirectionDescTitle:"Orden: mas reciente primero",sortDirectionAscTitle:"Orden: mas antiguo primero",resetFiltersTitle:"Restablecer todos los filtros",archiveAllTitle:"Archivar todas las tareas completadas y canceladas",noTasksToArchiveTitle:"No hay tareas para archivar",archiveFinished:"Archivar finalizadas",linksLabel:"Vinculos",linksAll:"Todas",linksParents:"Padres",linksLinked:"Vinculadas",linksUnlinked:"Sin vinculo",includeArchive:"Incluir archivo",noMatchingTasks:"No hay tareas coincidentes",noActiveTasks:"No hay tareas activas",addTaskToCategoryTitle:"Agregar tarea a {category}"},actionHeader:{saveChangesTitle:"Guardar cambios",update:"Actualizar",copyTaskIdTitle:"Haz clic para copiar el ID de la tarea",startWorking:"Comenzar trabajo",stopWorking:"Detener trabajo",unlockAndContinue:"Desbloquear y continuar",readyForReview:"Lista para revision",markComplete:"Marcar como completada",unmarkComplete:"Quitar completada",cancelTask:"Cancelar tarea",unmarkCancelled:"Quitar cancelada",archiveNow:"Archivar ahora",completeTaskToArchive:"Completa la tarea para archivar",clearFormTitle:"Limpiar formulario",clear:"Limpiar",addTaskTitle:"Agregar tarea",addTask:"Agregar tarea"},standalone:{searchPlaceholder:"Buscar tareas...",clearSearchTitle:"Limpiar busqueda",sortLabel:"Orden:",sortCreated:"Creado",sortUpdated:"Actualizado",sortPriority:"Prioridad",sortComplexity:"Complejidad",sortDirectionDescTitle:"Orden: mas reciente primero",sortDirectionAscTitle:"Orden: mas antiguo primero",groupLabel:"Agrupar:",groupCategory:"Categoria",groupType:"Tipo",groupPriority:"Prioridad",groupComplexity:"Complejidad",groupApproach:"Flujo de trabajo",groupAssignee:"Asignado a",groupStatus:"Estado",groupHierarchy:"Jerarquia",groupSchedule:"Calendario",showEmptyColumns:"Mostrar columnas vacias",compressEmptyColumns:"Comprimir columnas vacias",hideEmptyColumns:"Ocultar columnas vacias",expandCards:"Expandir tarjetas",compressCards:"Comprimir tarjetas",exitZenMode:"Salir del modo zen",enterZenMode:"Entrar en modo zen",toggleFilters:"Alternar filtros",addTask:"Agregar tarea",helpTutorial:"Ayuda / Tutorial",settings:"Configuracion",filtersCaps:"FILTROS:",categoryLabel:"Categoria",typeLabel:"Tipo",priorityLabel:"Prioridad",statusLabel:"Estado",assigneeLabel:"Asignado a",linksLabel:"Vinculos:",chooseLinksTitle:"Elige que tareas vinculadas se muestran",linksAll:"Todas",linksParents:"Padres",linksLinked:"Vinculadas",linksUnlinked:"Sin vinculo",includeArchiveTitle:"Incluir tareas archivadas",includeArchive:"Incluir archivo",clearFilters:"Limpiar filtros",noTasksMatchFilters:"Ninguna tarea coincide con los filtros actuales.",showingWithLinksHint:"Mostrando: {parentFilterLabel}. Cambia Vinculos a Todas o limpia filtros.",visibleActiveTasksTitle:"Tareas activas visibles / total de tareas activas",totalActiveTasksTitle:"Total de tareas activas"},setup:{headingCheckFailed:"Fallo en verificacion de configuracion",headingGlobalRequired:"Configuracion global requerida",headingWorkspaceRequired:"Configuracion del espacio requerida",subtitleUnreadable:"Taskforce no pudo leer el estado de configuracion. Reintenta para continuar.",subtitleGlobalRequired:"Elige tu modo operativo predeterminado para continuar.",subtitleWorkspaceRequired:"Configura el perfil de tu espacio para continuar.",runtimeLabel:"Entorno",workspaceTermProject:"Proyecto",workspaceTermMission:"Mision",coreModeOption:"Modo Core: valores predeterminados de planificacion para {workspaceLabel}",operationsModeOption:"Modo Operaciones: terminologia y flujos orientados a Mision",workspaceNamePlaceholder:"Nombre de {workspaceLabel}",workspaceDescriptionPlaceholder:"Descripcion de {workspaceLabel} (opcional)",saving:"Guardando...",saveGlobalSetup:"Guardar configuracion global",saveWorkspaceSetup:"Guardar configuracion de {workspaceLabel}",globalSetupSaved:"Configuracion global guardada.",workspaceSetupSaved:"Configuracion de {workspaceLabel} guardada.",saveFailedWithStatus:"Error al guardar la configuracion ({status})",saveFailed:"Error al guardar la configuracion.",saveWorkspaceFailed:"Error al guardar el perfil del espacio.",retrySetupCheck:"Reintentar verificacion",signOut:"Cerrar sesion"}},sy={taskForm:{commentsSectionTitle:"Atividade e comentarios",hideComments:"Ocultar comentarios",showComments:"Mostrar comentarios",noComments:"Ainda nao ha comentarios. Inicie a conversa.",you:"Voce",commentPlaceholder:"Digite um comentario...",scheduledLabel:"Agendado:",dueLabel:"Vencimento:",createdLabel:"Criado:",updatedLabel:"Atualizado:",completedLabel:"Concluido:",emptyValue:"—",parentCannotSchedule:"Tarefas pai nao podem ser agendadas. Agende as tarefas folha.",dueBeforeScheduled:"A data de vencimento e anterior a data agendada.",overdue:"Esta tarefa esta atrasada."},schedule:{},taskList:{searchPlaceholder:"Buscar tarefas...",clearSearchTitle:"Limpar busca",categoryLabel:"Categoria",typeLabel:"Tipo",priorityLabel:"Prioridade",statusLabel:"Status",assigneeLabel:"Atribuido para",sortByLabel:"Ordenar por:",sortCreated:"Criado",sortUpdated:"Atualizado",sortPriority:"Prioridade",sortDirectionDescTitle:"Ordem: mais recente primeiro",sortDirectionAscTitle:"Ordem: mais antigo primeiro",resetFiltersTitle:"Redefinir todos os filtros",archiveAllTitle:"Arquivar todas as tarefas concluidas e canceladas",noTasksToArchiveTitle:"Nao ha tarefas para arquivar",archiveFinished:"Arquivar finalizadas",linksLabel:"Vinculos",linksAll:"Todas",linksParents:"Pais",linksLinked:"Vinculadas",linksUnlinked:"Sem vinculo",includeArchive:"Incluir arquivo",noMatchingTasks:"Nenhuma tarefa correspondente",noActiveTasks:"Nenhuma tarefa ativa",addTaskToCategoryTitle:"Adicionar tarefa a {category}"},actionHeader:{saveChangesTitle:"Salvar alteracoes",update:"Atualizar",copyTaskIdTitle:"Clique para copiar o ID da tarefa",startWorking:"Iniciar trabalho",stopWorking:"Parar trabalho",unlockAndContinue:"Desbloquear e continuar",readyForReview:"Pronto para revisao",markComplete:"Marcar como concluida",unmarkComplete:"Desmarcar concluida",cancelTask:"Cancelar tarefa",unmarkCancelled:"Desmarcar cancelada",archiveNow:"Arquivar agora",completeTaskToArchive:"Conclua a tarefa para arquivar",clearFormTitle:"Limpar formulario",clear:"Limpar",addTaskTitle:"Adicionar tarefa",addTask:"Adicionar tarefa"},standalone:{searchPlaceholder:"Buscar tarefas...",clearSearchTitle:"Limpar busca",sortLabel:"Ordenar:",sortCreated:"Criado",sortUpdated:"Atualizado",sortPriority:"Prioridade",sortComplexity:"Complexidade",sortDirectionDescTitle:"Ordem: mais recente primeiro",sortDirectionAscTitle:"Ordem: mais antigo primeiro",groupLabel:"Agrupar:",groupCategory:"Categoria",groupType:"Tipo",groupPriority:"Prioridade",groupComplexity:"Complexidade",groupApproach:"Fluxo de trabalho",groupAssignee:"Atribuido para",groupStatus:"Status",groupHierarchy:"Hierarquia",groupSchedule:"Agenda",showEmptyColumns:"Mostrar colunas vazias",compressEmptyColumns:"Comprimir colunas vazias",hideEmptyColumns:"Ocultar colunas vazias",expandCards:"Expandir cards",compressCards:"Comprimir cards",exitZenMode:"Sair do modo zen",enterZenMode:"Entrar no modo zen",toggleFilters:"Alternar filtros",addTask:"Adicionar tarefa",helpTutorial:"Ajuda / Tutorial",settings:"Configuracoes",filtersCaps:"FILTROS:",categoryLabel:"Categoria",typeLabel:"Tipo",priorityLabel:"Prioridade",statusLabel:"Status",assigneeLabel:"Atribuido para",linksLabel:"Vinculos:",chooseLinksTitle:"Escolha quais tarefas vinculadas sao exibidas",linksAll:"Todas",linksParents:"Pais",linksLinked:"Vinculadas",linksUnlinked:"Sem vinculo",includeArchiveTitle:"Incluir tarefas arquivadas",includeArchive:"Incluir arquivo",clearFilters:"Limpar filtros",noTasksMatchFilters:"Nenhuma tarefa corresponde aos filtros atuais.",showingWithLinksHint:"Mostrando: {parentFilterLabel}. Mude Vinculos para Todas ou limpe os filtros.",visibleActiveTasksTitle:"Tarefas ativas visiveis / total de tarefas ativas",totalActiveTasksTitle:"Total de tarefas ativas"},setup:{headingCheckFailed:"Falha na verificacao da configuracao",headingGlobalRequired:"Configuracao global obrigatoria",headingWorkspaceRequired:"Configuracao do espaco obrigatoria",subtitleUnreadable:"Taskforce nao conseguiu ler o estado da configuracao. Tente novamente para continuar.",subtitleGlobalRequired:"Escolha seu modo operacional padrao para continuar.",subtitleWorkspaceRequired:"Configure o perfil do seu espaco para continuar.",runtimeLabel:"Ambiente",workspaceTermProject:"Projeto",workspaceTermMission:"Missao",coreModeOption:"Modo Core: padroes de planejamento para {workspaceLabel}",operationsModeOption:"Modo Operacoes: terminologia e fluxos orientados por Missao",workspaceNamePlaceholder:"Nome de {workspaceLabel}",workspaceDescriptionPlaceholder:"Descricao de {workspaceLabel} (opcional)",saving:"Salvando...",saveGlobalSetup:"Salvar configuracao global",saveWorkspaceSetup:"Salvar configuracao de {workspaceLabel}",globalSetupSaved:"Configuracao global salva.",workspaceSetupSaved:"Configuracao de {workspaceLabel} salva.",saveFailedWithStatus:"Falha ao salvar configuracao ({status})",saveFailed:"Falha ao salvar configuracao.",saveWorkspaceFailed:"Falha ao salvar perfil do espaco.",retrySetupCheck:"Tentar verificacao novamente",signOut:"Sair"}},_f=["en-US","es-419","pt-BR"],iu="en-US",sp={"en-US":ny,"es-419":ay,"pt-BR":sy},Cf={en:"en-US",es:"es-419",pt:"pt-BR"};let Ti=iu;function ry(e){return e.split(".").filter(Boolean)}function rp(e,n){let s=e;for(const r of n){if(!s||typeof s!="object")return;s=s[r]}return typeof s=="string"?s:void 0}function xf(e){if(!e)return iu;const n=_f.find(r=>r.toLowerCase()===e.toLowerCase());if(n)return n;const s=e.split("-")[0]?.toLowerCase()||"";return Cf[s]||iu}function op(e,n){return n?e.replace(/\{([^}]+)\}/g,(s,r)=>{const o=n[r];return o==null?"":String(o)}):e}function Af(){return Ti}function oy(){return[..._f]}function Tf(e){const n=xf(e);return Ti=n,n}function iy(e){const n=typeof navigator<"u"?navigator.language:null;return Ti=xf(n),Ti}function xe(e,n){const s=ry(e),r=rp(sp[Ti],s);if(r)return op(r,n);const o=Ti.split("-")[0]?.toLowerCase()||"",l=Cf[o];if(l&&l!==Ti){const p=rp(sp[l],s);if(p)return op(p,n)}const c=rp(sp[iu],s);return c?op(c,n):e}const cy="default",Mo="bootstrap";function ly(e){let n=2166136261;for(let s=0;s<e.length;s+=1)n^=e.charCodeAt(s),n=Math.imul(n,16777619);return(n>>>0).toString(16).padStart(8,"0")}function Wp(e){const n=String(e||"").trim().toLowerCase();return n?`${(n.replace(/[^a-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")||"project").slice(0,56)}-${ly(n)}`:Mo}function If(e){const n=String(e||"").trim().toLowerCase();if(!n)return Mo;const s=n.replace(/[^a-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"");return s?s.slice(0,96):Mo}function Nf(e){const n=String(e||"").trim();return n?Wp(n):Mo}function dy(e){return(e.runtimeMode==="cloud"?"cloud":"local")==="cloud"?Mo:Nf(e.projectRoot)}function uy(e){if((e.runtimeMode==="cloud"?"cloud":"local")==="cloud"){const s=String(e.workspaceId||"").trim();return s&&!Fp(s)?Wp(`cloud-workspace:${s}`):Mo}return Nf(e.projectRoot)}function Fp(e){return String(e||"").trim().toLowerCase()===cy}const py={local:{runtimeMode:"local",authSource:"cloud",workspaceMode:"single-local",workspaceSwitchingEnabled:!1},cloud:{runtimeMode:"cloud",authSource:"cloud",workspaceMode:"multi-cloud",workspaceSwitchingEnabled:!0}};function my(e){return String(e||"").trim().toLowerCase()==="cloud"?"cloud":"local"}function fy(e){return py[my(e)]}function gm(e){if(!Array.isArray(e))return;const n=e.filter(s=>typeof s=="string"&&s.trim().length>0).map(s=>s.trim());return n.length>0?n:void 0}function hy(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;const n=e;return Array.isArray(n.categories)||Array.isArray(n.types)||Array.isArray(n.priorities)||Array.isArray(n.taxonomies)||!!n.displayLabels&&typeof n.displayLabels=="object"&&!Array.isArray(n.displayLabels)}function gy(e){const n=e||{};return{categories:Array.isArray(n.categories)?n.categories.map(r=>typeof r=="string"?{value:r.toLowerCase().replace(/\s+/g,"-"),label:r}:r):[],types:Array.isArray(n.types)?n.types.map(r=>({...Wg(r.value),...r,aliases:Array.isArray(r.aliases)?r.aliases.filter(l=>typeof l=="string"&&l.trim().length>0).map(l=>l.trim()):void 0,status:r.status==="retired"?"retired":"active"})):[],priorities:Array.isArray(n.priorities)?n.priorities:[],taxonomies:Array.isArray(n.taxonomies)?n.taxonomies.map(r=>({...r,aliases:gm(r.aliases),options:Array.isArray(r.options)?r.options.map(o=>({...o,aliases:gm(o.aliases),status:o.status==="retired"?"retired":"active"})):[],status:r.status==="retired"?"retired":"active",formEnabled:r.formEnabled!==!1,filterEnabled:r.filterEnabled!==!1,sortEnabled:r.sortEnabled===!0})):[],displayLabels:{category:typeof n.displayLabels?.category=="string"&&n.displayLabels.category.trim().length>0?n.displayLabels.category.trim():void 0,type:typeof n.displayLabels?.type=="string"&&n.displayLabels.type.trim().length>0?n.displayLabels.type.trim():void 0,priority:typeof n.displayLabels?.priority=="string"&&n.displayLabels.priority.trim().length>0?n.displayLabels.priority.trim():void 0}}}const zl={production:{appBaseUrl:"https://app.taskforcehq.ai",mcpBaseUrl:"https://mcp.taskforcehq.ai",label:"Production",themeToken:"production"},staging:{appBaseUrl:"https://staging-app.taskforcehq.ai",mcpBaseUrl:"https://staging-mcp.taskforcehq.ai",label:"Staging",themeToken:"staging"},performance:{appBaseUrl:"https://performance-app.taskforcehq.ai",mcpBaseUrl:"https://performance-mcp.taskforcehq.ai",label:"Performance",themeToken:"performance"}};function ku(e){const n=String(e||"").trim().toLowerCase();return n==="production"||n==="staging"||n==="performance"?n:null}function yy(e){return ku(e)||"production"}function ym(e){return zl[yy(String(e||""))]}function ky(e){const n=String(e||"").trim().toLowerCase();if(!n)return null;for(const[s,r]of Object.entries(zl))if(new URL(r.appBaseUrl).hostname.toLowerCase()===n||new URL(r.mcpBaseUrl).hostname.toLowerCase()===n)return s;return null}function zp(e){const n=String(e||"").trim();if(!n)return null;try{return ky(new URL(n).hostname)}catch{return null}}function Sy(e){const n=zp(e);return n?zl[n].mcpBaseUrl:null}function yi(e,n){return String(e[n]||"").trim()}function km(e,n,s){e.push(n),s?.(n)}function vy(e,n){const s=[],r=yi(e,"ENV"),o=ku(r);if(o)return km(s,`[Taskforce compat] ENV=${r} is deprecated; set TASKFORCE_CLOUD_ENVIRONMENT=${o} instead.`,n),{cloudEnvironment:o,warnings:s};const l=[{key:"TASKFORCE_CLOUD_PROXY_BASE_URL",value:yi(e,"TASKFORCE_CLOUD_PROXY_BASE_URL")},{key:"VITE_TASKFORCE_CLOUD_AUTH_BASE_URL",value:yi(e,"VITE_TASKFORCE_CLOUD_AUTH_BASE_URL")},{key:"VITE_TASKFORCE_CLOUD_MCP_BASE_URL",value:yi(e,"VITE_TASKFORCE_CLOUD_MCP_BASE_URL")},{key:"VITE_TASKFORCE_API_BASE_URL",value:yi(e,"VITE_TASKFORCE_API_BASE_URL")},{key:"VITE_TASKFORCE_BASE_URL",value:yi(e,"VITE_TASKFORCE_BASE_URL")},{key:"TASKFORCE_BASE_URL",value:yi(e,"TASKFORCE_BASE_URL")}];for(const c of l){if(!c.value)continue;const p=zp(c.value);if(p)return km(s,`[Taskforce compat] ${c.key} is being used to infer TASKFORCE_CLOUD_ENVIRONMENT=${p}. Set TASKFORCE_CLOUD_ENVIRONMENT explicitly.`,n),{cloudEnvironment:p,warnings:s}}return{cloudEnvironment:null,warnings:s}}function Nr(e,n){return String(e[n]||"").trim()}function wy(e){return e.toLowerCase()==="cloud"?"cloud":"local"}function vc(e){return String(e||"").trim().replace(/\/+$/,"")}function by(e){return String(e||"").trim().replace(/\/+$/,"")}function Xr(...e){for(const n of e)if(String(n||"").trim())return String(n||"").trim();return""}function _y(e,n={}){const s=[],r=D=>{s.push(D),n.onWarning?.(D)},o=wy(Nr(e,"TASKFORCE_RUNTIME_MODE")),l=ku(Nr(e,"TASKFORCE_CLOUD_ENVIRONMENT")),c=l?{cloudEnvironment:l}:vy(e,r),p=l||c.cloudEnvironment,g=vc(String(n.requestBaseUrl||"")),w=vc(Xr(Nr(e,"VITE_TASKFORCE_BASE_URL"),Nr(e,"TASKFORCE_BASE_URL"))),C=vc(Nr(e,"VITE_TASKFORCE_API_BASE_URL")),_=vc(Nr(e,"VITE_TASKFORCE_CLOUD_AUTH_BASE_URL")),y=vc(Xr(Nr(e,"VITE_TASKFORCE_CLOUD_MCP_BASE_URL"),Nr(e,"TASKFORCE_CLOUD_MCP_BASE_URL"))),k=vc(Nr(e,"TASKFORCE_CLOUD_PROXY_BASE_URL")),b=by(Nr(e,"VITE_TASKFORCE_WS_BASE_URL")),E=p?zl[p].appBaseUrl:"",S=p?zl[p].mcpBaseUrl:"",W=Xr(k,_,C,w,E),Q=Xr(y,S,W),z=Xr(g,w,C,_,W),K=Xr(g,C,w,W),V=Xr(_,w,C,W),ne=o==="local"?Xr(b,g,C,w,k,_,E,W):Xr(g,b,K,z,W);return{runtimeMode:o,cloudEnvironment:p,cloudBaseUrl:W,cloudMcpBaseUrl:Q,baseUrl:z,apiBaseUrl:K,cloudAuthBaseUrl:V,wsBaseUrl:ne,cloudAuthViaLocalProxy:o==="local"||!!k,warnings:s}}function Op(e){return _y({TASKFORCE_CLOUD_ENVIRONMENT:"",VITE_TASKFORCE_BASE_URL:e.VITE_TASKFORCE_BASE_URL,VITE_TASKFORCE_API_BASE_URL:e.VITE_TASKFORCE_API_BASE_URL,VITE_TASKFORCE_CLOUD_AUTH_BASE_URL:e.VITE_TASKFORCE_CLOUD_AUTH_BASE_URL,VITE_TASKFORCE_CLOUD_MCP_BASE_URL:e.VITE_TASKFORCE_CLOUD_MCP_BASE_URL,VITE_TASKFORCE_WS_BASE_URL:e.VITE_TASKFORCE_WS_BASE_URL})}const cu="unassigned",jf="agent",Cy="user",xy=/^[0-9a-f]{8,}$/i;function Rf(e){const n=String(e||"").trim().toLowerCase();return n===jf||n==="ai"||n.startsWith("ai-profile-")}function Df(e){const n=String(e||"").trim().toLowerCase();return!n||n===cu||n==="none"||n==="null"||n===Cy}function lu(e){return Rf(e)?"agent":Df(e)?"unassigned":"member"}function Ay(e){const n=String(e.displayName||"").trim(),s=String(e.email||"").trim().toLowerCase();return n||s||String(e.userId||"").trim()||"Workspace member"}function wi(){return[{value:cu,label:"Unassigned",icon:"HelpCircle",color:"var(--text-secondary)",kind:"unassigned"}]}function Ty(e){const n=new Map;for(const s of e){const r=String(s.userId||"").trim();r&&n.set(r,{value:r,label:Ay(s),icon:"User",color:"#22c55e",kind:"member"})}return Ol(Array.from(n.values()))}function Ol(e){const n=new Map;for(const r of wi())n.set(r.value,r);for(const r of Array.isArray(e)?e:[]){const o=String(r?.value||"").trim();!o||o===cu||o===jf||n.set(o,{value:o,label:String(r.label||o).trim()||o,icon:String(r.icon||(r.kind==="agent"?"Bot":"User")),color:String(r.color||(r.kind==="agent"?"#8b5cf6":"#22c55e")),kind:r.kind==="agent"?"agent":"member"})}const s=[cu];return Array.from(n.values()).sort((r,o)=>{const l=s.indexOf(r.value),c=s.indexOf(o.value);return l>=0||c>=0?l<0?1:c<0?-1:l-c:r.label.localeCompare(o.label,void 0,{sensitivity:"base"})})}function Iy(e,n){const s=String(n||"").trim();if(!s||e.some(l=>l.value===s))return e;const r=s.replace(/^ai-profile-/i,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim(),o=r?r.split(" ").map(l=>l.charAt(0).toUpperCase()+l.slice(1)).join(" "):s;if(lu(s)==="agent"){const l=String(s).toLowerCase().startsWith("ai-profile-")&&r.split(" ").every(c=>xy.test(c));return Ol([...e,{value:s,label:l?"AI":o||"AI",icon:"Bot",color:"#8b5cf6",kind:"agent"}])}return lu(s)==="member"?Ol([...e,{value:s,label:o||s,icon:"User",color:"#22c55e",kind:"member"}]):e}function Pf(e){const n=Array.isArray(e)?e.filter(Boolean):[];return Ol(n)}function wc(e,n){const s=String(e||"").trim(),o=Pf(n).find(l=>l.value===s);return o?o.label:Rf(s)?"AI":Df(s)?"Unassigned":s||"Unassigned"}const Ef="taskforce.workspaceContext.v2",Ny="taskforce.uiState.app.v1",jy="taskforce.bootstrapDebug.v1";function Ry(){if(typeof window>"u")return!1;try{const e=String(window.localStorage.getItem(jy)||"").trim().toLowerCase();return e==="1"||e==="true"||e==="on"||e==="yes"}catch{return!1}}function Bn(e,n){if(!Ry())return;console.info("[Taskforce Bootstrap]",e,n&&typeof n=="object"?n:{})}function Lf(e){const n=Wp(e);return`${Ef}.${n}`}function Dy(e){const n=If(e);return`${Ef}.${n}`}function qd(e){if(typeof window>"u")return"";try{const n=Lf(e),s=String(window.localStorage.getItem(n)||"").trim();if(s&&s.length<=120&&!/\s/.test(s))return s;const r=Dy(e),o=String(window.localStorage.getItem(r)||"").trim();return o&&o.length<=120&&!/\s/.test(o)?(window.localStorage.setItem(n,o),o):""}catch{return""}}function Py(e,n){if(typeof window>"u")return;const s=String(e||"").trim();try{if(!s||Fp(s))return;const r=Lf(n),o=String(window.localStorage.getItem(r)||"").trim();if(!s&&o&&o.toLowerCase()!=="default")return;window.localStorage.setItem(r,s)}catch{}}function Mf(e){const n=If(e);return`${Ny}.${n}`}function Sm(e){if(typeof window>"u")return null;try{const n=window.localStorage.getItem(Mf(e));if(!n)return null;const s=JSON.parse(n);return s&&typeof s=="object"?s:null}catch{return null}}function Ey(e,n){if(!(typeof window>"u"))try{window.localStorage.setItem(Mf(n),JSON.stringify(e))}catch{}}const Ap="taskforce.localMutationActorUserId.v1";function Bf(e){return typeof e=="string"?e.trim().replace(/\/+$/,""):""}function Ly(e){const n=String(e||"").trim().toLowerCase();return n==="localhost"||n==="127.0.0.1"||n==="::1"||n==="[::1]"}function Tl(e){if(!(typeof window>"u"))try{const n=String(e||"").trim();if(!n||n==="anonymous"){window.sessionStorage.removeItem(Ap);return}window.sessionStorage.setItem(Ap,n)}catch{}}function Wf(){if(typeof window>"u")return"";try{return String(window.sessionStorage.getItem(Ap)||"").trim()}catch{return""}}function My(e,n){if(typeof window>"u"||!e.startsWith("/api/taskforce/")||!Ly(window.location.hostname))return!1;try{return new URL(n,window.location.origin).origin===window.location.origin}catch{return e.startsWith("/")}}function By(e,n,s){if(!My(e,n))return s;const r=Wf();if(!r)return s;const o=new Headers(s?.headers||void 0);return o.has("x-taskforce-user-id")||o.set("x-taskforce-user-id",r),{...s,headers:o}}function Wy(e,n){if(!e.startsWith("/"))return e;const s=Bf(n);return s?`${s}${e}`:e}async function Hd(e,n,s){const r=Wy(e,s),o=Bf(s).length>0,l=By(e,r,n),c=typeof performance<"u"?performance.now():Date.now();try{const p=await fetch(r,l);if(!(o&&r!==e&&e.startsWith("/api/taskforce/")&&(p.status===401||p.status===403)))return p;Bn("taskforce_api_auth_fallback_retry",{path:e,primaryUrl:r,fallbackUrl:e,status:p.status,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-c)});try{const w=await fetch(e,l);return Bn("taskforce_api_auth_fallback_completed",{path:e,primaryUrl:r,fallbackUrl:e,primaryStatus:p.status,fallbackStatus:w.status,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-c)}),w}catch{return Bn("taskforce_api_auth_fallback_failed",{path:e,primaryUrl:r,fallbackUrl:e,status:p.status,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-c)}),p}}catch(p){if(!o||!e.startsWith("/"))throw p;Bn("taskforce_api_network_fallback_retry",{path:e,primaryUrl:r,fallbackUrl:e,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-c),error:p instanceof Error?p.message:String(p)});const g=await fetch(e,l);return Bn("taskforce_api_network_fallback_completed",{path:e,primaryUrl:r,fallbackUrl:e,fallbackStatus:g.status,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-c)}),g}}function Fy(e){const n=Number(e?.status);return Number.isFinite(n)&&n>0?Math.floor(n):0}async function Ec(e){try{const n=await e,s=await n.text().catch(()=>"");let r={};if(s)try{r=JSON.parse(s)}catch{r={error:!n.ok&&n.statusText?`${n.status} ${n.statusText}`:s.slice(0,400)}}else!n.ok&&n.statusText&&(r={error:`${n.status} ${n.statusText}`});const o=n.headers.get("retry-after");let l;if(o){const c=Number.parseInt(o,10);if(Number.isFinite(c)&&c>0)l=c*1e3;else{const p=Date.parse(o);if(Number.isFinite(p)){const g=p-Date.now();g>0&&(l=g)}}}return{ok:n.ok,status:n.status,data:r,retryAfterMs:l}}catch(n){return{ok:!1,status:Fy(n),data:{}}}}async function zy(e){return Ec(fetch(e("/api/taskforce/sync/user-settings"),{method:"GET",credentials:"include"}))}async function Oy(e,n){return Ec(fetch(e("/api/taskforce/sync/user-settings"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(n)}))}async function vm(e,n){return Ec(fetch(e("/api/taskforce/sync/workspace/handshake"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({workspaceId:n})}))}async function $y(e,n){return Ec(fetch(e("/api/taskforce/sync/workspace/provision"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(n)}))}async function Uy(e,n){const s=new URLSearchParams({limit:String(n.limit),workspaceId:n.workspaceId});n.cursor&&s.set("cursor",n.cursor),n.repairMode===!0&&s.set("repair","1");const r=e("/api/taskforce/sync/workspace/pull"),o=r.includes("?")?"&":"?";return Ec(fetch(`${r}${o}${s.toString()}`,{method:"GET",credentials:"include"}))}async function qy(e,n){return Ec(fetch(e("/api/taskforce/sync/workspace/push"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({...n,...n.repairMode===!0?{repair:!0}:{}})}))}async function wm(e,n,s){const r=JSON.stringify({workspaceId:e,changes:n,workspaceMembers:Array.isArray(s?.workspaceMembers)?s.workspaceMembers:void 0,...s?.repairMode===!0?{repair:!0}:{},bootstrapSnapshot:s?.bootstrapSnapshot?{currentAnnotatedAttachmentSessionIds:Array.isArray(s.bootstrapSnapshot.currentAnnotatedAttachmentSessionIds)?s.bootstrapSnapshot.currentAnnotatedAttachmentSessionIds:[]}:void 0}),o="/api/taskforce/sync/workspace/apply-local",l=[];try{const c=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json","x-taskforce-workspace-id":e},credentials:"include",body:r});if(c.ok){const w=await c.json().catch(()=>({}));return{ok:!0,status:c.status,data:w,failures:l}}const p=await c.text().catch(()=>"");let g={};if(p)try{g=JSON.parse(p)}catch{g={error:p.slice(0,400)}}else c.statusText&&(g={error:`${c.status} ${c.statusText}`});return l.push(`${o}:${c.status}`),{ok:!1,status:c.status,data:g,failures:l}}catch{l.push(`${o}:network`)}return{ok:!1,status:0,data:{},failures:l}}const Tp="V1:AESGCM:",$p="AES-GCM",Hy=12;async function Ff(e){const n=Buffer.from(e,"base64");if(n.length!==32)throw new Error("Encryption key must be exactly 32 bytes (256-bit).");return crypto.subtle.importKey("raw",n,{name:$p},!1,["encrypt","decrypt"])}async function bm(e,n){if(!e)return e;const s=crypto.getRandomValues(new Uint8Array(Hy)),r=await Ff(n),l=new TextEncoder().encode(e),c=await crypto.subtle.encrypt({name:$p,iv:s},r,l),p=Buffer.from(c).toString("base64"),g=Buffer.from(s).toString("base64");return`${Tp}${g}:${p}`}async function _m(e,n){if(!e||!e.startsWith(Tp))return e;const s=e.slice(Tp.length),[r,o]=s.split(":");if(!r||!o)throw new Error("Malformed encrypted document payload.");const l=Buffer.from(r,"base64"),c=Buffer.from(o,"base64"),p=await Ff(n);try{const g=await crypto.subtle.decrypt({name:$p,iv:l},p,c);return new TextDecoder("utf-8").decode(g)}catch(g){throw new Error(`Failed to decrypt document: ${g.message}`)}}var _c={};function Dr(e){return e&&typeof e=="object"?e:{}}function ao(e){const n=Number(e||0);return n===0||n===429||n>=500}function Gy(e,n){const s=String(e.code||"").trim().toUpperCase(),r=String(e.error||"").trim();return s==="WORKSPACE_ID_ALREADY_EXISTS"||r.toLowerCase()==="workspace id already exists"?"This workspace is already linked to another cloud account. Sign in with the original account, ask the workspace owner to grant you access, or keep this workspace local-only.":r||`Workspace provisioning failed (${n})`}async function Vy(e){if(!e.cloudAuthConfigured)return{success:!1,error:"Cloud auth endpoint is not configured."};if(e.runtimeMode!=="local")return{success:!1,error:"Workspace sync is only available in local runtime."};if(!e.isAuthenticated)return{success:!1,error:"Authentication required."};try{let n=await vm(e.resolveCloudAuthUrl,e.workspaceId);if(n.ok)return{success:!0,provisioned:!1};const s=Dr(n.data);if(n.status===401)return{success:!1,statusCode:401,transient:!1,error:String(s.error||"Authentication required for workspace sync.")};if(n.status===429)return{success:!1,statusCode:429,retryAfterMs:n.retryAfterMs,transient:!0,error:String(s.error||"Workspace sync rate limited. Please retry later.")};if(n.status===409&&s.code==="WORKSPACE_ID_MISMATCH"){const r=await $y(e.resolveCloudAuthUrl,{workspaceId:e.workspaceId,name:e.workspaceName||e.workspaceId});if(!r.ok){const o=Dr(r.data);return{success:!1,statusCode:r.status,error:Gy(o,r.status)}}if(n=await vm(e.resolveCloudAuthUrl,e.workspaceId),!n.ok){const o=Dr(n.data);return n.status===401?{success:!1,statusCode:401,transient:!1,error:String(o.error||"Authentication required for workspace sync.")}:n.status===429?{success:!1,statusCode:429,retryAfterMs:n.retryAfterMs,transient:!0,error:String(o.error||"Workspace sync rate limited. Please retry later.")}:{success:!1,statusCode:n.status,transient:ao(n.status),error:String(o.error||`Workspace sync handshake failed (${n.status})`)}}return{success:!0,provisioned:!0}}return{success:!1,statusCode:n.status,transient:ao(n.status),error:String(s.error||`Workspace sync handshake failed (${n.status})`)}}catch{return{success:!1,statusCode:0,transient:!0,error:"Failed to validate workspace sync access."}}}async function Zy(e,n){const s=JSON.stringify([e,n]);try{const r=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(s));return Array.from(new Uint8Array(r)).map(o=>o.toString(16).padStart(2,"0")).join("")}catch{let r=2166136261;for(let l=0;l<s.length;l+=1)r^=s.charCodeAt(l),r=Math.imul(r,16777619);const o=(r>>>0).toString(16).padStart(8,"0");return`${e}:fallback:${o}`}}async function Ky(e){const n=e.payload.changes.length,s=e.payload.deleteTaskIds.size,r=await Zy(e.workspaceId,e.payload.changes);let o=0,l=e.payload.changes;if(typeof process<"u"&&_c?.TASKFORCE_SYNC_KEY){const C=_c.TASKFORCE_SYNC_KEY,_=[];for(const y of l)y.op==="document-upsert"&&typeof y.content=="string"?_.push({...y,content:await bm(y.content,C)}):y.op==="asset-upsert"&&typeof y.contentBase64=="string"&&y.contentBase64.length>0?_.push({...y,contentBase64:await bm(y.contentBase64,C)}):_.push(y);l=_}const c=async()=>{const C=Date.now(),_=await qy(e.resolveCloudAuthUrl,{workspaceId:e.workspaceId,idempotencyKey:r,changes:l,repairMode:e.repairMode===!0});return o+=Date.now()-C,_};let p=await c();if(!p.ok&&(p.status===403||p.status===409)&&(await e.ensureCloudWorkspaceReadyForSync()).success&&(p=await c()),!p.ok){const C=Dr(p.data);return{success:!1,status:p.status,error:typeof C.error=="string"?C.error:void 0,code:typeof C.code=="string"?C.code:void 0,retryAfterMs:p.retryAfterMs,transient:ao(p.status),requestMs:o,changeCount:n,deleteCount:s,currentTaskIds:e.payload.currentTaskIds,deleteTaskIds:e.payload.deleteTaskIds,currentInitiativeIds:e.payload.currentInitiativeIds,currentInitiativeWatermarks:e.payload.currentInitiativeWatermarks,currentWorkstreamIds:e.payload.currentWorkstreamIds,currentWorkstreamWatermarks:e.payload.currentWorkstreamWatermarks,currentAiProfileIds:e.payload.currentAiProfileIds,currentAiProfileWatermarks:e.payload.currentAiProfileWatermarks,currentDocumentPaths:e.payload.currentDocumentPaths,deleteDocumentPaths:e.payload.deleteDocumentPaths,currentDocumentWatermarks:e.payload.currentDocumentWatermarks,currentAssetPaths:e.payload.currentAssetPaths,deleteAssetPaths:e.payload.deleteAssetPaths,currentAssetWatermarks:e.payload.currentAssetWatermarks,currentDocumentReviewSessionIds:e.payload.currentDocumentReviewSessionIds,deleteDocumentReviewSessionIds:e.payload.deleteDocumentReviewSessionIds,currentDocumentReviewSessionWatermarks:e.payload.currentDocumentReviewSessionWatermarks,currentDocumentReviewCommentIds:e.payload.currentDocumentReviewCommentIds,deleteDocumentReviewCommentIds:e.payload.deleteDocumentReviewCommentIds,currentDocumentReviewCommentWatermarks:e.payload.currentDocumentReviewCommentWatermarks,currentAnnotatedAttachmentSessionIds:e.payload.currentAnnotatedAttachmentSessionIds,deleteAnnotatedAttachmentSessionIds:e.payload.deleteAnnotatedAttachmentSessionIds,currentAnnotatedAttachmentSessionWatermarks:e.payload.currentAnnotatedAttachmentSessionWatermarks,pushedWatermarks:new Map,emittedEventIds:[]}}const g=Dr(p.data),w=Array.isArray(g.emittedEventIds)?Array.from(new Set(g.emittedEventIds.map(C=>String(C||"").trim()).filter(Boolean))):[];return{success:!0,syncedAt:new Date().toISOString(),requestMs:o,changeCount:n,deleteCount:s,currentTaskIds:e.payload.currentTaskIds,deleteTaskIds:e.payload.deleteTaskIds,currentInitiativeIds:e.payload.currentInitiativeIds,currentInitiativeWatermarks:e.payload.currentInitiativeWatermarks,currentWorkstreamIds:e.payload.currentWorkstreamIds,currentWorkstreamWatermarks:e.payload.currentWorkstreamWatermarks,currentAiProfileIds:e.payload.currentAiProfileIds,currentAiProfileWatermarks:e.payload.currentAiProfileWatermarks,currentDocumentPaths:e.payload.currentDocumentPaths,deleteDocumentPaths:e.payload.deleteDocumentPaths,currentDocumentWatermarks:e.payload.currentDocumentWatermarks,currentAssetPaths:e.payload.currentAssetPaths,deleteAssetPaths:e.payload.deleteAssetPaths,currentAssetWatermarks:e.payload.currentAssetWatermarks,currentDocumentReviewSessionIds:e.payload.currentDocumentReviewSessionIds,deleteDocumentReviewSessionIds:e.payload.deleteDocumentReviewSessionIds,currentDocumentReviewSessionWatermarks:e.payload.currentDocumentReviewSessionWatermarks,currentDocumentReviewCommentIds:e.payload.currentDocumentReviewCommentIds,deleteDocumentReviewCommentIds:e.payload.deleteDocumentReviewCommentIds,currentDocumentReviewCommentWatermarks:e.payload.currentDocumentReviewCommentWatermarks,currentAnnotatedAttachmentSessionIds:e.payload.currentAnnotatedAttachmentSessionIds,deleteAnnotatedAttachmentSessionIds:e.payload.deleteAnnotatedAttachmentSessionIds,currentAnnotatedAttachmentSessionWatermarks:e.payload.currentAnnotatedAttachmentSessionWatermarks,pushedWatermarks:e.payload.pushedWatermarks,emittedEventIds:w}}async function Yy(e){let n=e.cursor,s=!0,r=0,o=0,l=0,c=0;const p=new Set;let g=!1,w=!1;const C=new Set,_=new Set,y=new Set,k=Number.isFinite(Number(e.maxPages))?Math.max(1,Math.floor(Number(e.maxPages))):20;try{for(;s&&r<k;){const b=async()=>{const K=Date.now(),V=await Uy(e.resolveCloudAuthUrl,{workspaceId:e.workspaceId,cursor:n,limit:e.bootstrap?500:200,repairMode:e.repairMode===!0});return l+=Date.now()-K,V};let E=await b();if(!E.ok&&E.status===403&&e.ensureCloudWorkspaceReadyForSync&&(await e.ensureCloudWorkspaceReadyForSync()).success&&(E=await b()),!E.ok)return{success:!1,kind:"pull_http",status:E.status,retryAfterMs:E.retryAfterMs,transient:ao(E.status),cursor:n,pages:r,appliedChanges:o,pullRequestMs:l,applyMs:c,pulledDeleteTaskIds:p,pulledActiveUpserts:g,pulledArchivedUpserts:w,documentDecryptFailures:Array.from(C)};const S=E.data||{},W=Array.isArray(S?.changes)?S.changes:[],Q=Array.isArray(S?.workspaceMembers),z=Q?S.workspaceMembers:void 0;for(const K of W){if(K.op==="upsert"){K?.archived===!0||K?.task?.isArchived===!0?w=!0:g=!0;continue}if(K.op==="annotated-attachment-session-upsert"){const ne=String(K?.session?.id||"").trim();ne&&y.add(ne);continue}if(K.op==="document-upsert"){if(typeof K.content=="string"&&typeof process<"u"&&_c?.TASKFORCE_SYNC_KEY)try{K.content=await _m(K.content,_c.TASKFORCE_SYNC_KEY)}catch{const ne=String(K.path||"").trim();ne&&C.add(ne)}continue}if(K.op==="asset-upsert"){if(typeof K.contentBase64=="string"&&typeof process<"u"&&_c?.TASKFORCE_SYNC_KEY)try{K.contentBase64=await _m(K.contentBase64,_c.TASKFORCE_SYNC_KEY)}catch{const ne=String(K.path||"").trim();ne&&C.add(ne)}continue}if(K.op!=="delete")continue;const V=String(K.taskId||"").trim();V&&p.add(V)}if(e.onPagePulled&&e.onPagePulled(),W.length>0||Q){const K=Date.now(),V=await wm(e.workspaceId,W,{...Q?{workspaceMembers:z}:{},repairMode:e.repairMode===!0}),ne=V.failures;if(!V.ok){c+=Date.now()-K;const Ae=Dr(V.data);if(ne.some(be=>be.endsWith(":401")))return{success:!1,kind:"apply_auth",status:401,transient:!1,failures:ne,cursor:n,pages:r,appliedChanges:o,pullRequestMs:l,applyMs:c,pulledDeleteTaskIds:p,pulledActiveUpserts:g,pulledArchivedUpserts:w,documentDecryptFailures:Array.from(C)};const ee=ne.some(be=>{if(be.endsWith(":network"))return!0;const me=be.split(":").pop()||"",Y=Number.parseInt(me,10);return Number.isFinite(Y)&&(Y===429||Y>=500)});return{success:!1,kind:"apply_all_candidates",status:V.status||void 0,transient:ee,error:String(Ae.error||"").trim()||void 0,failures:ne,hasTransientApplyFailure:ee,cursor:n,pages:r,appliedChanges:o,pullRequestMs:l,applyMs:c,pulledDeleteTaskIds:p,pulledActiveUpserts:g,pulledArchivedUpserts:w,documentDecryptFailures:Array.from(C),emittedEventIds:Array.from(_)}}const D=Dr(V.data);if(D.success===!1)return c+=Date.now()-K,{success:!1,kind:"apply_payload",transient:!1,error:String(D.error||"Workspace sync apply failed."),cursor:n,pages:r,appliedChanges:o,pullRequestMs:l,applyMs:c,pulledDeleteTaskIds:p,pulledActiveUpserts:g,pulledArchivedUpserts:w,documentDecryptFailures:Array.from(C),emittedEventIds:Array.from(_)};if(c+=Date.now()-K,o+=W.length,Array.isArray(D.emittedEventIds))for(const Ae of D.emittedEventIds)_.add(String(Ae));e.onChangesApplied&&e.onChangesApplied(W.length)}S&&"nextCursor"in S&&(S.nextCursor===null||typeof S.nextCursor=="string")&&(n=S.nextCursor),s=!!S?.hasMore,r+=1}if(e.bootstrap){const b=Date.now(),E=await wm(e.workspaceId,[],{bootstrapSnapshot:{currentAnnotatedAttachmentSessionIds:Array.from(y)}}),S=E.failures;if(!E.ok){c+=Date.now()-b;const W=Dr(E.data);if(S.some(K=>K.endsWith(":401")))return{success:!1,kind:"apply_auth",status:401,transient:!1,failures:S,cursor:n,pages:r,appliedChanges:o,pullRequestMs:l,applyMs:c,pulledDeleteTaskIds:p,pulledActiveUpserts:g,pulledArchivedUpserts:w,documentDecryptFailures:Array.from(C),emittedEventIds:Array.from(_)};const z=S.some(K=>{if(K.endsWith(":network"))return!0;const V=K.split(":").pop()||"",ne=Number.parseInt(V,10);return Number.isFinite(ne)&&(ne===429||ne>=500)});return{success:!1,kind:"apply_all_candidates",status:E.status||void 0,transient:z,error:String(W.error||"").trim()||void 0,failures:S,hasTransientApplyFailure:z,cursor:n,pages:r,appliedChanges:o,pullRequestMs:l,applyMs:c,pulledDeleteTaskIds:p,pulledActiveUpserts:g,pulledArchivedUpserts:w,documentDecryptFailures:Array.from(C),emittedEventIds:Array.from(_)}}c+=Date.now()-b}return{success:!0,syncedAt:new Date().toISOString(),cursor:n||null,pages:r,appliedChanges:o,pullRequestMs:l,applyMs:c,pulledDeleteTaskIds:p,pulledActiveUpserts:g,pulledArchivedUpserts:w,documentDecryptFailures:Array.from(C),emittedEventIds:Array.from(_)}}catch(b){return{success:!1,kind:"exception",status:0,transient:!0,error:String(b?.message||b||"Workspace sync pull failed unexpectedly."),cursor:n||null,pages:r,appliedChanges:o,pullRequestMs:l,applyMs:c,pulledDeleteTaskIds:p,pulledActiveUpserts:g,pulledArchivedUpserts:w,documentDecryptFailures:Array.from(C),emittedEventIds:Array.from(_)}}}async function Jy(e){const n=await zy(e.resolveCloudAuthUrl);if(!n.ok){const y=Number(n.status||0);return{success:!1,error:`Sync pull failed (${n.status})`,statusCode:n.status,retryAfterMs:n.retryAfterMs,transient:ao(y)}}const s=Dr(n.data),r=s.settings&&typeof s.settings=="object"?s.settings:{},o=typeof s.updatedAt=="string"&&s.updatedAt.trim().length>0?s.updatedAt.trim():null,l=e.getLocalUpdatedAt(e.userId),c=l?Date.parse(l):NaN,p=o?Date.parse(o):NaN;if(!l&&e.preferCloudOnFirstSync&&Number.isFinite(p))return await e.applyRemoteSettings(r),{success:!0,mode:"pulled",updatedAt:o};if(Number.isFinite(p)&&(!Number.isFinite(c)||p>c))return await e.applyRemoteSettings(r),{success:!0,mode:"pulled",updatedAt:o};const g=l||new Date().toISOString(),w=await Oy(e.resolveCloudAuthUrl,{settings:e.buildLocalSettings(),updatedAt:g});if(!w.ok){const y=Number(w.status||0);return{success:!1,error:`Sync push failed (${w.status})`,statusCode:w.status,retryAfterMs:w.retryAfterMs,transient:ao(y)}}const C=Dr(w.data);return{success:!0,mode:"pushed",updatedAt:typeof C.updatedAt=="string"&&C.updatedAt.trim().length>0?C.updatedAt.trim():g}}function Xy(e){const n=Math.max(1,Math.floor(Number(e)||1)),s=Math.min(12e4,1500*2**Math.max(0,n-1)),r=Math.floor(s*(.15*Math.random()));return s+r}const Qy=["chat_app","ide","coding_tool","agent","other"],mM=["chat_app","ide","coding_tool","agent","other","unclassified"],ek={chat_app:"Chat app",ide:"IDE",coding_tool:"Coding tool",agent:"Agent",other:"Other"},tk={chat_app:"Chat Apps",ide:"IDEs",coding_tool:"Coding Tools",agent:"Agents",other:"Other",unclassified:"Unclassified"};function nk(e){return typeof e=="string"&&Qy.includes(e)}function zf(e){if(typeof e!="string")return null;const n=e.trim();return nk(n)?n:null}function fM(e){return ek[e]}function hM(e){return e??"unclassified"}function gM(e){return tk[e]}function Gd(e){if(e==null)return;const n=String(e).trim();return n.length>0?n:void 0}function Vd(e){if(e===void 0)return;if(e===null)return null;const n=String(e).trim();return n.length>0?n:null}function ak(e){return typeof e=="boolean"?e:void 0}function Zd(e,n){if(e===void 0)return;if(e===null||e==="")return n?.nullable?null:void 0;const s=typeof e=="number"?e:Number(e);if(!Number.isFinite(s))return n?.nullable?null:void 0;const r=Math.floor(s);return Number.isFinite(n?.min)&&r<Number(n?.min)?n?.nullable?null:void 0:r}function sk(e){if(!e||typeof e!="object"||Array.isArray(e))return;const s=Object.entries(e).reduce((r,[o,l])=>Array.isArray(l)?(r[o]=l.map(c=>String(c??"")),r):(l==null||(r[o]=String(l)),r),{});return Object.keys(s).length>0?s:{}}function rk(e){return Array.isArray(e)?e:void 0}function ok(e){return Array.isArray(e)?e:void 0}function ik(e){return Array.isArray(e)?e:void 0}function ck(e){const n=e&&typeof e=="object"?e:{};return{id:String(n.id||"").trim(),title:String(n.title||"").trim(),description:n.description===void 0?void 0:n.description||null,status:String(n.status||"task").trim()||"task",priority:Zd(n.priority,{min:1})??void 0,complexity:Zd(n.complexity,{min:1,nullable:!0}),type:String(n.type||"").trim(),category:String(n.category||"").trim(),approach:Gd(n.approach),canceledReason:n.canceledReason===void 0?void 0:n.canceledReason||null,createdAt:String(n.createdAt||"").trim(),updatedAt:Gd(n.updatedAt),completedAt:n.completedAt===void 0?void 0:n.completedAt||null,isArchived:ak(n.isArchived),taxonomies:sk(n.taxonomies),createdBy:Gd(n.createdBy),assignee:Gd(n.assignee),scheduledDate:Vd(n.scheduledDate),dueDate:Vd(n.dueDate),scheduledWeekKey:Vd(n.scheduledWeekKey),orderInDay:Zd(n.orderInDay,{min:0,nullable:!0}),workstreamId:Vd(n.workstreamId),referenceNumber:Zd(n.referenceNumber,{min:1,nullable:!0}),comments:rk(n.comments),attachments:ok(n.attachments),checklistItems:ik(n.checklistItems)}}function Cm(e){return ck(e)}function xm(e){return[...e].sort((n,s)=>{const r=String(n?.id||"").trim(),o=String(s?.id||"").trim();return r.localeCompare(o)})}function lk(e){const n=new Date().toISOString(),s=new Set(Array.from(e.pendingDeletedTaskIds).map(d=>String(d||"").trim()).filter(d=>d.length>0)),r=e.lastPushedWatermarks,o=d=>{if((d?.referenceNumber===void 0||d?.referenceNumber===null)&&Number.isFinite(Number(d?.localReferenceNumber))||!r||r.size===0)return!0;const rt=String(d?.id||"").trim();if(!rt)return!1;const mt=String(d?.updatedAt||d?.createdAt||"").trim();return r.get(rt)!==mt},l=xm(e.tasks||[]),c=xm(e.archivedTasks||[]),p=new Map,g=l.filter(d=>!s.has(String(d?.id||"").trim())&&o(d)).map(d=>{const rt=String(d?.id||"").trim(),mt=String(d?.updatedAt||d?.createdAt||"").trim();return rt&&p.set(rt,mt),{op:"upsert",archived:!1,task:Cm(d)}}),w=c.filter(d=>!s.has(String(d?.id||"").trim())&&o(d)).map(d=>{const rt=String(d?.id||"").trim(),mt=String(d?.updatedAt||d?.createdAt||"").trim();return rt&&p.set(rt,mt),{op:"upsert",archived:!0,task:Cm(d)}}),C=new Set;for(const d of e.tasks||[]){const rt=String(d?.id||"").trim();rt&&C.add(rt)}for(const d of e.archivedTasks||[]){const rt=String(d?.id||"").trim();rt&&C.add(rt)}const _=Array.from(e.lastPushedTaskIds).filter(d=>!C.has(d)).map(d=>({op:"delete",taskId:d})),y=Array.from(s).map(d=>({op:"delete",taskId:d})),k=new Set([..._.map(d=>String(d.taskId)),...y.map(d=>String(d.taskId))]),b=new Set((Array.isArray(e.initiatives)?e.initiatives:[]).map(d=>String(d?.id||"").trim()).filter(d=>d.length>0)),E=new Map((Array.isArray(e.initiatives)?e.initiatives:[]).map(d=>[String(d?.id||"").trim(),String(d?.updatedAt||d?.createdAt||"").trim()]).filter(([d])=>d.length>0)),S=e.lastPushedInitiativeWatermarks,W=!S||S.size===0,Q=(Array.isArray(e.initiatives)?e.initiatives:[]).map(d=>({op:"initiative-upsert",initiative:{id:String(d?.id||"").trim(),referenceNumber:Number.isFinite(Number(d?.referenceNumber))?Math.max(1,Math.floor(Number(d.referenceNumber))):null,referenceLabel:typeof d?.referenceLabel=="string"&&d.referenceLabel.trim().length>0?d.referenceLabel.trim():void 0,title:String(d?.title||"").trim(),description:typeof d?.description=="string"?d.description:null,ownerId:typeof d?.ownerId=="string"&&d.ownerId.trim().length>0?d.ownerId.trim():null,createdAt:String(d?.createdAt||"").trim(),updatedAt:String(d?.updatedAt||d?.createdAt||"").trim(),order:Number.isFinite(Number(d?.order))?Math.floor(Number(d.order)):null,isArchived:!!d?.isArchived}})).filter(d=>d.initiative.id.length>0).filter(d=>W?!0:S.get(d.initiative.id)!==d.initiative.updatedAt),z=new Set((Array.isArray(e.workstreams)?e.workstreams:[]).map(d=>String(d?.id||"").trim()).filter(d=>d.length>0)),K=new Map((Array.isArray(e.workstreams)?e.workstreams:[]).map(d=>[String(d?.id||"").trim(),String(d?.updatedAt||d?.createdAt||"").trim()]).filter(([d])=>d.length>0)),V=e.lastPushedWorkstreamWatermarks,ne=!V||V.size===0,D=(Array.isArray(e.workstreams)?e.workstreams:[]).map(d=>({op:"workstream-upsert",workstream:{id:String(d?.id||"").trim(),referenceNumber:Number.isFinite(Number(d?.referenceNumber))?Math.max(1,Math.floor(Number(d.referenceNumber))):null,referenceLabel:typeof d?.referenceLabel=="string"&&d.referenceLabel.trim().length>0?d.referenceLabel.trim():void 0,initiativeId:typeof d?.initiativeId=="string"&&d.initiativeId.trim().length>0?d.initiativeId.trim():null,title:String(d?.title||"").trim(),description:typeof d?.description=="string"?d.description:null,ownerId:typeof d?.ownerId=="string"&&d.ownerId.trim().length>0?d.ownerId.trim():null,createdAt:String(d?.createdAt||"").trim(),updatedAt:String(d?.updatedAt||d?.createdAt||"").trim(),order:Number.isFinite(Number(d?.order))?Math.floor(Number(d.order)):null,isArchived:!!d?.isArchived}})).filter(d=>d.workstream.id.length>0).filter(d=>ne?!0:V.get(d.workstream.id)!==d.workstream.updatedAt),Ae=new Set((Array.isArray(e.aiProfiles)?e.aiProfiles:[]).map(d=>String(d?.id||"").trim()).filter(d=>d.length>0)),U=new Map((Array.isArray(e.aiProfiles)?e.aiProfiles:[]).map(d=>[String(d?.id||"").trim(),String(d?.updatedAt||d?.createdAt||"").trim()]).filter(([d])=>d.length>0)),ee=e.lastPushedAiProfileWatermarks,be=!ee||ee.size===0,me=(Array.isArray(e.aiProfiles)?e.aiProfiles:[]).map(d=>({op:"ai-profile-upsert",profile:{id:String(d.id||"").trim(),workspaceId:String(d.workspaceId||"").trim(),profileToken:String(d.profileToken||"").trim(),name:String(d.name||"").trim(),username:String(d.username||"").trim(),icon:String(d.icon||"Bot").trim()||"Bot",color:String(d.color||"#8b5cf6").trim()||"#8b5cf6",surfaceType:zf(d.surfaceType),providerMetadata:d.providerMetadata&&typeof d.providerMetadata=="object"&&!Array.isArray(d.providerMetadata)?d.providerMetadata:null,createdAt:String(d.createdAt||"").trim(),updatedAt:String(d.updatedAt||d.createdAt||"").trim(),lastActiveAt:typeof d.lastActiveAt=="string"&&d.lastActiveAt.trim().length>0?d.lastActiveAt.trim():null}})).filter(d=>d.profile.id.length>0&&d.profile.workspaceId.length>0).filter(d=>be?!0:ee.get(d.profile.id)!==d.profile.updatedAt),Y=new Set((Array.isArray(e.documents)?e.documents:[]).map(d=>String(d?.path||"").trim()).filter(d=>d.length>0)),R=new Set(Array.from(e.lastPushedDocumentPaths||new Set).map(d=>String(d||"").trim()).filter(d=>d.length>0&&!Y.has(d))),B=new Map((Array.isArray(e.documents)?e.documents:[]).map(d=>[String(d?.path||"").trim(),String(d?.updatedAt||"").trim()]).filter(([d])=>d.length>0)),fe=e.lastPushedDocumentWatermarks,Ne=!fe||fe.size===0,de=(Array.isArray(e.documents)?e.documents:[]).map(d=>({op:"document-upsert",path:String(d.path||"").trim(),updatedAt:String(d.updatedAt||"").trim(),content:typeof d.content=="string"?d.content:"",assetId:typeof d.assetId=="string"&&d.assetId.trim().length>0?d.assetId.trim():void 0,documentId:typeof d.documentId=="string"&&d.documentId.trim().length>0?d.documentId.trim():null,referenceNumber:Number.isFinite(Number(d.referenceNumber))?Math.max(1,Math.floor(Number(d.referenceNumber))):null,version:Number.isFinite(Number(d.version))?Math.max(1,Math.floor(Number(d.version))):null,taskId:typeof d.taskId=="string"&&d.taskId.trim().length>0?d.taskId.trim():null,logicalName:typeof d.logicalName=="string"&&d.logicalName.trim().length>0?d.logicalName.trim():null,caption:typeof d.caption=="string"&&d.caption.trim().length>0?d.caption.trim():null,originalFilename:typeof d.originalFilename=="string"&&d.originalFilename.trim().length>0?d.originalFilename.trim():null,linkRole:d.linkRole==="reference"?"reference":"attachment"})).filter(d=>d.path.length>0).filter(d=>Ne?!0:fe.get(d.path)!==d.updatedAt),ae=new Set((Array.isArray(e.assets)?e.assets:[]).map(d=>String(d?.path||"").trim()).filter(d=>d.length>0)),Ve=new Set(Array.from(e.lastPushedAssetPaths||new Set).map(d=>String(d||"").trim()).filter(d=>d.length>0&&!ae.has(d))),Re=new Map((Array.isArray(e.assets)?e.assets:[]).map(d=>[String(d?.path||"").trim(),String(d?.updatedAt||"").trim()]).filter(([d])=>d.length>0)),Ce=e.lastPushedAssetWatermarks,Fe=!Ce||Ce.size===0,x=(Array.isArray(e.assets)?e.assets:[]).map(d=>({op:"asset-upsert",path:String(d.path||"").trim(),updatedAt:String(d.updatedAt||"").trim(),contentBase64:typeof d.contentBase64=="string"?d.contentBase64:"",assetId:typeof d.assetId=="string"&&d.assetId.trim().length>0?d.assetId.trim():void 0,kind:d.kind==="image"?"image":"file",mimeType:typeof d.mimeType=="string"&&d.mimeType.trim().length>0?d.mimeType.trim():"application/octet-stream",referenceNumber:Number.isFinite(Number(d.referenceNumber))?Math.max(1,Math.floor(Number(d.referenceNumber))):null,taskId:typeof d.taskId=="string"&&d.taskId.trim().length>0?d.taskId.trim():null,logicalName:typeof d.logicalName=="string"&&d.logicalName.trim().length>0?d.logicalName.trim():null,caption:typeof d.caption=="string"&&d.caption.trim().length>0?d.caption.trim():null,originalFilename:typeof d.originalFilename=="string"&&d.originalFilename.trim().length>0?d.originalFilename.trim():null,linkRole:d.linkRole==="reference"?"reference":d.linkRole==="image"?"image":"attachment"})).filter(d=>d.path.length>0&&d.contentBase64.length>0).filter(d=>Fe?!0:Ce.get(d.path)!==d.updatedAt),L=Array.isArray(e.documentReviewSessions)?e.documentReviewSessions:[],P=new Set(L.filter(d=>String(d?.deletedAt||"").trim().length===0).map(d=>String(d?.id||"").trim()).filter(d=>d.length>0)),Z=new Set([...Array.from(e.lastPushedDocumentReviewSessionIds||new Set).map(d=>String(d||"").trim()).filter(d=>d.length>0&&!P.has(d)),...L.filter(d=>String(d?.deletedAt||"").trim().length>0).map(d=>String(d?.id||"").trim()).filter(d=>d.length>0)]),M=new Map(L.map(d=>[String(d?.id||"").trim(),String(d?.updatedAt||d?.createdAt||"").trim()]).filter(([d])=>d.length>0)),h=e.lastPushedDocumentReviewSessionWatermarks,A=!h||h.size===0,H=L.map(d=>({op:"document-review-session-upsert",session:{id:String(d.id||"").trim(),assetId:String(d.assetId||"").trim(),documentId:typeof d.documentId=="string"&&d.documentId.trim().length>0?d.documentId.trim():null,documentVersion:Number.isFinite(Number(d.documentVersion))?Math.max(1,Math.floor(Number(d.documentVersion))):null,title:typeof d.title=="string"&&d.title.trim().length>0?d.title.trim():null,status:d.status==="resolved"?"resolved":"open",comments:[],createdByActorId:typeof d.createdByActorId=="string"&&d.createdByActorId.trim().length>0?d.createdByActorId.trim():null,updatedByActorId:typeof d.updatedByActorId=="string"&&d.updatedByActorId.trim().length>0?d.updatedByActorId.trim():null,createdAt:String(d.createdAt||"").trim(),updatedAt:String(d.updatedAt||d.createdAt||"").trim(),deletedAt:typeof d.deletedAt=="string"&&d.deletedAt.trim().length>0?d.deletedAt.trim():null}})).filter(d=>d.session.id.length>0&&d.session.assetId.length>0&&!d.session.deletedAt).filter(d=>A?!0:h.get(d.session.id)!==d.session.updatedAt),j=Array.isArray(e.documentReviewComments)?e.documentReviewComments:[],je=new Set(j.filter(d=>String(d?.deletedAt||"").trim().length===0).map(d=>String(d?.id||"").trim()).filter(d=>d.length>0)),O=new Set([...Array.from(e.lastPushedDocumentReviewCommentIds||new Set).map(d=>String(d||"").trim()).filter(d=>d.length>0&&!je.has(d)),...j.filter(d=>String(d?.deletedAt||"").trim().length>0).map(d=>String(d?.id||"").trim()).filter(d=>d.length>0)]),ue=new Map(j.map(d=>[String(d?.id||"").trim(),String(d?.updatedAt||d?.createdAt||"").trim()]).filter(([d])=>d.length>0)),re=e.lastPushedDocumentReviewCommentWatermarks,pe=!re||re.size===0,G=j.map(d=>({op:"document-review-comment-upsert",comment:{id:String(d.id||"").trim(),sessionId:String(d.sessionId||"").trim(),body:String(d.body||"").trim(),anchor:d.anchor??null,order:Number.isFinite(Number(d.order))?Math.max(0,Math.floor(Number(d.order))):0,authorActorId:typeof d.authorActorId=="string"&&d.authorActorId.trim().length>0?d.authorActorId.trim():null,createdAt:String(d.createdAt||"").trim(),updatedAt:String(d.updatedAt||d.createdAt||"").trim(),deletedAt:typeof d.deletedAt=="string"&&d.deletedAt.trim().length>0?d.deletedAt.trim():null}})).filter(d=>d.comment.id.length>0&&d.comment.sessionId.length>0&&!d.comment.deletedAt).filter(d=>pe?!0:re.get(d.comment.id)!==d.comment.updatedAt),q=Array.isArray(e.annotatedAttachmentSessions)?e.annotatedAttachmentSessions:[],ye=new Set(q.filter(d=>String(d?.deletedAt||"").trim().length===0).map(d=>String(d?.id||"").trim()).filter(d=>d.length>0)),Be=new Set([...Array.from(e.lastPushedAnnotatedAttachmentSessionIds||new Set).map(d=>String(d||"").trim()).filter(d=>d.length>0&&!ye.has(d)),...q.filter(d=>String(d?.deletedAt||"").trim().length>0).map(d=>String(d?.id||"").trim()).filter(d=>d.length>0)]),le=new Map(q.map(d=>[String(d?.id||"").trim(),String(d?.updatedAt||d?.createdAt||"").trim()]).filter(([d])=>d.length>0)),ze=e.lastPushedAnnotatedAttachmentSessionWatermarks,Ye=!ze||ze.size===0,Xe=q.map(d=>({op:"annotated-attachment-session-upsert",session:{id:String(d.id||"").trim(),workspaceId:String(d.workspaceId||"").trim(),taskId:String(d.taskId||"").trim(),baseImageAssetId:String(d.baseImageAssetId||"").trim(),title:typeof d.title=="string"&&d.title.trim().length>0?d.title.trim():null,globalInstruction:typeof d.globalInstruction=="string"&&d.globalInstruction.trim().length>0?d.globalInstruction.trim():null,annotations:Array.isArray(d.annotations)?d.annotations:[],createdByActorId:typeof d.createdByActorId=="string"&&d.createdByActorId.trim().length>0?d.createdByActorId.trim():null,updatedByActorId:typeof d.updatedByActorId=="string"&&d.updatedByActorId.trim().length>0?d.updatedByActorId.trim():null,createdAt:String(d.createdAt||"").trim(),updatedAt:String(d.updatedAt||d.createdAt||"").trim(),deletedAt:typeof d.deletedAt=="string"&&d.deletedAt.trim().length>0?d.deletedAt.trim():null}})).filter(d=>d.session.id.length>0&&d.session.workspaceId.length>0&&d.session.baseImageAssetId.length>0&&!d.session.deletedAt).filter(d=>Ye?!0:ze.get(d.session.id)!==d.session.updatedAt);return{changes:[...Q,...D,...e.taxonomyState&&typeof e.taxonomyState=="object"?[{op:"taxonomy-upsert",taxonomyState:e.taxonomyState,updatedAt:n}]:Array.isArray(e.taxonomies)?[{op:"taxonomy-upsert",taxonomies:e.taxonomies,updatedAt:n}]:[],...me,...de,...Array.from(R).map(d=>({op:"document-delete",path:d,deletedAt:n})),...x,...Array.from(Ve).map(d=>({op:"asset-delete",path:d,deletedAt:n})),...H,...Array.from(Z).map(d=>({op:"document-review-session-delete",sessionId:d,deletedAt:n})),...G,...Array.from(O).map(d=>({op:"document-review-comment-delete",commentId:d,deletedAt:n})),...Xe,...Array.from(Be).map(d=>({op:"annotated-attachment-session-delete",sessionId:d,deletedAt:n})),...g,...w,...Array.from(k).map(d=>({op:"delete",taskId:d}))],currentTaskIds:new Set(Array.from(C).filter(d=>!s.has(d))),deleteTaskIds:k,currentInitiativeIds:b,currentInitiativeWatermarks:E,currentWorkstreamIds:z,currentWorkstreamWatermarks:K,currentAiProfileIds:Ae,currentAiProfileWatermarks:U,currentDocumentPaths:Y,deleteDocumentPaths:R,currentDocumentWatermarks:B,currentAssetPaths:ae,deleteAssetPaths:Ve,currentAssetWatermarks:Re,currentDocumentReviewSessionIds:P,deleteDocumentReviewSessionIds:Z,currentDocumentReviewSessionWatermarks:M,currentDocumentReviewCommentIds:je,deleteDocumentReviewCommentIds:O,currentDocumentReviewCommentWatermarks:ue,currentAnnotatedAttachmentSessionIds:ye,deleteAnnotatedAttachmentSessionIds:Be,currentAnnotatedAttachmentSessionWatermarks:le,pushedWatermarks:p}}function dk(e){const n=(e.tasks||[]).map(c=>`${c.id}:${c.updatedAt||c.createdAt||""}:${c.status}`).sort(),s=(e.archivedTasks||[]).map(c=>`${c.id}:${c.updatedAt||c.createdAt||""}:${c.status}`).sort(),r=e.pendingDeletedTaskIds?Array.from(e.pendingDeletedTaskIds).sort():[],o=(e.initiatives||[]).map(c=>({id:String(c.id||"").trim(),updatedAt:String(c.updatedAt||c.createdAt||"").trim(),title:String(c.title||"").trim(),ownerId:typeof c.ownerId=="string"?c.ownerId.trim():"",isArchived:!!c.isArchived})).filter(c=>c.id.length>0).sort((c,p)=>c.id.localeCompare(p.id)),l=(e.workstreams||[]).map(c=>({id:String(c.id||"").trim(),updatedAt:String(c.updatedAt||c.createdAt||"").trim(),initiativeId:typeof c.initiativeId=="string"?c.initiativeId.trim():"",title:String(c.title||"").trim(),ownerId:typeof c.ownerId=="string"?c.ownerId.trim():"",isArchived:!!c.isArchived})).filter(c=>c.id.length>0).sort((c,p)=>c.id.localeCompare(p.id));return JSON.stringify({workspaceId:e.workspaceId,initiatives:o,workstreams:l,taxonomyState:e.taxonomyState&&typeof e.taxonomyState=="object"?e.taxonomyState:null,taxonomies:Array.isArray(e.taxonomies)?e.taxonomies:[],aiProfiles:Array.isArray(e.aiProfiles)?e.aiProfiles.map(c=>({id:String(c.id||"").trim(),updatedAt:String(c.updatedAt||c.createdAt||"").trim(),name:String(c.name||"").trim(),username:String(c.username||"").trim()})).filter(c=>c.id.length>0).sort((c,p)=>c.id.localeCompare(p.id)):[],documents:Array.isArray(e.documents)?e.documents.map(c=>({path:String(c.path||"").trim(),updatedAt:String(c.updatedAt||"").trim(),length:typeof c.content=="string"?c.content.length:0})).filter(c=>c.path.length>0).sort((c,p)=>c.path.localeCompare(p.path)):[],assets:Array.isArray(e.assets)?e.assets.map(c=>({path:String(c.path||"").trim(),updatedAt:String(c.updatedAt||"").trim(),length:typeof c.contentBase64=="string"?c.contentBase64.length:0,kind:c.kind==="image"?"image":"file"})).filter(c=>c.path.length>0).sort((c,p)=>c.path.localeCompare(p.path)):[],documentReviewSessions:Array.isArray(e.documentReviewSessions)?e.documentReviewSessions.map(c=>({id:String(c.id||"").trim(),updatedAt:String(c.updatedAt||c.createdAt||"").trim(),assetId:String(c.assetId||"").trim(),status:c.status==="resolved"?"resolved":"open",deletedAt:String(c.deletedAt||"").trim(),commentCount:Array.isArray(c.comments)?c.comments.length:0})).filter(c=>c.id.length>0).sort((c,p)=>c.id.localeCompare(p.id)):[],documentReviewComments:Array.isArray(e.documentReviewComments)?e.documentReviewComments.map(c=>({id:String(c.id||"").trim(),sessionId:String(c.sessionId||"").trim(),updatedAt:String(c.updatedAt||c.createdAt||"").trim(),deletedAt:String(c.deletedAt||"").trim(),bodyLength:String(c.body||"").length})).filter(c=>c.id.length>0).sort((c,p)=>c.id.localeCompare(p.id)):[],annotatedAttachmentSessions:Array.isArray(e.annotatedAttachmentSessions)?e.annotatedAttachmentSessions.map(c=>({id:String(c.id||"").trim(),updatedAt:String(c.updatedAt||c.createdAt||"").trim(),taskId:String(c.taskId||"").trim(),baseImageAssetId:String(c.baseImageAssetId||"").trim(),deletedAt:String(c.deletedAt||"").trim(),annotationCount:Array.isArray(c.annotations)?c.annotations.length:0})).filter(c=>c.id.length>0).sort((c,p)=>c.id.localeCompare(p.id)):[],active:n,archived:s,pendingDeletes:r})}function Qd(){return{version:2,enabled:!1,phase:"idle",pullCursor:null,lastPullAt:null,lastPushAt:null,lastSyncedAt:null,lastErrorMessage:null}}function Eo(e){const n=String(e||"").trim();return n.length>0?n:null}function uk(e,n){if(!!!(e.enabled??e.cloudSyncEnabled))return"idle";const r=String(e.phase||"").trim().toLowerCase();if(r==="idle"||r==="provision-local"||r==="attach-cloud"||r==="active"||r==="error")return r;const o=String(e.bootstrapMode||"").trim().toLowerCase();if(o==="provision-local"||o==="attach-cloud")return o;const l=String(e.sourceOfTruth||"").trim().toLowerCase();return e.onboardingCompleted?"active":l==="cloud"?n.lastPullAt?"active":"attach-cloud":l==="local"?n.lastPullAt||n.lastPushAt?"active":"provision-local":(n.lastPullAt||n.lastPushAt,"active")}function pk(e){const n=Qd();if(!e||typeof e!="object")return{state:n,changed:!1};const s=e,r=s.lastErrorMessage,o=typeof r=="string"&&r.trim().length>0?r:null,l={version:2,enabled:!!(s.enabled??s.cloudSyncEnabled),phase:"idle",pullCursor:Eo(s.pullCursor),lastPullAt:Eo(s.lastPullAt),lastPushAt:Eo(s.lastPushAt),lastSyncedAt:Eo(s.lastSyncedAt),lastErrorMessage:o};l.phase=uk(s,l),l.enabled||(l.phase="idle",l.pullCursor=null);const p=Number(s.version||0)!==2||!!(s.enabled??s.cloudSyncEnabled)!==l.enabled||String(s.phase||"").trim()!==l.phase||Eo(s.pullCursor)!==l.pullCursor||Eo(s.lastPullAt)!==l.lastPullAt||Eo(s.lastPushAt)!==l.lastPushAt||Eo(s.lastSyncedAt)!==l.lastSyncedAt||o!==l.lastErrorMessage;return{state:l,changed:p}}const mk="taskforce.sync.lease.v1",fk="taskforce.sync.lease.v1",hk=2500,gk=9e3;function Il(e){const n=String(e||"").trim();return n.length>0&&n.toLowerCase()!=="default"}function Kd(e){const n=String(e||"").trim();return n.length>0?n:null}function ip(e){return`${mk}.${e}`}function yk(e){if(!e)return null;try{const n=JSON.parse(e),s=String(n?.ownerId||"").trim(),r=String(n?.workspaceId||"").trim(),o=String(n?.operation||"").trim(),l=String(n?.heartbeatAt||"").trim(),c=String(n?.expiresAt||"").trim();return!s||!r||!l||!c||o!=="pull"&&o!=="push"&&o!=="repair"?null:{ownerId:s,workspaceId:r,operation:o,heartbeatAt:l,expiresAt:c}}catch{return null}}function kk(e,n,s,r){return{ownerId:e,workspaceId:n,operation:s,heartbeatAt:new Date(r).toISOString(),expiresAt:new Date(r+gk).toISOString()}}function Sk(e,n=Date.now()){if(!e)return!0;const s=Date.parse(e.expiresAt);return!Number.isFinite(s)||s<=n}function Am(e,n){const s={...e,...n,version:2,phase:n.phase||e.phase,pullCursor:n.pullCursor===void 0?e.pullCursor:Kd(n.pullCursor),lastPullAt:n.lastPullAt===void 0?e.lastPullAt:Kd(n.lastPullAt),lastPushAt:n.lastPushAt===void 0?e.lastPushAt:Kd(n.lastPushAt),lastSyncedAt:n.lastSyncedAt===void 0?e.lastSyncedAt:Kd(n.lastSyncedAt),lastErrorMessage:n.lastErrorMessage===void 0?e.lastErrorMessage:n.lastErrorMessage??null};return s.enabled||(s.phase="idle",s.pullCursor=null),s}function vk(e){const{currentWorkspaceId:n,setWorkspaceCloudSyncEnabled:s,setWorkspaceSyncPhase:r,setWorkspaceLastPullAt:o,setWorkspaceLastPushAt:l,setWorkspaceLastErrorMessage:c}=e,[p,g]=a.useState(null),w=a.useRef(null),C=a.useRef(null),_=a.useRef(0),y=a.useRef(!1),k=a.useRef(!1),b=a.useRef(""),E=a.useRef(""),S=a.useRef(new Set),W=a.useRef(new Set),Q=a.useRef(null),z=a.useRef(Qd()),K=a.useRef(""),V=a.useRef(null),ne=a.useRef(null),D=a.useRef(null),Ae=a.useRef(null);if(!K.current){const x=Date.now().toString(36),L=Math.random().toString(36).slice(2,10);K.current=`sync-lease-${x}-${L}`}const U=a.useCallback(()=>{_.current=0,C.current=null,w.current!==null&&typeof window<"u"&&(window.clearTimeout(w.current),w.current=null),g(null)},[]),ee=a.useCallback((x,L)=>{if(typeof window>"u")return;const P=Math.max(1,_.current+1);_.current=P;const Z=Xy(P),M=Number(L?.minDelayMs),h=Number.isFinite(M)&&M>0?Math.max(Z,Math.floor(M)):Z,A=Date.now()+h;C.current=A,g(new Date(A).toISOString()),w.current!==null&&window.clearTimeout(w.current),w.current=window.setTimeout(()=>{w.current=null,C.current=null,g(null),x()},h)},[]),be=a.useCallback(()=>{const x=C.current;return typeof x=="number"&&Number.isFinite(x)&&x>Date.now()},[]),me=a.useCallback(x=>{if(typeof window>"u")return null;const L=String(x||"").trim();return Il(L)?yk(window.localStorage.getItem(ip(L))):null},[]),Y=a.useCallback(x=>{const L=String(x||"").trim();if(L)try{Ae.current?.postMessage({workspaceId:L})}catch{}},[]),R=a.useCallback((x,L)=>{if(typeof window>"u")return null;const P=String(x||"").trim();if(!Il(P))return null;const Z=kk(K.current,P,L,Date.now());try{window.localStorage.setItem(ip(P),JSON.stringify(Z))}catch{return null}return Y(P),Z},[Y]),B=a.useCallback(()=>{D.current!==null&&typeof window<"u"&&(window.clearInterval(D.current),D.current=null)},[]),fe=a.useCallback((x,L)=>{if(typeof window>"u")return;const P=String(x||V.current||"").trim();if(!P)return;const Z=me(P),M=Z?.ownerId===K.current;if(!(!L?.force&&Z&&!M)){B();try{window.localStorage.removeItem(ip(P))}catch{}V.current=null,ne.current=null,Y(P)}},[Y,me,B]),Ne=a.useCallback((x,L)=>{typeof window>"u"||(B(),D.current=window.setInterval(()=>{const P=String(V.current||"").trim(),Z=ne.current;if(!P||!Z){B();return}if(me(P)?.ownerId!==K.current){B(),V.current=null,ne.current=null;return}R(P,Z)},hk),V.current=x,ne.current=L)},[me,B,R]),de=a.useCallback(async(x,L)=>{if(typeof window>"u")return!0;const P=String(x||"").trim();if(!Il(P))return!1;const Z=me(P);if(Z?.ownerId===K.current)return R(P,L)?(Ne(P,L),!0):!1;if(Z&&!Sk(Z)||!R(P,L))return!1;const A=me(P);return!A||A.ownerId!==K.current?!1:(Ne(P,L),!0)},[me,Ne,R]),ae=a.useCallback(x=>{fe(x,{force:!0})},[fe]),Ve=a.useCallback(x=>{const L=z.current,P=Am(L,{enabled:!!x.enabled,phase:x.phase||L.phase,pullCursor:x.pullCursor,lastPullAt:x.lastPullAt,lastPushAt:x.lastPushAt,lastSyncedAt:x.lastSyncedAt,lastErrorMessage:x.lastErrorMessage});z.current=P,Q.current=P.pullCursor,s(P.enabled),r(P.phase),o(P.lastPullAt),l(P.lastPushAt),c(P.lastErrorMessage??null)},[s,r,o,l,c]),Re=a.useCallback(async x=>{const L=Am(z.current,x);z.current=L,Q.current=L.pullCursor;const P=await fetch("/api/taskforce/ui-state",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({workspaceId:n,stateKey:"workspace-sync",patch:L})}),Z=await P.json().catch(()=>({}));if(!P.ok||Z?.success===!1)throw new Error(Z?.error||`Failed to persist workspace sync state (${P.status})`);return Ve(L),L},[Ve,n]),Ce=a.useCallback(async()=>{if(!Il(n)){const x=Qd();z.current=x,Ve(x);return}try{const x=await fetch(`/api/taskforce/ui-state?key=workspace-sync&workspaceId=${encodeURIComponent(n)}`,{method:"GET",credentials:"include"});if(!x.ok)return;const L=await x.json().catch(()=>({})),P=pk(L?.state&&typeof L.state=="object"?L.state:null);z.current=P.state,Ve(P.state),P.changed&&Re(P.state)}catch{}},[Ve,n,Re]),Fe=a.useCallback(async(x,L)=>{if(!Il(n))return{success:!1,error:"Workspace setup is required before enabling sync."};try{if(!x.enabled)return await Re({enabled:!1,phase:"idle",pullCursor:null}),{success:!0};if(!L.isAuthenticated)return{success:!1,error:"Sign in is required before enabling workspace sync."};if(!L.cloudAuthConfigured)return{success:!1,error:"Cloud authentication endpoint is not configured."};const P=await L.ensureCloudWorkspaceReadyForSync();return P.success?(await Re({enabled:!0,phase:P.provisioned?"provision-local":"attach-cloud",pullCursor:null,lastPullAt:null,lastPushAt:null,lastSyncedAt:null}),{success:!0}):{success:!1,error:P.error||"Workspace sync handshake failed."}}catch{return{success:!1,error:"Failed to save workspace sync settings."}}},[n,Re]);return a.useEffect(()=>{b.current="",E.current="",S.current=new Set,W.current=new Set,Q.current=null,z.current=Qd(),y.current=!1,k.current=!1,fe(),U()},[U,n,fe]),a.useEffect(()=>{if(typeof window>"u"||typeof BroadcastChannel>"u")return;const x=new BroadcastChannel(fk);return Ae.current=x,()=>{x.close(),Ae.current===x&&(Ae.current=null)}},[]),a.useEffect(()=>()=>{w.current!==null&&typeof window<"u"&&(window.clearTimeout(w.current),w.current=null),fe()},[fe]),{workspaceRetryAt:p,isWorkspaceRetryPending:be,workspacePushInFlightRef:y,workspacePullInFlightRef:k,workspaceLastPushedSignatureRef:b,workspacePendingSignatureRef:E,workspaceLastPushedTaskIdsRef:S,workspaceDeletedTaskIdsRef:W,workspacePullCursorRef:Q,clearWorkspaceRetry:U,scheduleWorkspaceRetry:ee,persistWorkspaceSyncPatch:Re,loadWorkspaceSyncState:Ce,applyWorkspaceSyncStateSnapshot:Ve,saveWorkspaceCloudSyncSettings:Fe,acquireWorkspaceSyncLease:de,releaseWorkspaceSyncLease:fe,forceClearWorkspaceSyncLease:ae,readWorkspaceSyncLease:me}}class wk{constructor(n=2048){this.maxSeenEventIds=n}seenEventIds=new Set;seenEventIdQueue=[];activeEpoch="";lastSeq=null;telemetry={accepted:0,duplicateDiscarded:0,outOfOrderDiscarded:0,invalidDiscarded:0,recoveryTriggered:0};process(n){const s=typeof n.eventId=="string"?n.eventId.trim():"";if(s&&this.seenEventIds.has(s))return this.telemetry.duplicateDiscarded+=1,{accepted:!1,reason:"duplicate",shouldRecover:!1};const r=typeof n.serverEpoch=="string"?n.serverEpoch.trim():"",o=Number(n.seq);if(!(r.length>0&&Number.isFinite(o)&&o>=0))return s?(this.rememberEventId(s),this.telemetry.accepted+=1,{accepted:!0,shouldRecover:!1}):(this.telemetry.invalidDiscarded+=1,{accepted:!1,reason:"invalid",shouldRecover:!1});const c=Math.floor(o);if(this.activeEpoch&&this.activeEpoch!==r)return this.activeEpoch=r,this.lastSeq=c,s&&this.rememberEventId(s),this.telemetry.accepted+=1,{accepted:!0,shouldRecover:!1};if(!this.activeEpoch)return this.activeEpoch=r,this.lastSeq=c,s&&this.rememberEventId(s),this.telemetry.accepted+=1,{accepted:!0,shouldRecover:!1};const p=this.lastSeq;if(typeof p=="number"){if(c<=p){this.telemetry.outOfOrderDiscarded+=c===p?0:1,this.telemetry.duplicateDiscarded+=c===p?1:0;const g=c<p;return g&&(this.telemetry.recoveryTriggered+=1),{accepted:!1,reason:c===p?"duplicate":"out-of-order",shouldRecover:g}}if(c>p+1)return this.telemetry.outOfOrderDiscarded+=1,this.telemetry.recoveryTriggered+=1,{accepted:!1,reason:"out-of-order",shouldRecover:!0}}return this.lastSeq=c,s&&this.rememberEventId(s),this.telemetry.accepted+=1,{accepted:!0,shouldRecover:!1}}getTelemetry(){return{...this.telemetry}}rememberEventId(n){for(this.seenEventIds.add(n),this.seenEventIdQueue.push(n);this.seenEventIdQueue.length>this.maxSeenEventIds;){const s=this.seenEventIdQueue.shift();s&&this.seenEventIds.delete(s)}}}function Of(e){const{enabled:n,workspaceId:s,websocketUrl:r,reconnectBaseMs:o=400,reconnectMaxMs:l=1e4,degradeAfterAttempts:c=5,replayLimit:p=200,onSignal:g,onTelemetry:w,userId:C}=e,[_,y]=a.useState("degraded-fallback"),k=a.useRef(null),b=a.useRef(null),E=a.useRef(0),S=a.useRef(""),W=a.useRef(!1),Q=a.useRef(null),z=a.useRef(null),K=a.useRef(new wk),V=a.useRef(g),ne=a.useRef(w);a.useEffect(()=>{V.current=g},[g]),a.useEffect(()=>{ne.current=w},[w]);const[D,Ae]=a.useState({accepted:0,duplicateDiscarded:0,outOfOrderDiscarded:0,invalidDiscarded:0,recoveryTriggered:0}),U=a.useMemo(()=>String(s||"").trim(),[s]),ee=a.useMemo(()=>String(r||"").trim(),[r]);return a.useEffect(()=>{let be=!1;const me=()=>{b.current!==null&&(window.clearTimeout(b.current),b.current=null)},Y=()=>{const Ce=k.current;if(k.current=null,Ce)try{Ce.close()}catch{}},R=Ce=>Ce==="taskforce:replay-gap"||Ce==="taskforce:replay-reset"?4:Ce==="taskforce:mutation"||Ce==="taskforce:replay"?3:1,B=Ce=>{const Fe=z.current;if(Fe){const x=R(Fe.type),L=R(Ce.type);if(L<x||L===x&&Fe.eventId&&!Ce.eventId)return}z.current=Ce,Q.current!==null&&window.clearTimeout(Q.current),Q.current=window.setTimeout(()=>{Q.current=null;const x=V.current;if(!z.current||typeof x!="function")return;const L=z.current;z.current=null,x(L)},80)},fe=Ce=>{try{const Fe=JSON.parse(String(Ce.data||""));return!Fe||typeof Fe!="object"?null:Fe}catch{return null}},Ne=Ce=>{const Fe=typeof Ce.serverEpoch=="string"?Ce.serverEpoch.trim():"",x=Number(Ce.seq);!Fe||!Number.isFinite(x)||x<0||(S.current=`${Fe}:${Math.floor(x)}`,W.current=!1)},de=()=>{const Ce=K.current.getTelemetry();Ae(Ce);const Fe=ne.current;typeof Fe=="function"&&Fe(Ce)},ae=Ce=>{const Fe={type:"taskforce:replay",workspaceId:U,limit:p},x=S.current;x&&(Fe.cursor=x),Ce.send(JSON.stringify(Fe))},Ve=()=>{if(!n||be)return;me(),E.current+=1;const Ce=E.current,Fe=Math.max(50,Math.floor(o)),x=Math.max(Fe,Math.floor(l)),L=Math.min(x,Fe*Math.pow(2,Math.max(0,Ce-1)));y(Ce>=c?"degraded-fallback":"reconnecting"),b.current=window.setTimeout(()=>{be||(b.current=null,Re())},L)},Re=()=>{if(!n||be||!U||!ee)return;Y();let Ce;try{Ce=new WebSocket(ee)}catch{Ve();return}k.current=Ce,Ce.addEventListener("open",()=>{E.current=0,y("connected"),Ce.send(JSON.stringify({type:"taskforce:subscribe",workspaceId:U,userId:C||void 0})),ae(Ce)}),Ce.addEventListener("message",Fe=>{const x=fe(Fe);if(!x||typeof x.type!="string")return;const L=typeof x.workspaceId=="string"?x.workspaceId.trim():U;if(!(!L||L!==U)){if(x.type==="taskforce:update"){B({type:"taskforce:update",workspaceId:U});return}if(x.type==="taskforce:mutation"){const P=K.current.process({eventId:x.eventId,serverEpoch:x.serverEpoch,seq:x.seq});if(!P.accepted){de(),P.shouldRecover&&(S.current="",W.current||(W.current=!0,B({type:"taskforce:replay-gap",workspaceId:U})));return}Ne(x),de(),B({type:x.type,workspaceId:U,eventId:typeof x.eventId=="string"?x.eventId.trim():void 0});return}if(x.type==="taskforce:replay"){const P=Array.isArray(x.events)?x.events:[];let Z=0;for(const M of P)K.current.process({eventId:M.eventId,serverEpoch:M.serverEpoch,seq:M.seq}).accepted&&(Z+=1,Ne(M));W.current=!1,de(),(Z>0||x.truncated===!0)&&B({type:"taskforce:replay",workspaceId:U}),x.truncated===!0&&ae(Ce);return}if(x.type==="taskforce:replay-gap"||x.type==="taskforce:replay-reset"){if(S.current="",W.current)return;W.current=!0,B({type:x.type,workspaceId:U})}}}),Ce.addEventListener("close",Fe=>{if(k.current===Ce&&(k.current=null),!be&&n){const x=Number(Fe?.code||0),L=String(Fe?.reason||"").trim();console.warn(`[Taskforce] Realtime socket closed workspace=${U} user=${String(C||"anonymous").trim()||"anonymous"} code=${x}${L?` reason=${L}`:""}`)}Ve()}),Ce.addEventListener("error",()=>{try{Ce.close()}catch{}})};return!n||!U||!ee?(y("degraded-fallback"),me(),Y(),()=>{me(),Y()}):(y("reconnecting"),Re(),()=>{be=!0,me(),Q.current!==null&&(window.clearTimeout(Q.current),Q.current=null),z.current=null,Y()})},[n,U,ee,o,l,c,p,C]),{connectionState:_,telemetry:D}}const Ip="taskforce:context-assets-mutated";function bk(e){typeof window>"u"||typeof window.dispatchEvent!="function"||window.dispatchEvent(new CustomEvent(Ip,{detail:e}))}const $f="taskforce.userGlobalSyncMeta.v1",_k="taskforce.syncDebug.v1",Ck=12e4,Uf="taskforce.syncWatermarks.v3",xk=7200*1e3,Tm="Another local window is already syncing this workspace. Wait a few seconds, or press Repair in that window.";function Lo(e){const n=String(e||"").trim();return n.length>0&&n.toLowerCase()!=="default"}function Ak(){if(typeof window>"u")return!1;try{const e=String(window.localStorage.getItem(_k)||"").trim().toLowerCase();return e==="1"||e==="true"||e==="on"||e==="yes"}catch{return!1}}function ps(e,n){if(!Ak())return;console.info("[Taskforce Sync]",e,n&&typeof n=="object"?n:{})}function Tk(e){const n=e?.providerMetadata??e?.provider_metadata??null;return{id:String(e?.id||"").trim(),workspaceId:String(e?.workspaceId||e?.workspace_id||"").trim(),profileToken:String(e?.profileToken||e?.profile_token||"").trim(),name:String(e?.name||"").trim(),username:String(e?.username||"").trim(),icon:String(e?.icon||"Bot").trim()||"Bot",color:String(e?.color||"#8b5cf6").trim()||"#8b5cf6",surfaceType:zf(e?.surfaceType??e?.surface_type),providerMetadata:n&&typeof n=="object"&&!Array.isArray(n)?n:null,createdAt:String(e?.createdAt||e?.created_at||"").trim(),updatedAt:String(e?.updatedAt||e?.updated_at||e?.createdAt||e?.created_at||"").trim(),lastActiveAt:typeof e?.lastActiveAt=="string"&&e.lastActiveAt.trim().length>0?e.lastActiveAt.trim():typeof e?.last_active_at=="string"&&e.last_active_at.trim().length>0?e.last_active_at.trim():null}}function Im(){if(typeof window>"u")return{};try{const e=window.localStorage.getItem($f);if(!e)return{};const n=JSON.parse(e);return n&&typeof n=="object"?n:{}}catch{return{}}}function Ik(e){if(!(typeof window>"u"))try{window.localStorage.setItem($f,JSON.stringify(e))}catch{}}function Nk(e){try{return JSON.stringify(e&&typeof e=="object"?e:null)}catch{return"null"}}function jk(e,n,s,r,o){return e?n==="provision-local"?s?"Uploading this workspace to cloud for the first time.":"Preparing the first upload to cloud.":n==="attach-cloud"?s?"Pulling the cloud workspace into this device.":"Waiting for the first cloud pull into this device.":r?"Sync hit a temporary problem and will retry automatically.":o?"Sync needs attention before it can continue.":s?"Sync is currently running.":"Sync is healthy.":"Sync is turned off for this workspace."}function Rk(e,n,s,r){return e?n==="provision-local"?"Keep this window open while the first upload finishes. If it seems stalled, press Sync.":n==="attach-cloud"?"Keep this window open for the first cloud pull. If it does not move, press Repair.":s?"Wait for the automatic retry, or press Sync to retry now.":r?"Press Sync to retry. If the same error keeps returning, press Repair.":"No action needed.":"Turn on sync when you are ready to back up this workspace."}function Dk(e){return e.flatMap(n=>{const s=String(n?.id||"").trim();return!s||!Array.isArray(n?.comments)?[]:n.comments.map(r=>({id:String(r?.id||"").trim(),sessionId:s,body:String(r?.body||""),anchor:r?.anchor??null,order:Number.isFinite(Number(r?.order))?Math.max(0,Math.floor(Number(r.order))):0,authorActorId:typeof r?.authorActorId=="string"&&r.authorActorId.trim().length>0?r.authorActorId.trim():null,createdAt:String(r?.createdAt||"").trim(),updatedAt:String(r?.updatedAt||r?.createdAt||"").trim(),deletedAt:typeof r?.deletedAt=="string"&&r.deletedAt.trim().length>0?r.deletedAt.trim():null})).filter(r=>r.id.length>0&&r.sessionId.length>0)})}function Pk(e,n){if(typeof window>"u")return null;try{const s=`${Uf}.${e}`,r=window.localStorage.getItem(s);if(!r)return null;const o=JSON.parse(r);if(!o||o.v!==2&&o.v!==3&&o.v!==4&&o.v!==5&&o.v!==6&&o.v!==7)return null;const l=Date.parse(String(o.savedAt||""));if(!Number.isFinite(l)||Date.now()-l>xk)return null;const c=typeof o.taxonomyStateFingerprint=="string"?o.taxonomyStateFingerprint:"";return{taskWatermarks:!n||!c||c===n?new Map(Array.isArray(o.taskWatermarks)?o.taskWatermarks:[]):new Map,initiativeWatermarks:new Map(Array.isArray(o.initiativeWatermarks)?o.initiativeWatermarks:[]),workstreamWatermarks:new Map(Array.isArray(o.workstreamWatermarks)?o.workstreamWatermarks:[]),documentWatermarks:new Map(Array.isArray(o.documentWatermarks)?o.documentWatermarks:[]),assetWatermarks:new Map(Array.isArray(o.assetWatermarks)?o.assetWatermarks:[]),documentReviewSessionWatermarks:new Map(Array.isArray(o.documentReviewSessionWatermarks)?o.documentReviewSessionWatermarks:[]),documentReviewCommentWatermarks:new Map(Array.isArray(o.documentReviewCommentWatermarks)?o.documentReviewCommentWatermarks:[]),annotatedAttachmentSessionWatermarks:new Map(Array.isArray(o.annotatedAttachmentSessionWatermarks)?o.annotatedAttachmentSessionWatermarks:[])}}catch{return null}}function Nm(e,n){if(!(typeof window>"u"))try{const s=`${Uf}.${e}`;window.localStorage.setItem(s,JSON.stringify({v:7,savedAt:new Date().toISOString(),taskWatermarks:Array.from(n.taskWatermarks.entries()),initiativeWatermarks:Array.from(n.initiativeWatermarks.entries()),workstreamWatermarks:Array.from(n.workstreamWatermarks.entries()),documentWatermarks:Array.from(n.documentWatermarks.entries()),assetWatermarks:Array.from(n.assetWatermarks.entries()),documentReviewSessionWatermarks:Array.from(n.documentReviewSessionWatermarks.entries()),documentReviewCommentWatermarks:Array.from(n.documentReviewCommentWatermarks.entries()),annotatedAttachmentSessionWatermarks:Array.from(n.annotatedAttachmentSessionWatermarks.entries()),taxonomyStateFingerprint:typeof n.taxonomyStateFingerprint=="string"?n.taxonomyStateFingerprint:""}))}catch{}}const jm={documents:!1,aiProfiles:!1,assets:!1,documentReviewSessions:!1,annotatedAttachmentSessions:!1};function Ek(e){const{currentWorkspaceId:n,cloudAuthConfigured:s,runtimeMode:r,authSessionResolved:o,isAuthenticated:l,authUserId:c,projectName:p,resolveCloudAuthUrl:g,resolveWebSocketUrl:w,realtimeSyncEnabled:C,tasks:_,archivedTasks:y,initiatives:k,workstreams:b,taxonomies:E,taxonomyState:S,setupState:W,globalTheme:Q,locale:z,globalWeekStartsOn:K,themeUseGlobalDefault:V,setTasks:ne,setArchivedTasks:D,setAuthBlocked:Ae,setIsAuthenticated:U,checkAuthSession:ee,setGlobalTheme:be,setCurrentTheme:me,setSetupState:Y,setLocale:R,setGlobalWeekStartsOn:B,fetchPlanningEntities:fe}=e,Ne=a.useMemo(()=>Nk(S),[S]),[de,ae]=a.useState("disconnected"),[Ve,Re]=a.useState(null),[Ce,Fe]=a.useState(null),[x,L]=a.useState(null),[P,Z]=a.useState(null),[M,h]=a.useState(null),[A,H]=a.useState(!1),[j,je]=a.useState("idle"),[O,ue]=a.useState(!1),[re,pe]=a.useState(0),[G,q]=a.useState([]),[ye,Be]=a.useState(""),le=a.useRef(_||[]),ze=a.useRef(y||[]),Ye=a.useRef(k||[]),Xe=a.useRef(b||[]),bt=a.useRef([]),[d,rt]=a.useState([]),[mt,F]=a.useState(""),[Ke,St]=a.useState(null),[Lt,xt]=a.useState(null),[Zt,Jt]=a.useState(0),[on,cn]=a.useState(null),nn=a.useRef([]),[gn,yn]=a.useState([]),[an,kn]=a.useState(""),Xt=a.useRef([]),[Gn,At]=a.useState([]),[Se,Mt]=a.useState(""),Qt=a.useRef([]),zt=a.useRef([]),[Ge,An]=a.useState([]),[J,_e]=a.useState(""),we=a.useRef([]),[Ie,We]=a.useState(jm),[Qe,ot]=a.useState("degraded-fallback"),[et,_t]=a.useState({accepted:0,duplicateDiscarded:0,outOfOrderDiscarded:0,invalidDiscarded:0,recoveryTriggered:0}),vt=a.useRef(!1),Ot=a.useRef(null),it=a.useRef(0),It=a.useRef(!1),wt=a.useRef(new Set),_n=a.useRef(""),Dn=a.useRef(""),Jn=a.useRef(""),ht=a.useRef(""),gt=a.useRef(""),Xn=a.useRef(""),se=a.useRef(!1),He=a.useRef(null),Ee=a.useRef(new Set),De=a.useRef([]),Me=a.useRef(()=>Promise.resolve(!1)),tt=a.useRef(async()=>{}),Nn=a.useRef(null),Et=a.useRef(null),ya=a.useRef("idle"),Pn=a.useCallback(()=>{Ot.current!==null&&(window.clearTimeout(Ot.current),Ot.current=null)},[]),Cn=a.useCallback(I=>{if(typeof window>"u")return;Pn();const ke=Math.max(1,Math.floor(it.current)+1);it.current=ke;const $e=1500*2**Math.max(0,ke-1),Te=Number.isFinite(Number(I))?Math.max(0,Math.floor(Number(I))):0,X=Math.max(Math.min(12e4,$e),Te);Ot.current=window.setTimeout(()=>{Ot.current=null,tt.current({preferCloudOnFirstSync:!1})},X)},[Pn]);a.useEffect(()=>{Dn.current="",Jn.current="",ht.current="",gt.current="",Xn.current="",Zn.current="",hs.current=!1,q([]),Be(""),nn.current=[],rt([]),F(""),yn([]),kn(""),Qt.current=[],zt.current=[],At([]),Mt(""),we.current=[],An([]),_e(""),We(jm),h(null),Z(null),pe(0),Ee.current=new Set,De.current=[],$n.current=new Map,Ka.current=new Set,Wn.current=new Map,rn.current=new Set,ra.current=new Map,Yt.current=new Set,Fn.current=new Map,jn.current=new Set,xn.current=new Map,fa.current=new Set,nt.current=new Map,vn.current=new Set,dn.current=new Map,za.current=new Set,oa.current=new Map,Ya.current=new Set,Qn.current=new Map,Ya.current=new Set,Qn.current=new Map;const I=Pk(n,Ne);I&&($n.current=I.taskWatermarks,Wn.current=I.initiativeWatermarks,ra.current=I.workstreamWatermarks,xn.current=I.documentWatermarks,nt.current=I.assetWatermarks,dn.current=I.documentReviewSessionWatermarks,oa.current=I.documentReviewCommentWatermarks,Qn.current=I.annotatedAttachmentSessionWatermarks)},[n,Ne]);const Sn=a.useCallback(I=>{We(ke=>ke[I]?ke:{...ke,[I]:!0})},[]),ln=Object.values(Ie).every(Boolean),{workspaceRetryAt:Kt,isWorkspaceRetryPending:yt,workspacePushInFlightRef:qt,workspacePullInFlightRef:Ht,workspaceLastPushedSignatureRef:sn,workspacePendingSignatureRef:ft,workspaceLastPushedTaskIdsRef:Ze,workspaceDeletedTaskIdsRef:Vn,workspacePullCursorRef:pn,clearWorkspaceRetry:$t,scheduleWorkspaceRetry:Wt,persistWorkspaceSyncPatch:Rt,loadWorkspaceSyncState:fs,applyWorkspaceSyncStateSnapshot:Ds,saveWorkspaceCloudSyncSettings:aa,acquireWorkspaceSyncLease:fn,releaseWorkspaceSyncLease:sa,forceClearWorkspaceSyncLease:On}=vk({currentWorkspaceId:n,setWorkspaceCloudSyncEnabled:H,setWorkspaceSyncPhase:je,setWorkspaceLastPullAt:Fe,setWorkspaceLastPushAt:L,setWorkspaceLastErrorMessage:h}),$n=a.useRef(new Map),Ka=a.useRef(new Set),Wn=a.useRef(new Map),rn=a.useRef(new Set),ra=a.useRef(new Map),Yt=a.useRef(new Set),Fn=a.useRef(new Map),jn=a.useRef(new Set),xn=a.useRef(new Map),fa=a.useRef(new Set),nt=a.useRef(new Map),vn=a.useRef(new Set),dn=a.useRef(new Map),za=a.useRef(new Set),oa=a.useRef(new Map),Ya=a.useRef(new Set),Qn=a.useRef(new Map),Ta=a.useRef(!1),ka=a.useRef(!1),Zn=a.useRef(""),hs=a.useRef(!1),en=3e4,Ia=C?3e4:15e3,ha=a.useMemo(()=>{const I=Ce?Date.parse(Ce):NaN,ke=x?Date.parse(x):NaN;return Number.isFinite(I)&&Number.isFinite(ke)?I>=ke?Ce:x:Number.isFinite(I)?Ce:Number.isFinite(ke)?x:null},[Ce,x]),Ca=a.useMemo(()=>A?O||j==="provision-local"||j==="attach-cloud"?"syncing":Kt||M||j==="error"?"attention":"healthy":"off",[A,O,j,Kt,M]),Na=a.useMemo(()=>jk(A,j,O,Kt,M),[A,j,O,Kt,M]),Us=a.useMemo(()=>Rk(A,j,Kt,M),[A,j,Kt,M]),io=a.useCallback(I=>{const ke=String(I||"").trim();if(!ke)return null;const Te=Im()[ke]?.updatedAt;return typeof Te=="string"&&Te.trim().length>0?Te.trim():null},[]),Oa=a.useCallback((I,ke)=>{const $e=String(I||"").trim(),Te=String(ke||"").trim();if(!$e||!Te)return;const X=Im();X[$e]={updatedAt:Te},Ik(X)},[]),oe=a.useCallback(()=>{const I=W?.mode==="operations"?"operations":"core";return{theme:Q,operatingMode:I,localization:{locale:z,weekStartsOn:K}}},[Q,W?.mode,z,K]),lt=a.useCallback(async I=>{if(!(!I||typeof I!="object")){It.current=!0;try{const ke={},$e=bc(I.theme);if($e&&(be($e),V&&me($e),ke.theme=$e),(I.operatingMode==="core"||I.operatingMode==="operations")&&(Y(Te=>Te&&{...Te,mode:I.operatingMode}),ke.setup={mode:I.operatingMode}),I.localization&&typeof I.localization=="object"){const Te={};if(typeof I.localization.locale=="string"&&I.localization.locale.trim().length>0){const Pe=Tf(I.localization.locale.trim());R(Pe)}const X=String(I.localization.weekStartsOn||"").trim().toLowerCase();(X==="sunday"||X==="monday")&&(B(X),Te.weekStartsOn=X),Object.keys(Te).length>0&&(ke.schedulePreferences=Te)}Object.keys(ke).length>0&&await fetch("/api/taskforce/global-settings",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(ke)})}finally{It.current=!1}}},[V,be,me,Y,R,B]),Ft=a.useCallback(async I=>{const ke=I?.preferCloudOnFirstSync!==!1;if(!s)return;if(r!=="local"||!l){Pn(),it.current=0,ae("disconnected");return}const $e=String(c||"").trim();if(!$e||$e==="anonymous"){Pn(),it.current=0,ae("disconnected");return}if(!vt.current){ae("syncing"),Re(null),vt.current=!0;try{const Te=await Jy({resolveCloudAuthUrl:g,userId:$e,preferCloudOnFirstSync:ke,getLocalUpdatedAt:io,buildLocalSettings:oe,applyRemoteSettings:lt});if(!Te.success){ae("error"),Te.transient?(Re(Te.error||"Sync failed temporarily. Retrying automatically."),Cn(Te.retryAfterMs)):(Pn(),it.current=0,Re(Te.error||"Sync failed."));return}Pn(),it.current=0;const X=String(Te.updatedAt||"").trim()||new Date().toISOString();Oa($e,X),ae("idle"),Re(null),wt.current.add($e),Te.mode==="pulled"&&(_n.current="")}catch{ae("error"),Re("Sync failed temporarily. Retrying automatically."),Cn()}finally{vt.current=!1}}},[s,r,l,c,g,io,oe,lt,Oa,Pn,Cn]);a.useEffect(()=>{tt.current=Ft},[Ft]),a.useEffect(()=>()=>{Pn()},[Pn]);const Tt=a.useCallback(()=>{h(null),Z(null)},[]),Tn=a.useCallback(I=>{h(Tm),Z(new Date().toISOString()),ae("error"),Re(Tm),ps("workspace_sync_window_contention",{workspaceId:n,operation:I})},[n]),dt=a.useCallback(I=>{Rt(I).catch(()=>{})},[Rt]),wn=a.useCallback(I=>{Wt(()=>Me.current(),{minDelayMs:I})},[Wt]);a.useEffect(()=>{if(j==="attach-cloud"||j==="provision-local"){ya.current=j,Nn.current===null&&(Nn.current=Date.now()),Et.current=null;return}Nn.current=null,Et.current=null},[j]),a.useEffect(()=>{if(!A||j!=="attach-cloud"&&j!=="provision-local")return;const I=window.setInterval(()=>{if(j!=="attach-cloud"&&j!=="provision-local"||Ht.current||qt.current)return;const ke=Math.max(Nn.current??0,Et.current??0);if(ke>0&&Date.now()-ke<Ck)return;const Te=`Workspace sync ${j==="attach-cloud"?"initial cloud pull":"initial cloud upload"} stalled. Press Repair to restart sync for this workspace.`;h(Te),Z(new Date().toISOString()),ae("error"),Re(Te),ue(!1),dt({phase:"error",lastErrorMessage:Te}),ps("workspace_sync_bootstrap_timeout",{workspaceId:n,phase:j})},1e4);return()=>window.clearInterval(I)},[n,A,j,dt,Ht,qt]);const ia=a.useCallback(async()=>Vy({cloudAuthConfigured:s,runtimeMode:r,isAuthenticated:l,resolveCloudAuthUrl:g,workspaceId:n,workspaceName:p||n}),[s,r,l,g,n,p]);a.useEffect(()=>{le.current=_||[]},[_]),a.useEffect(()=>{ze.current=y||[]},[y]),a.useEffect(()=>{Ye.current=k||[]},[k]),a.useEffect(()=>{Xe.current=b||[]},[b]);const ga=a.useRef(!1),ja=a.useCallback(I=>{const ke=I?.forceAllAiProfiles===!0;return lk({tasks:le.current,archivedTasks:ze.current,lastPushedTaskIds:Ze.current,pendingDeletedTaskIds:Vn.current,initiatives:Ye.current,workstreams:Xe.current,taxonomies:E||[],taxonomyState:S,lastPushedInitiativeIds:Ka.current,lastPushedInitiativeWatermarks:Wn.current,lastPushedWorkstreamIds:rn.current,lastPushedWorkstreamWatermarks:ra.current,aiProfiles:nn.current,lastPushedAiProfileIds:ke?new Set:Yt.current,lastPushedAiProfileWatermarks:ke?new Map:Fn.current,documents:bt.current,assets:Xt.current,documentReviewSessions:Qt.current,documentReviewComments:zt.current,annotatedAttachmentSessions:we.current,lastPushedDocumentPaths:jn.current,lastPushedDocumentWatermarks:xn.current,lastPushedAssetPaths:fa.current,lastPushedAssetWatermarks:nt.current,lastPushedDocumentReviewSessionIds:vn.current,lastPushedDocumentReviewSessionWatermarks:dn.current,lastPushedDocumentReviewCommentIds:za.current,lastPushedDocumentReviewCommentWatermarks:oa.current,lastPushedAnnotatedAttachmentSessionIds:Ya.current,lastPushedAnnotatedAttachmentSessionWatermarks:Qn.current,lastPushedWatermarks:$n.current})},[E,S]),Kn=a.useCallback((I,ke)=>{r==="local"&&fetch("/api/taskforce/sync/events",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({...ke,workspaceId:I})}).catch($e=>{ps("sync_event_post_failed",{workspaceId:I,eventType:ke.eventType,status:ke.status,error:String($e?.message||$e||"")})})},[r]),ea=a.useCallback(()=>dk({workspaceId:n,tasks:le.current,archivedTasks:ze.current,pendingDeletedTaskIds:Vn.current,initiatives:Ye.current,workstreams:Xe.current,taxonomies:E||[],aiProfiles:nn.current,documents:bt.current,assets:Xt.current,documentReviewSessions:Qt.current,documentReviewComments:zt.current,annotatedAttachmentSessions:we.current}),[n,E]),rr=a.useMemo(()=>{const I=[];for(const ke of _||[]){const $e=Array.isArray(ke.attachments)?ke.attachments.length:0;$e>0&&I.push(`${ke.id}:${$e}`)}return I.join("|")},[_]),Ra=a.useCallback(I=>{if(!I)return!1;if(hs.current)return hs.current=!1,Zn.current=I,sn.current=I,pe(0),!0;const ke=Zn.current;return ke?I===ke?(sn.current=I,pe(0),!0):(Zn.current="",!1):!1},[]),pa=a.useCallback(async()=>{if(r==="local"&&Lo(n)&&!(s&&(!o||!l)))try{const I=await fetch(`/api/taskforce/sync/workspace/documents?workspaceId=${encodeURIComponent(n)}`,{method:"GET",credentials:"include"});if(!I.ok)return;const ke=await I.json().catch(()=>({})),$e=Array.isArray(ke?.documents)?ke.documents.map(X=>({path:String(X?.path||"").trim(),updatedAt:String(X?.updatedAt||"").trim(),content:typeof X?.content=="string"?X.content:"",assetId:typeof X?.assetId=="string"&&X.assetId.trim().length>0?X.assetId.trim():void 0,documentId:typeof X?.documentId=="string"&&X.documentId.trim().length>0?X.documentId.trim():null,referenceNumber:Number.isFinite(Number(X?.referenceNumber))?Math.max(1,Math.floor(Number(X.referenceNumber))):null,version:Number.isFinite(Number(X?.version))?Math.max(1,Math.floor(Number(X.version))):null,taskId:typeof X?.taskId=="string"&&X.taskId.trim().length>0?X.taskId.trim():null,logicalName:typeof X?.logicalName=="string"&&X.logicalName.trim().length>0?X.logicalName.trim():null,caption:typeof X?.caption=="string"&&X.caption.trim().length>0?X.caption.trim():null,originalFilename:typeof X?.originalFilename=="string"&&X.originalFilename.trim().length>0?X.originalFilename.trim():null,linkRole:X?.linkRole==="reference"?"reference":"attachment"})).filter(X=>X.path.length>0):[],Te=typeof ke?.fingerprint=="string"?ke.fingerprint:JSON.stringify($e.map(X=>`${X.path}:${X.updatedAt}:${X.content.length}`).sort());if(Te===Dn.current)return;Dn.current=Te,bt.current=$e,q($e),Be(Te)}catch(I){ps("documents_snapshot_refresh_failed",{workspaceId:n,error:String(I?.message||I||"")})}finally{Sn("documents")}},[r,n,s,o,l,Sn]),ca=a.useCallback(async()=>{if(r!=="local"){cn("runtime-not-local");return}if(!Lo(n)){cn("workspace-id-invalid");return}if(s&&(!o||!l)){cn(o?"auth-required":"auth-unresolved");return}cn(null);try{const I=await fetch(`/api/taskforce/sync/workspace/ai-profiles?workspaceId=${encodeURIComponent(n)}`,{method:"GET",credentials:"include"});if(!I.ok){xt(`HTTP ${I.status}`),St(new Date().toISOString());return}const ke=await I.json().catch(()=>({})),$e=Array.isArray(ke?.aiProfiles)?ke.aiProfiles:[];Jt($e.length);const Te=Array.isArray(ke?.aiProfiles)?ke.aiProfiles.map(Pe=>Tk(Pe)).filter(Pe=>Pe.id.length>0&&Pe.workspaceId.length>0):[];xt(null),St(new Date().toISOString());const X=typeof ke?.fingerprint=="string"?ke.fingerprint:JSON.stringify(Te.map(Pe=>`${Pe.id}:${Pe.updatedAt}:${Pe.name}:${Pe.username}`).sort());if(X===Jn.current)return;Jn.current=X,nn.current=Te,rt(Te),F(X)}catch(I){xt(String(I?.message||I||"unknown-error")),St(new Date().toISOString()),ps("ai_profiles_snapshot_refresh_failed",{workspaceId:n,error:String(I?.message||I||"")})}finally{Sn("aiProfiles")}},[r,n,s,o,l,Sn]),Da=a.useCallback(async()=>{if(r==="local"&&Lo(n)&&!(s&&(!o||!l)))try{const I=await fetch(`/api/taskforce/sync/workspace/assets?workspaceId=${encodeURIComponent(n)}`,{method:"GET",credentials:"include"});if(!I.ok)return;const ke=await I.json().catch(()=>({})),$e=Array.isArray(ke?.assets)?ke.assets.map(X=>({path:String(X?.path||"").trim(),updatedAt:String(X?.updatedAt||"").trim(),contentBase64:typeof X?.contentBase64=="string"?X.contentBase64:"",assetId:typeof X?.assetId=="string"&&X.assetId.trim().length>0?X.assetId.trim():void 0,kind:X?.kind==="image"?"image":"file",mimeType:typeof X?.mimeType=="string"&&X.mimeType.trim().length>0?X.mimeType.trim():"application/octet-stream",referenceNumber:Number.isFinite(Number(X?.referenceNumber))?Math.max(1,Math.floor(Number(X.referenceNumber))):null,taskId:typeof X?.taskId=="string"&&X.taskId.trim().length>0?X.taskId.trim():null,logicalName:typeof X?.logicalName=="string"&&X.logicalName.trim().length>0?X.logicalName.trim():null,caption:typeof X?.caption=="string"&&X.caption.trim().length>0?X.caption.trim():null,originalFilename:typeof X?.originalFilename=="string"&&X.originalFilename.trim().length>0?X.originalFilename.trim():null,linkRole:X?.linkRole==="reference"?"reference":X?.linkRole==="image"?"image":"attachment"})).filter(X=>X.path.length>0&&X.contentBase64.length>0):[],Te=typeof ke?.fingerprint=="string"?ke.fingerprint:JSON.stringify($e.map(X=>`${X.path}:${X.updatedAt}:${X.contentBase64.length}`).sort());if(Te===ht.current)return;ht.current=Te,Xt.current=$e,yn($e),kn(Te)}catch(I){ps("assets_snapshot_refresh_failed",{workspaceId:n,error:String(I?.message||I||"")})}finally{Sn("assets")}},[r,n,s,o,l,Sn]),Sa=a.useCallback(async()=>{if(r==="local"&&Lo(n)&&!(s&&(!o||!l)))try{const I=await fetch(`/api/taskforce/sync/workspace/document-reviews?workspaceId=${encodeURIComponent(n)}`,{method:"GET",credentials:"include"});if(!I.ok)return;const ke=await I.json().catch(()=>({})),$e=Array.isArray(ke?.sessions)?ke.sessions.map(Pe=>({id:String(Pe?.id||"").trim(),assetId:String(Pe?.assetId||"").trim(),documentId:typeof Pe?.documentId=="string"&&Pe.documentId.trim().length>0?Pe.documentId.trim():null,documentVersion:Number.isFinite(Number(Pe?.documentVersion))?Math.max(1,Math.floor(Number(Pe.documentVersion))):null,title:typeof Pe?.title=="string"&&Pe.title.trim().length>0?Pe.title.trim():null,status:Pe?.status==="resolved"?"resolved":"open",comments:Array.isArray(Pe?.comments)?Pe.comments:[],createdByActorId:typeof Pe?.createdByActorId=="string"&&Pe.createdByActorId.trim().length>0?Pe.createdByActorId.trim():null,updatedByActorId:typeof Pe?.updatedByActorId=="string"&&Pe.updatedByActorId.trim().length>0?Pe.updatedByActorId.trim():null,createdAt:String(Pe?.createdAt||"").trim(),updatedAt:String(Pe?.updatedAt||Pe?.createdAt||"").trim(),deletedAt:typeof Pe?.deletedAt=="string"&&Pe.deletedAt.trim().length>0?Pe.deletedAt.trim():null})).filter(Pe=>Pe.id.length>0&&Pe.assetId.length>0):[],Te=Array.isArray(ke?.comments)?ke.comments.map(Pe=>({id:String(Pe?.id||"").trim(),sessionId:String(Pe?.sessionId||"").trim(),body:typeof Pe?.body=="string"?Pe.body:"",anchor:Pe?.anchor??null,order:Number.isFinite(Number(Pe?.order))?Math.max(0,Math.floor(Number(Pe.order))):0,authorActorId:typeof Pe?.authorActorId=="string"&&Pe.authorActorId.trim().length>0?Pe.authorActorId.trim():null,createdAt:String(Pe?.createdAt||"").trim(),updatedAt:String(Pe?.updatedAt||Pe?.createdAt||"").trim(),deletedAt:typeof Pe?.deletedAt=="string"&&Pe.deletedAt.trim().length>0?Pe.deletedAt.trim():null})).filter(Pe=>Pe.id.length>0&&Pe.sessionId.length>0):Dk($e),X=typeof ke?.fingerprint=="string"?ke.fingerprint:JSON.stringify([...$e.map(Pe=>`${Pe.id}:${Pe.updatedAt}:${Pe.status}:${Pe.deletedAt||""}:${Pe.comments.length}`).sort(),...Te.map(Pe=>`${Pe.id}:${Pe.sessionId}:${Pe.updatedAt}:${Pe.deletedAt||""}`).sort()]);if(X===gt.current)return;gt.current=X,Qt.current=$e,zt.current=Te,At($e),Mt(X)}catch(I){ps("document_review_sessions_snapshot_refresh_failed",{workspaceId:n,error:String(I?.message||I||"")})}finally{Sn("documentReviewSessions")}},[r,n,s,o,l,Sn]),rs=a.useCallback(async()=>{if(r==="local"&&Lo(n)&&!(s&&(!o||!l)))try{const I=await fetch(`/api/taskforce/sync/workspace/annotated-attachments?workspaceId=${encodeURIComponent(n)}`,{method:"GET",credentials:"include"});if(!I.ok)return;const ke=await I.json().catch(()=>({})),$e=Array.isArray(ke?.sessions)?ke.sessions.map(X=>({id:String(X?.id||"").trim(),workspaceId:String(X?.workspaceId||"").trim(),taskId:String(X?.taskId||"").trim(),baseImageAssetId:String(X?.baseImageAssetId||"").trim(),title:typeof X?.title=="string"&&X.title.trim().length>0?X.title.trim():null,globalInstruction:typeof X?.globalInstruction=="string"&&X.globalInstruction.trim().length>0?X.globalInstruction.trim():null,annotations:Array.isArray(X?.annotations)?X.annotations:[],createdByActorId:typeof X?.createdByActorId=="string"&&X.createdByActorId.trim().length>0?X.createdByActorId.trim():null,updatedByActorId:typeof X?.updatedByActorId=="string"&&X.updatedByActorId.trim().length>0?X.updatedByActorId.trim():null,createdAt:String(X?.createdAt||"").trim(),updatedAt:String(X?.updatedAt||X?.createdAt||"").trim(),deletedAt:typeof X?.deletedAt=="string"&&X.deletedAt.trim().length>0?X.deletedAt.trim():null})).filter(X=>X.id.length>0&&X.workspaceId.length>0&&X.taskId.length>0&&X.baseImageAssetId.length>0):[],Te=typeof ke?.fingerprint=="string"?ke.fingerprint:JSON.stringify($e.map(X=>`${X.id}:${X.updatedAt}:${X.taskId}:${X.baseImageAssetId}:${X.annotations.length}:${X.deletedAt||""}`).sort());if(Te===Xn.current)return;Xn.current=Te,we.current=$e,An($e),_e(Te)}catch(I){ps("annotated_attachment_sessions_snapshot_refresh_failed",{workspaceId:n,error:String(I?.message||I||"")})}finally{Sn("annotatedAttachmentSessions")}},[r,n,s,o,l,Sn]),co=a.useCallback(()=>{jn.current=new Set(bt.current.map(I=>String(I?.path||"").trim()).filter(I=>I.length>0)),xn.current=new Map(bt.current.map(I=>[String(I?.path||"").trim(),String(I?.updatedAt||"").trim()]).filter(([I])=>I.length>0)),fa.current=new Set(Xt.current.map(I=>String(I?.path||"").trim()).filter(I=>I.length>0)),nt.current=new Map(Xt.current.map(I=>[String(I?.path||"").trim(),String(I?.updatedAt||"").trim()]).filter(([I])=>I.length>0)),vn.current=new Set(Qt.current.map(I=>String(I?.id||"").trim()).filter(I=>I.length>0)),dn.current=new Map(Qt.current.map(I=>[String(I?.id||"").trim(),String(I?.updatedAt||I?.createdAt||"").trim()]).filter(([I])=>I.length>0)),za.current=new Set(zt.current.map(I=>String(I?.id||"").trim()).filter(I=>I.length>0)),oa.current=new Map(zt.current.map(I=>[String(I?.id||"").trim(),String(I?.updatedAt||I?.createdAt||"").trim()]).filter(([I])=>I.length>0)),Ya.current=new Set(we.current.map(I=>String(I?.id||"").trim()).filter(I=>I.length>0)),Qn.current=new Map(we.current.map(I=>[String(I?.id||"").trim(),String(I?.updatedAt||I?.createdAt||"").trim()]).filter(([I])=>I.length>0))},[]),Ri=a.useCallback(async()=>{const[I,ke]=await Promise.all([fetch("/api/taskforce/tasks",{method:"GET",credentials:"include"}),fetch("/api/taskforce/archive",{method:"GET",credentials:"include"})]);if(I.ok){const $e=await I.json().catch(()=>({})),Te=Array.isArray($e?.tasks)?$e.tasks.map(X=>ro(X)):[];ne(Te)}if(ke.ok){const $e=await ke.json().catch(()=>({})),Te=Array.isArray($e?.archived)?$e.archived.map(X=>({...ro(X),isArchived:!0})):[];D(Te)}await fe().catch(()=>{ps("refresh_planning_entities_failed",{workspaceId:n})})},[n,fe,D,ne]),qs=a.useCallback(async(I,ke)=>{$t(),ue(!1),ae("error");const $e="Session expired. Sign in again to resume cloud sync.";Re($e),h($e),Z(new Date().toISOString()),Kn(n,{eventType:I==="handshake"?"handshake":I,status:"error",statusCode:ke,errorMessage:$e}),Ae(!0),U(!1),await ee()},[$t,Kn,n,Ae,U,ee]),or=a.useCallback(async()=>{if(!Lo(n)){const $e="Workspace sync blocked: local workspace ID is unresolved.";return h($e),Z(new Date().toISOString()),Re($e),ae("error"),!1}const I=await ia();if(I.success)return!0;if(I.statusCode===401)return await qs("handshake",401),!1;const ke=I.error||"Workspace sync handshake failed.";return h(ke),Z(new Date().toISOString()),Re(ke),ae("error"),Kn(n,{eventType:"handshake",status:"error",statusCode:I.statusCode,errorMessage:ke}),I.transient||ao(I.statusCode)?wn(I.retryAfterMs):j==="active"&&dt({phase:"error",lastErrorMessage:ke}),!1},[n,ia,qs,Kn,wn,j,dt]),la=a.useCallback(async(I,ke)=>{if(!s||r!=="local"||!A||!Lo(n))return!1;if(ka.current===!0&&ke?.repairMode!==!0||j==="attach-cloud")return ft.current=I,!1;if(!l&&!await ee()||Ra(I))return!1;if(qt.current||Ht.current)return ft.current=I,!1;if(!await fn(n,"push"))return ft.current=I,Tn("push"),!1;qt.current=!0,ue(!0),ae("syncing"),Re(null);const Te=Date.now(),X=ke?.forceAllAiProfiles===!0||ga.current===!0;try{if(await pa(),await ca(),await Da(),await Sa(),!await or())return!1;const Dt=ja({forceAllAiProfiles:X});pe(Dt.changes.length);const Nt=await Ky({resolveCloudAuthUrl:g,workspaceId:n,payload:Dt,ensureCloudWorkspaceReadyForSync:ia,repairMode:ke?.repairMode===!0||ka.current===!0});if(!Nt.success){if(Nt.status===401)return await qs("push",401),!1;let qn=Nt.error?`Workspace sync push failed (${Nt.status||0}): ${Nt.error}`:`Workspace sync push failed (${Nt.status||0})`;return Nt.status===413&&(qn="Workspace sync failed because the payload is too large. This usually happens when one or more attachments exceed the project limit."),ae("error"),Re(qn),h(qn),Z(new Date().toISOString()),Kn(n,{eventType:"push",status:"error",statusCode:Nt.status,errorMessage:qn,requestMs:Nt.requestMs}),ft.current=I,Nt.transient||ao(Nt.status)?wn(Nt.retryAfterMs):j==="active"&&dt({phase:"error",lastErrorMessage:qn}),!1}sn.current=I,Ze.current=Nt.currentTaskIds,Ka.current=new Set(Nt.currentInitiativeIds),Wn.current=new Map(Nt.currentInitiativeWatermarks),rn.current=new Set(Nt.currentWorkstreamIds),ra.current=new Map(Nt.currentWorkstreamWatermarks),Yt.current=new Set(Nt.currentAiProfileIds),Fn.current=new Map(Nt.currentAiProfileWatermarks),jn.current=new Set(Nt.currentDocumentPaths),xn.current=new Map(Nt.currentDocumentWatermarks),fa.current=new Set(Nt.currentAssetPaths),nt.current=new Map(Nt.currentAssetWatermarks),vn.current=new Set(Nt.currentDocumentReviewSessionIds),dn.current=new Map(Nt.currentDocumentReviewSessionWatermarks),za.current=new Set(Nt.currentDocumentReviewCommentIds),oa.current=new Map(Nt.currentDocumentReviewCommentWatermarks),Ya.current=new Set(Nt.currentAnnotatedAttachmentSessionIds),Qn.current=new Map(Nt.currentAnnotatedAttachmentSessionWatermarks),X&&(ga.current=!1);for(const[qn,En]of Nt.pushedWatermarks)$n.current.set(qn,En);if(Nt.deleteTaskIds.size>0)for(const qn of Nt.deleteTaskIds)Vn.current.delete(qn),$n.current.delete(qn);if(Nm(n,{taskWatermarks:$n.current,initiativeWatermarks:Wn.current,workstreamWatermarks:ra.current,documentWatermarks:xn.current,assetWatermarks:nt.current,documentReviewSessionWatermarks:dn.current,documentReviewCommentWatermarks:oa.current,annotatedAttachmentSessionWatermarks:Qn.current,taxonomyStateFingerprint:Ne}),Array.isArray(Nt.emittedEventIds)&&Nt.emittedEventIds.length>0){for(const qn of Nt.emittedEventIds){const En=String(qn||"").trim();!En||Ee.current.has(En)||(Ee.current.add(En),De.current.push(En))}for(;De.current.length>2048;){const qn=De.current.shift();qn&&Ee.current.delete(qn)}}$t(),Tt();const Ja=Nt.syncedAt||new Date().toISOString();return L(Ja),pe(0),ae("idle"),dt({phase:"active",lastPushAt:Ja,lastSyncedAt:Ja,lastErrorMessage:null}),Kn(n,{eventType:j==="provision-local"?"bootstrap":"push",status:"success",changeCount:Nt.changeCount,requestMs:Nt.requestMs}),!0}catch(Pe){const Dt="Workspace sync push failed.";return ae("error"),Re(Dt),h(Dt),Z(new Date().toISOString()),ft.current=I,wn(),Kn(n,{eventType:"push",status:"error",errorMessage:`${Dt} ${String(Pe?.message||"").trim()}`.trim()}),ps("push_failed_exception",{workspaceId:n,elapsedMs:Date.now()-Te}),!1}finally{qt.current=!1,ue(Ht.current),sa(n);const Pe=ft.current;Pe&&Pe!==sn.current&&!Ht.current&&(ft.current="",window.setTimeout(()=>{la(Pe)},120))}},[s,r,A,n,j,l,ee,Tt,pa,ca,Da,Sa,or,ja,g,ia,Ra,qs,$t,Rt,Kn,wn,fn,sa,Tn,qt,Ht,dt]),da=a.useCallback(async I=>{if(!s||r!=="local"||!A||!Lo(n)||ka.current===!0&&I?.repairMode!==!0||j==="provision-local"||yt()||!l&&!await ee()||Ht.current||qt.current)return!1;if(!await fn(n,"pull"))return Tn("pull"),!1;Ht.current=!0,ue(!0),ae("syncing"),Re(null);const $e=Date.now();try{if(!await or())return!1;const X=j==="attach-cloud",Pe=X?null:pn.current,Dt=await Yy({resolveCloudAuthUrl:g,workspaceId:n,cursor:Pe,bootstrap:X,ensureCloudWorkspaceReadyForSync:ia,maxPages:20,repairMode:I?.repairMode===!0||ka.current===!0,onPagePulled:()=>{Et.current=Date.now()},onChangesApplied:()=>{Et.current=Date.now()}});if(!Dt.success){if(Dt.kind==="pull_http"&&Dt.status===401)return await qs("pull",401),!1;if(Dt.kind==="apply_auth")return await qs("apply",401),!1;let En=Dt.kind==="apply_payload"||Dt.kind==="apply_all_candidates"||Dt.kind==="exception"?String(Dt.error||"Workspace sync apply failed."):`Workspace sync pull failed (${Dt.status||0})`;return Dt.status===413&&(En="Local sync failed because the downloaded payload is too large. This usually happens when the workspace contains massive attachments."),ae("error"),Re(En),h(En),Z(new Date().toISOString()),Kn(n,{eventType:Dt.kind?.startsWith("apply")?"apply":"pull",status:"error",statusCode:Dt.status,errorMessage:En,requestMs:Dt.pullRequestMs}),Dt.transient||Dt.hasTransientApplyFailure||ao(Dt.status)?wn(Dt.retryAfterMs):dt({phase:"error",lastErrorMessage:En}),!1}if(Array.isArray(Dt.emittedEventIds))for(const En of Dt.emittedEventIds)En&&(Ee.current.add(En),setTimeout(()=>{Ee.current.delete(En)},6e4));Dt.pulledDeleteTaskIds.size>0&&(ne(En=>En.filter(os=>!Dt.pulledDeleteTaskIds.has(String(os.id||"")))),D(En=>En.filter(os=>!Dt.pulledDeleteTaskIds.has(String(os.id||"")))));const Nt=Array.isArray(Dt.documentDecryptFailures)?Dt.documentDecryptFailures.filter(En=>String(En||"").trim().length>0):[];if(Nt.length>0&&ps("pull_document_decrypt_failures",{workspaceId:n,failureCount:Nt.length}),pn.current=Dt.cursor||null,Dt.appliedChanges>0&&(Dt.pulledActiveUpserts||Dt.pulledArchivedUpserts))try{await Ri()}catch{ps("pull_local_refresh_failed",{workspaceId:n,appliedChanges:Dt.appliedChanges})}$t(),Tt();const Ja=Dt.syncedAt||new Date().toISOString();if(Fe(Ja),pe(0),ae("idle"),j==="attach-cloud"&&(hs.current=!0,ft.current=""),await Rt({phase:"active",pullCursor:pn.current,lastPullAt:Ja,lastSyncedAt:Ja,lastErrorMessage:null}),Kn(n,{eventType:j==="attach-cloud"?"bootstrap":"pull",status:"success",changeCount:Dt.appliedChanges,requestMs:Dt.pullRequestMs}),j==="attach-cloud")return await pa(),await Da(),await Sa(),await rs(),co(),!0;const qn=ft.current||ea();return qn&&qn!==sn.current&&(ft.current="",window.setTimeout(()=>{la(qn)},120)),!0}catch(Te){const X=String(Te?.message||"").trim(),Pe=X?`Workspace sync pull failed. ${X}`:"Workspace sync pull failed.";return ae("error"),Re(Pe),h(Pe),Z(new Date().toISOString()),wn(),Kn(n,{eventType:"pull",status:"error",errorMessage:Pe,requestMs:Date.now()-$e}),ps("pull_failed_exception",{workspaceId:n,elapsedMs:Date.now()-$e,error:X||null}),!1}finally{Ht.current=!1,ue(qt.current),sa(n)}},[s,r,A,n,j,yt,l,ee,Tt,or,g,ia,qs,Ri,pa,Da,Sa,rs,$t,Rt,Kn,ea,la,co,wn,fn,sa,Tn,qt,Ht,dt]),Ps=a.useCallback(I=>{if(!s||r!=="local"||!A||j==="provision-local")return;const ke=String(I?.eventId||"").trim();ke&&Ee.current.delete(ke)||yt()||Ht.current||(He.current!==null&&window.clearTimeout(He.current),He.current=window.setTimeout(()=>{He.current=null,da()},180))},[s,r,A,j,yt,Ht,da]),lo=w("/taskforce-ws"),ir=String(c||"").trim(),Gt=Of({enabled:!!(C&&s&&r==="local"&&A&&o&&l&&ir&&ir!=="anonymous"&&lo),workspaceId:n,websocketUrl:lo,onSignal:Ps,onTelemetry:_t,userId:ir||void 0});a.useEffect(()=>{ot(Gt.connectionState)},[Gt.connectionState]),a.useEffect(()=>()=>{He.current!==null&&(window.clearTimeout(He.current),He.current=null)},[]),a.useCallback(async()=>{const[I,ke]=await Promise.all([fetch("/api/taskforce/tasks",{method:"GET",credentials:"include"}),fetch("/api/taskforce/archive",{method:"GET",credentials:"include"})]);if(!I.ok||!ke.ok)return{tasks:[],archived:[],error:"Failed to read local workspace snapshot before sync bootstrap."};const $e=await I.json().catch(()=>({})),Te=await ke.json().catch(()=>({}));return{tasks:Array.isArray($e?.tasks)?$e.tasks:[],archived:Array.isArray(Te?.archived)?Te.archived:[]}},[]);const Pa=a.useCallback(async I=>aa(I,{cloudAuthConfigured:s,isAuthenticated:l,ensureCloudWorkspaceReadyForSync:ia}),[aa,s,l,ia]),va=a.useCallback(async()=>{await Ft({preferCloudOnFirstSync:!1})},[Ft]),gs=a.useCallback(async()=>{if($t(),!s||r!=="local"||!A||!l&&!await ee())return!1;if(ga.current=!0,j==="provision-local"){const Te=ea();return Te?la(Te,{forceAllAiProfiles:!0}):!1}const I=await da();if(j==="attach-cloud")return I;const ke=ea(),$e=ga.current===!0;if(!$e&&Ra(ke))return I;if(ke){ft.current=ke;const Te=await la(ke,{forceAllAiProfiles:$e});return I||Te}return I},[$t,s,r,A,l,ee,j,ea,Ra,la,da]),Pr=a.useCallback(async()=>{if(!await fn(n,"repair")&&(On(n),!await fn(n,"repair"))){Tn("repair");return}$t(),Tt(),Nn.current=null,Et.current=null,pn.current=null,Zn.current="",hs.current=!1,ft.current="",sn.current="",$n.current=new Map,Ka.current=new Set,Wn.current=new Map,rn.current=new Set,ra.current=new Map,Yt.current=new Set,Fn.current=new Map,jn.current=new Set,xn.current=new Map,fa.current=new Set,nt.current=new Map,vn.current=new Set,dn.current=new Map,za.current=new Set,oa.current=new Map,ga.current=!1,Ta.current=!1,Nm(n,{taskWatermarks:new Map,initiativeWatermarks:new Map,workstreamWatermarks:new Map,documentWatermarks:new Map,assetWatermarks:new Map,documentReviewSessionWatermarks:new Map,documentReviewCommentWatermarks:new Map,annotatedAttachmentSessionWatermarks:new Map,taxonomyStateFingerprint:Ne});try{if(!A)return;ka.current=!0;const ke=j==="provision-local"?"provision-local":j==="attach-cloud"?"attach-cloud":ya.current==="provision-local"||ya.current==="attach-cloud"?ya.current:Ce?"attach-cloud":"provision-local";if(await Rt({phase:ke,pullCursor:null,lastErrorMessage:null}),ke==="provision-local"){const $e=ea();if(!$e)return;await la($e,{forceAllAiProfiles:!0,repairMode:!0});return}await da({repairMode:!0})}finally{ka.current=!1,sa(n)}},[fn,$t,Tt,n,On,A,j,Rt,ea,Ce,da,la,sa,Tn]),Wo=a.useCallback(()=>({workspaceId:n,enabled:A,phase:j,status:Ca,summary:Na,lastSuccessfulSyncAt:ha,lastPullAt:Ce,lastPushAt:x,lastErrorAt:P,pendingChanges:re,lastErrorMessage:M,recommendedAction:Us,documentSnapshotCount:G.length,aiProfileSnapshotCount:d.length,aiProfileSnapshotRawCount:Zt,aiProfileSnapshotLastFetchAt:Ke,aiProfileSnapshotLastFetchError:Lt,aiProfileSnapshotLastSkipReason:on,assetSnapshotCount:gn.length,documentReviewSessionSnapshotCount:Gn.length,documentReviewSessionSnapshotFingerprint:Se,annotatedAttachmentSessionSnapshotCount:Ge.length,annotatedAttachmentSessionSnapshotFingerprint:J,lastPushedAiProfileCount:Yt.current.size,lastPushedAiProfileWatermarkCount:Fn.current.size,forceFullAiProfilePushQueued:ga.current===!0}),[n,A,j,Ca,Na,ha,Ce,x,P,re,M,Us,G.length,d.length,Zt,Ke,Lt,on,gn.length,Gn.length,Se,Ge.length,J]);return a.useEffect(()=>{Me.current=gs},[gs]),a.useEffect(()=>{if(!s||r!=="local"||!A||!o||!l)return;pa(),ca(),Da(),Sa(),rs();const I=Dt=>{const Nt=Dt.detail;(String(Nt?.workspaceId||"").trim()||"default")===n&&(pa(),ca(),Da(),Sa(),rs())};window.addEventListener(Ip,I);const ke=window.setInterval(()=>{pa()},en),$e=window.setInterval(()=>{ca()},en),Te=window.setInterval(()=>{Da()},en),X=window.setInterval(()=>{Sa()},en),Pe=window.setInterval(()=>{rs()},en);return()=>{window.removeEventListener(Ip,I),window.clearInterval(ke),window.clearInterval($e),window.clearInterval(Te),window.clearInterval(X),window.clearInterval(Pe)}},[s,r,A,o,l,n,pa,ca,Da,Sa,rs,en]),a.useEffect(()=>{!s||r!=="local"||!A||!o||!l||rr&&(Da(),pa(),ca(),Sa(),rs())},[s,r,A,o,l,rr,Da,pa,ca,Sa,rs]),a.useEffect(()=>{if(!s||r!=="local"||!A||!o||j==="attach-cloud"||!ln)return;const I=ea();if(Ra(I)||!I||I===sn.current)return;const ke=ja();if(pe(ke.changes.length),qt.current||Ht.current){ft.current=I;return}const $e=window.setTimeout(()=>{la(I)},1500);return()=>window.clearTimeout($e)},[s,r,A,o,j,ln,ea,Ra,ja,mt,ye,an,Se,J,la,qt,Ht]),a.useEffect(()=>{s&&r==="local"&&A||($t(),ue(!1))},[s,r,A,$t]),a.useEffect(()=>{if(!s||r!=="local"||!A||!o||j==="provision-local"||yt())return;da();const I=window.setInterval(()=>{da()},Ia);return()=>window.clearInterval(I)},[s,r,A,o,j,yt,da,Ia]),a.useEffect(()=>{r!=="local"||!l||!c||c==="anonymous"||Ft({preferCloudOnFirstSync:!0})},[r,l,c,Ft]),a.useEffect(()=>{if(r!=="local"||!l||!c||c==="anonymous"||!wt.current.has(c)||It.current)return;const I=oe(),ke=JSON.stringify(I);if(!_n.current){_n.current=ke;return}if(ke===_n.current)return;_n.current=ke,Oa(c,new Date().toISOString());const $e=window.setTimeout(()=>{Ft({preferCloudOnFirstSync:!1})},350);return()=>window.clearTimeout($e)},[r,l,c,oe,Oa,Ft]),a.useEffect(()=>{!s||r!=="local"||!A||!o||!l||j==="provision-local"||j==="attach-cloud"||Ta.current||(Ta.current=!0,fetch("/api/taskforce/sync/workspace/repair-startup",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({workspaceId:n})}).then(async I=>{if(!I.ok)return;const ke=await I.json().catch(()=>({}));ke?.applied>0&&(ps("startup_repair_applied",{workspaceId:n,applied:ke.applied,skipped:ke.skipped,failed:ke.failed}),pa(),ca(),Da(),Sa())}).catch(()=>{}))},[s,r,A,o,l,j,n,pa,ca,Da,Sa]),{userGlobalSyncStatus:de,setUserGlobalSyncStatus:ae,userGlobalSyncError:Ve,setUserGlobalSyncError:Re,workspaceLastPullAt:Ce,workspaceLastPushAt:x,workspaceLastErrorAt:P,workspaceLastErrorMessage:M,workspaceLastSuccessfulSyncAt:ha,workspaceCloudSyncEnabled:A,workspaceSyncPhase:j,workspaceSyncStatus:Ca,workspaceSyncSummary:Na,workspaceSyncRecommendedAction:Us,workspaceSyncBusy:O,workspaceSyncPendingChanges:re,syncInFlightRef:se,workspaceRetryAt:Kt,isWorkspaceRetryPending:yt,workspacePushInFlightRef:qt,workspacePullInFlightRef:Ht,workspaceLastPushedSignatureRef:sn,workspacePendingSignatureRef:ft,workspaceLastPushedTaskIdsRef:Ze,workspaceDeletedTaskIdsRef:Vn,workspacePullCursorRef:pn,clearWorkspaceRetry:$t,persistWorkspaceSyncPatch:Rt,loadWorkspaceSyncState:fs,applyWorkspaceSyncStateSnapshot:Ds,syncUserGlobalSettings:Ft,buildWorkspaceSyncSignature:ea,pushWorkspaceChangesToCloud:la,pullWorkspaceChangesFromCloud:da,saveWorkspaceCloudSyncSettings:Pa,retryUserGlobalSettingsSync:va,retryWorkspaceCloudSync:gs,resetWorkspaceSyncCursorAndPull:Pr,getWorkspaceSyncDiagnostics:Wo}}function Lk(e,n){return typeof n=="number"&&Number.isFinite(n)&&n>0?n:e==="error"?3600:2600}function Mk(){const[e,n]=a.useState(null),s=a.useRef(null),r=a.useCallback(()=>{s.current!==null&&(window.clearTimeout(s.current),s.current=null),n(null)},[]),o=a.useCallback((l,c="info",p)=>{if(!l)return;s.current!==null&&(window.clearTimeout(s.current),s.current=null),n({message:l,tone:c,ttlMs:p});const g=Lk(c,p);s.current=window.setTimeout(()=>{s.current=null,n(null)},g)},[]);return a.useEffect(()=>()=>{s.current!==null&&(window.clearTimeout(s.current),s.current=null)},[]),{uiNotice:e,pushNotice:o,clearNotice:r}}function Bk({storagePath:e}){const[n,s]=a.useState("antigravity"),[r,o]=a.useState([]),[l,c]=a.useState(".agent/workflows"),[p,g]=a.useState(null),[w,C]=a.useState(null),_=a.useRef(null);a.useEffect(()=>{const E=r.find(S=>S.id===n);E&&c(E.directory)},[n,r]);const y=a.useCallback(()=>{typeof window>"u"||(_.current!==null&&window.clearTimeout(_.current),_.current=window.setTimeout(()=>{_.current=null,C(null)},5e3))},[]),k=a.useCallback(async()=>{const E=await fetch("/api/taskforce/environments");if(!E.ok)return;const S=await E.json().catch(()=>({}));S.environments&&o(S.environments)},[]),b=a.useCallback(async(E,S)=>{g("workflows"),C(null);try{const Q=await(await fetch("/api/taskforce/export-resources",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"workflows",environment:E,workflowNames:S,variables:{STORAGE_PATH:e.replace(/\/$/,"")||".Taskforce"}})})).json();Q.success?C({type:"success",message:`Successfully exported ${Q.count} workflows to ${E}`}):C({type:"error",message:Q.error||"Export failed"})}catch{C({type:"error",message:"Network error exporting workflows"})}finally{g(null),y()}},[y,e]);return a.useEffect(()=>()=>{_.current!==null&&typeof window<"u"&&(window.clearTimeout(_.current),_.current=null)},[]),{exportEnvironment:n,setExportEnvironment:s,availableEnvironments:r,loadAvailableEnvironments:k,exportWorkflowsPath:l,setExportWorkflowsPath:c,exportingResource:p,exportResult:w,handleExportWorkflows:b}}function Wk(e){const{resolveCloudAuthUrl:n,currentWorkspaceId:s,normalizedCloudAuthBaseUrl:r,normalizedCloudMcpBaseUrl:o,mergedConfig:l,availableWorkspaces:c,currentTheme:p,configLoaded:g,globalTheme:w,themeUseGlobalDefault:C,keyShortcut:_,jsonBackupEnabled:y,globalJsonBackupEnabled:k,globalWeekStartsOn:b,locale:E,supportedLocales:S,jsonBackupUseGlobalDefault:W,manualComplexityEnabled:Q,checklistDropdownEnabled:z,showTaskCardStatusLabel:K,exportWorkflowsPath:V,exportingResource:ne,exportResult:D,pathSaved:Ae,settingsSection:U,exportEnvironment:ee,setupState:be,buildInfo:me,saveSetupMode:Y,saveWorkspaceProfile:R,setCurrentTheme:B,handleSaveTheme:fe,handleSaveGlobalTheme:Ne,setKeyShortcut:de,handleJsonBackupEnabledChange:ae,handleSaveGlobalJsonBackupEnabled:Ve,handleSaveGlobalWeekStartsOn:Re,handleSaveLocale:Ce,handleManualComplexityEnabledChange:Fe,handleChecklistDropdownEnabledChange:x,handleShowTaskCardStatusLabelChange:L,handleResetProjectToGlobal:P,handleSaveSettings:Z,setExportWorkflowsPath:M,setExportEnvironment:h,availableWorkflows:A,initiativeTemplates:H,availableEnvironments:j,fetchWorkflows:je,fetchInitiativeTemplates:O,createInitiativeFromTemplate:ue,fetchWorkflowTemplate:re,fetchWorkflowOverrideNames:pe,saveWorkflowTemplateDraft:G,resetWorkflowTemplateDraft:q,handleExportWorkflows:ye,setShowFolderBrowser:Be,setBrowserTarget:le,fetchFolders:ze,activeCategories:Ye,pathValidation:Xe,taxonomyDisplayLabels:bt,handleUpdateCategory:d,handleRemoveCategory:rt,handleSaveCategory:mt,handleAddPath:F,handleRemovePath:Ke,handleUpdateCategoryIcon:St,handleUpdateCategoryColor:Lt,activeTypes:xt,handleSaveType:Zt,handleRemoveType:Jt,handleUpdateType:on,taxonomies:cn,handleUpdateTaxonomies:nn,priorities:gn,handleUpdatePriorities:yn,analyzeSystemTaxonomyPack:an,handleApplySystemTaxonomyPack:kn,handleUpdateTaxonomyDisplayLabels:Xt,projectRoot:Gn,projectName:At,mcpHostRoot:Se,serverHostRoot:Mt,mcpScriptPath:Qt,tenantId:zt,runtimeMode:Ge,workspaceSwitchingEnabled:An,deleteWorkspace:J,setMcpHostRoot:_e,isAuthenticated:we}=e,Ie=a.useCallback(async(Qe,ot)=>{const et=n(Qe),_t=new Headers(ot?.headers||void 0);if(Qe.startsWith("/api/taskforce/settings/mcp/")){const Ot=String(s||"").trim();Ot&&Ot!=="default"&&!_t.has("x-taskforce-workspace-id")&&_t.set("x-taskforce-workspace-id",Ot)}const vt={...ot,headers:_t,credentials:ot?.credentials??"include"};if(typeof window<"u"&&/^https?:\/\//i.test(et))try{new URL(et,window.location.origin).origin!==window.location.origin&&vt.mode===void 0&&(vt.mode="cors")}catch{}return fetch(et,vt)},[s,n]),We=c.find(Qe=>Qe.id===s);return{fetchCloudAuthApi:Ie,currentTheme:p,configLoaded:g,globalTheme:w,themeUseGlobalDefault:C,keyShortcut:_,jsonBackupEnabled:y,globalJsonBackupEnabled:k,globalWeekStartsOn:b,locale:E,supportedLocales:S,jsonBackupUseGlobalDefault:W,manualComplexityEnabled:Q,checklistDropdownEnabled:z,showTaskCardStatusLabel:K,exportWorkflowsPath:V,exportingResource:ne,exportResult:D,pathSaved:Ae,initialSection:U,exportEnvironment:ee,setupState:be,buildInfo:me,onSaveSetupMode:Y,onSaveWorkspaceProfile:R,onThemeChange:B,onSaveTheme:fe,onSaveGlobalTheme:Ne,onKeyShortcutChange:de,onJsonBackupEnabledChange:ae,onSaveGlobalJsonBackupEnabled:Ve,onSaveGlobalWeekStartsOn:Re,onSaveLocale:Ce,onManualComplexityEnabledChange:Fe,onChecklistDropdownEnabledChange:x,onShowTaskCardStatusLabelChange:L,onResetProjectToGlobal:P,onSaveSettings:Z,onExportWorkflowsPathChange:M,onExportEnvironmentChange:h,availableWorkflows:A,initiativeTemplates:H,availableEnvironments:j,onRefreshWorkflows:je,onRefreshInitiativeTemplates:O,onCreateInitiativeFromTemplate:ue,onFetchWorkflowTemplate:re,onFetchWorkflowOverrideNames:pe,onSaveWorkflowTemplateDraft:G,onResetWorkflowTemplateDraft:q,onExportWorkflows:ye,onShowFolderBrowserChange:Be,onBrowserTargetChange:le,onFetchFolders:ze,categories:Ye,pathValidation:Xe,taxonomyDisplayLabels:bt,onUpdateCategory:d,onRemoveCategory:rt,onSaveCategory:mt,onAddPath:F,onRemovePath:Ke,onUpdateCategoryIcon:St,onUpdateCategoryColor:Lt,types:xt,onSaveType:Zt,onRemoveType:Jt,onUpdateType:on,taxonomies:cn,onUpdateTaxonomies:nn,priorities:gn,onUpdatePriorities:yn,onAnalyzeSystemTaxonomyPack:an,onApplySystemTaxonomyPack:kn,onUpdateTaxonomyDisplayLabels:Xt,projectRoot:Gn,projectName:At,mcpHostRoot:Se,serverHostRoot:Mt,mcpScriptPath:Qt,tenantId:zt,workspaceId:s,runtimeMode:Ge,cloudAuthBaseUrl:r||l.cloudAuthBaseUrl,cloudMcpBaseUrl:o||void 0,workspaceSwitchingEnabled:An,currentWorkspaceRole:We?.role||"member",currentWorkspaceName:String(We?.name||""),onDeleteWorkspace:J,onMcpHostRootChange:_e,isAuthenticated:we}}function Fk(e){const{keyShortcut:n,themeUseGlobalDefault:s,runtimeMode:r,jsonBackupUseGlobalDefault:o,globalTheme:l,globalJsonBackupEnabled:c,setCurrentTheme:p,setThemeUseGlobalDefault:g,setGlobalTheme:w,setJsonBackupEnabled:C,setJsonBackupUseGlobalDefault:_,setGlobalJsonBackupEnabled:y,setGlobalWeekStartsOn:k,setLocale:b,setManualComplexityEnabled:E,setChecklistDropdownEnabled:S,setShowTaskCardStatusLabel:W,setShowChecklist:Q}=e,z=a.useCallback(async()=>{try{const R=await fetch("/api/taskforce/global-settings",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({shortcut:n})});if(!R.ok)throw new Error(`Failed to save global settings (${R.status})`);return!0}catch{return console.error("[Taskforce] Failed to save shortcut"),!1}},[n]),K=a.useCallback(async R=>{p(R),g(!1);try{const B=await fetch("/api/taskforce/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({theme:R})});if(!B.ok)throw new Error(`Failed to save config (${B.status})`);return!0}catch{return console.error("[Taskforce] Failed to save project theme"),!1}},[p,g]),V=a.useCallback(async R=>{w(R),s&&p(R);try{const B=await fetch("/api/taskforce/global-settings",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({theme:R})});if(!B.ok)throw new Error(`Failed to save global settings (${B.status})`);return!0}catch{return console.error("[Taskforce] Failed to save global theme"),!1}},[w,s,p]),ne=a.useCallback(async R=>{if(r==="cloud")return C(!1),_(!1),!1;C(R),_(!1);try{const B=await fetch("/api/taskforce/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonBackupEnabled:R})});if(!B.ok)throw new Error(`Failed to save config (${B.status})`);return!0}catch{return console.error("[Taskforce] Failed to save project backup setting"),!1}},[r,C,_]),D=a.useCallback(async R=>{if(r==="cloud")return y(!1),o&&C(!1),!1;y(R),o&&C(R);try{const B=await fetch("/api/taskforce/global-settings",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonBackupEnabled:R})});if(!B.ok)throw new Error(`Failed to save global settings (${B.status})`);return!0}catch{return console.error("[Taskforce] Failed to save global backup setting"),!1}},[r,y,o,C]),Ae=a.useCallback(async R=>{k(R);try{const B=await fetch("/api/taskforce/global-settings",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({schedulePreferences:{weekStartsOn:R}})});if(!B.ok)throw new Error(`Failed to save global settings (${B.status})`);return!0}catch{return console.error("[Taskforce] Failed to save regional week start setting"),!1}},[k]),U=a.useCallback(async R=>{const B=Tf(R);return b(B),!0},[b]),ee=a.useCallback(async R=>{E(R);try{const B=await fetch("/api/taskforce/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({manualComplexityEnabled:R})});if(!B.ok)throw new Error(`Failed to save config (${B.status})`);return!0}catch{return console.error("[Taskforce] Failed to save manual complexity setting"),!1}},[E]),be=a.useCallback(async R=>{S(R),R||Q(!1);try{const B=await fetch("/api/taskforce/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({checklistDropdownEnabled:R})});if(!B.ok)throw new Error(`Failed to save config (${B.status})`);return!0}catch{return console.error("[Taskforce] Failed to save checklist dropdown setting"),!1}},[S,Q]),me=a.useCallback(async R=>{W(R);try{const B=await fetch("/api/taskforce/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({showTaskCardStatusLabel:R})});if(!B.ok)throw new Error(`Failed to save config (${B.status})`);return!0}catch{return console.error("[Taskforce] Failed to save task card status label setting"),!1}},[W]),Y=a.useCallback(async()=>{g(!0),_(!0),p(l),C(c),E(!1),S(!0),W(!0),Q(!1);try{const R=await fetch("/api/taskforce/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({theme:null,jsonBackupEnabled:null,manualComplexityEnabled:null,checklistDropdownEnabled:null,showTaskCardStatusLabel:null})});if(!R.ok)throw new Error(`Failed to save config (${R.status})`);return!0}catch{return console.error("[Taskforce] Failed to reset project settings"),!1}},[g,_,p,l,C,c,E,S,W,Q]);return{handleSaveSettings:z,handleSaveTheme:K,handleSaveGlobalTheme:V,handleJsonBackupEnabledChange:ne,handleSaveGlobalJsonBackupEnabled:D,handleSaveGlobalWeekStartsOn:Ae,handleSaveLocale:U,handleManualComplexityEnabledChange:ee,handleChecklistDropdownEnabledChange:be,handleShowTaskCardStatusLabelChange:me,handleResetProjectToGlobal:Y}}function zk(e){const{activeCategories:n,activeTab:s,activeTypes:r,archivedTasks:o,browserTarget:l,category:c,configLoaded:p,customCategories:g,refreshTaskCollections:w,fetchTasks:C,filterCategories:_,getCategoryPaths:y,normalizePath:k,pathValidation:b,setBrowserTarget:E,setCategory:S,setCustomCategories:W,setCustomTypes:Q,setFilterCategories:z,setPathValidation:K,setPriorities:V,setShowFolderBrowser:ne,setTaxonomies:D,tasks:Ae}=e,U=a.useCallback(async(M,h)=>{const A=await M.json().catch(()=>({}));return String(A?.error||h)},[]),ee=a.useCallback(()=>[...Ae,...o],[o,Ae]),be=a.useCallback(M=>M.priorities.find(h=>h.value===2)?.value||M.priorities[0]?.value||2,[]),me=a.useCallback(async M=>{if(M.length!==0)try{const h=await fetch("/api/taskforce/validate-paths",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({paths:M})});if(h.ok){const A=await h.json();K(H=>({...H,...A.results}))}}catch(h){console.error("[Taskforce] Failed to validate paths:",h)}},[K]);a.useEffect(()=>{if(s!=="settings"||!p)return;const M=[];n.forEach(A=>{y(A).forEach(j=>{M.includes(j)||M.push(j)})});const h=M.filter(A=>!b[A]);h.length>0&&me(h)},[n,s,p,y,b,me]);const Y=a.useCallback(async(M,h)=>{if(p){W(A=>(A.length>0?A:n).map(j=>j.value===M.value?M:j)),h&&h!==M.label&&(c===h&&S(M.label),_.includes(h)&&z(A=>A.map(H=>H===h?M.label:H)));try{const j={categories:(g.length>0?g:n).map(je=>je.value===M.value?M:je)};h&&h!==M.label&&(j.reassignFrom=h,j.reassignTo=M.label),await fetch("/api/taskforce/categories",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(j)}),h&&await C()}catch(A){console.error("[Taskforce] Failed to update category",A)}}},[n,c,p,g,C,_,S,W,z]),R=a.useCallback(async M=>{if(!p)return;const h=M.trim().toLowerCase().replace(/\s+/g,"-");if(n.some(H=>H.value===h))return;const A={value:h,label:M.trim(),color:"blue-200",icon:"Folder"};W(H=>[...H.length>0?H:n,A]);try{const j=[...g.length>0?g:n,A];await fetch("/api/taskforce/categories",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({categories:j})})}catch(H){console.error("[Taskforce] Failed to create category",H)}},[n,p,g,W]),B=a.useCallback((M,h)=>{if(!h.trim())return;const A=n.find(O=>O.value===M);if(!A)return;const H=y(A),j=h.trim();if(H.includes(j))return;const je=[...H,j];Y({...A,path:void 0,paths:je}),me(je)},[n,y,Y,me]),fe=a.useCallback((M,h)=>{const A=n.find(H=>H.value===M);A&&Y({...A,icon:h})},[n,Y]),Ne=a.useCallback((M,h)=>{const A=n.find(H=>H.value===M);A&&Y({...A,color:h})},[n,Y]),de=a.useCallback((M,h)=>{const A=n.find(je=>je.value===M);if(!A)return;const j=y(A).filter(je=>je!==h);Y({...A,path:void 0,paths:j})},[n,y,Y]),ae=a.useCallback(M=>{const h=k(M);if(l&&typeof l=="object"&&l.type==="category"){const A=n.find(H=>H.value===l.value);if(A){const H=y(A);if(!H.includes(h)){const j=[...H,h];Y({...A,path:void 0,paths:j})}}}ne(!1),E(null)},[n,l,y,Y,k,E,ne]),Ve=a.useCallback(async M=>{if(!p)return;const h=Ic,A=n.find(O=>O.value===h),H=A?{...A}:{value:h,label:yu,icon:"Inbox"},j=H.label,je=n.find(O=>O.value===M);W(O=>{let re=(O.length>0?O:n).filter(pe=>pe.value!==M);return re.some(pe=>pe.value===h)||(re=[H,...re]),re}),je&&((c===je.label||c===je.value)&&S(h),(_.includes(je.label)||_.includes(je.value))&&z(O=>{const ue=O.filter(re=>re!==je.label&&re!==je.value);return ue.includes(h)?ue:[...ue,h]}));try{let O=(g.length>0?g:n).filter(ue=>ue.value!==M);O.some(ue=>ue.value===h)||(O=[H,...O]),await fetch("/api/taskforce/categories",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({categories:O,reassignFrom:je?.label||M,reassignTo:j})}),await C()}catch(O){console.error("[Taskforce] Failed to remove category",O)}},[n,c,p,g,C,_,S,W,z]),Re=a.useCallback(async M=>{if(!M.trim())return;const h=M.trim().toLowerCase().replace(/\s+/g,"-");if(r.some(H=>H.value===h))return;const A=[...r,{value:h,label:M.trim(),status:"active"}];Q(A);try{await fetch("/api/taskforce/types",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({types:A})})}catch(H){console.error("Failed to save type",H)}},[r,Q]),Ce=a.useCallback(async M=>{const h=r.map(A=>A.value===M?{...A,status:"retired"}:A);Q(h);try{await fetch("/api/taskforce/types",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({types:h})}),await C()}catch(A){console.error("Failed to save type",A)}},[r,C,Q]),Fe=a.useCallback(async(M,h)=>{const A=r.find(O=>O.value===M);if(!A)return;const H=typeof h.label=="string"?h.label.trim():A.label;if(!H)return;const j=r.map(O=>O.value===M?{...O,...h,label:H}:O);if(JSON.stringify(j)!==JSON.stringify(r)){Q(j);try{await fetch("/api/taskforce/types",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({types:j})})}catch(O){console.error("Failed to update type",O)}}},[r,Q]),x=a.useCallback(async M=>{if(p){D(M);try{await fetch("/api/taskforce/taxonomies",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({taxonomies:M})})}catch(h){console.error("[Taskforce] Failed to save taxonomies",h)}}},[p,D]),L=a.useCallback(async M=>{if(p){V(M);try{await fetch("/api/taskforce/priorities",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({priorities:M})})}catch(h){console.error("[Taskforce] Failed to save priorities",h)}}},[p,V]),P=a.useCallback(M=>{const h=ee(),A=new Set(M.categories.map(re=>re.value)),H=new Set(M.types.map(re=>re.value)),j=new Set(M.priorities.map(re=>Number(re.value))),je=Array.from(new Set(h.map(re=>String(re.category||"").trim()).filter(re=>re.length>0&&!A.has(re)))).sort(),O=Array.from(new Set(h.map(re=>String(re.type||"").trim()).filter(re=>re.length>0&&!H.has(re)))).sort(),ue=Array.from(new Set(h.map(re=>Number(re.priority)).filter(re=>Number.isFinite(re)&&re>0&&!j.has(re)))).sort((re,pe)=>re-pe);return{unmatchedCategoryValues:je,unmatchedTypeValues:O,incompatiblePriorityValues:ue}},[ee]),Z=a.useCallback(async M=>{if(!p)return{success:!1,error:"Settings are still loading."};const{pack:h,sections:A,remapExistingValuesToDefault:H,workspaceIdOverride:j}=M,je=String(j||"").trim(),O=je.length>0,ue=O?[]:ee(),re=G=>{if(!je)return G;const q=G.includes("?")?"&":"?";return`${G}${q}workspaceId=${encodeURIComponent(je)}`},pe=()=>{const G={"Content-Type":"application/json"};return je&&(G["x-taskforce-workspace-id"]=je),G};try{if(A.categories){const G=new Set(h.categories.map(Be=>Be.value)),q=H?[...h.categories]:[...h.categories,...n.filter(Be=>!G.has(Be.value)).map(Be=>({...Be,disabled:!0}))];O||W(q);const ye=await fetch(re("/api/taskforce/categories"),{method:"POST",headers:pe(),body:JSON.stringify({categories:q})});if(!ye.ok)return{success:!1,error:await U(ye,"Failed to apply category library pack.")}}if(A.types){const G=new Set(h.types.map(le=>le.value)),q=h.types.find(le=>le.value===ms)?.value||h.types[0]?.value||ms;if(H){const le=ue.filter(ze=>ze.type&&!G.has(String(ze.type))).map(ze=>({id:ze.id,type:q}));if(le.length>0){const ze=await fetch(re("/api/taskforce/bulk-update-fields"),{method:"POST",headers:pe(),body:JSON.stringify({updates:le})});if(!ze.ok)return{success:!1,error:await U(ze,"Failed to remap task types to the pack default.")}}}const ye=H?[...h.types]:[...h.types,...r.filter(le=>!G.has(le.value)).map(le=>({...le,status:"retired"}))];O||Q(ye);const Be=await fetch(re("/api/taskforce/types"),{method:"POST",headers:pe(),body:JSON.stringify({types:ye})});if(!Be.ok)return{success:!1,error:await U(Be,"Failed to apply task type library pack.")}}if(A.priorities){const G=new Set(h.priorities.map(le=>le.value)),q=Array.from(new Set(ue.map(le=>Number(le.priority)).filter(le=>Number.isFinite(le)&&le>0&&!G.has(le)))).sort((le,ze)=>le-ze);if(q.length>0&&!H)return{success:!1,error:`This workspace still uses priority levels ${q.join(", ")}. Enable "Remap unmatched existing values to default" to replace them before applying this pack.`};if(q.length>0){const le=be(h),ze=ue.filter(Ye=>q.includes(Number(Ye.priority))).map(Ye=>({id:Ye.id,priority:le}));if(ze.length>0){const Ye=await fetch(re("/api/taskforce/bulk-update-fields"),{method:"POST",headers:pe(),body:JSON.stringify({updates:ze})});if(!Ye.ok)return{success:!1,error:await U(Ye,"Failed to remap task priorities to the pack default.")}}}const ye=h.priorities.map(le=>({...le,value:Number(le.value)}));O||V(ye);const Be=await fetch(re("/api/taskforce/priorities"),{method:"POST",headers:pe(),body:JSON.stringify({priorities:ye})});if(!Be.ok)return{success:!1,error:await U(Be,"Failed to apply priority library pack.")}}return O||await w({isSilent:!0}),{success:!0}}catch(G){return console.error("[Taskforce] Failed to apply system taxonomy pack",G),{success:!1,error:G instanceof Error?G.message:"Failed to apply system taxonomy pack."}}},[n,r,p,ee,be,U,w,W,Q,V]);return{getCategoryPaths:y,validatePaths:me,handleUpdateCategory:Y,handleSaveCategory:R,handleAddPath:B,handleUpdateCategoryIcon:fe,handleUpdateCategoryColor:Ne,handleRemovePath:de,handleSelectPath:ae,handleRemoveCategory:Ve,handleSaveType:Re,handleRemoveType:Ce,handleUpdateType:Fe,handleUpdateTaxonomies:x,handleUpdatePriorities:L,analyzeSystemTaxonomyPack:P,handleApplySystemTaxonomyPack:Z}}function Ok({shouldDeferProtectedApiCalls:e,shouldBlockProtectedApiCalls:n}){const[s,r]=a.useState([]),[o,l]=a.useState([]),c=a.useCallback(async()=>{if(!(e||n))try{const y=await fetch("/api/taskforce/workflow-templates");if(y.ok){const k=await y.json();r(k.templates||[])}}catch{}},[e,n]),p=a.useCallback(async()=>{try{const y=await fetch("/api/taskforce/initiative-templates");if(!y.ok)return[];const k=await y.json(),b=Array.isArray(k?.templates)?k.templates:[];return l(b),b}catch{return[]}},[]),g=a.useCallback(async y=>{if(!y)return null;const k=[`/api/taskforce/workflow-template/${encodeURIComponent(y)}`,`/api/taskforce/workflow-templates/${encodeURIComponent(y)}`];try{for(const b of k){const E=await fetch(b);if(!E.ok)continue;const S=await E.json();if(S?.template)return S.template}return null}catch{return null}},[]),w=a.useCallback(async()=>{try{const y=await fetch("/api/taskforce/workflow-editor/overrides");if(!y.ok)return[];const k=await y.json();return Array.isArray(k?.names)?k.names:[]}catch{return[]}},[]),C=a.useCallback(async(y,k)=>{try{const b=await fetch("/api/taskforce/workflow-editor/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:y,draft:k})}),E=await b.json().catch(()=>({}));return!b.ok||!E.success?{success:!1,error:E.error||`Save failed (${b.status})`}:(c(),{success:!0})}catch(b){return{success:!1,error:b.message}}},[c]),_=a.useCallback(async y=>{try{const k=await fetch(`/api/taskforce/workflow-editor/reset/${encodeURIComponent(y)}`,{method:"POST"}),b=await k.json().catch(()=>({}));return!k.ok||!b.success?{success:!1,error:b.error||`Reset failed (${k.status})`}:(c(),{success:!0})}catch(k){return{success:!1,error:k.message}}},[c]);return{availableWorkflows:s,initiativeTemplates:o,fetchWorkflows:c,fetchInitiativeTemplates:p,fetchWorkflowTemplate:g,fetchWorkflowOverrideNames:w,saveWorkflowTemplateDraft:C,resetWorkflowTemplateDraft:_}}function $k(){const[e,n]=a.useState(!1),s=a.useCallback(async()=>{if(!document.fullscreenElement){try{await document.documentElement.requestFullscreen(),n(!0)}catch(r){console.error(`Error attempting to enable full-screen mode: ${r}`)}return}document.exitFullscreen&&(await document.exitFullscreen(),n(!1))},[]);return a.useEffect(()=>{const r=()=>{n(!!document.fullscreenElement)};return document.addEventListener("fullscreenchange",r),()=>document.removeEventListener("fullscreenchange",r)},[]),{zenMode:e,setZenModeState:n,toggleZenMode:s}}async function Uk(e,n,s){if(e.current){n.current=!0;return}e.current=!0;try{do n.current=!1,await s();while(n.current)}finally{e.current=!1}}function qk({tasks:e,archivedTasks:n,setTasks:s,setArchivedTasks:r,setLoadingTasks:o,getCurrentWorkspaceId:l,workspaceResetKey:c,shouldDeferProtectedApiCalls:p,shouldBlockProtectedApiCalls:g,handleUnauthorized:w,authRequiredForApi:C}){const _=a.useRef(new Map),y=a.useRef(!1),k=a.useRef([]),b=a.useRef([]),E=a.useRef(!1),S=a.useRef(!1),W=a.useRef(null),Q=a.useRef(null);a.useEffect(()=>{k.current=e},[e]),a.useEffect(()=>{b.current=n},[n]);const z=a.useCallback(R=>`${R.updatedAt||R.createdAt||""}|${R.status}|${R.priority}|${R.title}`,[]),K=a.useCallback((R,B)=>B.aborted?R===B.reason?!0:R instanceof DOMException?R.name==="AbortError":String(R?.name||"").toLowerCase()==="aborterror":!1,[]),[V,ne]=a.useState([]),D=a.useRef(new Map),Ae=a.useCallback(R=>{!R.length||typeof window>"u"||(ne(B=>Array.from(new Set([...B,...R]))),R.forEach(B=>{const fe=D.current.get(B);fe&&window.clearTimeout(fe);const Ne=window.setTimeout(()=>{D.current.delete(B),ne(de=>de.filter(ae=>ae!==B))},4e3);D.current.set(B,Ne)}))},[]);a.useEffect(()=>()=>{typeof window>"u"||(D.current.forEach(R=>window.clearTimeout(R)),D.current.clear())},[]),a.useEffect(()=>{_.current=new Map,y.current=!1,E.current=!1,S.current=!1,W.current?.abort("workspace-reset"),W.current=null,Q.current?.abort("workspace-reset"),Q.current=null,typeof window<"u"&&(D.current.forEach(R=>window.clearTimeout(R)),D.current.clear()),ne([])},[c]);const U=a.useCallback(async(R=!1,B)=>{if(!(B?.ignoreAuthGuard===!0)&&(p||g))return;R||o(!0);const Ne=String(l()||"").trim();W.current?.abort("superseded");const de=new AbortController;W.current=de;try{const ae=await fetch("/api/taskforce/tasks",{signal:de.signal});if(ae.status===401){w(),s([]),R||o(!1);return}if(ae.ok){const Re=((await ae.json()).tasks||[]).map(L=>ro(L));if(String(l()||"").trim()!==Ne)return;const Fe=new Map,x=[];for(const L of Re){const P=z(L);if(Fe.set(L.id,P),!y.current)continue;const Z=_.current.get(L.id);(!Z||Z!==P)&&x.push(L.id)}_.current=Fe,y.current?Ae(x):y.current=!0,s(Re)}}catch(ae){if(K(ae,de.signal))return;console.error("[Taskforce] Failed to fetch tasks:",ae)}finally{const ae=W.current===de;ae&&(W.current=null),!R&&ae&&o(!1)}},[z,l,Ae,w,s,o,C,p,g]),ee=a.useCallback(async(R=!1,B)=>{if(!(B?.ignoreAuthGuard===!0)&&(p||g))return;const Ne=String(l()||"").trim();Q.current?.abort("superseded");const de=new AbortController;Q.current=de;try{const ae=await fetch("/api/taskforce/archive",{signal:de.signal});if(ae.ok){const Ve=await ae.json();if(String(l()||"").trim()!==Ne)return;const Ce=(Ve.archived||[]).map(Fe=>({...ro(Fe),isArchived:!0}));r(Ce)}}catch(ae){if(K(ae,de.signal))return;console.error("[Taskforce] Failed to fetch archive:",ae)}finally{Q.current===de&&(Q.current=null)}},[l,K,r,p,g]),be=a.useCallback(async R=>{const B=R?.isSilent!==!1,fe=R?.ignoreAuthGuard===!0;await Promise.all([U(B,{ignoreAuthGuard:fe}),ee(B,{ignoreAuthGuard:fe})])},[ee,U]),me=a.useCallback(async()=>{await Uk(E,S,async()=>{await be({isSilent:!0})})},[be]),Y=a.useCallback(R=>{const B=Qg(R,k.current,b.current);k.current=B.tasks,b.current=B.archivedTasks,s(B.tasks),r(B.archivedTasks)},[s,r]);return{tasksRef:k,archivedTasksRef:b,recentlyChangedTaskIds:V,markRecentlyChangedTasks:Ae,fetchTasks:U,fetchArchive:ee,refreshTaskCollections:be,refreshTaskCollectionsFromInvalidation:me,mergeTaskFromServer:Y,getTaskRevisionKey:z}}function Hk(e){const{editingTaskId:n,relationshipTasks:s,initiatives:r=[],workstreams:o=[],supplementalTasks:l=[],setComments:c}=e,p=a.useMemo(()=>{if(l.length===0)return s;const _=new Map;return s.forEach(y=>_.set(y.id,y)),l.forEach(y=>_.set(y.id,y)),Array.from(_.values())},[s,l]),g=a.useMemo(()=>{if(n)return p.find(_=>_.id===n)},[p,n]);a.useEffect(()=>{n&&c(g?.comments||[])},[n,g?.id,g?.updatedAt,g?.comments,c]);const w=a.useMemo(()=>{if(g?.workstreamId)return o.find(_=>_.id===g.workstreamId)},[g,o]),C=a.useMemo(()=>{if(w?.initiativeId)return r.find(_=>_.id===w.initiativeId)},[w,r]);return{currentTask:g,currentTaskWorkstream:w,currentTaskInitiative:C}}const Up="WS-",qp="IN-";function to(e){return Dc(Up,e)}function qf(e){return Mp(Up,e)}function Hp(e){return Hl(Up,e)}function ar(e){return Dc(qp,e)}function Gk(e){return Mp(qp,e)}function Vk(e){return Hl(qp,e)}function cp(e,n){const s=String(n||"").trim();if(!s)return null;const r=Gk(s);return e.find(o=>o.id===s||ar(o)===s||r!==null&&o.referenceNumber===r)||null}function Zk(e){const n={};return e.forEach(s=>{const r=s.defaultValue;if(r!=null){if(Array.isArray(r)){r.length>0&&(n[s.id]=r.map(o=>typeof o=="number"?o:String(o)));return}n[s.id]=typeof r=="number"?r:String(r)}}),n}function Kk(e,n){return e.filter(s=>{const r=n[s.id],o=Array.isArray(r)?r.length>0:r!=null&&r!=="";return s.status==="retired"&&!o?!1:s.formEnabled!==!1||s.isRequired===!0||o})}function Yk(e){const{activeCategories:n,activeTypes:s,activeTab:r,attachments:o,checklistItems:l,comments:c,description:p,editingTaskId:g,flushPendingAutoSave:w,getPreferredCategoryValue:C,lastUsedCategory:_,newCommentText:y,relationshipTasks:k,workstreams:b,showArchive:E,taxonomies:S,setActiveTab:W,setApproach:Q,setAssignee:z,setAttachments:K,setAttachmentsDirty:V,setCategory:ne,setChecklistItems:D,setComments:Ae,setComplexity:U,setDescription:ee,setDueDate:be,setEditingTaskId:me,setError:Y,setFormTaxonomies:R,setIsOpen:B,setNewCommentText:fe,setPendingNavigation:Ne,setWorkstreamInput:de,setPriority:ae,setScheduledDate:Ve,setShowArchive:Re,setStatus:Ce,setTaskReturnTrail:Fe,setTitle:x,setType:L,setUnsavedModalOpen:P,taskReturnTrail:Z,title:M}=e,h=a.useCallback(()=>s.find(q=>String(q.value||"").trim().length>0)?.value||ms,[s]),A=a.useCallback(q=>{if(g){w(),q();return}if(!(M.trim()!==""||p.trim()!==""||l.length>0||y.trim()!==""||c.length>0||o.length>0)){q();return}Ne(()=>q),P(!0)},[o,c.length,p,g,w,l,y,Ne,P,M]),H=a.useCallback(()=>{B(!1)},[B]),j=a.useCallback(()=>{me(null),x(""),ee("");const q=_,ye=n.some(Be=>Be.label===q||Be.value===q);if(q&&ye){const Be=n.find(le=>le.label===q||le.value===q);ne(Be?.value||q)}else ne(C(n));L(h()),ae(2),U(3),Ce("task"),Q("default"),z("unassigned"),Ve(""),be(""),de(""),D([]),R(Zk(S)),Ae([]),fe(""),K([]),V(!1),Y("")},[n,C,h,_,Q,z,K,V,ne,D,Ae,U,ee,be,me,Y,R,fe,ae,Ve,Ce,x,L,S]),je=a.useCallback(q=>{const ye=q.trim();if(!ye)return null;const Be=wf(ye);if(Be){const Ye=k.find(Xe=>Xe.referenceNumber===Be);if(Ye)return Ye}const le=k.find(Ye=>Ye.id===ye);if(le)return le;const ze=k.find(Ye=>Rr(Ye)===ye);return ze||null},[k]),O=a.useCallback(q=>{const ye=q.trim();if(!ye)return null;const Be=ye.toLowerCase(),le=qf(ye);if(le){const Xe=b.find(bt=>bt.referenceNumber===le);if(Xe)return Xe}const ze=b.find(Xe=>Xe.id===ye);if(ze)return ze;const Ye=b.find(Xe=>Xe.title.trim().toLowerCase()===Be);return Ye||null},[b]),ue=a.useCallback((q,ye)=>{ye?.preserveReturnTrail||Fe([]),me(q.id),x(q.title),ee(q.description||""),ne(q.category||C(n)),L(q.type||h()),ae(typeof q.priority=="number"?q.priority:2),U(typeof q.complexity=="number"?q.complexity:3),Ce(q.status||"task"),Q(q.approach||"default"),z(q.assignee||"unassigned"),Ve(q.scheduledDate||""),be(q.dueDate||"");const Be=q.workstreamId&&b.find(le=>le.id===q.workstreamId)||null;de(Be?to(Be)||Be.id:""),D(q.checklistItems||[]),Ae(q.comments||[]),R(q.taxonomies||{}),q.taxonomies?.approach&&Q(q.taxonomies.approach),K(q.attachments||[]),V(!1),W("add")},[n,C,h,W,Q,z,K,V,ne,D,Ae,U,ee,be,me,R,ae,Ve,Ce,Fe,x,L,b]),re=a.useCallback(q=>{const ye=k.find(Be=>Be.id===q);ye&&(r==="add"&&g&&g!==ye.id&&Fe(Be=>Be[Be.length-1]===g?Be:[...Be,g]),ye.isArchived&&!E&&Re(!0),ue(ye,{preserveReturnTrail:!0}))},[r,g,ue,k,Re,Fe,E]),pe=a.useCallback(()=>{if(r!=="add"||!g||Z.length===0)return!1;const q=[...Z];for(;q.length>0;){const ye=q.pop();if(!ye)continue;const Be=k.find(le=>le.id===ye);if(Be)return Be.isArchived&&!E&&Re(!0),Fe(q),ue(Be,{preserveReturnTrail:!0}),!0}return Fe([]),!1},[r,g,ue,k,Re,Fe,E,Z]),G=a.useCallback(()=>{Fe([])},[Fe]);return{handleNavigation:A,handleClose:H,resetForm:j,resolveTaskIdInput:je,resolveWorkstreamIdInput:O,handleEdit:ue,handleOpenTaskById:re,returnToPreviousTask:pe,clearReturnToParentTask:G}}function Jk(e){return e.map(n=>({...n}))}function Xk(e){return e.map(n=>({...n}))}function Qk(e){return e.map(n=>({...n}))}const eS={id:"software-development",label:"Software Development",description:"A software-oriented starter pack with developer-focused work types and a 4-level priority scale.",categories:[{value:"default",label:"General",icon:"Inbox"},{value:"product",label:"Product",icon:"Layers",color:"blue-500"},{value:"ui-ux",label:"UI/UX",icon:"Palette",color:"violet-500"},{value:"backend",label:"Backend",icon:"Server",color:"emerald-500"}],types:[{value:"feature",label:"Feature",icon:"Star",color:"teal-500",status:"active"},{value:"bug",label:"Bug",icon:"Bug",color:"red-500",status:"active"},{value:"chore",label:"Chore",icon:"Zap",color:"amber-500",status:"active"},{value:"refactor",label:"Refactor",icon:"Code",color:"blue-500",status:"active"},{value:"documentation",label:"Docs",icon:"Book",color:"sky-500",status:"active"}],priorities:[{value:1,label:"Low",color:"amber-200",icon:"ArrowDown"},{value:2,label:"Medium",color:"yellow-500",icon:"Minus"},{value:3,label:"High",color:"orange-500",icon:"ArrowUp"},{value:4,label:"Critical",color:"red-500",icon:"AlertTriangle"}]},tS=[{id:"general",label:"General",description:"A neutral starter pack for broad project and AI collaboration workflows.",isDefaultStarter:!0,categories:[{value:Ic,label:yu,icon:"Inbox"}],types:[{value:"task",label:"Task",icon:"CheckSquare",color:"blue-500",status:"active"},{value:"deliverable",label:"Deliverable",icon:"Package",color:"teal-500",status:"active"},{value:"issue",label:"Issue",icon:"AlertCircle",color:"red-500",status:"active"},{value:"idea",label:"Idea",icon:"Lightbulb",color:"amber-500",status:"active"},{value:"review",label:"Review",icon:"Search",color:"violet-500",status:"active"}],priorities:[{value:1,label:"Low",color:"teal-500",icon:"ArrowDown"},{value:2,label:"Medium",color:"blue-500",icon:"Minus"},{value:3,label:"High",color:"amber-500",icon:"ArrowUp"}]},eS];function Hf(){return tS.map(e=>({...e,categories:Jk(e.categories),types:Xk(e.types),priorities:Qk(e.priorities)}))}const Cc=[{value:"task",label:"To Do",shortLabel:"To Do",icon:"Square",color:"blue-200"},{value:"on-hold",label:"Blocked",shortLabel:"Blocked",icon:"Pause",color:"amber-500"},{value:"in-progress",label:"Working",shortLabel:"Working",icon:"Play",color:"blue-500"},{value:"review",label:"Review",shortLabel:"Review",icon:"ScanSearch",color:"violet-500"},{value:"done",label:"Done",shortLabel:"Done",icon:"SquareCheck",color:"green-500"},{value:"cancelled",label:"Cancelled",shortLabel:"Cancelled",icon:"Ban",color:"red-500"}],no=Cc.map(({value:e,label:n,icon:s,color:r})=>({value:e,label:n,icon:s,color:r}));function Ml(e){const n=String(e||"task").trim().toLowerCase();return n==="completed"?Cc.find(s=>s.value==="done")||Cc[0]:Cc.find(s=>s.value===n)||Cc[0]}const Gf=["Folder","Code","FileText","Terminal","Database","Cpu","Globe","Layout","Server","Search","Settings","Zap","Shield","Star","Layers","Bug","Box","Book","MessageSquare","Image","Music","Video","Map","Mail","Camera","Heart","Anchor","Rocket","Target","Flag","Bookmark","Briefcase","Puzzle","SquareUserRound","Users","User","Unplug","Clock","Lock","Pencil","TrafficCone","CircleDollarSign","Activity","Wrench","Microscope","Palette","Webhook","FlaskConical","Bot","Cloud","Kanban","Infinity","Monitor","Smartphone","History","Brain","Calendar","Play","Pause","Sparkles","Check","Ban","Circle","CheckCircle","Wind","Github","Square","SquareCheck","CheckSquare","Package","AlertCircle","Lightbulb","ScanSearch","Inbox","HelpCircle","Gauge","FileCode","ArrowDown","Minus","ArrowUp","AlertTriangle","CircleQuestionMark","TriangleAlert"],Ni=Gf.reduce((e,n)=>(e[n]=$s[n]||xi,e),{}),yM=Gf,du=Object.fromEntries(Hf().flatMap(e=>e.types).filter(e=>e.icon&&e.color).reduce((e,n)=>(e.some(([s])=>s===n.value)||e.push([n.value,{icon:n.icon,color:n.color}]),e),[])),nS={PDF:"red-500",DOC:"blue-500",DOCX:"blue-500",CSV:"teal-500",JSON:"amber-500",TXT:"violet-200",MD:"violet-200"},Rm={"red-200":"#eb7a7a","orange-200":"#eba87a","amber-200":"#ebc17a","yellow-200":"#ebd07a","green-200":"#7aeba4","teal-200":"#7aebdf","sky-200":"#7ac8eb","blue-200":"#7aa5eb","indigo-200":"#7a7ceb","violet-200":"#9c7aeb","red-500":"#e42525","orange-500":"#e47325","amber-500":"#e49d25","yellow-500":"#e4b625","green-500":"#25e46b","teal-500":"#25e4cf","sky-500":"#25a9e4","blue-500":"#256ee4","indigo-500":"#2529e4","violet-500":"#5f25e4","red-700":"#951818","orange-700":"#954b18","amber-700":"#956718","yellow-700":"#957718","green-700":"#189546","teal-700":"#189587","sky-700":"#186e95","blue-700":"#184895","indigo-700":"#181b95","violet-700":"#3e1895"},kM=["red-200","orange-200","amber-200","yellow-200","green-200","teal-200","sky-200","blue-200","indigo-200","violet-200","red-500","orange-500","amber-500","yellow-500","green-500","teal-500","sky-500","blue-500","indigo-500","violet-500","red-700","orange-700","amber-700","yellow-700","green-700","teal-700","sky-700","blue-700","indigo-700","violet-700"];function _a(e){if(e)return Rm[e]?Rm[e]:e}function aS(e){const n=String(e||"").trim().toLowerCase();return _a(du[n]?.color)||_a("violet-200")||"#9c7aeb"}function SM(e){switch(Number(e)){case 1:return"var(--text-muted)";case 2:return"var(--text-secondary)";case 3:return"var(--priority-high)";case 4:return"var(--priority-critical)";default:return"var(--text-secondary)"}}function sS(e){const n=String(e||"").trim().toUpperCase();return _a(nS[n])||"var(--text-muted)"}function rS(e,n){const s=e.taxonomies?.[n];return s==null||s===""?!1:Array.isArray(s)?s.some(r=>String(r).trim().length>0):String(s).trim().length>0}function Gl(e,n){const s=e.filter(o=>o.status!=="retired"),r=e.filter(o=>o.status==="retired"&&n.some(l=>rS(l,o.id)));return[...s,...r.filter(o=>!s.some(l=>l.id===o.id))]}function Vf(e,n=[]){return Gl(e,n).filter(s=>s.sortEnabled===!0).map(s=>({value:`taxonomy:${s.id}`,label:s.status==="retired"?`${s.label} (Retired)`:s.label}))}function Dm(e,n){const s=e.taxonomies?.[n.id];if(s==null||s==="")return null;const r=Array.isArray(s)?s.map(o=>String(o)):[String(s)];for(let o=0;o<n.options.length;o+=1)if(r.includes(String(n.options[o]?.value)))return o;return null}function ki(e,n){return new Date(n.createdAt).getTime()-new Date(e.createdAt).getTime()}function uu(e,n,s,r,o=[]){let l=0;if(s==="created")return l=ki(e,n),r==="desc"?l:-l;if(s==="updated"){const c=e.updatedAt||e.createdAt,p=n.updatedAt||n.createdAt;return l=new Date(p).getTime()-new Date(c).getTime(),r==="desc"?l:-l}if(s==="priority"){const c=ou(e.priority),p=ou(n.priority);return l=c!==p?p-c:ki(e,n),r==="desc"?l:-l}if(s==="complexity"){const c=typeof e.complexity=="number"?e.complexity:3,p=typeof n.complexity=="number"?n.complexity:3;return l=c!==p?p-c:ki(e,n),r==="desc"?l:-l}if(s.startsWith("taxonomy:")){const c=s.slice(9),p=o.find(C=>C.id===c);if(!p)return l=ki(e,n),r==="desc"?l:-l;const g=Dm(e,p),w=Dm(n,p);return g===null&&w===null?ki(e,n):g===null?1:w===null?-1:g!==w?r==="desc"?w-g:g-w:ki(e,n)}return l=ki(e,n),r==="desc"?l:-l}function oS(e,n,s){const r=e.taxonomies?.[n];return r==null||r===""?!1:Array.isArray(r)?r.some(o=>String(o)===String(s)):String(r)===String(s)}function Gp(e,n){const s=e.options.filter(o=>o.status!=="retired"),r=e.options.filter(o=>o.status==="retired"&&n.some(l=>oS(l,e.id,o.value)));return[...s,...r.filter(o=>!s.some(l=>String(l.value)===String(o.value)))]}function iS({tasks:e,archivedTasks:n,activeCategories:s,activeTypes:r,priorities:o,taxonomies:l,configLoaded:c,referenceDataLoaded:p,assigneeOptionsLoaded:g,assigneeOptions:w}){const C=a.useMemo(()=>Pf(w),[w]),_=a.useMemo(()=>Gl(l,[...e,...n]).filter(O=>O.filterEnabled!==!1).map(O=>({...O,options:Gp(O,[...e,...n])})),[n,e,l]),y=a.useMemo(()=>C.map(O=>O.value),[C]),[k,b]=a.useState(""),[E,S]=a.useState([]),[W,Q]=a.useState([]),[z,K]=a.useState([]),[V,ne]=a.useState(!1),[D,Ae]=a.useState(no.map(O=>O.value)),[U,ee]=a.useState(y),[be,me]=a.useState(!0),[Y,R]=a.useState({}),[B,fe]=a.useState("created"),[Ne,de]=a.useState("desc"),ae=a.useCallback(()=>{de(O=>O==="asc"?"desc":"asc")},[]),[Ve,Re]=a.useState("category"),[Ce,Fe]=a.useState("show"),[x,L]=a.useState({}),P=a.useCallback((O,ue)=>ue.length===0?!0:ue.every(re=>O.includes(re)),[]),Z=a.useCallback((O,ue)=>O.length===ue.length&&O.every((re,pe)=>re===ue[pe]),[]);a.useEffect(()=>{Ve==="approach"&&Re("status")},[Ve]),a.useEffect(()=>{if(!(!c||!p)&&g&&!V&&s.length>0&&r.length>0&&o.length>0){S(s.map(ue=>ue.value)),Q(o.map(ue=>ue.value)),K(r.map(ue=>ue.value)),ee(y),me(!0);const O={};_.forEach(ue=>{O[ue.id]=ue.options.map(re=>re.value)}),R(O),ne(!0)}},[c,p,g,s,r,o,_,V,y]),a.useEffect(()=>{if(!V||!g)return;const O=new Set(y),ue=U.filter(G=>O.has(G)),re=be?y:ue.length>0||U.length===0?ue:y;(re.length!==U.length||re.some((G,q)=>G!==U[q]))&&ee(re)},[y,U,be,V,g]),a.useEffect(()=>{if(!V||!g)return;const O=U.filter(re=>y.includes(re)),ue=y.length>0&&y.every(re=>O.includes(re));ue!==be&&me(ue)},[y,U,be,V,g]),a.useEffect(()=>{if(!c||!p||!V||s.length===0)return;const O=ty(E,s);(O.length!==E.length||O.some((re,pe)=>re!==E[pe]))&&S(O)},[c,p,s,V,E]),a.useEffect(()=>{if(!c||!p||!V||o.length===0||W.length===0)return;const O=ey(W,o),ue=Array.from(new Set(W.map(pe=>Number(pe)).filter(pe=>Number.isFinite(pe))));(O.length!==ue.length||O.some((pe,G)=>pe!==ue[G]))&&Q(O)},[c,p,V,o,W]),a.useEffect(()=>{if(!c||!p||!V||r.length===0)return;const O=new Set(r.map(pe=>pe.value)),ue=z.filter(pe=>O.has(pe)),re=ue.length>0||z.length===0?ue:r.map(pe=>pe.value);Z(re,z)||K(re)},[r,c,z,V,Z,p]),a.useEffect(()=>{if(!c||!p||!V)return;const O={};_.forEach(q=>{const ye=q.options.map(ze=>ze.value);if(ye.length===0)return;const Be=Array.isArray(Y[q.id])?Y[q.id]:[],le=Be.filter(ze=>ye.includes(ze));O[q.id]=le.length>0||Be.length===0?le:ye});const ue=Object.keys(Y).sort(),re=Object.keys(O).sort(),pe=ue.length!==re.length||ue.some((q,ye)=>q!==re[ye]),G=re.some(q=>!Z(Y[q]||[],O[q]||[]));(pe||G)&&R(O)},[c,Y,_,V,Z,p]);const M=a.useCallback(()=>{b(""),S(s.map(ue=>ue.value)),Q(o.map(ue=>ue.value)),K(r.map(ue=>ue.value)),Ae(no.map(ue=>ue.value)),ee(y),me(!0);const O={};_.forEach(ue=>{O[ue.id]=ue.options.map(re=>re.value)}),R(O),fe("created"),de("desc")},[s,o,r,_,y]),h=a.useCallback(O=>{ee(ue=>{const re=typeof O=="function"?O(ue):O,pe=Array.from(new Set(re.filter(q=>typeof q=="string"&&q.trim().length>0))),G=y.length>0&&y.every(q=>pe.includes(q));return me(G),pe})},[y]),A=a.useMemo(()=>{const O=P(E,s.map(G=>G.value)),ue=P(z,r.map(G=>G.value)),re=P(Array.from(new Set(W.map(G=>Number(G)).filter(G=>Number.isFinite(G)))),o.map(G=>Number(G.value)).filter(G=>Number.isFinite(G))),pe=P(D,no.map(G=>G.value));return e.filter(G=>{const q=Rr(G).toLowerCase(),ye=G.title.toLowerCase().includes(k.toLowerCase())||(G.description?.toLowerCase()||"").includes(k.toLowerCase())||G.id.toLowerCase().includes(k.toLowerCase())||q.includes(k.toLowerCase()),Be=!V||O||E.includes(G.category),le=!V||re||ap(G.priority,W),ze=!V||ue||z.includes(G.type||ms),Ye=!V||pe||D.includes(G.status),Xe=!V||be||U.includes(G.assignee||"unassigned"),bt=Object.entries(Y).every(([d,rt])=>{const mt=_.find(St=>St.id===d);if(!mt)return!0;const F=mt?.options.every(St=>rt.includes(St.value))??!0;if(F)return!0;const Ke=G.taxonomies?.[d];return Ke?Array.isArray(Ke)?Ke.some(St=>rt.includes(St)):rt.includes(Ke):F||rt.includes("")});return ye&&Be&&le&&ze&&Ye&&Xe&&bt}).sort((G,q)=>uu(G,q,B,Ne,l))},[e,n,k,E,W,z,D,U,be,Y,B,Ne,V,_,s,r,o,P,l]),H=a.useMemo(()=>{const O=P(E,s.map(G=>G.value)),ue=P(z,r.map(G=>G.value)),re=P(Array.from(new Set(W.map(G=>Number(G)).filter(G=>Number.isFinite(G)))),o.map(G=>Number(G.value)).filter(G=>Number.isFinite(G))),pe=P(D,no.map(G=>G.value));return e.filter(G=>{const q=!V||O||E.includes(G.category),ye=!V||re||ap(G.priority,W),Be=!V||ue||z.includes(G.type||ms),le=!V||pe||D.includes(G.status),ze=!V||be||U.includes(G.assignee||"unassigned"),Ye=Object.entries(Y).every(([Xe,bt])=>{const d=_.find(F=>F.id===Xe);if(!d)return!0;const rt=d?.options.every(F=>bt.includes(F.value))??!0;if(rt)return!0;const mt=G.taxonomies?.[Xe];return mt?Array.isArray(mt)?mt.some(F=>bt.includes(F)):bt.includes(mt):rt||bt.includes("")});return q&&ye&&Be&&le&&ze&&Ye})},[e,n,E,W,z,D,U,be,Y,V,_,s,r,o,P]),j=a.useMemo(()=>{const O=s.every(pe=>E.includes(pe.value)),ue=P(z,r.map(pe=>pe.value)),re=P(Array.from(new Set(W.map(pe=>Number(pe)).filter(pe=>Number.isFinite(pe)))),o.map(pe=>Number(pe.value)).filter(pe=>Number.isFinite(pe)));return n.filter(pe=>{const G=Rr(pe).toLowerCase(),q=pe.title.toLowerCase().includes(k.toLowerCase())||(pe.description?.toLowerCase()||"").includes(k.toLowerCase())||pe.id.toLowerCase().includes(k.toLowerCase())||G.includes(k.toLowerCase()),ye=!V||O||E.includes(pe.category),Be=!V||re||ap(pe.priority,W),le=!V||ue||z.includes(pe.type||ms),ze=!V||be||U.includes(pe.assignee||"unassigned"),Ye=Object.entries(Y).every(([Xe,bt])=>{const d=_.find(F=>F.id===Xe);if(!d)return!0;const rt=d?.options.every(F=>bt.includes(F.value))??!0;if(rt)return!0;const mt=pe.taxonomies?.[Xe];return mt?Array.isArray(mt)?mt.some(F=>bt.includes(F)):bt.includes(mt):rt||bt.includes("")});return q&&ye&&Be&&le&&ze&&Ye}).sort((pe,G)=>uu(pe,G,B,Ne,l))},[n,k,E,W,z,U,be,Y,B,Ne,V,s,r,o,_,P,l]),je=a.useMemo(()=>{const O={};return A.forEach(ue=>{const re=s.find(G=>G.value===ue.category),pe=re?re.label:ue.category||"General";O[pe]||(O[pe]=[]),O[pe].push(ue)}),O},[A,s]);return{searchQuery:k,setSearchQuery:b,filterCategories:E,setFilterCategories:S,filterPriorities:W,setFilterPriorities:Q,filterTypes:z,setFilterTypes:K,filterStatus:D,setFilterStatus:Ae,filterAssignees:U,setFilterAssignees:h,filterAssigneesAllSelected:be,setFilterAssigneesAllSelected:me,filterTaxonomies:Y,setFilterTaxonomies:R,hasInitedFilters:V,setHasInitedFilters:ne,sortBy:B,setSortBy:fe,sortOrder:Ne,setSortOrder:de,toggleSortOrder:ae,groupBy:Ve,setGroupBy:Re,emptyColumnMode:Ce,setEmptyColumnMode:Fe,collapsedCategories:x,setCollapsedCategories:L,clearFilters:M,filteredTasks:A,searchAgnosticTasks:H,filteredArchive:j,groupedTasks:je}}const cS=iS;function lS(e){const{activeCategories:n,activeTab:s,apiEndpoint:r,approach:o,assignee:l,attachments:c,attachmentsDirty:p,category:g,checklistItems:w,comments:C,complexity:_,description:y,dueDate:k,editingTaskId:b,fetchTasks:E,formTaxonomies:S,getPreferredCategoryValue:W,mergeTaskFromServer:Q,workstreamInput:z,priority:K,pushNotice:V,queueWorkspaceSyncFromAuthoritativeTaskState:ne,relationshipTasks:D,resetForm:Ae,resolveWorkstreamIdInput:U,scheduledDate:ee,setActiveTab:be,setAttachmentsDirty:me,setComments:Y,setError:R,setLastUsedCategory:B,setLoading:fe,setNewCommentText:Ne,status:de,title:ae,taxonomies:Ve,type:Re}=e,[Ce,Fe]=a.useState(null),[x,L]=a.useState("idle"),[P,Z]=a.useState(null),M=a.useRef(null),h=a.useCallback(()=>JSON.stringify({title:ae.trim(),description:y||"",category:typeof g=="string"?g:g.label||W(n),type:typeof Re=="string"?Re:Re.label||ms,priority:Number(K),complexity:Number(_)||3,approach:o||"default",assignee:l||"agent",scheduledDate:ee||"",dueDate:k||"",workstreamInput:z.trim(),checklistItems:w,comments:C,taxonomies:S,attachments:c}),[n,o,l,c,g,w,C,_,y,k,S,W,K,ee,ae,Re,z]),A=a.useCallback(()=>{M.current!==null&&(window.clearTimeout(M.current),M.current=null)},[]),H=a.useCallback(async G=>{const q=G?.quiet??!1,ye=G?.source??"manual";if(!ae.trim())return R("Title is required"),b&&L(ye==="autosave"?"error":"idle"),!1;const Be=Ve.filter(le=>le.isRequired).filter(le=>{const ze=S[le.id];return Array.isArray(ze)?ze.filter(Ye=>String(Ye).trim().length>0).length===0:typeof ze!="string"&&typeof ze!="number"||String(ze).trim().length===0}).map(le=>le.label);if(Be.length>0)return R(`Required taxonomy values are missing: ${Be.join(", ")}`),b&&L(ye==="autosave"?"error":"idle"),!1;if(b&&D.find(ze=>ze.id===b)?.isArchived)return R("Archived tasks are read-only. Unarchive first to make changes."),L(ye==="autosave"?"error":"idle"),!1;fe(!0),R(""),b&&L("saving");try{const le=b?`/api/taskforce/task/${b}`:r.replace("/api/dev/task","/api/taskforce/task").replace("/api/taskforce/task","/api/taskforce/task"),ze=b?"PATCH":"POST",Ye=typeof g=="string"?g:g.label||W(n),Xe=typeof Re=="string"?Re:Re.label||ms,bt=z.trim()?U(z):null,d={title:ae,description:y||null,category:Ye||W(n),type:Xe,priority:K,complexity:Number(_)||3,status:b?void 0:de,completedAt:b?void 0:de==="done"?new Date().toISOString():null,approach:o||"default",assignee:l||"agent",scheduledDate:ee||null,dueDate:k||null,workstreamId:z.trim()?bt?.id||z.trim():null,checklistItems:w,comments:C,taxonomies:S,...b?{}:{createdAt:new Date().toISOString(),createdBy:"user"}};(!b||p)&&(d.attachments=c),b&&(d.saveSource=ye);const rt=await fetch(le,{method:ze,headers:{"Content-Type":"application/json"},body:JSON.stringify(d)});if(!rt.ok){const Ke=(await rt.json()).message||`Failed to ${b?"update":"save"} task`;return R(Ke),q||V(Ke,"error"),fe(!1),b&&L("error"),!1}const mt=await rt.json().catch(()=>null);return b&&mt&&typeof mt=="object"&&(Q(mt),ne()),B(Ye),me(!1),fe(!1),b&&L("saved"),!0}catch{return R("Failed to connect to server"),q||V("Failed to connect to server","error"),fe(!1),b&&L("error"),!1}},[n,r,o,l,c,p,g,w,C,_,y,k,b,S,W,Q,z,K,V,ne,U,me,R,B,fe,ee,de,ae,Ve,Re]),j=a.useCallback(async()=>{await H({source:"manual"})&&(b||V("Task added successfully","success"),s==="add"&&!b&&(Ae(),be("tasks"),await E()))},[s,b,E,V,Ae,H,be]);a.useEffect(()=>{if(A(),!b){Z(null),L("idle");return}Z(h()),L("idle")},[A,b]);const je=a.useCallback(async()=>{if(A(),!b||P===null)return;const G=h();if(G===P||!ae.trim()||k&&ee&&k<ee)return;await H({quiet:!0,source:"autosave"})&&Z(G)},[h,A,k,b,P,H,ee,ae]);a.useEffect(()=>{if(!b||P===null)return;const G=h();if(G!==P){if(!ae.trim()){L("idle");return}if(k&&ee&&k<ee){L("error");return}return L(q=>q==="error"?"error":"idle"),A(),M.current=window.setTimeout(async()=>{await H({quiet:!0,source:"autosave"})&&Z(G)},700),()=>{A()}}},[h,A,k,b,P,H,ee,ae]);const O=a.useCallback(async G=>{if(G.preventDefault(),k&&ee&&k<ee){Fe({dueDate:k,scheduledDate:ee});return}await j()},[k,j,ee]),ue=a.useCallback(async()=>{Fe(null),await j()},[j]),re=a.useCallback(()=>{Fe(null)},[]),pe=a.useCallback(async G=>{if(!b||!G.trim())return;const q=G.trim();try{const ye=await fetch(`/api/taskforce/task/${b}/comment`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:q,author:"user"})});if(!ye.ok){const ze=(await ye.json().catch(()=>({}))).error||"Failed to add comment.";R(ze),V(ze,"error");return}const Be=await ye.json().catch(()=>null);if(Ne(""),Be&&typeof Be=="object"){const le=ro(Be);Y(le.comments||[]),Q(Be),Z(h()),L("saved")}else await E(!0);ne()}catch(ye){console.error("Failed to add comment",ye),R("Failed to add comment."),V("Failed to add comment.","error")}},[b,E,h,Q,V,ne,Y,R,Ne]);return{autoSaveState:x,flushAutoSave:je,scheduleWarningPrompt:Ce,saveTask:H,handleSubmit:O,confirmScheduleWarning:ue,cancelScheduleWarning:re,handleAddComment:pe}}function dS(e){const{editingTaskId:n,fetchTasks:s,mergeTaskFromServer:r,workstreamInput:o,pushNotice:l,queueWorkspaceSyncFromAuthoritativeTaskState:c,relationshipTasks:p,resolveWorkstreamIdInput:g,setError:w}=e;return{handleSetWorkstreamForCurrentTask:a.useCallback(async _=>{if(!n)return;const y=p.find(S=>S.id===n);if(!y)return;const k=typeof _=="string"?_.trim():_===null?"":o.trim(),b=k?g(k):null,E=k.length>0?b?.id||k:null;if((y.workstreamId||null)===E){l(E?"Task already belongs to that workstream.":"Task is already standalone.","info");return}try{const S=await fetch(`/api/taskforce/task/${n}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({workstreamId:E})});if(!S.ok){const z=(await S.json().catch(()=>({}))).error||"Failed to set workstream.";w(z),l(z,"error");return}w(""),l(E?"Workstream set":"Workstream removed","info");const W=await S.json().catch(()=>null);W?(r(W),c()):(await s(!0),c())}catch{w("Failed to set workstream."),l("Failed to set workstream.","error")}},[n,s,r,o,l,c,p,g,w])}}function uS({tasks:e,archivedTasks:n,editingTaskId:s,setTasks:r,setArchivedTasks:o,setDeletedTasks:l,setError:c,resetForm:p,setActiveTab:g,fetchTasks:w,fetchArchive:C,fetchDeletedTasks:_,mergeTaskFromServer:y,pushNotice:k,cloudAuthConfigured:b,runtimeMode:E,isAuthenticated:S,workspaceCloudSyncEnabled:W,buildWorkspaceSyncSignature:Q,pushWorkspaceChangesToCloud:z,workspacePendingSignatureRef:K,workspaceDeletedTaskIdsRef:V}){const[ne,D]=a.useState(null),Ae=a.useRef(null),U=a.useCallback((x=0)=>{b&&E==="local"&&S&&W&&(typeof window>"u"||window.setTimeout(()=>{const L=Q();L&&(K.current=L,z(L))},Math.max(0,x)))},[b,E,S,W,Q,K,z]),ee=a.useCallback(async(x,L)=>{let P=await fetch(`/api/taskforce/deleted${x}`,L);return P.status===404&&(P=await fetch(`/api/taskforce/trash${x}`,L)),P},[]),be=async(x,L=!1,P={})=>{if(!P.skipConfirm&&!confirm("Move this task to Trash? You can restore it later."))return!1;const Z=L||n.some(M=>M.id===x);try{const M=await fetch(`/api/taskforce/task/${x}`,{method:"DELETE"});if(!M.ok){const j=(await M.json().catch(()=>({}))).error||"Failed to delete task.";return c(j),k(j,"error"),!1}const h=await M.json().catch(()=>({})),A=h?.deleted&&typeof h.deleted=="object"&&h.deleted.taskSnapshot?{...h.deleted,taskSnapshot:ro(h.deleted.taskSnapshot)}:null;if(window.location.search.includes(x)){const H=new URL(window.location.href);H.searchParams.delete("task"),window.history.pushState({},"",H.toString())}if(Z?o(H=>H.filter(j=>j.id!==x)):r(H=>H.filter(j=>j.id!==x)),A?l(H=>[A,...H.filter(j=>j.taskId!==x)]):await _(!0),V.current.add(x),b&&E==="local"&&S&&W){const H=Q();K.current=H,z(H)}return s===x&&(p(),g("tasks")),c(""),k("Task moved to Trash.","info"),!0}catch(M){return console.error("Failed to delete task:",M),c("Failed to delete task."),k("Failed to delete task.","error"),!1}},me=a.useCallback(async x=>{try{const L=await ee(`/${x}/restore`,{method:"POST"});if(!L.ok){const M=(await L.json().catch(()=>({}))).error||"Failed to restore deleted task.";return c(M),k(M,"error"),null}const P=await L.json().catch(()=>null);return P?y(P):await w(!0),l(Z=>Z.filter(M=>M.id!==x&&M.taskId!==x)),V.current.delete(x),U(),c(""),k("Task restored from Trash.","info"),P?ro(P):null}catch(L){return console.error("Failed to restore deleted task:",L),c("Failed to restore deleted task."),k("Failed to restore deleted task.","error"),null}},[w,y,k,U,ee,l,c]),Y=a.useCallback(async x=>{try{const L=await ee(`/${x}`,{method:"DELETE"});if(!L.ok){const Z=(await L.json().catch(()=>({}))).error||"Failed to permanently delete deleted task.";return c(Z),k(Z,"error"),!1}return l(P=>P.filter(Z=>Z.id!==x&&Z.taskId!==x)),U(),c(""),k("Deleted task permanently removed.","info"),!0}catch(L){return console.error("Failed to permanently delete deleted task:",L),c("Failed to permanently delete deleted task."),k("Failed to permanently delete deleted task.","error"),!1}},[k,U,ee,l,c]),R=a.useCallback(async()=>{try{const x=await ee("/empty",{method:"POST"});if(!x.ok){const M=(await x.json().catch(()=>({}))).error||"Failed to permanently delete deleted tasks.";return c(M),k(M,"error"),null}const L=await x.json().catch(()=>({})),P=Number(L?.deleted||0);return l([]),U(),c(""),k(P===1?"Deleted task permanently removed.":`${P} deleted tasks permanently removed.`,"info"),P}catch(x){return console.error("Failed to empty deleted tasks:",x),c("Failed to permanently delete deleted tasks."),k("Failed to permanently delete deleted tasks.","error"),null}},[k,U,ee,l,c]),B=a.useCallback(async(x,L)=>{const P=e,Z=n;r(M=>M.map(h=>h.id===x?{...h,...L}:h)),o(M=>M.map(h=>h.id===x?{...h,...L}:h));try{const M=await fetch(`/api/taskforce/task/${x}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(L)});if(!M.ok){const H=(await M.json().catch(()=>({}))).error||`Failed to update task ${x}.`;c(H),k(H,"error"),r(P),o(Z);return}const h=await M.json().catch(()=>null);y(h),U(L.attachments!==void 0?150:0),c("")}catch(M){console.error("Failed to update task",M);const h=`Failed to update task ${x}.`;c(h),k(h,"error"),r(P),o(Z)}},[e,n,k,y,U]);return{copiedId:ne,handleDelete:be,handleUpdateTask:B,handleToggleComplete:async x=>{const L=x.status==="done"?"task":"done";try{const P=L==="done"?new Date().toISOString():void 0,Z=await fetch(`/api/taskforce/task/${x.id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({status:L,completedAt:P})});if(!Z.ok){const A=(await Z.json().catch(()=>({}))).error||"Failed to update task status.";c(A),k(A,"error"),await w(!0);return}const M=await Z.json().catch(()=>null);M?(y(M),U()):(await w(!0),U()),c("")}catch(P){console.error("Failed to toggle complete",P),c("Failed to update task status."),k("Failed to update task status.","error"),w()}},handleToggleCancel:async x=>{const L=x.status==="cancelled"?"task":"cancelled";try{const P=await fetch(`/api/taskforce/task/${x.id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({status:L})});if(!P.ok){const h=(await P.json().catch(()=>({}))).error||"Failed to update task status.";c(h),k(h,"error"),await w(!0);return}const Z=await P.json().catch(()=>null);Z?(y(Z),U()):(await w(!0),U()),c("")}catch(P){console.error("Failed to toggle cancel",P),c("Failed to update task status."),k("Failed to update task status.","error"),w()}},handleToggleInProgress:async x=>{const L=x.status==="in-progress"?"task":"in-progress";r(P=>P.map(Z=>Z.id===x.id?{...Z,status:L}:Z));try{const P=await fetch(`/api/taskforce/task/${x.id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({status:L})});if(!P.ok){await w(!0);return}const Z=await P.json().catch(()=>null);y(Z),U()}catch{w()}},handleToggleReview:async x=>{const L=x.status==="review"?"task":"review";r(P=>P.map(Z=>Z.id===x.id?{...Z,status:L}:Z));try{const P=await fetch(`/api/taskforce/task/${x.id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({status:L})});if(!P.ok){await w(!0);return}const Z=await P.json().catch(()=>null);y(Z),U()}catch{w()}},handleArchiveTask:async x=>{try{const P=x.status==="cancelled"?"cancel":"complete",Z=await fetch(`/api/taskforce/task/${x.id}/${P}`,{method:"POST"});if(Z.ok){const M=await Z.json().catch(()=>null),h=[];if(M&&typeof M=="object"&&h.push(M),h.length>0){for(const H of h)y(H);U()}else C();const A=new Set(h.map(H=>String(H?.id||"").trim()).filter(H=>H.length>0));s&&A.has(s)&&(p(),g("tasks"))}else{const h=(await Z.json().catch(()=>({}))).error||"Failed to archive task.";c(h),k(h,"error")}}catch(L){console.error("Failed to archive",L),c("Failed to archive task."),k("Failed to archive task.","error")}},handleBulkArchive:async()=>{const x=e.filter(L=>L.status==="done"||L.status==="cancelled");if(x.length!==0&&confirm(`Archive ${x.length} completed/cancelled tasks?`))try{const L=await fetch("/api/taskforce/bulk-archive",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({ids:x.map(P=>P.id)})});if(L.ok){const P=await L.json(),Z=Array.isArray(P?.results?.archived)?P.results.archived:[];if(Z.length>0){for(const M of Z)y(M);U()}else r(M=>M.filter(h=>!["done","cancelled"].includes(h.status))),C();k(`${P.archived||x.length} tasks archived`,"info"),c("")}else{const Z=(await L.json().catch(()=>({}))).error||"Failed to bulk archive tasks.";c(Z),k(Z,"error")}}catch(L){console.error("Failed to bulk archive",L),c("Failed to bulk archive tasks."),k("Failed to bulk archive tasks.","error")}},handleUnarchive:async x=>{try{const L=await fetch(`/api/taskforce/task/${x}/unarchive`,{method:"POST"});if(L.ok){const P=await L.json().catch(()=>null);P?(y(P),U()):(o(Z=>Z.filter(M=>M.id!==x)),await w(!0),U()),c(""),k("Task restored from archive.","info")}}catch(L){console.error("Failed to unarchive",L),c("Failed to unarchive task."),k("Failed to unarchive task.","error")}},handleRestoreDeletedTask:me,handlePermanentlyDeleteDeletedTask:Y,handleEmptyDeletedTasks:R,handleCopyId:(x,L)=>{x.stopPropagation(),navigator.clipboard.writeText(L),D(L),Ae.current!==null&&window.clearTimeout(Ae.current),Ae.current=window.setTimeout(()=>{Ae.current=null,D(null)},2e3)},queueWorkspaceSyncFromAuthoritativeTaskState:U}}const pS=uS;function Yd(e){return e==="/api/taskforce/auth/runtime-config"||e==="/api/taskforce/sync/workspace/apply-local"||e==="/api/taskforce/sync/workspace/repair-startup"}function mS(e){try{return typeof window>"u"?null:typeof e=="string"?new URL(e,window.location.origin):e instanceof URL?e:typeof Request<"u"&&e instanceof Request?new URL(e.url,window.location.origin):null}catch{return null}}function fS({currentWorkspaceIdRef:e,resolveApiUrl:n,runtimeMode:s}){a.useEffect(()=>{if(typeof window>"u"||typeof window.fetch!="function")return;const r=window.fetch.bind(window),o=l=>{if(typeof l=="string")return s!=="cloud"?l:l.startsWith("/api/taskforce")&&!Yd(l)?n(l):l;if(l instanceof URL)return s!=="cloud"?l:l.origin===window.location.origin&&l.pathname.startsWith("/api/taskforce")?Yd(l.pathname)?l:new URL(n(`${l.pathname}${l.search}${l.hash}`)):l;if(typeof Request<"u"&&l instanceof Request){if(s!=="cloud")return l;const c=new URL(l.url,window.location.origin);if(c.origin===window.location.origin&&c.pathname.startsWith("/api/taskforce"))return Yd(c.pathname)?l:n(`${c.pathname}${c.search}${c.hash}`)}return l};return window.fetch=((l,c)=>{const p=o(l),g=mS(p);if(!!!(g&&g.pathname.startsWith("/api/taskforce")&&!Yd(g.pathname)))return r(p,c);const C=String(e.current||"").trim();if(typeof Request<"u"&&p instanceof Request){const y=new Headers(p.headers);c?.headers&&new Headers(c.headers).forEach((E,S)=>y.set(S,E)),C&&C!=="default"&&!y.has("x-taskforce-workspace-id")&&(y.set("x-taskforce-workspace-id",C),y.set("x-taskforce-workspace-authoritative","1"));const k=new Request(p,{...c,headers:y});return r(k)}const _=new Headers(c?.headers);return C&&C!=="default"&&!_.has("x-taskforce-workspace-id")&&(_.set("x-taskforce-workspace-id",C),_.set("x-taskforce-workspace-authoritative","1")),r(p,{...c,headers:_})}),()=>{window.fetch=r}},[e,n,s])}function hS(e){const n=e.runtimeMode==="cloud",s=!!(e.shouldGateProtectedApiCalls&&n&&!e.authSessionResolved),r=!!(e.shouldGateProtectedApiCalls&&n&&e.authSessionResolved&&e.authRequiredForApi&&!e.isAuthenticated);return{shouldDeferProtectedApiCalls:s,shouldBlockProtectedApiCalls:r,canCallProtectedApi:!(s||r)}}function gS(e){return!!(!e.isOpen||!e.canCallProtectedApi||e.authBlocked||e.authRequiredForApi&&!e.isAuthenticated)}function yS(e){return!!(e.shouldGateProtectedApiCalls&&!e.authSessionResolved||e.authRequiredForApi&&!e.isAuthenticated)}const kS={},eo=Op(kS),lp=(()=>{const e=eo.baseUrl,n=eo.cloudAuthBaseUrl;if(n)return n;const s=eo.apiBaseUrl;return s||e||"https://app.taskforcehq.ai"})(),Si=12e3;function SS({config:e={},initialTaskId:n,onTaskCountChange:s,onClose:r}){const o={...Og,...e},{categories:l,types:c,apiEndpoint:p,apiBaseUrl:g,cloudAuthBaseUrl:w,cloudMcpBaseUrl:C,wsBaseUrl:_,shortcut:y}=o,k=typeof window<"u"?String(window.location.hostname||"").trim().toLowerCase():"",b=k==="localhost"||k==="127.0.0.1"||k==="::1",E=typeof window<"u"&&!b,[S,W]=a.useState({cloudEnvironment:"",cloudBaseUrl:"",cloudMcpBaseUrl:"",baseUrl:"",apiBaseUrl:"",cloudAuthBaseUrl:"",wsBaseUrl:"",cloudAuthViaLocalProxy:!1,authSource:"",workspaceMode:"",workspaceSwitchingEnabled:null}),[Q,z]=a.useState(!1),K=a.useCallback(m=>typeof m=="string"?m.trim().replace(/\/+$/,""):"",[]);a.useEffect(()=>{if(typeof window>"u"){z(!0);return}let m=!1;return(async()=>{try{const T=await fetch("/api/taskforce/auth/runtime-config",{method:"GET",credentials:"include"});if(!T.ok)return;const N=await T.json().catch(()=>({})),$=N?.config&&typeof N.config=="object"?N.config:{};if(m)return;const he=String($.runtimeMode||"").trim().toLowerCase()==="cloud"?"cloud":"local",Oe=String($.workspaceMode||"").trim(),kt=Oe==="single-local"||Oe==="multi-cloud"?Oe:he==="cloud"?"multi-cloud":"single-local";W({cloudEnvironment:typeof $.cloudEnvironment=="string"?String($.cloudEnvironment).trim().toLowerCase():"",cloudBaseUrl:K($.cloudBaseUrl),cloudMcpBaseUrl:K($.cloudMcpBaseUrl),baseUrl:K($.baseUrl),apiBaseUrl:K($.apiBaseUrl),cloudAuthBaseUrl:K($.cloudAuthBaseUrl),wsBaseUrl:K($.wsBaseUrl),cloudAuthViaLocalProxy:!!$.cloudAuthViaLocalProxy,authSource:"cloud",workspaceMode:kt,workspaceSwitchingEnabled:typeof $.workspaceSwitchingEnabled=="boolean"?!!$.workspaceSwitchingEnabled:kt==="multi-cloud"})}catch{}finally{m||z(!0)}})(),()=>{m=!0}},[K]);const V=typeof window>"u"?"":b?lp:"",ne=K(eo.baseUrl),D=K(eo.apiBaseUrl),Ae=K(eo.cloudBaseUrl),U=K(eo.cloudMcpBaseUrl),ee=K(eo.cloudAuthBaseUrl),be=K(eo.wsBaseUrl),me=K(g),Y=K(w),R=K(C),B=me||D||ne,fe=S.apiBaseUrl||S.baseUrl,Ne=B||fe||"",de=Y||ee||ne,ae=S.cloudAuthBaseUrl||S.baseUrl,Re=((b?ae||de:de||ae)||Ne||V).trim().replace(/\/+$/,""),Ce=K(Sy(S.cloudMcpBaseUrl||S.cloudAuthBaseUrl||S.cloudBaseUrl||R||Y||U||ee||Ae||Re)),Fe=(S.cloudMcpBaseUrl||R||Ce||S.cloudBaseUrl||U||Ae||Re||V).trim().replace(/\/+$/,""),x=!!Re&&!Ne,L=Q&&(!!(Re||Ne)||E),P=L&&!x,Z=!!(Re||Ne||E),M=E?"cloud":"local",h=M==="local"&&b&&Z?Wf():"",A=h.length>0,H=a.useCallback(m=>!m||/^https?:\/\//i.test(m)||!Ne||!m.startsWith("/")?m:`${Ne}${m}`,[Ne]),j=a.useCallback(m=>{if(!m||/^https?:\/\//i.test(m)||!m.startsWith("/"))return m;const T=m.startsWith("/api/taskforce/auth/")||m.startsWith("/api/taskforce/sync/")||m.startsWith("/api/taskforce/settings/mcp/");if(!E&&T&&(!Q||S.cloudAuthViaLocalProxy))return m;const N=Re||Ne;if(N){const $=`${N}${m}`;if(typeof window<"u"&&!E&&T)try{if(new URL($,window.location.origin).origin===window.location.origin)return`${lp}${m}`}catch{return`${lp}${m}`}return $}return m},[Q,S.cloudAuthViaLocalProxy,Re,Ne,E]),je=a.useCallback(m=>{const T=String(m||"").trim()||"/taskforce-ws",N=T.startsWith("/")?T:`/${T}`,$=String(_||S.wsBaseUrl||be||Ne||"").trim().replace(/\/+$/,""),te=typeof window<"u"?window.location.origin:"",he=$||te;if(!he)return"";try{const Oe=new URL(N,he);return Oe.protocol==="https:"&&(Oe.protocol="wss:"),Oe.protocol==="http:"&&(Oe.protocol="ws:"),Oe.toString()}catch{return""}},[_,S.wsBaseUrl,be,Ne]),[O,ue]=a.useState("tasks"),[re,pe]=a.useState(!1),[G,q]=a.useState(!1),[ye,Be]=a.useState("open"),[le,ze]=a.useState(bc(o.theme)||ru),[Ye,Xe]=a.useState(bc(o.theme)||ru),[bt,d]=a.useState(!0),[rt]=a.useState(".taskforce"),mt=!1,[F,Ke]=a.useState(!1),[St,Lt]=a.useState([]),[xt,Zt]=a.useState([]),[Jt,on]=a.useState(""),[cn,nn]=a.useState(null),[gn,yn]=a.useState(null),[an,kn]=a.useState(""),[Xt,Gn]=a.useState(""),At=a.useMemo(()=>dy({projectRoot:an,runtimeMode:M}),[an,M]),[Se,Mt]=a.useState(""),[Qt,zt]=a.useState(""),[Ge,An]=a.useState(()=>M),J=fy(Ge),_e=S.workspaceMode==="single-local"||S.workspaceMode==="multi-cloud"?S.workspaceMode:J.workspaceMode,we=typeof S.workspaceSwitchingEnabled=="boolean"?S.workspaceSwitchingEnabled:J.workspaceSwitchingEnabled,[Ie,We]=a.useState(!1),[Qe,ot]=a.useState(!1),[et,_t]=a.useState(A),[vt,Ot]=a.useState(A?h:"anonymous"),[it,It]=a.useState(""),[wt,_n]=a.useState(""),[Dn,Jn]=a.useState(""),[ht,gt]=a.useState(""),[Xn,se]=a.useState(!0),[He,Ee]=a.useState(null),[De,Me]=a.useState(()=>{if(M==="local")return"default";const m=qd(At);return m&&m.toLowerCase()!=="default"?m:"default"}),tt=a.useMemo(()=>uy({projectRoot:an,runtimeMode:Ge,workspaceId:De}),[an,Ge,De]),[Nn,Et]=a.useState([]),[ya,Pn]=a.useState(()=>wi()),[Cn,Sn]=a.useState(!1),[ln,Kt]=a.useState(A),[yt,qt]=a.useState("idle"),[Ht,sn]=a.useState(null),[ft,Ze]=a.useState(null),Vn=a.useRef(null),pn=a.useRef(0),$t=a.useRef(A),Wt=a.useRef(De),Rt=a.useRef(null),fs=a.useRef(0),[Ds,aa]=a.useState(0),fn=a.useRef(null),sa=a.useRef(null),On=a.useRef(null),$n=a.useRef(null),Ka=a.useRef(null),Wn=a.useRef(null),rn=a.useCallback((m,T)=>{const N=String(m||"").trim();if(!N)return;const $=String(Wt.current||"").trim();$&&$!==N&&(fs.current+=1,aa(fs.current)),Wt.current=N,T?.clearExplicitSelection!==!1&&(Rt.current=null),Me(N)},[]);a.useEffect(()=>{Wt.current=De},[De]);const ra=a.useCallback((m,T)=>{const N=String(m||"").trim();N&&Me($=>{const te=String(Rt.current||"").trim();let he=N;if(te&&te!==N)he=te;else{const Oe=String($||"").trim();T?.preserveNonDefaultDefault&&N==="default"&&Oe&&Oe.toLowerCase()!=="default"&&(he=Oe)}return Wt.current=he,he})},[]),Yt=a.useCallback(()=>({workspaceId:String(Wt.current||"default").trim()||"default",epoch:fs.current}),[]),Fn=a.useCallback(m=>(String(Wt.current||"default").trim()||"default")!==m.workspaceId||fs.current!==m.epoch,[]),jn=a.useCallback(m=>fs.current!==m.epoch,[]),xn=a.useCallback(m=>m instanceof DOMException?m.name==="AbortError":String(m?.name||"").toLowerCase()==="aborterror",[]),fa=a.useCallback(()=>{[fn,sa,On,$n,Ka,Wn].forEach(m=>{m.current?.abort("workspace-transition"),m.current=null}),Js.current=null},[]),nt=a.useMemo(()=>hS({shouldGateProtectedApiCalls:P,runtimeMode:Ge,authSessionResolved:ln,authRequiredForApi:Ie,isAuthenticated:et}),[P,Ge,ln,Ie,et]),vn=nt.shouldDeferProtectedApiCalls,dn=nt.shouldBlockProtectedApiCalls,[za,oa]=a.useState(null),[Ya,Qn]=a.useState(null),[Ta,ka]=a.useState(!1),[Zn,hs]=a.useState("unknown"),[en,Ia]=a.useState(null),[ha,Ca]=a.useState(o.shortcut||"Alt+T"),[Na,Us]=a.useState(o.priorities||[]),[io]=a.useState(kf()),[Oa,oe]=a.useState(""),[lt,Ft]=a.useState(!1),[Tt,Tn]=a.useState(!1),[dt,wn]=a.useState(!0),[ia,ga]=a.useState(()=>iy()),ja=a.useMemo(()=>oy(),[]),[Kn,ea]=a.useState(()=>{try{return(Intl.DateTimeFormat().resolvedOptions().locale||"").toLowerCase().startsWith("en-us")?"sunday":"monday"}catch{return"monday"}}),[rr,Ra]=a.useState(!1),[pa,ca]=a.useState(!0),[Da,Sa]=a.useState(!0),[rs,co]=a.useState(""),[Ri,qs]=a.useState(null);fS({currentWorkspaceIdRef:Wt,resolveApiUrl:H,runtimeMode:Ge});const{availableWorkflows:or,initiativeTemplates:la,fetchWorkflows:da,fetchInitiativeTemplates:Ps,fetchWorkflowTemplate:lo,fetchWorkflowOverrideNames:ir,saveWorkflowTemplateDraft:qe,resetWorkflowTemplateDraft:Gt}=Ok({shouldDeferProtectedApiCalls:vn,shouldBlockProtectedApiCalls:dn}),{zenMode:Pa,setZenModeState:va,toggleZenMode:gs}=$k(),{exportEnvironment:Pr,setExportEnvironment:Wo,availableEnvironments:I,loadAvailableEnvironments:ke,exportWorkflowsPath:$e,setExportWorkflowsPath:Te,exportingResource:X,exportResult:Pe,handleExportWorkflows:Dt}=Bk({storagePath:rt}),[Nt,Ja]=a.useState(!1),[qn,En]=a.useState(null),{uiNotice:os,pushNotice:Es,clearNotice:uo}=Mk(),[Ls,Vl]=a.useState([]),Di=a.useRef(null),[Fo,cr]=a.useState(0),vu=a.useCallback(m=>!m||!an?m:m.startsWith(an)?m.slice(an.length).replace(/^[/\\]+/,""):m,[an]),[ta,Er]=a.useState([]),[is,ys]=a.useState([]),[Lc,ks]=a.useState([]),[zo,lr]=a.useState([]),[Pi,Hs]=a.useState([]),[Zl,Gs]=a.useState(!1),[Ss,Lr]=a.useState(null),[Mc,Bc]=a.useState(!1),[Mr,Oo]=a.useState([]),[Xa,dr]=a.useState(!1),[$o,Uo]=a.useState({}),Ei=a.useRef({authSessionResolved:!1,configLoaded:!1,workspaceBootstrapPending:!1});a.useEffect(()=>{Ei.current={authSessionResolved:ln,configLoaded:Xa,workspaceBootstrapPending:Cn}},[ln,Xa,Cn]);const Yn=a.useCallback(m=>{qt(m),m!=="ready"&&(sn(null),Ze(Date.now()))},[]),$a=a.useCallback(m=>{const T=Ei.current;T.authSessionResolved&&T.configLoaded&&!T.workspaceBootstrapPending||(qt("stalled"),sn(m),Ze(N=>N??Date.now()))},[]),cs=a.useCallback(async(m,T,N=Si,$)=>{const te=new AbortController,he=$?.signal,Oe=Number(N)>0?Number(N):Si,kt=typeof window<"u"?window.setTimeout(()=>te.abort("bootstrap-timeout"),Oe):null,Ut=()=>{te.abort(he?.reason||"external-abort")};he&&(he.aborted?Ut():he.addEventListener("abort",Ut,{once:!0}));try{return await fetch(m,{...T||{},signal:te.signal})}catch(Bt){if(Bt instanceof DOMException?Bt.name==="AbortError":String(Bt?.name||"").toLowerCase()==="aborterror"){const tn=new Error(`Startup checks timed out after ${Oe}ms.`);throw tn.name="BootstrapTimeoutError",tn}throw Bt}finally{he&&he.removeEventListener("abort",Ut),kt!==null&&typeof window<"u"&&window.clearTimeout(kt)}},[]),ur=a.useCallback(m=>String(m?.name||"")==="BootstrapTimeoutError",[]),[Br,Wr]=a.useState([]),[Vs,vs]=a.useState({}),[Rn,pr]=a.useState(o.taxonomies||[]),un=a.useMemo(()=>(Mr.length>0?Mr:l||[]).map(T=>typeof T=="string"?{value:T.toLowerCase().replace(/\s+/g,"-"),label:T}:T).sort((T,N)=>T.label.localeCompare(N.label)),[Mr,l]),Fr=a.useMemo(()=>({categories:un,types:Br,priorities:Na,taxonomies:Rn,displayLabels:Vs}),[un,Br,Na,Rn,Vs]);a.useMemo(()=>un.filter(m=>!m.disabled),[un]);const Ms=a.useCallback(m=>m.find(N=>N.value==="default"||N.value==="general"||N.label==="General"||N.value==="Taskforce"||N.label==="Taskforce")?.value||m[0]?.value||"default",[]),ls=Br.length>0?Br:c,[mr,Bs]=a.useState(!1),[po,Un]=a.useState(""),zr="Authentication required. Sign in to continue.",[fr,hr]=a.useState(!1),[Zs,Ws]=a.useState(!1),Qa=a.useCallback(()=>{ot(Ge==="cloud"),_t(!1),_n(""),Jn(""),gt(""),Un(zr)},[zr,Ge]),{recentlyChangedTaskIds:qo,fetchTasks:gr,fetchArchive:Li,refreshTaskCollections:yr,refreshTaskCollectionsFromInvalidation:Fs,mergeTaskFromServer:ws}=qk({tasks:ta,archivedTasks:is,setTasks:Er,setArchivedTasks:ys,setLoadingTasks:Gs,getCurrentWorkspaceId:()=>Wt.current,workspaceResetKey:`${De}:${Ds}`,shouldDeferProtectedApiCalls:vn,shouldBlockProtectedApiCalls:dn,handleUnauthorized:Qa,authRequiredForApi:Ie});a.useEffect(()=>{Ds!==0&&(fa(),Js.current=null,La.current="",ic.current="",ri.current="",xo.current="",oi.current="",cc.current="",al(!1),hr(!1),Pn(wi()),Ws(!1),Hs([]),Er([]),ys([]),ks([]),lr([]),Gs(!1),_s.current!==null&&typeof window<"u"&&(window.clearTimeout(_s.current),_s.current=null),Ga.current!==null&&typeof window<"u"&&(window.clearTimeout(Ga.current),Ga.current=null))},[fa,ys,Gs,Er,Ds]);const Ua=a.useCallback(async(m=!1,T)=>{if(!(T?.ignoreAuthGuard===!0)&&(vn||dn))return;m||Gs(!0);const $=Yt(),te=new AbortController;Ka.current=te;try{let he=await fetch("/api/taskforce/deleted",{signal:te.signal});if(he.status===404&&(he=await fetch("/api/taskforce/trash",{signal:te.signal})),he.status===401){Qa(),Hs([]);return}if(he.status===404){Hs([]);return}if(he.ok){const Oe=await he.json();if(Fn($))return;const kt=Array.isArray(Oe?.deleted)?Oe.deleted.map(Ut=>{const Bt=Ut?.taskSnapshot&&typeof Ut.taskSnapshot=="object"?ro(Ut.taskSnapshot):null;return Bt?{...Ut,taskSnapshot:Bt}:null}).filter(Ut=>!!Ut):[];Hs(kt)}}catch(he){if(xn(he))return;console.error("[Taskforce] Failed to fetch deleted tasks:",he)}finally{Ka.current===te&&(Ka.current=null),m||Gs(!1)}},[Yt,Qa,xn,Fn,vn,dn]),bn=a.useCallback(async m=>{if(!(m?.ignoreAuthGuard===!0)&&(vn||dn))return;const N=Yt(),$=new AbortController;Wn.current=$;try{const[te,he]=await Promise.all([fetch("/api/taskforce/initiatives",{signal:$.signal}),fetch("/api/taskforce/workstreams",{signal:$.signal})]);if(te.status===401||he.status===401){Qa(),ks([]),lr([]);return}const[Oe,kt]=await Promise.all([te.ok?te.json().catch(()=>[]):[],he.ok?he.json().catch(()=>[]):[]]);if(Fn(N))return;ks(Array.isArray(Oe)?Oe.filter(Ut=>!!(Ut&&typeof Ut=="object"&&typeof Ut.id=="string")):[]),lr(Array.isArray(kt)?kt.filter(Ut=>!!(Ut&&typeof Ut=="object"&&typeof Ut.id=="string")):[])}catch(te){if(xn(te))return;console.error("[Taskforce] Failed to fetch planning entities:",te)}finally{Wn.current===$&&(Wn.current=null)}},[Yt,Qa,xn,Fn,vn,dn]),In=a.useCallback(async(m=!1,T)=>{await gr(m,T)},[gr]),es=a.useCallback(async(m=!1,T)=>{await Li(m,T)},[Li]),Mi=a.useCallback(async m=>{const T=m?.isSilent!==!1,N=m?.ignoreAuthGuard===!0;await Promise.all([yr({isSilent:T,ignoreAuthGuard:N}),Ua(T,{ignoreAuthGuard:N}),bn({ignoreAuthGuard:N})])},[Ua,bn,yr]),Or=a.useCallback(async()=>{await Fs(),await Ua(!0),await bn()},[Ua,bn,Fs]),na=a.useCallback(async m=>{const T=m?.force===!0;if(Yn("auth"),!Q)return $t.current;if(!L)return An("local"),We(!1),_t(!1),Ot("anonymous"),It(""),Tl(null),_n(""),Jn(""),gt(""),wa("disconnected"),Ks(null),se(!0),Et([]),Ee(null),Pn(wi()),ot(!1),Kt(!0),$t.current=!1,pn.current=Date.now(),!1;const N=j("/api/taskforce/auth/session"),$=Date.now();if(!T&&Vn.current)return Vn.current;if(!T&&ln&&$-pn.current<1500)return $t.current;const te=(async()=>{const he=typeof performance<"u"?performance.now():Date.now(),Oe=new AbortController,kt=typeof window<"u"?window.setTimeout(()=>Oe.abort(),8e3):null;try{const Ut=await fetch(N,{method:"GET",credentials:"include",mode:"cors",signal:Oe.signal});if(Ut.status===429)return Kt(!0),$t.current;if(!Ut.ok)return b&&Tl(null),Kt(!0),$t.current=!1,!1;const Bt=await Ut.json(),Pt=!!Bt.authRequiredForApi,tn=!!Bt.authenticated,Va=tn?Bt.betaAccess!==!1:!0,Wa=typeof Bt.workspaceId=="string"&&Bt.workspaceId.trim().length>0?Bt.workspaceId.trim():"",Is=typeof Bt.userId=="string"&&Bt.userId.trim().length>0?Bt.userId.trim():"anonymous",Ir=typeof Bt.email=="string"&&Bt.email.trim().length>0?Bt.email.trim().toLowerCase():"",Ln=typeof Bt.displayName=="string"?Bt.displayName.trim():"",Sc=typeof Bt.avatarUrl=="string"?Bt.avatarUrl.trim():"",Os=Ge==="local",tr=Ge==="local"||x;return We(x||Os?!1:Pt),_t(tn),Ot(tn?Is:"anonymous"),It(tn?Wa:""),b&&Tl(tn?Is:null),_n(tn?Ir:""),Jn(tn?Ln:""),gt(tn?Sc:""),tn&&Un(Cl=>Cl===zr?"":Cl),wa(tn?"idle":"disconnected"),Ks(null),se(Va),tr||ra(Wa||qd(At)||"default"),ot(x||Os?!1:Pt&&!tn),Kt(!0),$t.current=tn,Bn("auth_session_resolved",{authenticated:tn,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-he)}),tn&&Yn("ready"),tn}catch{return b&&Tl(null),Kt(!0),$t.current=!1,Bn("auth_session_failed",{durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-he)}),$a("Unable to verify your session."),$t.current}finally{kt!==null&&typeof window<"u"&&window.clearTimeout(kt),pn.current=Date.now(),Vn.current=null}})();return Vn.current=te,te},[Q,L,ln,j,x,zr,Ge,ra,At,Yn,$a]),{userGlobalSyncStatus:Wc,setUserGlobalSyncStatus:wa,userGlobalSyncError:$r,setUserGlobalSyncError:Ks,workspaceLastPullAt:Ho,workspaceLastPushAt:wu,workspaceLastErrorAt:Kl,workspaceLastErrorMessage:mo,workspaceLastSuccessfulSyncAt:bu,workspaceCloudSyncEnabled:Go,workspaceSyncPhase:Yl,workspaceSyncStatus:Jl,workspaceSyncSummary:Fc,workspaceSyncRecommendedAction:Xl,workspaceSyncBusy:zc,workspaceSyncPendingChanges:fo,workspacePendingSignatureRef:Vo,workspaceDeletedTaskIdsRef:Bi,loadWorkspaceSyncState:ho,applyWorkspaceSyncStateSnapshot:Wi,syncUserGlobalSettings:ds,buildWorkspaceSyncSignature:ma,pushWorkspaceChangesToCloud:Zo,saveWorkspaceCloudSyncSettings:Oc,retryUserGlobalSettingsSync:Ql,retryWorkspaceCloudSync:Fi,resetWorkspaceSyncCursorAndPull:kr,getWorkspaceSyncDiagnostics:zi}=Ek({currentWorkspaceId:De,cloudAuthConfigured:Z,runtimeMode:Ge,authSessionResolved:ln,isAuthenticated:et,authUserId:vt,projectName:Xt,resolveCloudAuthUrl:j,resolveWebSocketUrl:je,realtimeSyncEnabled:Ta,tasks:ta,archivedTasks:is,initiatives:Lc,workstreams:zo,taxonomies:Rn,taxonomyState:fr?Fr:void 0,setupState:za,globalTheme:Ye,locale:ia,globalWeekStartsOn:Kn,themeUseGlobalDefault:bt,setTasks:Er,setArchivedTasks:ys,setAuthBlocked:ot,setIsAuthenticated:_t,checkAuthSession:na,setGlobalTheme:Xe,setCurrentTheme:ze,setSetupState:oa,setLocale:ga,setGlobalWeekStartsOn:ea,fetchPlanningEntities:bn}),Oi=a.useCallback((m=ls)=>m.find(T=>String(T.value||"").trim().length>0)?.value||ms,[ls]),[go,Ys]=a.useState(()=>Ms(un)),[ba,zs]=a.useState(()=>Oi(ls)),[ed,td]=a.useState(2),[qa,$i]=a.useState(3),[Ui,Ko]=a.useState("task"),[$c,Uc]=a.useState("default"),[Ur,qi]=a.useState("unassigned"),[nd,Yo]=a.useState(""),[Jo,Hi]=a.useState(""),[ct,qc]=a.useState(""),[Gi,Xo]=a.useState(""),[Vi,Zi]=a.useState(""),[Ki,ad]=a.useState([]),[Hc,ts]=a.useState([]),[ua,yo]=a.useState(""),[sd,ko]=a.useState({}),_u=a.useRef(null),[Gc,us]=a.useState(!1),[Qo,rd]=a.useState("");a.useEffect(()=>{if(Ss)return;const m=String(ba||"").trim();ls.some(N=>String(N.value||"").trim()===m)||zs(Oi(ls))},[ls,Ss,Oi,ba]);const{searchQuery:Yi,setSearchQuery:ei,filterCategories:Sr,setFilterCategories:So,filterPriorities:Ji,setFilterPriorities:Xi,filterTypes:Vc,setFilterTypes:od,filterStatus:vo,setFilterStatus:bs,filterAssignees:Ea,setFilterAssignees:vr,filterAssigneesAllSelected:wo,setFilterAssigneesAllSelected:Zc,filterTaxonomies:ti,setFilterTaxonomies:Qi,hasInitedFilters:ec,setHasInitedFilters:id,sortBy:tc,setSortBy:Kc,sortOrder:nc,setSortOrder:wr,toggleSortOrder:cd,groupBy:ni,setGroupBy:Yc,emptyColumnMode:Jc,setEmptyColumnMode:ac,collapsedCategories:Ha,setCollapsedCategories:ld,clearFilters:dd,filteredTasks:ud,searchAgnosticTasks:Xc,filteredArchive:pd,groupedTasks:Qc}=cS({tasks:ta,archivedTasks:is,activeCategories:un,activeTypes:ls,priorities:Na,taxonomies:Rn,configLoaded:Xa,referenceDataLoaded:fr,assigneeOptionsLoaded:Zs,assigneeOptions:ya}),[ai,bo]=a.useState("tasks"),[md,fd]=a.useState(!1),[el,Cu]=a.useState(!1),[tl,nl]=a.useState(!1),[sc,hd]=a.useState([]),[_o,rc]=a.useState(!1),br=a.useRef(null),_s=a.useRef(null),Ga=a.useRef(null),gd=a.useRef(!1),oc=a.useRef(ln),yd=a.useRef(Ie),Co=a.useRef(et),si=a.useRef(!1),La=a.useRef(""),ic=a.useRef(""),ri=a.useRef(""),xo=a.useRef(""),oi=a.useRef(""),cc=a.useRef(""),lc=a.useRef(!1),Js=a.useRef(null),Xs=a.useRef(!1),[ii,al]=a.useState(!1),{handleSaveSettings:dc,handleSaveTheme:xu,handleSaveGlobalTheme:Au,handleJsonBackupEnabledChange:kd,handleSaveGlobalJsonBackupEnabled:Tu,handleSaveGlobalWeekStartsOn:sl,handleSaveLocale:qr,handleManualComplexityEnabledChange:Iu,handleChecklistDropdownEnabledChange:Nu,handleShowTaskCardStatusLabelChange:Sd,handleResetProjectToGlobal:ju}=Fk({keyShortcut:ha,themeUseGlobalDefault:bt,runtimeMode:Ge,jsonBackupUseGlobalDefault:dt,globalTheme:Ye,globalJsonBackupEnabled:Tt,setCurrentTheme:ze,setThemeUseGlobalDefault:d,setGlobalTheme:Xe,setJsonBackupEnabled:Ft,setJsonBackupUseGlobalDefault:wn,setGlobalJsonBackupEnabled:Tn,setGlobalWeekStartsOn:ea,setLocale:ga,setManualComplexityEnabled:Ra,setChecklistDropdownEnabled:ca,setShowTaskCardStatusLabel:Sa,setShowChecklist:us});a.useEffect(()=>{Ge==="cloud"&&At!==Mo&&Py(De,At)},[Ge,De,At]),a.useEffect(()=>{oc.current=ln,yd.current=Ie,Co.current=et},[ln,Ie,et]);const rl=a.useCallback(m=>{if(!m)return;const T=Array.isArray(m.filterCategories)||Array.isArray(m.filterPriorities)||Array.isArray(m.filterTypes)||Array.isArray(m.filterStatus)||Array.isArray(m.filterAssignees)||typeof m.filterAssigneesAllSelected=="boolean"||m.filterTaxonomies&&typeof m.filterTaxonomies=="object";typeof m.activeWorkspaceModule=="string"?bo(m.activeWorkspaceModule):m.groupBy==="docs"&&bo("docs"),m.groupBy&&m.groupBy!=="docs"&&Yc(m.groupBy),(m.emptyColumnMode==="show"||m.emptyColumnMode==="collapse"||m.emptyColumnMode==="hide")&&ac(m.emptyColumnMode),typeof m.zenMode=="boolean"&&va(m.zenMode),typeof m.searchQuery=="string"&&ei(m.searchQuery),Array.isArray(m.filterCategories)&&So(m.filterCategories),Array.isArray(m.filterPriorities)&&Xi(m.filterPriorities),Array.isArray(m.filterTypes)&&od(m.filterTypes),Array.isArray(m.filterStatus)&&bs(m.filterStatus),Array.isArray(m.filterAssignees)&&vr(m.filterAssignees),typeof m.filterAssigneesAllSelected=="boolean"&&Zc(m.filterAssigneesAllSelected),m.filterTaxonomies&&typeof m.filterTaxonomies=="object"&&Qi(m.filterTaxonomies),(m.sortBy==="created"||m.sortBy==="priority"||m.sortBy==="updated"||m.sortBy==="complexity")&&Kc(m.sortBy),(m.sortOrder==="asc"||m.sortOrder==="desc")&&wr(m.sortOrder),typeof m.hasInitedFilters=="boolean"?id(m.hasInitedFilters):T&&id(!0),typeof m.showChecklist=="boolean"&&us(m.showChecklist),typeof m.lastCategory=="string"&&rd(m.lastCategory),typeof m.exportEnvironment=="string"&&m.exportEnvironment.trim().length>0&&Wo(m.exportEnvironment.trim())},[]),ci=a.useCallback(async m=>{const T=String(m||Wt.current||De||"default").trim()||"default",N=`${Ge}:${tt}:${T}`;try{const $=await fetch(`/api/taskforce/ui-state?key=app&workspaceId=${encodeURIComponent(T)}`,{method:"GET",credentials:"include"}),te=$.ok?await $.json().catch(()=>({})):{},he=te?.state&&typeof te.state=="object"?te.state:null,Oe=Sm(tt),kt=he||Oe?{...Oe||{},...he||{}}:null;if(Wt.current!==T)return;rl(kt),La.current=N}catch{const $=Sm(tt);Wt.current===T&&(rl($),La.current=N)}finally{if(Wt.current!==T)return;lc.current=!0,al(!0)}},[rl,De,Ge,tt]);a.useEffect(()=>{const m=`${Ge}:${tt}:${De}`;si.current&&La.current!==m&&(al(!1),ci(De))},[De,ci,Ge,tt]),a.useEffect(()=>{if(!ii)return;if(lc.current){lc.current=!1;return}const m={groupBy:ni,activeWorkspaceModule:ai,emptyColumnMode:Jc,zenMode:Pa,searchQuery:Yi,filterCategories:Sr,filterPriorities:Ji,filterTypes:Vc,filterStatus:vo,filterAssignees:Ea,filterAssigneesAllSelected:wo,filterTaxonomies:ti,sortBy:tc,sortOrder:nc,hasInitedFilters:ec,showChecklist:Gc,lastCategory:Qo||"",exportEnvironment:Pr};Ey(m,tt);const T=window.setTimeout(async()=>{try{await fetch("/api/taskforce/ui-state",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({stateKey:"app",workspaceId:Wt.current,patch:m})})}catch{}},250);return()=>window.clearTimeout(T)},[ii,ni,ai,Jc,Pa,Yi,Sr,Ji,Vc,vo,Ea,wo,ti,tc,nc,ec,Gc,Qo,Pr,tt]);const vd=a.useCallback(m=>{const T=m.runtimeMode==="cloud"?"cloud":"local",N=!!m.authRequiredForApi,$=typeof m.userId=="string"&&m.userId.trim().length>0?m.userId.trim():"anonymous",te=T==="cloud"&&$!=="anonymous";if(An(T),We(N),te&&(_t(!0),Ot($),ot(!1),ln||Kt(!0)),typeof m.workspaceId=="string"&&m.workspaceId.trim().length>0){const tn=m.workspaceId.trim();T==="local"?rn(tn):ra(tn,{preserveNonDefaultDefault:!0})}ot(T==="cloud"&&N?!(te||et):!1),m.setupState&&typeof m.setupState=="object"?oa(m.setupState):oa(null),m.runtimeCapabilities&&typeof m.runtimeCapabilities=="object"?Qn(m.runtimeCapabilities):Qn(null),ka(!!m.realtimeSyncEnabled);const he=String(m.realtimeSyncFlagSource||"").trim().toLowerCase();hs(he==="env"||he==="settings"||he==="default"?he:"unknown"),typeof m.shortcut=="string"&&m.shortcut.trim().length>0&&Ca(m.shortcut);const Oe=bc(m.theme);Oe&&ze(Oe);const kt=bc(m.globalTheme);kt&&Xe(kt),typeof m.themeUseGlobalDefault=="boolean"&&d(m.themeUseGlobalDefault);const Ut=m.runtimeMode==="cloud"?"cloud":"local";typeof m.projectRoot=="string"?kn(m.projectRoot):Ut==="cloud"&&kn(""),typeof m.tenantId=="string"?zt(m.tenantId.trim()):Ut==="cloud"&&zt("");const Bt=Ut==="cloud"?String(m.projectName||"").trim():m.projectName||m.paths?.projectName||"";(String(Bt||"").trim().length>0||Ut==="cloud")&&Gn(Bt),typeof m.mcpScript=="string"?Mt(m.mcpScript):Ut==="cloud"&&Mt(""),typeof m.hostRoot=="string"?co(m.hostRoot):Ut==="cloud"&&co(""),typeof m.jsonBackupEnabled=="boolean"&&Ft(m.jsonBackupEnabled),typeof m.globalJsonBackupEnabled=="boolean"&&Tn(m.globalJsonBackupEnabled),typeof m.jsonBackupUseGlobalDefault=="boolean"&&wn(m.jsonBackupUseGlobalDefault);const Pt=m?.schedulePreferences?.weekStartsOn;(Pt==="sunday"||Pt==="monday")&&ea(Pt),typeof m.manualComplexityEnabled=="boolean"&&Ra(m.manualComplexityEnabled),typeof m.checklistDropdownEnabled=="boolean"?ca(m.checklistDropdownEnabled):ca(!0),typeof m.showTaskCardStatusLabel=="boolean"?Sa(m.showTaskCardStatusLabel):Sa(!0)},[ra,ln,rn,et]),wd=a.useCallback(async()=>{const m=typeof performance<"u"?performance.now():Date.now();try{const T=await cs("/api/taskforce/version",void 0,Si);if(!T.ok)return;const N=await T.json().catch(()=>({}));N?.build&&typeof N.build=="object"&&Ia({version:String(N.build.version||""),gitSha:N.build.gitSha?String(N.build.gitSha):null,buildTime:N.build.buildTime?String(N.build.buildTime):null,deployId:N.build.deployId?String(N.build.deployId):null}),Bn("build_info_loaded",{durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-m)})}catch(T){ur(T)&&$a("Startup checks timed out.")}},[cs,ur,$a]),Hr=a.useCallback(async m=>{const T=m?.ignoreAuthGuard===!0,N=m?.force===!0;if(!T&&(vn||dn))return;const $=Yt();if(!N&&Js.current?.workspaceId===$.workspaceId){await Js.current.promise;return}hr(!1);const te=new AbortController;sa.current=te;const he=(async()=>{const Oe=typeof performance<"u"?performance.now():Date.now();await Promise.allSettled([(async()=>{const kt=await fetch("/api/taskforce/taxonomy-state",{signal:te.signal});if(!kt.ok)return;const Ut=await kt.json().catch(()=>({}));if(!hy(Ut)){const[tn,Va,Wa,Is]=await Promise.all([fetch("/api/taskforce/categories",{signal:te.signal}),fetch("/api/taskforce/types",{signal:te.signal}),fetch("/api/taskforce/priorities",{signal:te.signal}),fetch("/api/taskforce/taxonomies",{signal:te.signal})]),[Ir,Ln,Sc,Os]=await Promise.all([tn.ok?tn.json().catch(()=>({})):Promise.resolve({}),Va.ok?Va.json().catch(()=>({})):Promise.resolve({}),Wa.ok?Wa.json().catch(()=>({})):Promise.resolve({}),Is.ok?Is.json().catch(()=>({})):Promise.resolve({})]);Ut.categories=Ir.categories,Ut.types=Ln.types,Ut.priorities=Sc.priorities,Ut.taxonomies=Os.taxonomies}const Pt=gy(Ut);Fn($)||(Pt.categories.length>0&&Oo(Pt.categories),Pt.types.length>0&&Wr(Pt.types),Pt.priorities.length>0&&Us(Pt.priorities),pr(Pt.taxonomies),vs(Pt.displayLabels||{}))})(),(async()=>{await da()})(),(async()=>{await Ps()})(),(async()=>{await ke()})()]),!Fn($)&&(hr(!0),Bn("reference_data_loaded",{durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-Oe)}))})();Js.current={workspaceId:$.workspaceId,promise:he};try{await he}catch(Oe){if(!xn(Oe))throw Oe}finally{Js.current?.promise===he&&(Js.current=null),sa.current===te&&(sa.current=null)}},[da,Ps,Yt,xn,Fn,ke,vn,dn]),Cs=a.useCallback(async m=>{if(!(m?.ignoreAuthGuard===!0)&&(vn||dn))return;Yn("config");const N=Yt(),$=new AbortController;fn.current=$;const te=typeof performance<"u"?performance.now():Date.now();try{const he=await cs("/api/taskforce/config",void 0,Si,{signal:$.signal});if(jn(N))return;if(he.status===401){Qa(),dr(!0);return}let Oe="";if(he.ok){const kt=await he.json();if(jn(N))return;Oe=typeof kt?.workspaceId=="string"&&kt.workspaceId.trim().length>0?kt.workspaceId.trim():"",vd(kt)}if(jn(N)){const kt=String(Wt.current||"default").trim()||"default";if(!Oe||kt!==Oe)return}if(!si.current){const kt=Oe||N.workspaceId;si.current=!0,await ci(kt)}if(jn(N)){const kt=String(Wt.current||"default").trim()||"default";if(!Oe||kt!==Oe)return}dr(!0),Yn("ready"),Bn("bootstrap_config_loaded",{durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-te)}),wd()}catch(he){if(xn(he)||jn(N))return;si.current||(si.current=!0,await ci(N.workspaceId)),ur(he)?$a("Startup checks timed out."):$a("Unable to finish startup checks."),dr(!0)}finally{fn.current===$&&(fn.current=null)}},[vd,wd,cs,Yt,Qa,xn,ur,jn,Fn,ci,Yn,$a,vn,dn]),Hn=a.useCallback(async m=>{await Cs(m),await Hr(m)},[Cs,Hr]),Ao=a.useCallback(async()=>{await na(),await Hn()},[na,Hn]),ns=a.useCallback(async()=>{if(!we)return Et([]),Xs.current=!1,{success:!0,workspaces:[]};const m=Yt(),T=new AbortController;On.current=T;const N=typeof performance<"u"?performance.now():Date.now();try{const $=await cs("/api/taskforce/workspaces",{method:"GET",credentials:"include"},Si,{signal:T.signal});if(jn(m))return{success:!1,error:"Workspace changed while loading workspaces."};if($.status===401)return Et([]),Xs.current=!1,{success:!1,error:"Authentication required."};const te=await $.json().catch(()=>({}));if(jn(m))return{success:!1,error:"Workspace changed while loading workspaces."};if(!$.ok||te?.success===!1)return Et([]),Xs.current=!1,{success:!1,error:te?.error||`Failed to load workspaces (${$.status})`};const he=Array.isArray(te?.workspaces)?te.workspaces:[];return Et(he),Xs.current=!0,Ge!=="local"&&typeof te?.currentWorkspaceId=="string"&&te.currentWorkspaceId.trim().length>0&&ra(te.currentWorkspaceId.trim(),{preserveNonDefaultDefault:!0}),Bn("workspace_list_loaded",{workspaceCount:he.length,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-N)}),{success:!0,workspaces:he}}catch($){return xn($)?{success:!1,error:"Workspace list request aborted."}:(ur($)&&$a("Startup checks timed out."),Et([]),Xs.current=!1,{success:!1,error:"Failed to load workspaces."})}finally{On.current===T&&(On.current=null)}},[ra,cs,Yt,xn,jn,ur,Fn,$a,Ge,we]),To=a.useCallback(async()=>{const m=Yt(),T=new AbortController;$n.current=T,Ws(!1);try{const[N,$]=await Promise.all([cs("/api/taskforce/workspace/assignee-options",{method:"GET",credentials:"include"},Si,{signal:T.signal}),ln&&et?cs("/api/taskforce/auth/workspace-members",{method:"GET",credentials:"include"},Si,{signal:T.signal}).catch(()=>null):Promise.resolve(null)]);if(Fn(m))return{success:!1,error:"Workspace changed while loading assignee options."};if(N.status===401)return Pn(wi()),Ws(!0),{success:!1,error:"Authentication required."};const te=await N.json().catch(()=>({}));if(Fn(m))return{success:!1,error:"Workspace changed while loading assignee options."};if(!N.ok)return Pn(wi()),Ws(!0),{success:!1,error:te?.error||`Failed to load assignee options (${N.status})`};const he=Array.isArray(te?.assignees)?te.assignees:[],Oe=he.map(Pt=>{const tn=String(Pt?.value||"").trim(),Va=String(Pt?.kind||"").trim().toLowerCase();return tn?Va==="agent"||Va==="ai"?{value:tn,label:String(Pt?.label||tn).trim()||tn,icon:String(Pt?.icon||"Bot"),color:String(Pt?.color||"#8b5cf6"),kind:"agent"}:Va==="member"||Va==="human"?{value:tn,label:String(Pt?.label||tn).trim()||tn,icon:String(Pt?.icon||"User"),color:String(Pt?.color||"#22c55e"),kind:"member"}:null:null}).filter(Pt=>!!Pt),kt=he.map(Pt=>({userId:String(Pt?.userId||"").trim(),email:String(Pt?.email||"").trim().toLowerCase(),displayName:typeof Pt?.displayName=="string"?Pt.displayName:null,status:typeof Pt?.status=="string"?Pt.status:null,disabled:Pt?.disabled===!0})).filter(Pt=>Pt.userId&&String(Pt.status||"active").trim().toLowerCase()==="active"&&Pt.disabled!==!0);let Ut=kt;if($?.ok){const Pt=await $.json().catch(()=>({})),tn=Array.isArray(Pt?.users)?Pt.users:[],Va=String(vt||"").trim(),Wa=tn.find(Ln=>String(Ln?.userId||"").trim()===Va),Is=String(Wa?.role||"").trim().toLowerCase();Is==="owner"||Is==="admin"||Is==="member"||Is==="read-only"?Ee(Is):!we&&tn.length===0&&Ee(null);const Ir=tn.map(Ln=>({userId:String(Ln?.userId||"").trim(),email:String(Ln?.email||"").trim().toLowerCase(),displayName:typeof Ln?.displayName=="string"?Ln.displayName:null,status:typeof Ln?.status=="string"?Ln.status:null,disabled:Ln?.disabled===!0})).filter(Ln=>Ln.userId&&String(Ln.status||"active").trim().toLowerCase()==="active"&&Ln.disabled!==!0).map(Ln=>({userId:Ln.userId,email:Ln.email,displayName:Ln.displayName??null}));Ut=Array.from(new Map([...kt,...Ir].map(Ln=>[String(Ln.userId||"").trim(),Ln])).values()).filter(Ln=>String(Ln.userId||"").trim().length>0)}else!we&&!kt.length&&Ee(null);const Bt=Ol([...Oe,...Ty(Ut).filter(Pt=>Pt.kind==="member")]);return Fn(m)?{success:!1,error:"Workspace changed while loading assignee options."}:(Pn(Bt),Ws(!0),{success:!0})}catch(N){return xn(N)?{success:!1,error:"Assignee options request aborted."}:(Fn(m)||(Pn(wi()),Ws(!0)),{success:!1,error:"Failed to load assignee options."})}finally{$n.current===T&&($n.current=null)}},[ln,vt,cs,Yt,xn,et,Fn,we]);a.useEffect(()=>{if(!Xa||Cn)return;const m=`${Ge}:${et?"auth":"guest"}:${De}`;Zs&&ic.current===m||(ic.current=m,To())},[Zs,Xa,De,To,et,Ge,Cn]);const ol=a.useMemo(()=>we?Nn.find(T=>T.id===De)?.role??null:He,[Nn,De,He,we]);a.useEffect(()=>{et||Ee(null)},[et]);const Gr=a.useCallback(async(m,T)=>{if(!we)return{success:!1,error:"Workspace switching is unavailable in local mode.",code:"WORKSPACE_SWITCHING_DISABLED"};const N=String(m||"").trim();if(!N)return{success:!1,error:"workspaceId is required."};try{const $=await fetch("/api/taskforce/session/workspace",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({workspaceId:N})}),te=await $.json().catch(()=>({}));if(!$.ok||te?.success===!1)return{success:!1,error:te?.error||`Failed to switch workspace (${$.status})`,code:te?.code};Rt.current=N,rn(N,{clearExplicitSelection:!1}),fa(),Sn(!0),Yn("workspace");const he=await na({force:!0});return T?.hydrate===!1?await ns():(ri.current=`${Ge}:${N}:${At}`,ic.current=`${Ge}:${he?"auth":"guest"}:${N}`,xo.current=N,re&&O==="tasks"&&(oi.current=`${N}:${O}:${G?"archive":"active"}:${ye}`),re&&O==="settings"&&(cc.current=`${N}:${O}:${gn}`),await Promise.all([Hn(),ns(),Mi({isSilent:!1}),To(),ho()])),Rt.current===N&&(Rt.current=null),{success:!0}}catch{return Rt.current===N&&(Rt.current=null),{success:!1,error:"Failed to switch workspace."}}finally{Sn(!1)}},[fa,O,na,rn,To,Hn,ns,re,ho,Yn,Mi,Ge,gn,G,ye,At,we]),as=a.useCallback(async m=>{Yn("workspace"),Sn(!0);const T=typeof performance<"u"?performance.now():Date.now();try{if(!we){const Bt=String(De||"").trim()||"default";return rn(Bt),Bn("workspace_resolved",{workspaceId:Bt,workspaceSetupRequired:!1,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-T)}),{success:!0,workspaceSetupRequired:!1,workspaceId:Bt}}const N=String(m?.preferredWorkspaceId||"").trim(),$=qd(At),te=await ns();if(!te.success)return{success:!1,workspaceSetupRequired:!1,error:te.error||"Failed to load workspaces after authentication."};const he=Array.isArray(te.workspaces)?te.workspaces:[];if(he.length===0)return rn("default"),Bn("workspace_resolved",{workspaceId:"default",workspaceSetupRequired:!0,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-T)}),{success:!0,workspaceSetupRequired:!0};const Oe=new Set(he.map(Bt=>String(Bt.id||"").trim()).filter(Boolean)),kt=(N&&Oe.has(N)?N:"")||($&&Oe.has($)?$:"")||String(he[0]?.id||"").trim();if(!kt)return rn("default"),{success:!0,workspaceSetupRequired:!0};if(String(Wt.current||"").trim()!==kt){const Bt=await Gr(kt,{hydrate:!1});if(!Bt.success)return{success:!1,workspaceSetupRequired:!1,error:Bt.error||"Failed to set workspace after authentication.",code:Bt.code}}else rn(kt);return Bn("workspace_resolved",{workspaceId:kt,workspaceSetupRequired:!1,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-T)}),{success:!0,workspaceSetupRequired:!1,workspaceId:kt}}catch{return $a("Unable to resolve workspace access."),{success:!1,workspaceSetupRequired:!1,error:"Failed to resolve workspace access."}}finally{Sn(!1)}},[rn,ns,Yn,$a,At,Gr,we]),Ru=a.useCallback(async()=>{sn(null),Yn("auth");const m=await na();if(we&&m){const T=await as();if(!T.success||T.workspaceSetupRequired){await Hn({ignoreAuthGuard:!0});return}}await Hn({ignoreAuthGuard:!0})},[na,Hn,Yn,as,we]),_r=a.useCallback(async(m,T)=>{if(!we)return{success:!1,error:"Workspace management is unavailable in local mode.",code:"WORKSPACE_MANAGEMENT_DISABLED"};const N=String(m||"").trim();if(!N)return{success:!1,error:"Workspace name is required."};try{const $=await fetch("/api/taskforce/workspaces",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({name:N,description:typeof T=="string"?T:void 0})}),te=await $.json().catch(()=>({}));if(!$.ok||te?.success===!1)return{success:!1,error:te?.error||`Failed to create workspace (${$.status})`,code:te?.code};const he=te?.workspace;if(await ns(),he?.id){const Oe=await Gr(he.id);if(!Oe.success)return{success:!1,error:Oe.error||"Workspace created but failed to activate.",code:Oe.code}}return{success:!0,workspace:he}}catch{return{success:!1,error:"Failed to create workspace."}}},[ns,Gr,we]),bd=a.useCallback(async m=>{if(!we)return{success:!1,error:"Workspace management is unavailable in local mode.",code:"WORKSPACE_MANAGEMENT_DISABLED"};const T=String(m||"").trim();if(!T)return{success:!1,error:"workspaceId is required.",code:"WORKSPACE_ID_REQUIRED"};try{const N=await fetch(`/api/taskforce/workspaces/${encodeURIComponent(T)}`,{method:"DELETE",credentials:"include"}),$=await N.json().catch(()=>({}));if(!N.ok||$?.success===!1)return{success:!1,error:$?.error||`Failed to delete workspace (${N.status})`,code:$?.code};await na(),await Promise.all([Hn(),ns()]);const te=typeof $?.nextWorkspaceId=="string"?$.nextWorkspaceId.trim():"";return te&&rn(te),{success:!0,nextWorkspaceId:te||void 0,workspaceSetupRequired:$?.workspaceSetupRequired===!0,cleanupWarnings:Array.isArray($?.cleanupWarnings)?$.cleanupWarnings.map(he=>String(he||"")):[]}}catch{return{success:!1,error:"Failed to delete workspace."}}},[na,rn,Hn,ns,we]),il=a.useCallback(async m=>{const T=m==="operations"?"operations":"core";try{const N=await fetch("/api/taskforce/global-settings",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({setup:{mode:T}})}),$=await N.json().catch(()=>({}));return!N.ok||$?.success===!1?!1:(await Ao(),!0)}catch{return!1}},[Ao]),Io=a.useCallback(async m=>{const T=String(m?.name||"").trim();if(!T)return{success:!1,error:"Workspace name is required.",code:"WORKSPACE_NAME_REQUIRED"};try{const N=await fetch("/api/taskforce/workspace-profile",{method:"POST",headers:{"Content-Type":"application/json","x-taskforce-runtime-mode":Ge},credentials:"include",body:JSON.stringify({workspaceId:m.workspaceId,name:T,description:typeof m.description=="string"?m.description:void 0,allowCreate:!0})}),$=await N.json().catch(()=>({}));if(!N.ok||$?.success===!1)return{success:!1,error:$?.error||`Failed to save workspace (${N.status})`,code:$?.code};const te=String($?.workspace?.id||"").trim();if(te&&(rn(te),await new Promise(he=>window.setTimeout(he,0)),Ge==="cloud"&&et&&te!==De)){const he=await Gr(te);if(!he.success)return{success:!1,error:he.error||"Workspace saved but failed to activate session workspace.",code:"WORKSPACE_SWITCH_FAILED"}}return await Ao(),{success:!0,workspaceId:te||void 0}}catch{return{success:!1,error:"Failed to save workspace profile."}}},[rn,Ao,Ge,et,De,Gr]),Du=a.useCallback(async(m,T)=>{if(!Z)return{success:!1,error:"Cloud auth endpoint is not configured."};const N=m.trim().toLowerCase(),$=T;if(!N||!$)return{success:!1,error:"Email and password are required."};try{const te=await fetch(j("/api/taskforce/auth/login"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({email:N,password:$})}),he=await te.json().catch(()=>({}));if(!te.ok||!he?.success)return{success:!1,error:he?.error||"Sign in failed.",code:he?.code};Un(""),await na();const Oe=await as();return Oe.success?Oe.workspaceSetupRequired?{success:!0,workspaceSetupRequired:!0}:(await Promise.all([Hn({ignoreAuthGuard:!0}),In(!0,{ignoreAuthGuard:!0})]),ds({preferCloudOnFirstSync:!0}),{success:!0}):{success:!1,error:Oe.error||"Unable to resolve workspace after sign in.",code:Oe.code}}catch{return{success:!1,error:"Sign in failed."}}},[na,Hn,In,as,ds,j,Z]),cl=a.useCallback(async(m,T,N)=>{if(!Z)return{success:!1,error:"Cloud auth endpoint is not configured."};const $=m.trim().toLowerCase(),te=T;if(!$||!te)return{success:!1,error:"Email and password are required."};try{const he=await fetch(j("/api/taskforce/auth/register"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({email:$,password:te,...typeof N?.displayName=="string"&&N.displayName.trim()?{displayName:N.displayName.trim()}:{},...typeof N?.planId=="string"&&N.planId.trim()?{planId:N.planId.trim()}:{},...typeof N?.planVersionId=="string"&&N.planVersionId.trim()?{planVersionId:N.planVersionId.trim()}:{},...typeof N?.interval=="string"&&N.interval.trim()?{interval:N.interval.trim()}:{}})}),Oe=await he.json().catch(()=>({}));return!he.ok||!Oe?.success?{success:!1,error:Oe?.error||"Create account failed.",code:Oe?.code}:{success:!0,workspaceSetupRequired:!!Oe?.workspaceSetupRequired,verificationRequired:!!Oe?.verificationRequired,verificationToken:typeof Oe?.verificationToken=="string"?Oe.verificationToken:void 0,emailSent:Oe?.emailSent!==!1,emailError:typeof Oe?.emailError=="string"?Oe.emailError:void 0}}catch{return{success:!1,error:"Create account failed."}}},[j,Z]),_d=a.useCallback(async m=>{if(!Z)return{success:!1,error:"Cloud auth endpoint is not configured."};const T=String(m.displayName||"").trim(),N=typeof m.avatarDraftId=="string"?m.avatarDraftId.trim():"",$=m.clearAvatar===!0;if(!T)return{success:!1,error:"Display name is required."};try{const te=await fetch(j("/api/taskforce/auth/profile"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({displayName:T,...N?{avatarDraftId:N}:{},...$?{clearAvatar:!0}:{}})}),he=await te.json().catch(()=>({}));if(!te.ok||!he?.success)return{success:!1,error:he?.error||"Failed to update profile.",code:he?.code};const Oe={userId:typeof he?.profile?.userId=="string"?he.profile.userId:vt,email:typeof he?.profile?.email=="string"?he.profile.email:wt,displayName:typeof he?.profile?.displayName=="string"?he.profile.displayName:null,avatarUrl:typeof he?.profile?.avatarUrl=="string"?he.profile.avatarUrl:null};return Jn(Oe.displayName||""),gt(Oe.avatarUrl||""),{success:!0,profile:Oe}}catch{return{success:!1,error:"Failed to update profile."}}},[j,Z,wt,vt]),ll=a.useCallback(async m=>{if(!Z)return{success:!1,error:"Cloud auth endpoint is not configured."};const T=m.trim().toLowerCase();if(!T)return{success:!1,error:"Email is required."};try{const N=await fetch(j("/api/taskforce/auth/verify-email/request"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({email:T})}),$=await N.json().catch(()=>({}));return!N.ok||!$?.success?{success:!1,error:$?.error||"Failed to request verification email.",code:$?.code}:{success:!0,verificationToken:$?.verificationToken??null,emailSent:$?.emailSent!==!1,emailError:typeof $?.emailError=="string"?$.emailError:void 0}}catch{return{success:!1,error:"Failed to request verification email."}}},[j,Z]),No=a.useCallback(async m=>{if(!Z)return{success:!1,error:"Cloud auth endpoint is not configured."};const T=m.trim();if(!T)return{success:!1,error:"Token is required."};try{const N=await fetch(j("/api/taskforce/auth/verify-email/confirm"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({token:T})}),$=await N.json().catch(()=>({}));return!N.ok||!$?.success?{success:!1,error:$?.error||"Verification failed.",code:$?.code}:{success:!0}}catch{return{success:!1,error:"Verification failed."}}},[j,Z]),ss=a.useCallback(async m=>{if(!Z)return{success:!1,error:"Cloud auth endpoint is not configured."};const T=m.trim().toLowerCase();if(!T)return{success:!1,error:"Email is required."};try{const N=await fetch(j("/api/taskforce/auth/password-reset/request"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({email:T})}),$=await N.json().catch(()=>({}));return!N.ok||!$?.success?{success:!1,error:$?.error||"Failed to request password reset.",code:$?.code}:{success:!0,resetToken:$?.resetToken??null,emailSent:$?.emailSent!==!1,emailError:typeof $?.emailError=="string"?$.emailError:void 0}}catch{return{success:!1,error:"Failed to request password reset."}}},[j,Z]),jo=a.useCallback(async(m,T)=>{if(!Z)return{success:!1,error:"Cloud auth endpoint is not configured."};const N=m.trim(),$=T;if(!N||!$)return{success:!1,error:"Token and password are required."};try{const te=await fetch(j("/api/taskforce/auth/password-reset/confirm"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({token:N,password:$})}),he=await te.json().catch(()=>({}));return!te.ok||!he?.success?{success:!1,error:he?.error||"Failed to reset password.",code:he?.code}:{success:!0}}catch{return{success:!1,error:"Failed to reset password."}}},[j,Z]),Pu=a.useCallback(async m=>{if(!Z)return{success:!1,error:"Cloud auth endpoint is not configured."};const T=m.trim();if(!T)return{success:!1,error:"Token is required."};try{const N=await fetch(j("/api/taskforce/auth/invite/inspect"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({token:T})}),$=await N.json().catch(()=>({}));return!N.ok||!$?.success?{success:!1,error:$?.error||"Invite inspection failed.",code:$?.code,state:$?.state}:{success:!0,state:$?.state,email:typeof $?.email=="string"?$.email:void 0,workspaceId:typeof $?.workspaceId=="string"?$.workspaceId:void 0,inviteeKind:$?.inviteeKind==="existing_user"?"existing_user":"new_user",passwordRequired:$?.passwordRequired===!0}}catch{return{success:!1,error:"Invite inspection failed."}}},[j,Z]),Cd=a.useCallback(async(m,T)=>{if(!Z)return{success:!1,error:"Cloud auth endpoint is not configured."};const N=m.trim(),$=T;if(!N||!$)return{success:!1,error:"Token and password are required."};try{const te=await fetch(j("/api/taskforce/auth/invite/accept"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({token:N,password:$})}),he=await te.json().catch(()=>({}));if(!te.ok||!he?.success)return{success:!1,error:he?.error||"Invite acceptance failed.",code:he?.code};Un(""),await na();const Oe=typeof he?.workspaceId=="string"?he.workspaceId:null,kt=await as({preferredWorkspaceId:Oe});return kt.success?kt.workspaceSetupRequired?{success:!0,workspaceSetupRequired:!0}:(await Promise.all([Hn({ignoreAuthGuard:!0}),In(!0,{ignoreAuthGuard:!0})]),ds({preferCloudOnFirstSync:!0}),{success:!0}):{success:!1,error:kt.error||"Unable to resolve workspace after invite acceptance.",code:kt.code}}catch{return{success:!1,error:"Invite acceptance failed."}}},[na,Hn,In,as,ds,j,Z]),Eu=a.useCallback(async m=>{if(!Z)return{success:!1,error:"Cloud auth endpoint is not configured."};const T=m.trim();if(!T)return{success:!1,error:"Token is required."};try{const N=await fetch(j("/api/taskforce/auth/invite/join"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({token:T})}),$=await N.json().catch(()=>({}));if(!N.ok||!$?.success)return{success:!1,error:$?.error||"Invite join failed.",code:$?.code};Un(""),await na();const te=typeof $?.workspaceId=="string"?$.workspaceId:null,he=await as({preferredWorkspaceId:te});return he.success?he.workspaceSetupRequired?{success:!0,workspaceSetupRequired:!0}:(await Promise.all([Hn({ignoreAuthGuard:!0}),In(!0,{ignoreAuthGuard:!0})]),ds({preferCloudOnFirstSync:!0}),{success:!0}):{success:!1,error:he.error||"Unable to resolve workspace after invite join.",code:he.code}}catch{return{success:!1,error:"Invite join failed."}}},[na,Hn,In,as,ds,j,Z]),dl=a.useCallback(async()=>{try{Z&&await fetch(j("/api/taskforce/auth/logout"),{method:"POST",credentials:"include"})}catch{}finally{if(Vn.current=null,$t.current=!1,pn.current=Date.now(),_t(!1),Kt(!0),Ot("anonymous"),It(""),Tl(null),_n(""),Jn(""),gt(""),wa("disconnected"),Ks(null),se(!0),ot(Ge==="cloud"&&Ie),Me(m=>{const T=String(m||"").trim();let N="default";return T&&T.toLowerCase()!=="default"?N=T:Ge!=="local"&&(N=qd(At)||"default"),Wt.current=N,N}),Et([]),Xs.current=!1,Ee(null),Ge==="local"){await Promise.allSettled([Hn({ignoreAuthGuard:!0}),In(!0,{ignoreAuthGuard:!0}),bn({ignoreAuthGuard:!0}),Hr({ignoreAuthGuard:!0,force:!0})]);return}Er([]),ks([]),lr([])}},[Ie,j,Z,At,Ge,Hn,bn,Hr,In]),xd=a.useCallback(async m=>{try{const T=await fetch("/api/taskforce/initiative-templates/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(m)}),N=await T.json().catch(()=>({}));return!T.ok||!N?.success?{success:!1,error:N?.error||`Create failed (${T.status})`}:(await In(!0),{success:!0,result:N?.results})}catch(T){return{success:!1,error:T.message}}},[In]),xs=a.useCallback(async m=>{const T=await fetch("/api/taskforce/initiative",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(m||{})}),N=await T.json().catch(()=>({}));if(!T.ok)throw new Error(N?.error||`Failed to create initiative (${T.status})`);return await bn(),N},[bn]),Lu=a.useCallback(async(m,T)=>{const N=await fetch(`/api/taskforce/initiative/${encodeURIComponent(m)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(T||{})}),$=await N.json().catch(()=>({}));if(!N.ok)throw new Error($?.error||`Failed to update initiative (${N.status})`);return await bn(),$},[bn]),As=a.useCallback(async m=>{const T=await fetch(`/api/taskforce/initiative/${encodeURIComponent(m)}/archive`,{method:"POST"}),N=await T.json().catch(()=>({}));if(!T.ok)throw new Error(N?.error||`Failed to archive initiative (${T.status})`);return await bn(),N},[bn]),Ad=a.useCallback(async m=>{const T=await fetch(`/api/taskforce/initiative/${encodeURIComponent(m)}/unarchive`,{method:"POST"}),N=await T.json().catch(()=>({}));if(!T.ok)throw new Error(N?.error||`Failed to unarchive initiative (${T.status})`);return await bn(),N},[bn]),Td=a.useCallback(async m=>{const T=await fetch("/api/taskforce/workstream",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(m||{})}),N=await T.json().catch(()=>({}));if(!T.ok)throw new Error(N?.error||`Failed to create workstream (${T.status})`);return await bn(),N},[bn]),uc=a.useCallback(async(m,T)=>{const N=await fetch(`/api/taskforce/workstream/${encodeURIComponent(m)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(T||{})}),$=await N.json().catch(()=>({}));if(!N.ok)throw new Error($?.error||`Failed to update workstream (${N.status})`);return await bn(),$},[bn]),li=a.useCallback(async m=>{const T=await fetch(`/api/taskforce/workstream/${encodeURIComponent(m)}/archive`,{method:"POST"}),N=await T.json().catch(()=>({}));if(!T.ok)throw new Error(N?.error||`Failed to archive workstream (${T.status})`);return await bn(),N},[bn]),ul=a.useCallback(async m=>{const T=await fetch(`/api/taskforce/workstream/${encodeURIComponent(m)}/unarchive`,{method:"POST"}),N=await T.json().catch(()=>({}));if(!T.ok)throw new Error(N?.error||`Failed to unarchive workstream (${T.status})`);return await bn(),N},[bn]),Id=a.useRef(!1),Ts=a.useRef(!1);a.useEffect(()=>{pe(!0),!Id.current&&(Id.current=!0,na())},[na]),a.useEffect(()=>{Q&&na()},[Q,na]),a.useEffect(()=>{if(Ge!=="local"||!L||typeof window>"u")return;const m=()=>{na()},T=()=>{document.visibilityState==="visible"&&m()};window.addEventListener("focus",m),window.addEventListener("online",m),document.addEventListener("visibilitychange",T);const N=window.setInterval(m,3e4);return()=>{window.removeEventListener("focus",m),window.removeEventListener("online",m),document.removeEventListener("visibilitychange",T),window.clearInterval(N)}},[Ge,L,na]),a.useEffect(()=>{vn||dn||Ts.current||(Ts.current=!0,(async()=>{if(Ge==="cloud"&&ln&&et){const m=await as();if(!m.success||m.workspaceSetupRequired){await Cs(),Hr();return}}await Cs(),await Promise.all([(async()=>{const m=typeof performance<"u"?performance.now():Date.now();await In(!1),Bn("bootstrap_tasks_loaded",{durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-m)})})(),Hr(),bn()]),typeof window<"u"&&(Ga.current!==null&&window.clearTimeout(Ga.current),Ga.current=window.setTimeout(()=>{Ga.current=null;const m=typeof performance<"u"?performance.now():Date.now();es(!0).then(()=>{Bn("bootstrap_archive_loaded_deferred",{durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-m)})})},1500))})())},[vn,dn,Ge,ln,et,as,Cs,In,es,Hr,bn]),a.useEffect(()=>{if(vn||dn||Cn||At===Mo||!Ts.current)return;const m=`${Ge}:${De}:${At}`;ri.current!==m&&(ri.current=m,Hn())},[De,vn,dn,Cn,Ge,At,Hn]),a.useEffect(()=>{if(vn||dn||Cn)return;const m=De;xo.current!==m&&(xo.current=m,ho())},[vn,dn,De,ho,Cn]),a.useEffect(()=>{if(Ge!=="cloud"||!ln||!et){Ge!=="cloud"&&Et([]),Xs.current=!1;return}Cn||!Ts.current||Xs.current||ns()},[Ge,ln,et,ns,Cn]),a.useEffect(()=>{s&&s(ta.length)},[ta.length,s]),a.useEffect(()=>{if(n&&ta.length>0){const m=ta.find(T=>T.id.endsWith(n)||T.id===n);m&&(Vr(m),fi("add"))}},[n,ta]);const di=a.useRef(!1);a.useEffect(()=>{if(!Xa)return;if(!di.current&&un.length>0){di.current=!0;const T=Qo,N=un.some($=>$.label===T||$.value===T);if(T&&N){const $=un.find(te=>te.label===T||te.value===T);Ys($?.value||T)}else Ys(Ms(un));return}const m=un.some(T=>T.value===go);un.length>0&&!m&&Ys(Ms(un))},[Xa,un,go,Ms,Qo]),a.useEffect(()=>{if(!Xa||un.length===0)return;const m=$=>!un.some(te=>te.value===$.category),T=ta.some(m),N=is.some(m);if(T||N){const $=Ms(un);T&&Er(te=>te.map(he=>m(he)?{...he,category:$}:he)),N&&ys(te=>te.map(he=>m(he)?{...he,category:$}:he))}},[Xa,un,ta,is,Ms]),a.useEffect(()=>()=>{Ga.current!==null&&typeof window<"u"&&(window.clearTimeout(Ga.current),Ga.current=null),_s.current!==null&&typeof window<"u"&&(window.clearTimeout(_s.current),_s.current=null)},[]),a.useEffect(()=>{},[Mi]);const pl=a.useCallback(async()=>{await Or()},[Or]),pc=String(De||"").trim(),ml=String(vt||"").trim(),ui=je("/taskforce-ws"),mc=!!(Z&&Ge==="cloud"&&ln&&et&&ml&&ml!=="anonymous"&&pc&&!Fp(pc)&&ui),fc=a.useCallback(()=>{Ge==="cloud"&&(Or(),!(typeof window>"u")&&(_s.current!==null&&window.clearTimeout(_s.current),_s.current=window.setTimeout(()=>{_s.current=null,Or()},250)))},[Ge,Or]);Of({enabled:mc,workspaceId:pc,websocketUrl:ui,onSignal:fc,userId:ml||void 0}),a.useEffect(()=>{if(typeof window>"u"||typeof document>"u"||gS({isOpen:re,authBlocked:Qe,authRequiredForApi:Ie,isAuthenticated:et,canCallProtectedApi:nt.canCallProtectedApi}))return;let m=!1;const T=async()=>{if(!(m||document.visibilityState!=="visible")&&!yS({shouldGateProtectedApiCalls:P,authSessionResolved:oc.current,authRequiredForApi:yd.current,isAuthenticated:Co.current}))try{const te=await fetch("/api/taskforce/data-version");if(!te.ok)return;const he=await te.json(),Oe=Number(he?.dataVersion);if(!Number.isFinite(Oe))return;if(br.current===null){br.current=Oe;return}Oe!==br.current&&(br.current=Oe,await pl())}catch{}},N=()=>{document.visibilityState==="visible"&&T()},$=window.setInterval(T,3e3);return document.addEventListener("visibilitychange",N),T(),()=>{m=!0,window.clearInterval($),document.removeEventListener("visibilitychange",N)}},[re,In,es,Qe,Ie,et,nt,P,pl]);const Ma=a.useMemo(()=>{const m=new Map;for(const T of is)m.set(T.id,T);for(const T of ta)m.set(T.id,T);return Array.from(m.values())},[ta,is]),pi=a.useMemo(()=>Pi.map(m=>({...m.taskSnapshot,isDeleted:!0,deletedRecordId:m.id})),[Pi]);a.useEffect(()=>{if(!(vn||dn)&&re&&!Cn){if(O==="tasks"){const m=`${De}:${O}:${G?"archive":"active"}:${ye}`;if(!gd.current){gd.current=!0,oi.current=m;return}if(oi.current===m)return;oi.current=m,In(),(G||ye==="archived")&&es(!0),ye==="deleted"&&Ua();return}if(O==="settings"){const m=`${De}:${O}:${gn}`;if(cc.current===m)return;cc.current=m,Hn(),(gn==="commands"||gn==="resources")&&da()}}},[De,re,O,gn,G,ye,In,es,Ua,Hn,da,vn,dn,Cn]);const mi=a.useCallback(async(m="")=>{try{const T=await fetch(`/api/taskforce/folders?path=${encodeURIComponent(m)}`);if(T.ok){const N=await T.json();Lt(N.folders||[]),Zt(N.files||[]),on(m)}}catch(T){console.error("[Taskforce] Failed to fetch folders:",T)}},[]),fl=a.useCallback(m=>{const T=[];if(m.path&&T.push(m.path),m.paths&&m.paths.length>0)for(const N of m.paths)T.includes(N)||T.push(N);return T},[]),{validatePaths:Mu,handleUpdateCategory:Bu,handleSaveCategory:hl,handleAddPath:gl,handleUpdateCategoryIcon:Nd,handleUpdateCategoryColor:hc,handleRemovePath:jd,handleSelectPath:Cr,handleRemoveCategory:Rd,handleSaveType:Dd,handleRemoveType:Ro,handleUpdateType:Pd,handleUpdateTaxonomies:xr,handleUpdatePriorities:Ed,analyzeSystemTaxonomyPack:Ld,handleApplySystemTaxonomyPack:Ar}=zk({activeCategories:un,activeTab:O,activeTypes:ls,archivedTasks:is,browserTarget:cn,category:go,configLoaded:Xa,customCategories:Mr,refreshTaskCollections:Mi,fetchTasks:In,filterCategories:Sr,getCategoryPaths:fl,normalizePath:vu,pathValidation:$o,setBrowserTarget:nn,setCategory:Ys,setCustomCategories:Oo,setCustomTypes:Wr,setFilterCategories:So,setPathValidation:Uo,setPriorities:Us,setShowFolderBrowser:Ke,setTaxonomies:pr,tasks:ta}),Md=a.useCallback(async m=>{const T=Vs,N={...T,...m};vs(N);try{const $=await fetch("/api/taskforce/taxonomy-display-labels",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({displayLabels:m})});if(!$.ok)throw new Error(`Failed to save taxonomy display labels (${$.status})`);const te=await $.json().catch(()=>({}));te?.displayLabels&&typeof te.displayLabels=="object"&&vs({...N,...te.displayLabels})}catch($){console.error("[Taskforce] Failed to update taxonomy display labels",$),vs(T)}},[Vs]),fi=a.useCallback(m=>{O==="tasks"&&Di.current&&cr(Di.current.scrollTop),ue(m)},[O]),Bd=a.useRef(async()=>{}),{handleNavigation:Wu,handleClose:Fu,resetForm:Ba,resolveWorkstreamIdInput:yl,handleEdit:Vr,handleOpenTaskById:Zr,returnToPreviousTask:zu,clearReturnToParentTask:Ou}=Yk({activeCategories:un,activeTypes:ls,activeTab:O,attachments:sc,checklistItems:Ki,comments:Hc,description:Vi,editingTaskId:Ss,flushPendingAutoSave:()=>Bd.current(),getPreferredCategoryValue:Ms,lastUsedCategory:Qo,newCommentText:ua,relationshipTasks:Ma,workstreams:zo,showArchive:G,taxonomies:Rn,setActiveTab:fi,setApproach:Uc,setAssignee:qi,setAttachments:hd,setAttachmentsDirty:rc,setCategory:Ys,setChecklistItems:ad,setComments:ts,setComplexity:$i,setDescription:Zi,setDueDate:Hi,setEditingTaskId:Lr,setError:Un,setFormTaxonomies:ko,setIsOpen:pe,setNewCommentText:yo,setPendingNavigation:En,setWorkstreamInput:qc,setPriority:td,setScheduledDate:Yo,setShowArchive:q,setStatus:Ko,setTaskReturnTrail:Vl,setTitle:Xo,setType:zs,setUnsavedModalOpen:Ja,taskReturnTrail:Ls,title:Gi}),{copiedId:$u,handleDelete:Tr,handleUpdateTask:Kr,handleToggleComplete:Qs,handleToggleCancel:Do,handleToggleInProgress:gc,handleToggleReview:hi,handleArchiveTask:kl,handleBulkArchive:Wd,handleUnarchive:gi,handleRestoreDeletedTask:Uu,handlePermanentlyDeleteDeletedTask:Sl,handleEmptyDeletedTasks:qu,handleCopyId:vl,queueWorkspaceSyncFromAuthoritativeTaskState:wl}=pS({tasks:ta,archivedTasks:is,editingTaskId:Ss,setTasks:Er,setArchivedTasks:ys,setDeletedTasks:Hs,setError:Un,resetForm:Ba,setActiveTab:fi,fetchTasks:In,fetchArchive:es,fetchDeletedTasks:Ua,mergeTaskFromServer:ws,pushNotice:Es,cloudAuthConfigured:Z,runtimeMode:Ge,isAuthenticated:et,workspaceCloudSyncEnabled:Go,buildWorkspaceSyncSignature:ma,pushWorkspaceChangesToCloud:Zo,workspacePendingSignatureRef:Vo,workspaceDeletedTaskIdsRef:Bi}),{autoSaveState:Fd,flushAutoSave:er,scheduleWarningPrompt:zd,handleSubmit:yc,confirmScheduleWarning:Od,cancelScheduleWarning:Hu,handleAddComment:Gu}=lS({activeCategories:un,activeTab:O,apiEndpoint:p,approach:$c,assignee:Ur,attachments:sc,attachmentsDirty:_o,category:go,checklistItems:Ki,comments:Hc,complexity:qa,description:Vi,dueDate:Jo,editingTaskId:Ss,fetchTasks:In,formTaxonomies:sd,getPreferredCategoryValue:Ms,mergeTaskFromServer:ws,workstreamInput:ct,priority:ed,pushNotice:Es,queueWorkspaceSyncFromAuthoritativeTaskState:wl,relationshipTasks:Ma,resetForm:Ba,resolveWorkstreamIdInput:yl,scheduledDate:nd,setActiveTab:fi,setAttachmentsDirty:rc,setComments:ts,setError:Un,setLastUsedCategory:rd,setLoading:Bs,setNewCommentText:yo,status:Ui,title:Gi,taxonomies:Rn,type:ba});a.useEffect(()=>{Bd.current=er},[er]);const{handleSetWorkstreamForCurrentTask:Vu}=dS({editingTaskId:Ss,mergeTaskFromServer:ws,workstreamInput:ct,pushNotice:Es,queueWorkspaceSyncFromAuthoritativeTaskState:wl,relationshipTasks:Ma,resolveWorkstreamIdInput:yl,setError:Un,fetchTasks:In}),{currentTask:Zu,currentTaskWorkstream:Po,currentTaskInitiative:kc}=Hk({editingTaskId:Ss,relationshipTasks:Ma,initiatives:Lc,workstreams:zo,supplementalTasks:pi,setComments:ts}),bl=Wk({resolveCloudAuthUrl:j,currentWorkspaceId:De,normalizedCloudAuthBaseUrl:Re,normalizedCloudMcpBaseUrl:Fe,mergedConfig:o,availableWorkspaces:Nn,currentTheme:le,configLoaded:Xa,globalTheme:Ye,themeUseGlobalDefault:bt,keyShortcut:ha,jsonBackupEnabled:lt,globalJsonBackupEnabled:Tt,globalWeekStartsOn:Kn,locale:ia,supportedLocales:ja,jsonBackupUseGlobalDefault:dt,manualComplexityEnabled:rr,checklistDropdownEnabled:pa,showTaskCardStatusLabel:Da,exportWorkflowsPath:$e,exportingResource:X,exportResult:Pe,pathSaved:mt,settingsSection:gn,exportEnvironment:Pr,setupState:za,buildInfo:en,saveSetupMode:il,saveWorkspaceProfile:Io,setCurrentTheme:ze,handleSaveTheme:xu,handleSaveGlobalTheme:Au,setKeyShortcut:Ca,handleJsonBackupEnabledChange:kd,handleSaveGlobalJsonBackupEnabled:Tu,handleSaveGlobalWeekStartsOn:sl,handleSaveLocale:qr,handleManualComplexityEnabledChange:Iu,handleChecklistDropdownEnabledChange:Nu,handleShowTaskCardStatusLabelChange:Sd,handleResetProjectToGlobal:ju,handleSaveSettings:dc,setExportWorkflowsPath:Te,setExportEnvironment:Wo,availableWorkflows:or,initiativeTemplates:la,availableEnvironments:I,fetchWorkflows:da,fetchInitiativeTemplates:Ps,createInitiativeFromTemplate:xd,fetchWorkflowTemplate:lo,fetchWorkflowOverrideNames:ir,saveWorkflowTemplateDraft:qe,resetWorkflowTemplateDraft:Gt,handleExportWorkflows:Dt,setShowFolderBrowser:Ke,setBrowserTarget:nn,fetchFolders:mi,activeCategories:un,pathValidation:$o,taxonomyDisplayLabels:Vs,handleUpdateCategory:Bu,handleRemoveCategory:Rd,handleSaveCategory:hl,handleAddPath:gl,handleRemovePath:jd,handleUpdateCategoryIcon:Nd,handleUpdateCategoryColor:hc,activeTypes:ls,handleSaveType:Dd,handleRemoveType:Ro,handleUpdateType:Pd,taxonomies:Rn,handleUpdateTaxonomies:xr,priorities:Na,handleUpdatePriorities:Ed,analyzeSystemTaxonomyPack:Ld,handleApplySystemTaxonomyPack:Ar,handleUpdateTaxonomyDisplayLabels:Md,projectRoot:an,projectName:Xt,mcpHostRoot:Oa,serverHostRoot:rs,mcpScriptPath:Se,tenantId:Qt,runtimeMode:Ge,workspaceSwitchingEnabled:we,deleteWorkspace:bd,setMcpHostRoot:oe,isAuthenticated:et});a.useEffect(()=>{typeof window<"u"&&(window.__TASKFORCE_DEBUG__={tasks:ta,archivedTasks:is,runtimeMode:Ge,currentWorkspaceId:De,isAuthenticated:et,workspaceCloudSyncEnabled:Go,realtimeSyncEnabled:Ta,fetchTasks:In,fetchArchive:es,retryWorkspaceCloudSync:Fi,resetWorkspaceSyncCursorAndPull:kr,getSyncDiagnostics:zi,__dispatch:{handleUpdateTask:Kr,handleToggleComplete:Qs,handleArchiveTask:kl,handleToggleCancel:Do,handleToggleInProgress:gc,handleToggleReview:hi,handleSubmit:yc,handleDelete:Tr}})},[ta,is,Ge,De,et,Go,Ta,In,es,Fi,kr,zi,Kr,Qs,kl,Do,gc,hi,yc,Tr]);const _l=os&&os.tone!=="error"?{message:os.message,type:"info"}:null,$d=String(_||S.wsBaseUrl||Ne||"").trim().replace(/\/+$/,"");return{config:{...o,cloudEnvironment:S.cloudEnvironment||o.cloudEnvironment||"",apiBaseUrl:Ne||o.apiBaseUrl,cloudAuthBaseUrl:Re||o.cloudAuthBaseUrl,wsBaseUrl:$d||o.wsBaseUrl},isOpen:re,setIsOpen:pe,activeTab:O,setActiveTab:fi,currentTheme:le,setCurrentTheme:ze,configLoaded:Xa,storagePath:rt,saveSettings:dc,pathSaved:mt,keyShortcut:ha,setKeyShortcut:Ca,globalWeekStartsOn:Kn,locale:ia,supportedLocales:ja,saveLocale:qr,jsonBackupEnabled:lt,setJsonBackupEnabled:Ft,manualComplexityEnabled:rr,checklistDropdownEnabled:pa,showTaskCardStatusLabel:Da,setManualComplexityEnabled:Ra,mcpHostRoot:Oa,setMcpHostRoot:oe,settingsSection:gn,setSettingsSection:yn,runtimeMode:Ge,workspaceMode:_e,workspaceSwitchingEnabled:we,cloudAuthConfigured:Z,authRequiredForApi:Ie,authBlocked:Qe,isAuthenticated:et,authUserId:vt,authUserEmail:wt,authUserDisplayName:Dn,authUserAvatarUrl:ht,authWorkspaceId:it,userGlobalSyncStatus:Wc,workspaceLastPullAt:Ho,workspaceLastPushAt:wu,workspaceLastErrorAt:Kl,userGlobalSyncError:$r,workspaceLastErrorMessage:mo,workspaceLastSuccessfulSyncAt:bu,workspaceSyncPhase:Yl,workspaceSyncStatus:Jl,workspaceSyncSummary:Fc,workspaceSyncRecommendedAction:Xl,workspaceSyncBusy:zc,workspaceSyncPendingChanges:fo,retryUserGlobalSettingsSync:Ql,retryWorkspaceCloudSync:Fi,resetWorkspaceSyncCursorAndPull:kr,getWorkspaceSyncDiagnostics:zi,hasBetaAccess:Xn,realtimeSyncEnabled:Ta,realtimeSyncFlagSource:Zn,currentWorkspaceId:De,currentWorkspaceRole:ol,availableWorkspaces:Nn,assigneeOptions:ya,workspaceCloudSyncEnabled:Go,saveWorkspaceCloudSyncSettings:Oc,applyWorkspaceSyncStateSnapshot:Wi,authSessionResolved:ln,workspaceBootstrapPending:Cn,bootstrapPhase:yt,bootstrapError:Ht,bootstrapStartedAt:ft,setupState:za,runtimeCapabilities:Ya,refreshSetupContext:Ao,retryBootstrapChecks:Ru,saveWorkspaceProfile:Io,fetchWorkspaces:ns,createWorkspace:_r,deleteWorkspace:bd,switchWorkspace:Gr,loginWithCredentials:Du,registerWithCredentials:cl,updateCurrentUserProfile:_d,requestEmailVerification:ll,confirmEmailVerification:No,requestPasswordReset:ss,confirmPasswordReset:jo,inspectInviteAcceptance:Pu,acceptInviteWithToken:Cd,joinInviteWithToken:Eu,logout:dl,showFolderBrowser:F,setShowFolderBrowser:Ke,folders:St,files:xt,currentBrowsePath:Jt,fetchFolders:mi,browserTarget:cn,setBrowserTarget:nn,groupBy:ni,setGroupBy:Yc,activeWorkspaceModule:ai,setActiveWorkspaceModule:bo,emptyColumnMode:Jc,setEmptyColumnMode:ac,zenMode:Pa,setZenMode:gs,handleSelectPath:Cr,handleAddPath:gl,handleRemovePath:jd,tasks:ta,loadingTasks:Zl,archivedTasks:is,initiatives:Lc,workstreams:zo,deletedTasks:Pi,activeCategories:un,activeTypes:ls,priorities:Na,taxonomyDisplayLabels:Vs,approaches:io,taxonomies:Rn,searchQuery:Yi,setSearchQuery:ei,filterCategories:Sr,setFilterCategories:So,filterTypes:Vc,setFilterTypes:od,filterPriorities:Ji,setFilterPriorities:Xi,filterStatus:vo,setFilterStatus:bs,filterAssignees:Ea,setFilterAssignees:vr,filterTaxonomies:ti,setFilterTaxonomies:Qi,sortBy:tc,setSortBy:Kc,sortOrder:nc,setSortOrder:wr,toggleSortOrder:cd,showArchive:G,setShowArchive:q,taskScope:ye,setTaskScope:Be,clearFilters:dd,filteredTasks:ud,searchAgnosticTasks:Xc,filteredArchive:pd,groupedTasks:Qc,collapsedCategories:Ha,setCollapsedCategories:ld,fetchTasks:In,fetchArchive:es,fetchDeletedTasks:Ua,fetchPlanningEntities:bn,fetchAssigneeOptions:To,createInitiative:xs,updateInitiative:Lu,archiveInitiative:As,unarchiveInitiative:Ad,createWorkstream:Td,updateWorkstream:uc,archiveWorkstream:li,unarchiveWorkstream:ul,handleEdit:Vr,handleDelete:Tr,handleCopyId:vl,handleToggleComplete:Qs,handleToggleCancel:Do,handleToggleInProgress:gc,handleToggleReview:hi,handleArchiveTask:kl,handleBulkArchive:Wd,handleUnarchive:gi,handleRestoreDeletedTask:Uu,handlePermanentlyDeleteDeletedTask:Sl,handleEmptyDeletedTasks:qu,handleUpdateTask:Kr,editingTaskId:Ss,loading:mr,error:po,title:Gi,setTitle:Xo,description:Vi,setDescription:Zi,checklistItems:Ki,setChecklistItems:ad,category:go,setCategory:Ys,type:ba,setType:zs,priority:ed,setPriority:td,complexity:qa,setComplexity:$i,status:Ui,setStatus:Ko,approach:$c,setApproach:Uc,assignee:Ur,setAssignee:qi,scheduledDate:nd,setScheduledDate:Yo,dueDate:Jo,setDueDate:Hi,workstreamInput:ct,setWorkstreamInput:qc,formTaxonomies:sd,setFormTaxonomies:ko,comments:Hc,newCommentText:ua,setNewCommentText:yo,attachments:sc,setAttachments:hd,attachmentsDirty:_o,setAttachmentsDirty:rc,descriptionFocused:el,setDescriptionFocused:Cu,showMarkdownHelp:Mc,setShowMarkdownHelp:Bc,showChecklist:Gc,setShowChecklist:us,showComments:md,setShowComments:fd,isCapturingScreenshot:tl,setIsCapturingScreenshot:nl,handleSubmit:yc,resetForm:Ba,handleAddComment:Gu,handleSetWorkstreamForCurrentTask:Vu,handleOpenTaskById:Zr,returnToPreviousTask:zu,autoSaveState:Fd,unsavedModalOpen:Nt,setUnsavedModalOpen:Ja,pendingNavigation:qn,handleNavigation:Wu,handleClose:Fu,uiNotice:os,pushNotice:Es,clearNotice:uo,successBanner:_l,taskReturnTrail:Ls,clearReturnToParentTask:Ou,copiedId:$u,recentlyChangedTaskIds:qo,scheduleWarningPrompt:zd,confirmScheduleWarning:Od,cancelScheduleWarning:Hu,tasksScrollRef:Di,setTasksScrollPos:cr,exportEnvironment:Pr,setExportEnvironment:Wo,exportWorkflowsPath:$e,setExportWorkflowsPath:Te,exportResult:Pe,exportingResource:X,handleUpdateCategory:Bu,handleRemoveCategory:Rd,handleSaveCategory:hl,handleUpdateCategoryIcon:Nd,handleUpdateCategoryColor:hc,handleSaveType:Dd,handleRemoveType:Ro,handleUpdateType:Pd,handleUpdateTaxonomies:xr,handleUpdatePriorities:Ed,handleUpdateTaxonomyDisplayLabels:Md,pathValidation:$o,validatePaths:Mu,getCategoryPaths:fl,customCategories:Mr,setCustomCategories:Oo,projectRoot:an,projectName:Xt,mcpScriptPath:Se,serverHostRoot:rs,commentsEndRef:_u,currentTask:Zu,currentTaskWorkstream:Po,currentTaskInitiative:kc,availableWorkflows:or,initiativeTemplates:la,availableEnvironments:I,fetchWorkflows:da,fetchInitiativeTemplates:Ps,createInitiativeFromTemplate:xd,fetchWorkflowTemplate:lo,fetchWorkflowOverrideNames:ir,saveWorkflowTemplateDraft:qe,resetWorkflowTemplateDraft:Gt,onExportWorkflows:Dt,settingsModel:bl}}const vS="modulepreload",wS=function(e){return"/taskforce/"+e},Pm={},Bo=function(n,s,r){let o=Promise.resolve();if(s&&s.length>0){let g=function(w){return Promise.all(w.map(C=>Promise.resolve(C).then(_=>({status:"fulfilled",value:_}),_=>({status:"rejected",reason:_}))))};document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),p=c?.nonce||c?.getAttribute("nonce");o=g(s.map(w=>{if(w=wS(w),w in Pm)return;Pm[w]=!0;const C=w.endsWith(".css"),_=C?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${w}"]${_}`))return;const y=document.createElement("link");if(y.rel=C?"stylesheet":vS,C||(y.as="script"),y.crossOrigin="",y.href=w,p&&y.setAttribute("nonce",p),document.head.appendChild(y),C)return new Promise((k,b)=>{y.addEventListener("load",k),y.addEventListener("error",()=>b(new Error(`Unable to preload CSS for ${w}`)))})}))}function l(c){const p=new Event("vite:preloadError",{cancelable:!0});if(p.payload=c,window.dispatchEvent(p),!p.defaultPrevented)throw c}return o.then(c=>{for(const p of c||[])p.status==="rejected"&&l(p.reason);return n().catch(l)})},bS="_filterGlow_zc70q_13",_S="_floatingButton_zc70q_23",CS="_badge_zc70q_54",xS="_configBadge_zc70q_71",AS="_configBadgeActive_zc70q_81",TS="_configBadgeRevoked_zc70q_87",IS="_configBadgeExpired_zc70q_93",NS="_header_zc70q_103",jS="_headerTitle_zc70q_118",RS="_brandIcon_zc70q_135",DS="_brandCloudSuffix_zc70q_141",PS="_projectSlash_zc70q_146",ES="_projectName_zc70q_153",LS="_taskCountBadge_zc70q_172",MS="_headerActions_zc70q_188",BS="_sortDirectionBtn_zc70q_195",WS="_sortDirectionBtnWidget_zc70q_202",FS="_form_zc70q_210",zS="_topRow_zc70q_222",OS="_field_zc70q_228",$S="_labelRow_zc70q_234",US="_label_zc70q_234",qS="_manageLink_zc70q_248",HS="_input_zc70q_267",GS="_select_zc70q_268",VS="_textarea_zc70q_269",ZS="_taskIdInlineLink_zc70q_303",KS="_readOnly_zc70q_322",YS="_selectWithConfig_zc70q_330",JS="_configBtn_zc70q_340",XS="_configBtnActive_zc70q_370",QS="_hasPath_zc70q_378",ev="_pathIndicator_zc70q_383",tv="_formActions_zc70q_389",nv="_hasCancel_zc70q_396",av="_submitBtn_zc70q_400",sv="_cancelBtn_zc70q_416",rv="_successMessage_zc70q_448",ov="_successIcon_zc70q_454",iv="_spinner_zc70q_474",cv="_spin_zc70q_474",lv="_boardRefreshIndicator_zc70q_478",dv="_destructiveBtn_zc70q_508",uv="_warningBtn_zc70q_531",pv="_viewTab_zc70q_554",mv="_deleteBtn_zc70q_565",fv="_loading_zc70q_575",hv="_emptyState_zc70q_581",gv="_taskList_zc70q_591",yv="_taskIdBadge_zc70q_597",kv="_taskIdBadgeLabel_zc70q_619",Sv="_copiedId_zc70q_638",vv="_highlight_zc70q_644",wv="_modal_zc70q_656",bv="_priorityEmoji_zc70q_664",_v="_metaItem_zc70q_668",Cv="_taskFormDateInput_zc70q_682",xv="_metaBadge_zc70q_692",Av="_complexityPill_zc70q_707",Tv="_complexityDots_zc70q_711",Iv="_dot_zc70q_717",Nv="_dotFilled_zc70q_725",jv="_typePill_zc70q_731",Rv="_type_bug_zc70q_735",Dv="_type_feature_zc70q_739",Pv="_type_chore_zc70q_743",Ev="_type_refactor_zc70q_747",Lv="_type_documentation_zc70q_751",Mv="_type_research_zc70q_755",Bv="_type_security_zc70q_763",Wv="_approachPill_zc70q_768",Fv="_approach_evaluate_zc70q_773",zv="_approach_collaborate_zc70q_779",Ov="_approach_plan_zc70q_785",$v="_approachActive_zc70q_791",Uv="_statusActionsGroup_zc70q_796",qv="_statusActionsGroupCompact_zc70q_802",Hv="_statusSelectWrap_zc70q_806",Gv="_statusTaxonomyDropdownWrap_zc70q_812",Vv="_statusTaxonomyDropdown_zc70q_812",Zv="_statusTaxonomyDropdownCompact_zc70q_820",Kv="_statusTaxonomyDropdownIconOnly_zc70q_824",Yv="_taxonomyDropdownButton_zc70q_829",Jv="_taxonomyDropdownButtonContent_zc70q_846",Xv="_statusTaxonomyDropdownIconOnlyPanel_zc70q_850",Qv="_actionBtn_zc70q_856",ew="_startWorkBtn_zc70q_880",tw="_workingBtn_zc70q_889",nw="_pulse_zc70q_1",aw="_reviewBtn_zc70q_895",sw="_reviewActiveBtn_zc70q_905",rw="_reviewPill_zc70q_911",ow="_archiveTaskBtn_zc70q_918",iw="_bulkArchiveBtn_zc70q_927",cw="_bulkDeleteBtn_zc70q_949",lw="_completeBtn_zc70q_990",dw="_completeActiveBtn_zc70q_1000",uw="_deleteActiveBtn_zc70q_1006",pw="_disabledBtn_zc70q_1012",mw="_archiveList_zc70q_1019",fw="_archiveHeader_zc70q_1027",hw="_settingsTab_zc70q_1038",gw="_settingsTabs_zc70q_1050",yw="_settingsLayout_zc70q_1064",kw="_settingsSidebar_zc70q_1071",Sw="_settingsSidebarHeader_zc70q_1081",vw="_settingsSidebarNav_zc70q_1090",ww="_settingsSidebarBtn_zc70q_1099",bw="_settingsSidebarBtnActive_zc70q_1123",_w="_settingsSidebarGroup_zc70q_1130",Cw="_settingsSidebarGroupBtn_zc70q_1136",xw="_settingsSidebarGroupLabel_zc70q_1140",Aw="_settingsSidebarGroupChevron_zc70q_1144",Tw="_settingsSidebarSubnav_zc70q_1150",Iw="_settingsSidebarSubBtn_zc70q_1157",Nw="_appScrollbar_zc70q_1180",jw="_settingsTabBtn_zc70q_1184",Rw="_settingsTabBtnActive_zc70q_1210",Dw="_settingsContent_zc70q_1216",Pw="_settingsToast_zc70q_1264",Ew="_settingsToastSuccess_zc70q_1281",Lw="_settingsToastError_zc70q_1287",Mw="_inputWithPrefix_zc70q_1293",Bw="_pathHint_zc70q_1300",Ww="_settingGroup_zc70q_1313",Fw="_settingTitle_zc70q_1319",zw="_settingTitleRow_zc70q_1328",Ow="_settingTitleActionBtn_zc70q_1335",$w="_themeOptions_zc70q_1355",Uw="_buttonGrid_zc70q_1360",qw="_themeBtn_zc70q_1372",Hw="_activeTheme_zc70q_1396",Gw="_pathInputGroup_zc70q_1404",Vw="_saveSettingsBtn_zc70q_1413",Zw="_shortcutInputWrapper_zc70q_1434",Kw="_inputIcon_zc70q_1439",Yw="_settingHelper_zc70q_1448",Jw="_browseBtn_zc70q_1455",Xw="_inlineCategoryManager_zc70q_1474",Qw="_categoryManager_zc70q_1485",eb="_categoryList_zc70q_1491",tb="_categoryChip_zc70q_1503",nb="_categoryChipLabel_zc70q_1516",ab="_chipActionBtn_zc70q_1524",sb="_removeCategoryBtn_zc70q_1544",rb="_addCategoryForm_zc70q_1564",ob="_addCategoryBtn_zc70q_1569",ib="_filesList_zc70q_1594",cb="_helpLink_zc70q_1621",lb="_inlineCode_zc70q_1642",db="_codeBlock_zc70q_1653",ub="_taskChildrenSummaryBadges_zc70q_1677",pb="_taskChildrenProgressBar_zc70q_1685",mb="_taskChildrenProgressBarSegmentDone_zc70q_1696",fb="_taskChildrenProgressBarSegmentReview_zc70q_1702",hb="_taskChildrenProgressBarSegmentInProgress_zc70q_1708",gb="_taskChildrenProgressBarSegmentBlocked_zc70q_1714",yb="_taskChildrenProgressText_zc70q_1720",kb="_taskChildUnlinkBtn_zc70q_1729",Sb="_aboutText_zc70q_1747",vb="_versionInfo_zc70q_1754",wb="_filterBar_zc70q_1762",bb="_kanbanHintText_zc70q_1776",_b="_searchContainer_zc70q_1782",Cb="_searchIcon_zc70q_1789",xb="_searchInput_zc70q_1797",Ab="_searchActive_zc70q_1823",Tb="_searchCount_zc70q_1828",Ib="_clearSearchBtn_zc70q_1844",Nb="_filterRow_zc70q_1866",jb="_sortLabel_zc70q_1872",Rb="_archiveToggle_zc70q_1880",Db="_filterContainer_zc70q_1917",Pb="_filterButton_zc70q_1922",Eb="_filterActive_zc70q_1947",Lb="_filterDropdown_zc70q_1953",Mb="_filterOption_zc70q_1968",Bb="_filterDivider_zc70q_1998",Wb="_filterSelect_zc70q_2004",Fb="_filterToggleBtn_zc70q_2045",zb="_inProgressToggle_zc70q_2067",Ob="_activeInProgress_zc70q_2085",$b="_activeFilter_zc70q_2094",Ub="_resetFiltersBtn_zc70q_2104",qb="_categoryChip_disabled_zc70q_2137",Hb="_categoryVisibilityToggle_zc70q_2147",Gb="_editCategoryInput_zc70q_2160",Vb="_categoryChipActionBtn_zc70q_2171",Zb="_categoryChipActionBtn_active_zc70q_2189",Kb="_categoryGroup_zc70q_2194",Yb="_categoryHeader_zc70q_2202",Jb="_categoryTitle_zc70q_2216",Xb="_categoryCount_zc70q_2226",Qb="_categoryItems_zc70q_2232",e_="_priorityItem_low_zc70q_2241",t_="_priorityItem_medium_zc70q_2245",n_="_priorityItem_high_zc70q_2249",a_="_priorityItem_critical_zc70q_2253",s_="_priorityPill_low_zc70q_2257",r_="_priorityPill_medium_zc70q_2263",o_="_priorityPill_high_zc70q_2269",i_="_priorityPill_critical_zc70q_2275",c_="_selectPriority_low_zc70q_2290",l_="_selectPriority_medium_zc70q_2295",d_="_selectPriority_high_zc70q_2300",u_="_selectPriority_critical_zc70q_2305",p_="_levelSelect_zc70q_2314",m_="_levelOption_zc70q_2327",f_="_levelOptionFilled_zc70q_2344",h_="_levelOption_priority_low_zc70q_2351",g_="_levelOption_priority_medium_zc70q_2356",y_="_levelOption_priority_high_zc70q_2361",k_="_levelOption_priority_critical_zc70q_2366",S_="_levelOption_complexity_tiny_zc70q_2373",v_="_levelOption_complexity_low_zc70q_2378",w_="_levelOption_complexity_medium_zc70q_2383",b_="_levelOption_complexity_high_zc70q_2388",__="_levelOption_complexity_epic_zc70q_2393",C_="_levelOptionActive_zc70q_2400",x_="_levelOptionSelected_zc70q_2405",A_="_levelLabel_zc70q_2413",T_="_fadeIn_zc70q_1",I_="_closeConfigBtn_zc70q_2438",N_="_configItem_zc70q_2460",j_="_settingsLabel_zc70q_2466",R_="_settingsHint_zc70q_2475",D_="_pathList_zc70q_2482",P_="_pathChip_zc70q_2489",E_="_pathValid_zc70q_2502",L_="_pathInvalid_zc70q_2507",M_="_pathValidIcon_zc70q_2512",B_="_pathInvalidIcon_zc70q_2517",W_="_pathText_zc70q_2522",F_="_removePathBtn_zc70q_2529",z_="_pathCount_zc70q_2551",O_="_specialistSection_zc70q_2574",$_="_toggleHeading_zc70q_2582",U_="_dropdownList_zc70q_2622",q_="_specialistBadge_zc70q_2631",H_="_iconGrid_zc70q_2661",G_="_iconPickerBtn_zc70q_2672",V_="_iconPickerBtnActive_zc70q_2691",Z_="_categorySubConfig_zc70q_2698",K_="_colorPickerRow_zc70q_2706",Y_="_colorPickerGrid_zc70q_2712",J_="_colorSwatch_zc70q_2719",X_="_colorSwatchActive_zc70q_2738",Q_="_categoryChipIcon_zc70q_2744",eC="_fieldIconWrapper_zc70q_2749",tC="_fieldIcon_zc70q_2749",nC="_field_dynamic_zc70q_2771",aC="_fieldIcon_dynamic_zc70q_2777",sC="_categoryTitleIcon_zc70q_2781",rC="_editActionsHeader_zc70q_2787",oC="_editActionsGroup_zc70q_2796",iC="_urlInputGroup_zc70q_2803",cC="_iconBtn_zc70q_2816",lC="_stickyActionHeader_zc70q_2837",dC="_taskHierarchyHeader_zc70q_2854",uC="_taskHierarchyBadgeRow_zc70q_2861",pC="_taskHierarchyDivider_zc70q_2869",mC="_taskHierarchyMeta_zc70q_2875",fC="_taskHierarchyAddBtn_zc70q_2888",hC="_taskHierarchyEditor_zc70q_2894",gC="_taskHierarchyInput_zc70q_2901",yC="_taskSaveStatus_zc70q_2910",kC="_taskSaveStatusCenter_zc70q_2921",SC="_taskSaveStatusError_zc70q_2929",vC="_headerSuccessFeedback_zc70q_2933",wC="_slideInUp_zc70q_1",bC="_successCheck_zc70q_2945",_C="_scaleIn_zc70q_1",CC="_primaryUpdateBtn_zc70q_2981",xC="_secondaryHeaderBtn_zc70q_3009",AC="_secondaryHeaderBtnDestructive_zc70q_3030",TC="_commentSection_zc70q_3043",IC="_attachmentCaptureContainer_zc70q_3079",NC="_capturePrompt_zc70q_3087",jC="_previewContainer_zc70q_3101",RC="_previewHeader_zc70q_3107",DC="_attachmentCapturePreview_zc70q_3117",PC="_actions_zc70q_3124",EC="_primaryButton_zc70q_3130",LC="_secondaryButton_zc70q_3145",MC="_iconButton_zc70q_3160",BC="_attachmentGrid_zc70q_3182",WC="_attachmentCard_zc70q_3189",FC="_attachmentPreviewContainer_zc70q_3203",zC="_contextFileLink_zc70q_3224",OC="_attachmentActions_zc70q_3250",$C="_attachmentActionBtn_zc70q_3264",UC="_attachmentCaptionInput_zc70q_3286",qC="_hiddenInput_zc70q_3304",HC="_contextUploadPanel_zc70q_3308",GC="_contextUploadActions_zc70q_3316",VC="_contextDropzone_zc70q_3324",ZC="_contextDropzoneActive_zc70q_3340",KC="_contextDropzonePulse_zc70q_1",YC="_contextLinkRow_zc70q_3348",JC="_contextNotice_zc70q_3354",XC="_documentAttachmentList_zc70q_3360",QC="_documentAttachmentItem_zc70q_3367",ex="_documentAttachmentRow_zc70q_3374",tx="_documentAttachmentLink_zc70q_3382",nx="_documentAttachmentMain_zc70q_3396",ax="_documentAttachmentText_zc70q_3403",sx="_documentAttachmentIcon_zc70q_3411",rx="_documentAttachmentName_zc70q_3422",ox="_documentAttachmentType_zc70q_3431",ix="_documentAttachmentActions_zc70q_3444",cx="_documentAttachmentActionBtn_zc70q_3450",lx="_documentAttachmentCaptionInput_zc70q_3471",dx="_brokenImage_zc70q_3499",ux="_brokenImagePlaceholder_zc70q_3507",px="_regionOverlay_zc70q_3521",mx="_selectionBox_zc70q_3532",fx="_exportRow_zc70q_3540",hx="_exportItem_zc70q_3545",gx="_taxonomyDrillDown_zc70q_3554",yx="_drillDownList_zc70q_3564",kx="_drillDownSection_zc70q_3572",Sx="_drillDownSectionHeader_zc70q_3578",vx="_drillDownSectionTitle_zc70q_3585",wx="_drillDownItem_zc70q_3594",bx="_drillDownItemDimmed_zc70q_3616",_x="_drillDownItemActive_zc70q_3624",Cx="_drillDownItemInfo_zc70q_3629",xx="_drillDownItemText_zc70q_3635",Ax="_drillDownItemLabel_zc70q_3640",Tx="_drillDownItemSubtext_zc70q_3645",Ix="_addTaxonomyBtnSmall_zc70q_3650",Nx="_taxonomyDetailView_zc70q_3672",jx="_slideIn_zc70q_1",Rx="_detailHeader_zc70q_3692",Dx="_detailTitle_zc70q_3701",Px="_detailContent_zc70q_3708",Ex="_createOverlay_zc70q_3715",Lx="_createDialog_zc70q_3727",Mx="_zoomIn_zc70q_1",Bx="_dialogActions_zc70q_3755",Wx="_settingsGroup_zc70q_3773",Fx="_settingsItem_zc70q_3779",zx="_settingLabelGroup_zc70q_3785",Ox="_settingLabel_zc70q_3785",$x="_settingDescription_zc70q_3797",Ux="_settingInput_zc70q_3804",qx="_codeBlockWrapper_zc70q_3827",Hx="_codeHeader_zc70q_3836",Gx="_codeHeaderActions_zc70q_3847",Vx="_codeLabel_zc70q_3854",Zx="_copyBtn_zc70q_3877",Kx="_copyBtnActive_zc70q_3898",Yx="_copyBtnNeutralActive_zc70q_3904",Jx="_headerDivider_zc70q_3922",Xx="_groupByContainer_zc70q_3928",Qx="_groupByLabel_zc70q_3936",eA="_groupBySelect_zc70q_3941",tA="_viewSwitcher_zc70q_3963",nA="_selectWithIcon_zc70q_3971",aA="_marginBottom16_zc70q_3975",sA="_headerDraggable_zc70q_3980",rA="_headerDragging_zc70q_3984",oA="_filterSelectSort_zc70q_3992",iA="_archiveRow_zc70q_3996",cA="_taskScopeToggle_zc70q_4002",lA="_taskScopeTabs_zc70q_4010",dA="_taskScopeTab_zc70q_4010",uA="_taskScopeTabActive_zc70q_4043",pA="_taskToolbarAction_zc70q_4055",mA="_overlayHighZ_zc70q_4071",fA="_savedText_zc70q_4081",hA="_shortcutInput_zc70q_1434",gA="_saveSettingsBtnWrapper_zc70q_4089",yA="_marginBottom12_zc70q_4093",kA="_exportRowGrid_zc70q_4097",SA="_settingSubtitleCustom_zc70q_4102",vA="_capitalize_zc70q_4108",wA="_marginTop12_zc70q_4112",bA="_marginTop16_zc70q_4116",_A="_labelGroupFlex_zc70q_4120",CA="_codeBlockWrapperCustom_zc70q_4126",xA="_kanbanWrapper_zc70q_4132",AA="_kanbanContainer_zc70q_4140",TA="_kanbanTopScroll_zc70q_4162",IA="_kanbanTopScrollSpacer_zc70q_4171",NA="_kanbanColumn_zc70q_4175",jA="_kanbanColumnSticky_zc70q_4191",RA="_kanbanColumnCollapsed_zc70q_4197",DA="_kanbanColumnPast_zc70q_4202",PA="_kanbanColumnSelectedDay_zc70q_4207",EA="_kanbanHeader_zc70q_4214",LA="_kanbanCount_zc70q_4224",MA="_kanbanHeaderDraggable_zc70q_4244",BA="_kanbanHeaderPanning_zc70q_4248",WA="_kanbanQuickAdd_zc70q_4252",FA="_kanbanColorDot_zc70q_4273",zA="_kanbanDroppable_zc70q_4285",OA="_kanbanDroppableScroll_zc70q_4294",$A="_kanbanEmpty_zc70q_4304",UA="_kanbanCard_zc70q_4314",qA="_kanbanCardWrapper_zc70q_4324",HA="_taxonomyDropdownActive_zc70q_4332",GA="_kanbanCardWrapperRaised_zc70q_4336",VA="_kanbanCardTitle_zc70q_4340",ZA="_kanbanBadges_zc70q_4344",KA="_kanbanBadge_zc70q_4344",YA="_headerFlex_zc70q_4360",JA="_marginBottom8_zc70q_4367",XA="_marginBottom20_zc70q_4371",QA="_configPanel_zc70q_4375",eT="_configPanelLarge_zc70q_4384",tT="_subLabelBlock_zc70q_4388",nT="_subLabelBlock12_zc70q_4395",aT="_flexBetween_zc70q_4399",sT="_flexBetweenCenter_zc70q_4406",rT="_deleteBtnSmall_zc70q_4411",oT="_deleteBtnMedium_zc70q_4417",iT="_trashIcon_zc70q_4424",cT="_gridConfig_zc70q_4428",lT="_flexColGap4_zc70q_4435",dT="_flexColGap4Center_zc70q_4441",uT="_flex1_zc70q_4448",pT="_flexCol_zc70q_4435",mT="_flexGrow1_zc70q_4458",fT="_inputLabel_zc70q_4462",hT="_inputLabelBlock_zc70q_4466",gT="_checkboxInput_zc70q_4472",yT="_configDividerMargin_zc70q_4478",kT="_configDividerMargin24_zc70q_4483",ST="_pathListMargin_zc70q_4488",vT="_cancelBtnRed_zc70q_4492",wT="_code_zc70q_1653",bT="_workflowList_zc70q_4519",_T="_workflowActions_zc70q_4527",CT="_textBtn_zc70q_4536",xT="_workflowGrid_zc70q_4550",AT="_checkboxLabel_zc70q_4558",TT="_checkboxSmall_zc70q_4572",IT="_docWorkspace_zc70q_4585",NT="_docIndexPanel_zc70q_4594",jT="_docSpinning_zc70q_4606",RT="_docSpin_zc70q_4606",DT="_docViewerPanel_zc70q_4617",PT="_docViewerEmpty_zc70q_4625",ET="_marginTop24_zc70q_4640",LT="_settingSubTitle_zc70q_4644",MT="_dangerBtn_zc70q_4653",BT="_aiProfilesExplorer_zc70q_4669",WT="_aiProfilesListPane_zc70q_4676",FT="_aiProfilesList_zc70q_4676",zT="_aiProfilesSection_zc70q_4686",OT="_aiProfilesSectionHeader_zc70q_4692",$T="_aiProfileGroup_zc70q_4700",UT="_aiProfileGroupSelected_zc70q_4719",qT="_aiProfileGroupDuplicate_zc70q_4728",HT="_aiProfileGroupHeader_zc70q_4733",GT="_aiProfileName_zc70q_4741",VT="_aiProfileMetaRow_zc70q_4746",ZT="_aiProfileSurfaceBadge_zc70q_4756",KT="_aiProfileDuplicateBadge_zc70q_4766",YT="_aiProfileMergeSection_zc70q_4778",JT="_aiProfileMergeRow_zc70q_4785",XT="_aiProfileIdChip_zc70q_4792",QT="_aiProfileKeepBadge_zc70q_4804",eI="_aiProfileMergeActions_zc70q_4818",tI="_aiProfileDetailPane_zc70q_4825",nI="_aiProfileDetailCard_zc70q_4830",aI="_aiProfileDetailHero_zc70q_4839",sI="_aiProfileDetailIcon_zc70q_4845",rI="_aiProfileDetailHeading_zc70q_4859",oI="_aiProfileDetailTitleRow_zc70q_4864",iI="_aiProfileDetailTitle_zc70q_4864",cI="_aiProfileDetailMetaRow_zc70q_4878",lI="_aiProfileDetailHandle_zc70q_4886",dI="_aiProfileDetailSectionBadge_zc70q_4891",uI="_aiProfileDetailLinkedCount_zc70q_4905",pI="_aiProfileDetailDescription_zc70q_4910",mI="_aiProfileDetailGrid_zc70q_4917",fI="_aiProfileDetailStat_zc70q_4924",hI="_aiProfileDetailStatLabel_zc70q_4937",gI="_aiProfileDetailStatValue_zc70q_4947",yI="_aiProfileInstanceSection_zc70q_4954",kI="_aiProfileInstanceSectionHeader_zc70q_4960",SI="_aiProfileInstanceList_zc70q_4970",vI="_aiProfileInstanceCard_zc70q_4976",wI="_aiProfileInstanceTopRow_zc70q_4988",bI="_aiProfileInstanceName_zc70q_4995",_I="_aiProfileInstanceMeta_zc70q_5002",u={filterGlow:bS,floatingButton:_S,badge:CS,configBadge:xS,configBadgeActive:AS,configBadgeRevoked:TS,configBadgeExpired:IS,header:NS,headerTitle:jS,brandIcon:RS,brandCloudSuffix:DS,projectSlash:PS,projectName:ES,taskCountBadge:LS,headerActions:MS,sortDirectionBtn:BS,sortDirectionBtnWidget:WS,form:FS,topRow:zS,field:OS,labelRow:$S,label:US,manageLink:qS,input:HS,select:GS,textarea:VS,taskIdInlineLink:ZS,readOnly:KS,selectWithConfig:YS,configBtn:JS,configBtnActive:XS,hasPath:QS,pathIndicator:ev,formActions:tv,hasCancel:nv,submitBtn:av,cancelBtn:sv,successMessage:rv,successIcon:ov,spinner:iv,spin:cv,boardRefreshIndicator:lv,destructiveBtn:dv,warningBtn:uv,viewTab:pv,deleteBtn:mv,loading:fv,emptyState:hv,taskList:gv,taskIdBadge:yv,taskIdBadgeLabel:kv,copiedId:Sv,highlight:vv,modal:wv,priorityEmoji:bv,metaItem:_v,taskFormDateInput:Cv,metaBadge:xv,complexityPill:Av,complexityDots:Tv,dot:Iv,dotFilled:Nv,typePill:jv,type_bug:Rv,type_feature:Dv,type_chore:Pv,type_refactor:Ev,type_documentation:Lv,type_research:Mv,"type_ui-ux":"_type_ui-ux_zc70q_759",type_security:Bv,approachPill:Wv,approach_evaluate:Fv,approach_collaborate:zv,approach_plan:Ov,approachActive:$v,statusActionsGroup:Uv,statusActionsGroupCompact:qv,statusSelectWrap:Hv,statusTaxonomyDropdownWrap:Gv,statusTaxonomyDropdown:Vv,statusTaxonomyDropdownCompact:Zv,statusTaxonomyDropdownIconOnly:Kv,taxonomyDropdownButton:Yv,taxonomyDropdownButtonContent:Jv,statusTaxonomyDropdownIconOnlyPanel:Xv,actionBtn:Qv,startWorkBtn:ew,workingBtn:tw,pulse:nw,reviewBtn:aw,reviewActiveBtn:sw,reviewPill:rw,archiveTaskBtn:ow,bulkArchiveBtn:iw,bulkDeleteBtn:cw,completeBtn:lw,completeActiveBtn:dw,deleteActiveBtn:uw,disabledBtn:pw,archiveList:mw,archiveHeader:fw,settingsTab:hw,settingsTabs:gw,settingsLayout:yw,settingsSidebar:kw,settingsSidebarHeader:Sw,settingsSidebarNav:vw,settingsSidebarBtn:ww,settingsSidebarBtnActive:bw,settingsSidebarGroup:_w,settingsSidebarGroupBtn:Cw,settingsSidebarGroupLabel:xw,settingsSidebarGroupChevron:Aw,settingsSidebarSubnav:Tw,settingsSidebarSubBtn:Iw,appScrollbar:Nw,settingsTabBtn:jw,settingsTabBtnActive:Rw,settingsContent:Dw,settingsToast:Pw,settingsToastSuccess:Ew,settingsToastError:Lw,inputWithPrefix:Mw,pathHint:Bw,settingGroup:Ww,settingTitle:Fw,settingTitleRow:zw,settingTitleActionBtn:Ow,themeOptions:$w,buttonGrid:Uw,themeBtn:qw,activeTheme:Hw,pathInputGroup:Gw,saveSettingsBtn:Vw,shortcutInputWrapper:Zw,inputIcon:Kw,settingHelper:Yw,browseBtn:Jw,inlineCategoryManager:Xw,categoryManager:Qw,categoryList:eb,categoryChip:tb,categoryChipLabel:nb,chipActionBtn:ab,removeCategoryBtn:sb,addCategoryForm:rb,addCategoryBtn:ob,filesList:ib,helpLink:cb,inlineCode:lb,codeBlock:db,taskChildrenSummaryBadges:ub,taskChildrenProgressBar:pb,taskChildrenProgressBarSegmentDone:mb,taskChildrenProgressBarSegmentReview:fb,taskChildrenProgressBarSegmentInProgress:hb,taskChildrenProgressBarSegmentBlocked:gb,taskChildrenProgressText:yb,taskChildUnlinkBtn:kb,aboutText:Sb,versionInfo:vb,filterBar:wb,kanbanHintText:bb,searchContainer:_b,searchIcon:Cb,searchInput:xb,searchActive:Ab,searchCount:Tb,clearSearchBtn:Ib,filterRow:Nb,sortLabel:jb,archiveToggle:Rb,filterContainer:Db,filterButton:Pb,filterActive:Eb,filterDropdown:Lb,filterOption:Mb,filterDivider:Bb,filterSelect:Wb,filterToggleBtn:Fb,inProgressToggle:zb,activeInProgress:Ob,activeFilter:$b,resetFiltersBtn:Ub,categoryChip_disabled:qb,categoryVisibilityToggle:Hb,editCategoryInput:Gb,categoryChipActionBtn:Vb,categoryChipActionBtn_active:Zb,categoryGroup:Kb,categoryHeader:Yb,categoryTitle:Jb,categoryCount:Xb,categoryItems:Qb,priorityItem_low:e_,priorityItem_medium:t_,priorityItem_high:n_,priorityItem_critical:a_,priorityPill_low:s_,priorityPill_medium:r_,priorityPill_high:o_,priorityPill_critical:i_,selectPriority_low:c_,selectPriority_medium:l_,selectPriority_high:d_,selectPriority_critical:u_,"critical-glow":"_critical-glow_zc70q_1",levelSelect:p_,levelOption:m_,levelOptionFilled:f_,levelOption_priority_low:h_,levelOption_priority_medium:g_,levelOption_priority_high:y_,levelOption_priority_critical:k_,levelOption_complexity_tiny:S_,levelOption_complexity_low:v_,levelOption_complexity_medium:w_,levelOption_complexity_high:b_,levelOption_complexity_epic:__,levelOptionActive:C_,levelOptionSelected:x_,levelLabel:A_,fadeIn:T_,closeConfigBtn:I_,configItem:N_,settingsLabel:j_,settingsHint:R_,pathList:D_,pathChip:P_,pathValid:E_,pathInvalid:L_,pathValidIcon:M_,pathInvalidIcon:B_,pathText:W_,removePathBtn:F_,pathCount:z_,specialistSection:O_,toggleHeading:$_,dropdownList:U_,specialistBadge:q_,iconGrid:H_,iconPickerBtn:G_,iconPickerBtnActive:V_,categorySubConfig:Z_,colorPickerRow:K_,colorPickerGrid:Y_,colorSwatch:J_,colorSwatchActive:X_,categoryChipIcon:Q_,fieldIconWrapper:eC,fieldIcon:tC,field_dynamic:nC,fieldIcon_dynamic:aC,categoryTitleIcon:sC,editActionsHeader:rC,editActionsGroup:oC,urlInputGroup:iC,iconBtn:cC,stickyActionHeader:lC,taskHierarchyHeader:dC,taskHierarchyBadgeRow:uC,taskHierarchyDivider:pC,taskHierarchyMeta:mC,taskHierarchyAddBtn:fC,taskHierarchyEditor:hC,taskHierarchyInput:gC,taskSaveStatus:yC,taskSaveStatusCenter:kC,taskSaveStatusError:SC,headerSuccessFeedback:vC,slideInUp:wC,successCheck:bC,scaleIn:_C,primaryUpdateBtn:CC,secondaryHeaderBtn:xC,secondaryHeaderBtnDestructive:AC,commentSection:TC,attachmentCaptureContainer:IC,capturePrompt:NC,previewContainer:jC,previewHeader:RC,attachmentCapturePreview:DC,actions:PC,primaryButton:EC,secondaryButton:LC,iconButton:MC,attachmentGrid:BC,attachmentCard:WC,attachmentPreviewContainer:FC,contextFileLink:zC,attachmentActions:OC,attachmentActionBtn:$C,attachmentCaptionInput:UC,hiddenInput:qC,contextUploadPanel:HC,contextUploadActions:GC,contextDropzone:VC,contextDropzoneActive:ZC,contextDropzonePulse:KC,contextLinkRow:YC,contextNotice:JC,documentAttachmentList:XC,documentAttachmentItem:QC,documentAttachmentRow:ex,documentAttachmentLink:tx,documentAttachmentMain:nx,documentAttachmentText:ax,documentAttachmentIcon:sx,documentAttachmentName:rx,documentAttachmentType:ox,documentAttachmentActions:ix,documentAttachmentActionBtn:cx,documentAttachmentCaptionInput:lx,brokenImage:dx,brokenImagePlaceholder:ux,regionOverlay:px,selectionBox:mx,exportRow:fx,exportItem:hx,taxonomyDrillDown:gx,drillDownList:yx,drillDownSection:kx,drillDownSectionHeader:Sx,drillDownSectionTitle:vx,drillDownItem:wx,drillDownItemDimmed:bx,drillDownItemActive:_x,drillDownItemInfo:Cx,drillDownItemText:xx,drillDownItemLabel:Ax,drillDownItemSubtext:Tx,addTaxonomyBtnSmall:Ix,taxonomyDetailView:Nx,slideIn:jx,detailHeader:Rx,detailTitle:Dx,detailContent:Px,createOverlay:Ex,createDialog:Lx,zoomIn:Mx,dialogActions:Bx,settingsGroup:Wx,settingsItem:Fx,settingLabelGroup:zx,settingLabel:Ox,settingDescription:$x,settingInput:Ux,codeBlockWrapper:qx,codeHeader:Hx,codeHeaderActions:Gx,codeLabel:Vx,copyBtn:Zx,copyBtnActive:Kx,copyBtnNeutralActive:Yx,headerDivider:Jx,groupByContainer:Xx,groupByLabel:Qx,groupBySelect:eA,viewSwitcher:tA,selectWithIcon:nA,marginBottom16:aA,headerDraggable:sA,headerDragging:rA,filterSelectSort:oA,archiveRow:iA,taskScopeToggle:cA,taskScopeTabs:lA,taskScopeTab:dA,taskScopeTabActive:uA,taskToolbarAction:pA,overlayHighZ:mA,savedText:fA,shortcutInput:hA,saveSettingsBtnWrapper:gA,marginBottom12:yA,exportRowGrid:kA,settingSubtitleCustom:SA,capitalize:vA,marginTop12:wA,marginTop16:bA,labelGroupFlex:_A,codeBlockWrapperCustom:CA,kanbanWrapper:xA,kanbanContainer:AA,kanbanTopScroll:TA,kanbanTopScrollSpacer:IA,kanbanColumn:NA,kanbanColumnSticky:jA,kanbanColumnCollapsed:RA,kanbanColumnPast:DA,kanbanColumnSelectedDay:PA,kanbanHeader:EA,kanbanCount:LA,kanbanHeaderDraggable:MA,kanbanHeaderPanning:BA,kanbanQuickAdd:WA,kanbanColorDot:FA,kanbanDroppable:zA,kanbanDroppableScroll:OA,kanbanEmpty:$A,kanbanCard:UA,kanbanCardWrapper:qA,taxonomyDropdownActive:HA,kanbanCardWrapperRaised:GA,kanbanCardTitle:VA,kanbanBadges:ZA,kanbanBadge:KA,headerFlex:YA,marginBottom8:JA,marginBottom20:XA,configPanel:QA,configPanelLarge:eT,subLabelBlock:tT,subLabelBlock12:nT,flexBetween:aT,flexBetweenCenter:sT,deleteBtnSmall:rT,deleteBtnMedium:oT,trashIcon:iT,gridConfig:cT,flexColGap4:lT,flexColGap4Center:dT,flex1:uT,flexCol:pT,flexGrow1:mT,inputLabel:fT,inputLabelBlock:hT,checkboxInput:gT,configDividerMargin:yT,configDividerMargin24:kT,pathListMargin:ST,cancelBtnRed:vT,code:wT,workflowList:bT,workflowActions:_T,textBtn:CT,workflowGrid:xT,checkboxLabel:AT,checkboxSmall:TT,docWorkspace:IT,docIndexPanel:NT,docSpinning:jT,docSpin:RT,docViewerPanel:DT,docViewerEmpty:PT,marginTop24:ET,settingSubTitle:LT,dangerBtn:MT,aiProfilesExplorer:BT,aiProfilesListPane:WT,aiProfilesList:FT,aiProfilesSection:zT,aiProfilesSectionHeader:OT,aiProfileGroup:$T,aiProfileGroupSelected:UT,aiProfileGroupDuplicate:qT,aiProfileGroupHeader:HT,aiProfileName:GT,aiProfileMetaRow:VT,aiProfileSurfaceBadge:ZT,aiProfileDuplicateBadge:KT,aiProfileMergeSection:YT,aiProfileMergeRow:JT,aiProfileIdChip:XT,aiProfileKeepBadge:QT,aiProfileMergeActions:eI,aiProfileDetailPane:tI,aiProfileDetailCard:nI,aiProfileDetailHero:aI,aiProfileDetailIcon:sI,aiProfileDetailHeading:rI,aiProfileDetailTitleRow:oI,aiProfileDetailTitle:iI,aiProfileDetailMetaRow:cI,aiProfileDetailHandle:lI,aiProfileDetailSectionBadge:dI,aiProfileDetailLinkedCount:uI,aiProfileDetailDescription:pI,aiProfileDetailGrid:mI,aiProfileDetailStat:fI,aiProfileDetailStatLabel:hI,aiProfileDetailStatValue:gI,aiProfileInstanceSection:yI,aiProfileInstanceSectionHeader:kI,aiProfileInstanceList:SI,aiProfileInstanceCard:vI,aiProfileInstanceTopRow:wI,aiProfileInstanceName:bI,aiProfileInstanceMeta:_I},CI="_standaloneWrapper_1mq9f_1",xI="_standalonePage_1mq9f_11",AI="_standaloneHeader_1mq9f_21",TI="_standaloneTitle_1mq9f_27",II="_standaloneContent_1mq9f_31",NI="_workspaceToolRail_1mq9f_37",jI="_workspaceToolRailMain_1mq9f_54",RI="_workspaceToolRailBottom_1mq9f_62",DI="_workspaceToolRailDivider_1mq9f_72",PI="_workspaceToolButton_1mq9f_79",EI="_workspaceToolButtonActive_1mq9f_99",LI="_headerTitleWidget_1mq9f_123",hn={standaloneWrapper:CI,standalonePage:xI,standaloneHeader:AI,standaloneTitle:TI,standaloneContent:II,workspaceToolRail:NI,workspaceToolRailMain:jI,workspaceToolRailBottom:RI,workspaceToolRailDivider:DI,workspaceToolButton:PI,workspaceToolButtonActive:EI,headerTitleWidget:LI},MI="_overlay_11v7l_1",BI="_browser_11v7l_16",WI="_header_11v7l_27",FI="_pathInfo_11v7l_36",zI="_actions_11v7l_52",OI="_list_11v7l_57",$I="_item_11v7l_63",UI="_itemCurrent_11v7l_80",qI="_itemFile_11v7l_86",HI="_empty_11v7l_90",zn={overlay:MI,browser:BI,header:WI,pathInfo:FI,actions:zI,list:OI,item:$I,itemCurrent:UI,itemFile:qI,empty:HI},GI="_overlay_1hhtx_2",VI="_overlayHighZ_1hhtx_15",ZI="_modal_1hhtx_20",KI="_draggableModal_1hhtx_46",YI="_draggableHeader_1hhtx_53",JI="_headerActions_1hhtx_61",XI="_modalContent_1hhtx_69",QI="_form_1hhtx_78",e0="_formActions_1hhtx_89",t0="_modalFooter_1hhtx_96",n0="_modalSizeSm_1hhtx_102",a0="_modalSizeMd_1hhtx_106",s0="_modalSizeLg_1hhtx_110",r0="_modalSizeXl_1hhtx_114",o0="_modalSizeFull_1hhtx_118",i0="_settingsViewModal_1hhtx_123",c0="_unsavedOverlay_1hhtx_142",l0="_unsavedModal_1hhtx_147",d0="_unsavedHeader_1hhtx_153",u0="_unsavedTitle_1hhtx_158",p0="_unsavedContent_1hhtx_162",m0="_unsavedText_1hhtx_166",f0="_unsavedActions_1hhtx_171",ut={overlay:GI,overlayHighZ:VI,modal:ZI,draggableModal:KI,draggableHeader:YI,headerActions:JI,modalContent:XI,form:QI,formActions:e0,modalFooter:t0,modalSizeSm:n0,modalSizeMd:a0,modalSizeLg:s0,modalSizeXl:r0,modalSizeFull:o0,settingsViewModal:i0,unsavedOverlay:c0,unsavedModal:l0,unsavedHeader:d0,unsavedTitle:u0,unsavedContent:p0,unsavedText:m0,unsavedActions:f0};function h0(e){const n=e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),s={Category:"Categories",Priority:"Priorities",Status:"Statuses"};return s[n]?s[n]:`${e}s`}function bi({label:e,options:n,selected:s,onChange:r,variant:o="label",containerStyle:l}){const[c,p]=a.useState(!1),g=a.useRef(null);a.useEffect(()=>{const S=W=>{g.current&&!g.current.contains(W.target)&&p(!1)};return document.addEventListener("mousedown",S),()=>document.removeEventListener("mousedown",S)},[]);const w=S=>{s.includes(S)?r(s.filter(W=>W!==S)):r([...s,S])},C=n.length>0&&n.every(S=>{const W=o==="label"?S.label:S.value;return s.includes(W)}),_=!n.some(S=>{const W=o==="label"?S.label:S.value;return s.includes(W)}),y=()=>{r(C?[]:n.map(S=>o==="label"?S.label:S.value))},k=n.filter(S=>{const W=o==="label"?S.label:S.value;return s.includes(W)}).length,b=h0(e),E=C?`All ${b}`:_?`No ${b}`:k===1?`1 ${e}`:`${k} ${b}`;return t.jsxs("div",{className:u.filterContainer,ref:g,style:l,children:[t.jsxs("button",{className:`${u.filterButton} ${C?"":u.filterActive}`,onClick:()=>p(!c),title:`Filter by ${e}`,children:[t.jsx("span",{children:E}),t.jsx(jc,{size:14,style:{transform:c?"rotate(180deg)":"none",transition:"transform 0.2s",opacity:.5}})]}),c&&t.jsxs("div",{className:`${u.filterDropdown} ${u.appScrollbar} tf-scrollbar`,children:[t.jsxs("div",{className:u.filterOption,onClick:y,children:[t.jsx("input",{type:"checkbox",checked:C,onChange:()=>{}}),t.jsx("span",{style:{fontWeight:600},children:"Toggle All"})]}),t.jsx("div",{className:u.filterDivider}),n.map(S=>{const W=o==="label"?S.label:S.value,Q=s.includes(W);return t.jsxs("div",{className:u.filterOption,onClick:()=>w(W),children:[t.jsx("input",{type:"checkbox",checked:Q,onChange:()=>{}}),t.jsx("span",{children:S.label})]},S.value)})]})]})}const g0="_taskItem_x943c_1",y0="_compressed_x943c_20",k0="_taskHeader_x943c_25",S0="_taskReferenceCluster_x943c_30",v0="_taskMeta_x943c_34",w0="_taskTitle_x943c_40",b0="_taskItemRecentlyChanged_x943c_67",_0="_inProgress_x943c_128",C0="_onHold_x943c_139",x0="_readyForReview_x943c_150",A0="_completed_x943c_161",T0="_cancelled_x943c_172",I0="_archived_x943c_183",N0="_taskContent_x943c_193",j0="_kanbanCardOverlay_x943c_202",R0="_taskReferenceText_x943c_241",D0="_taskReferenceDivider_x943c_250",P0="_taskActions_x943c_257",E0="_taskMetaCompact_x943c_282",L0="_taskMetaRow_x943c_289",M0="_taskMetaBadgeGroup_x943c_297",B0="_taskDescription_x943c_303",W0="_taskLatestComment_x943c_362",F0="_taskCancellationReason_x943c_383",z0="_archiveBadge_x943c_537",O0="_attachmentThumbnails_x943c_542",$0="_attachmentImageRow_x943c_549",U0="_attachmentDocumentList_x943c_556",q0="_attachmentThumbnail_x943c_542",H0="_contextDocThumb_x943c_589",G0="_contextDocMain_x943c_615",V0="_contextDocText_x943c_622",Z0="_contextDocIcon_x943c_630",K0="_contextDocName_x943c_641",Y0="_contextDocType_x943c_651",J0="_taskSpecialists_x943c_663",X0="_taxonomiesList_x943c_672",Vt={taskItem:g0,compressed:y0,taskHeader:k0,taskReferenceCluster:S0,taskMeta:v0,taskTitle:w0,taskItemRecentlyChanged:b0,inProgress:_0,onHold:C0,readyForReview:x0,completed:A0,cancelled:T0,archived:I0,taskContent:N0,kanbanCardOverlay:j0,taskReferenceText:R0,taskReferenceDivider:D0,taskActions:P0,taskMetaCompact:E0,taskMetaRow:L0,taskMetaBadgeGroup:M0,taskDescription:B0,taskLatestComment:W0,taskCancellationReason:F0,archiveBadge:z0,attachmentThumbnails:O0,attachmentImageRow:$0,attachmentDocumentList:U0,attachmentThumbnail:q0,contextDocThumb:H0,contextDocMain:G0,contextDocText:V0,contextDocIcon:Z0,contextDocName:K0,contextDocType:Y0,taskSpecialists:J0,taxonomiesList:X0},Np=({children:e,className:n,onTaskIdClick:s})=>{if(!e)return null;const r=c=>pt.Children.toArray(c).some(g=>pt.isValidElement(g)?String(g.props?.className||"").includes("task-list-item"):!1),o=/\b(task-\d{10,}-[a-z0-9]+)\b/gi,l=c=>{if(!s)return c;if(typeof c=="string"){const w=Array.from(c.matchAll(o));if(!w.length)return c;const C=[];let _=0;for(let y=0;y<w.length;y+=1){const k=w[y],b=k[1],E=k.index??-1;E<_||(E>_&&C.push(c.slice(_,E)),C.push(t.jsx("button",{type:"button",className:u.taskIdInlineLink,onClick:S=>{S.preventDefault(),S.stopPropagation(),s(b)},children:b},`${b}-${E}-${y}`)),_=E+b.length)}return _<c.length&&C.push(c.slice(_)),C}if(Array.isArray(c))return c.map(l);if(!pt.isValidElement(c))return c;const p=typeof c.type=="string"?c.type:"";if(p==="code"||p==="pre"||p==="a")return c;const g=c.props?.children;return g===void 0?c:pt.cloneElement(c,{},pt.Children.map(g,l))};return t.jsx("div",{className:n,children:t.jsx(Sg,{remarkPlugins:[vg,wg],components:{p:({children:c})=>t.jsx("p",{children:l(c)}),ul:({children:c})=>t.jsx("ul",{style:r(c)?{paddingLeft:0}:void 0,children:c}),li:({children:c,className:p})=>{const g=String(p||"").includes("task-list-item");return t.jsx("li",{className:p,style:g?{listStyle:"none"}:void 0,children:l(c)})},input:({type:c,checked:p})=>c!=="checkbox"?t.jsx("input",{type:c,checked:p,readOnly:!0}):t.jsx("input",{type:"checkbox",checked:!!p,readOnly:!0,style:{cursor:"default",marginRight:8}}),code:({children:c,className:p,...g})=>{const w=String(c||"").replace(/\n$/,"");return/language-(\w+)/.test(p||"")||w.includes(`
3
+ `)?t.jsx("pre",{className:u.codeBlock,children:t.jsx("code",{className:p,...g,children:w})}):t.jsx("code",{className:u.inlineCode,...g,children:w})}},children:e})})};function Zf({label:e,title:n,ariaLabel:s,copied:r=!1,disabled:o=!1,className:l="",onClick:c,children:p}){return t.jsxs("button",{type:"button",className:`${u.taskIdBadge} ${r?u.copiedId:""} ${l}`.trim(),onClick:c,disabled:o,title:n,"aria-label":s,children:[r?t.jsx(so,{size:13}):t.jsx(Ll,{size:13}),t.jsx("span",{className:u.taskIdBadgeLabel,children:p??e})]})}function eu({copied:e,disabled:n=!1,label:s,onClick:r,title:o="Copy task reference",ariaLabel:l,className:c=""}){return t.jsx(Zf,{copied:e,disabled:n,label:"",onClick:r,title:o,ariaLabel:l,className:c,children:s})}const Q0=(e,n=10)=>{const s=du[e?.toLowerCase()]||{icon:"FileCode"},r=$s[s.icon]||Vh;return t.jsx(r,{size:n})},Jd=(e,n)=>{if(!e)return null;if(!n.trim())return e;const s=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=e.split(new RegExp(`(${s})`,"gi"));return t.jsx(t.Fragment,{children:r.map((o,l)=>o.toLowerCase()===n.toLowerCase()?t.jsx("mark",{className:u.highlight,children:o},l):o)})};function $l(e){return e.trim().replace(/\\/g,"/")}function Kf(e){return e.split("?")[0].split("#")[0]}function Su(e){return typeof e=="string"?e:String(e.path||"").trim()}function Yf(e){const s=Kf($l(e)).match(/\/api\/taskforce\/documents\/([^/]+)\/content$/i);if(!s?.[1])return null;try{return decodeURIComponent(s[1]).trim()||null}catch{return s[1].trim()||null}}function Jf(e){if(!e.includes("/api/taskforce/context-link?path="))return null;try{const s=new URL(e,window.location.origin).searchParams.get("path");return s?$l(s):null}catch{return null}}function eN(e,n){const s=(n||(typeof e=="string"?"":e.fsPath||"")).trim();if(s)return $l(s);const r=Su(e),o=Jf(r);return o?$l(o):null}function tN(e,n){const s=String(typeof e=="string"?"":e.assetId||"").trim();if(s)return s;const r=Su(e);return Yf(r)}function nN(e,n){const s=Su(e);return Yf(s)?!0:[(n||(typeof e=="string"?"":e.fsPath||"")).trim(),typeof e=="string"?"":String(e.originalFilename||"").trim(),typeof e=="string"?"":String(e.displayName||"").trim(),typeof e=="string"?"":String(e.caption||"").trim(),Jf(s)||"",s].some(o=>{if(!o)return!1;const l=Kf($l(o)).toLowerCase();return l.endsWith(".md")||l.endsWith(".markdown")})}function jp(e,n){const s=Su(e),r=eN(e,n);if(!r||!nN(e,r))return!1;const o=tN(e),l=new CustomEvent("taskforce:open-markdown-document",{detail:{path:s,fsPath:r,...o?{assetId:o}:{}},cancelable:!0});return!window.dispatchEvent(l)}const aN="I-";function Xf(e){return Hl(aN,e)}function sN(e){return e.trim().replace(/\\/g,"/")}function Qf(e){return typeof e=="string"?e:String(e.path||"").trim()}function rN(e){return/\.(png|jpe?g|webp)(\?|#|$)/i.test(e)}function oN(e){return typeof e=="string"?sN(e).split("/").pop()||"Image attachment":String(e.caption||e.displayName||e.originalFilename||e.fsPath||e.path.split("/").pop()||"Image attachment").trim()}function eh(e,n){if(typeof e=="string")return!1;const s=String(e.assetId||"").trim(),r=Qf(e);return!!(s&&r&&rN(r))}function Rp(e,n){if(!eh(e))return!1;const s=e,r=String(n?.taskId||s.taskId||"").trim(),o=String(n?.taskReferenceLabel||"").trim(),l=String(s.assetId||"").trim(),c=Xf(s),p=Qf(e),g=new CustomEvent("taskforce:open-annotated-attachment",{detail:{...r?{taskId:r}:{},...o?{taskReferenceLabel:o}:{},assetId:l,...c?{imageReferenceLabel:c}:{},path:p,displayName:oN(e)},cancelable:!0});return!window.dispatchEvent(g)}function Em(e,n){if(!e)return null;const s=String(e.taskId||"").trim(),r=String(e.assetId||"").trim(),o=String(e.path||"").trim(),l=String(e.displayName||"").trim()||"Image attachment";if(!r||!o)return null;const c=String(e.taskReferenceLabel||"").trim(),p=s?n.find(w=>w.id===s):void 0,g=s?c||Rr(p)||s:void 0;return{...s?{taskId:s}:{},...g?{taskReferenceLabel:g}:{},assetId:r,imageReferenceLabel:String(e.imageReferenceLabel||"").trim()||void 0,path:o,displayName:l}}function pu(e){const n=String(e||"").trim().replace(/\\/g,"/");if(!n)return"";const s=n.split("/").filter(Boolean);return s[s.length-1]||""}function Vp(e){const n=String(e||"").trim(),s=n.lastIndexOf(".");return s<=0?{stem:n,ext:""}:{stem:n.slice(0,s),ext:n.slice(s)}}function th(e,n){const s=String(e||"").trim(),r=String(n||"").trim();return s?r&&s.startsWith(`${r}-`)?s.slice(r.length+1):s.replace(/^asset-[a-z0-9-]+-/i,""):""}function iN(e){return String(e||"").replace(/-\d{13,}$/g,"").replace(/[_-]+/g," ").replace(/\s+/g," ").trim()}function Lm(e,n){const{stem:s,ext:r}=Vp(pu(e)),o=th(s,n),l=iN(o||s);return l?`${l}${r}`:pu(e)||"Untitled document"}function dp(e,n){const s=String(e||"").trim();if(!s)return!0;const r=pu(s),{stem:o}=Vp(r),l=String(n||"").trim();if(l&&o.toLowerCase()===l.toLowerCase())return!0;const c=th(o,n);return c?c!==o:!0}function cN(e){const n=String(e.logicalName||"").trim();if(n&&!dp(n,e.assetId))return n;const s=String(e.displayName||"").trim();if(s&&!dp(s,e.assetId))return s;const r=String(e.title||"").trim();if(r&&!dp(r,e.assetId))return r;const o=String(e.originalFilename||"").trim();if(o)return Lm(o,e.assetId);const l=String(e.fsPath||"").trim();return l?Lm(l,e.assetId):"Untitled document"}function lN(e){return cN(e)}function dN(e){const n=lN(e),s=String(e.originalFilename||e.fsPath||"").trim(),r=Vp(pu(s)).ext;return r?n.toLowerCase().endsWith(r.toLowerCase())?n:`${n}${r}`:n}const uN="_taxonomyDropdown_tt12a_1",pN="_taxonomyDropdownActive_tt12a_6",mN="_taxonomyDropdownButton_tt12a_11",fN="_taxonomyDropdownOpen_tt12a_50",hN="_taxonomyDropdownButtonContent_tt12a_56",gN="_taxonomyDropdownIcon_tt12a_64",yN="_taxonomyDropdownLabel_tt12a_72",kN="_taxonomyDropdownChevron_tt12a_81",SN="_taxonomyDropdownChevronOpen_tt12a_87",vN="_taxonomyDropdownPanel_tt12a_91",wN="_taxonomyDropdownPanelPortal_tt12a_110",bN="_taxonomyDropdownOption_tt12a_129",_N="_taxonomyDropdownOptionHighlighted_tt12a_157",CN="_taxonomyDropdownOptionSelected_tt12a_163",Za={taxonomyDropdown:uN,taxonomyDropdownActive:pN,taxonomyDropdownButton:mN,taxonomyDropdownOpen:fN,taxonomyDropdownButtonContent:hN,taxonomyDropdownIcon:gN,taxonomyDropdownLabel:yN,taxonomyDropdownChevron:kN,taxonomyDropdownChevronOpen:SN,taxonomyDropdownPanel:vN,taxonomyDropdownPanelPortal:wN,taxonomyDropdownOption:bN,taxonomyDropdownOptionHighlighted:_N,taxonomyDropdownOptionSelected:CN};function Rl({value:e,options:n,onChange:s,placeholder:r="Select...",required:o=!1,disabled:l=!1,className:c="",ariaLabelledBy:p,ariaLabel:g,hideSelectedLabel:w=!1,hideChevron:C=!1,panelClassName:_="",portalPanel:y=!1,panelMinWidth:k}){const[b,E]=a.useState(!1),[S,W]=a.useState(-1),[Q,z]=a.useState({}),K=a.useRef(null),V=a.useRef(null),ne=a.useRef(null),D=n.find(Y=>String(Y.value)===String(e));a.useEffect(()=>{if(!b)return;const Y=R=>{const B=R.target,fe=!!K.current?.contains(B),Ne=!!ne.current?.contains(B);!fe&&!Ne&&(E(!1),W(-1))};return document.addEventListener("mousedown",Y),()=>document.removeEventListener("mousedown",Y)},[b]),a.useEffect(()=>{if(!b)W(-1);else{const Y=n.findIndex(R=>String(R.value)===String(e));W(Y>=0?Y:0)}},[b,n,e]),a.useEffect(()=>{if(!b||!y)return;const Y=()=>{const R=V.current;if(!R)return;const B=R.getBoundingClientRect(),fe=Math.max(k||0,B.width),Ne=Math.max(8,B.right-fe),de=B.bottom;z({position:"fixed",top:de,left:Ne,minWidth:fe,zIndex:2e3})};return Y(),window.addEventListener("resize",Y),window.addEventListener("scroll",Y,!0),()=>{window.removeEventListener("resize",Y),window.removeEventListener("scroll",Y,!0)}},[b,y,k]);const Ae=()=>{l||E(!b)},U=Y=>{s(Y.value),E(!1),V.current?.focus()},ee=Y=>{if(!l)switch(Y.key){case"Enter":case" ":Y.preventDefault(),b?S>=0&&U(n[S]):E(!0);break;case"Escape":Y.preventDefault(),E(!1),V.current?.focus();break;case"ArrowDown":Y.preventDefault(),b?W(R=>R<n.length-1?R+1:0):E(!0);break;case"ArrowUp":Y.preventDefault(),b?W(R=>R>0?R-1:n.length-1):E(!0);break;case"Home":Y.preventDefault(),b&&W(0);break;case"End":Y.preventDefault(),b&&W(n.length-1);break;case"Tab":E(!1);break}},be=(Y,R)=>{const B=Y.icon&&$s[Y.icon]?$s[Y.icon]:xi,fe=Y.color?_a(Y.color):"var(--text-secondary)",Ne=R?.hideLabel===!0;return t.jsxs(t.Fragment,{children:[t.jsx("span",{className:`taxonomyDropdownIcon ${Za.taxonomyDropdownIcon}`,style:{color:fe},children:t.jsx(B,{size:16})}),!Ne&&t.jsx("span",{className:`taxonomyDropdownLabel ${Za.taxonomyDropdownLabel}`,children:Y.label})]})},me=b?t.jsx("div",{ref:ne,id:`taxonomy-listbox-${r.replace(/\s+/g,"-")}`,className:`taxonomyDropdownPanel ${Za.taxonomyDropdownPanel} ${y?Za.taxonomyDropdownPanelPortal:""} ${_}`,role:"listbox","aria-labelledby":p,"aria-label":g,style:y?Q:void 0,children:n.map((Y,R)=>{const B=String(Y.value)===String(e),fe=R===S;return t.jsx("div",{className:`taxonomyDropdownOption ${Za.taxonomyDropdownOption} ${B?`taxonomyDropdownOptionSelected ${Za.taxonomyDropdownOptionSelected}`:""} ${fe?`taxonomyDropdownOptionHighlighted ${Za.taxonomyDropdownOptionHighlighted}`:""}`,role:"option","aria-selected":B,onClick:()=>U(Y),onMouseEnter:()=>W(R),style:(()=>{const Ne=Y.color,de=_a(Ne),ae=!de||de.startsWith("var("),Ve=ae?"#8b5cf6":de,Re=ae?"20":"30",Ce=ae?"05":"10";return{"--option-color":de||"var(--text-primary)","--option-border":`${Ve}${Re}`,"--option-bg":`${Ve}${Ce}`}})(),children:be(Y)},String(Y.value))})}):null;return t.jsxs("div",{ref:K,className:`taxonomyDropdown ${Za.taxonomyDropdown} ${b?`taxonomyDropdownActive ${Za.taxonomyDropdownActive}`:""} ${c}`,children:[t.jsxs("button",{ref:V,type:"button",className:`taxonomyDropdownButton ${Za.taxonomyDropdownButton} ${b?`taxonomyDropdownOpen ${Za.taxonomyDropdownOpen}`:""}`,onClick:Ae,onKeyDown:ee,disabled:l,role:"combobox","aria-haspopup":"listbox","aria-expanded":b,"aria-controls":`taxonomy-listbox-${r.replace(/\s+/g,"-")}`,"aria-labelledby":p,"aria-label":g,style:(()=>{if(!D)return{};const Y=D.color,R=_a(Y),B=!R||R.startsWith("var("),fe=B?"#8b5cf6":R,Ne=B?"30":"50",de=B?"05":"10";return{"--field-color":R||"var(--text-primary)","--field-border":`${fe}${Ne}`,"--field-bg":`${fe}${de}`}})(),children:[t.jsx("span",{className:`taxonomyDropdownButtonContent ${Za.taxonomyDropdownButtonContent}`,children:D?be(D,{hideLabel:w}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:`taxonomyDropdownIcon ${Za.taxonomyDropdownIcon}`,children:t.jsx(xi,{size:16})}),t.jsx("span",{className:`taxonomyDropdownLabel ${Za.taxonomyDropdownLabel}`,children:r})]})}),!C&&t.jsx(jc,{size:16,className:`taxonomyDropdownChevron ${Za.taxonomyDropdownChevron} ${b?`taxonomyDropdownChevronOpen ${Za.taxonomyDropdownChevronOpen}`:""}`})]}),y?me?Ci.createPortal(me,document.body):null:me]})}function nh({task:e,disabled:n=!1,compressed:s=!1,shortLabels:r=!1,showLabel:o=!0,onSetStatus:l,onArchiveTask:c}){const p=e?.status||"task",g=!!e&&(p==="done"||p==="cancelled"),w=Cc.map(C=>({...C,label:(s||r)&&C.shortLabel||C.label}));return t.jsxs("div",{className:`${u.statusActionsGroup} ${s?u.statusActionsGroupCompact:""}`,children:[g&&t.jsx("button",{type:"button",className:`${u.actionBtn} ${u.archiveTaskBtn}`,onClick:()=>e&&!n&&c?.(e),disabled:n,title:"Archive Now","aria-label":"Archive task",children:t.jsx(Zh,{size:s?12:16})}),t.jsx("div",{className:`${u.statusSelectWrap} ${u.statusTaxonomyDropdownWrap}`,children:t.jsx(Rl,{value:p,options:w,disabled:n||!e,ariaLabel:"Status",hideSelectedLabel:!o,hideChevron:!o,className:`${u.statusTaxonomyDropdown} ${s?u.statusTaxonomyDropdownCompact:""} ${o?"":u.statusTaxonomyDropdownIconOnly}`,panelClassName:o?"":u.statusTaxonomyDropdownIconOnlyPanel,portalPanel:!o,panelMinWidth:o?void 0:144,onChange:C=>{e&&l?.(e,C)}})})]})}function xN(e){return e==="title"?"TITLE":e==="description"?"DESCRIPTION":e==="assignee"?"ASSIGNED TO":e}function Rs(e,n,s){const r=s?.(n,e);if(typeof r=="string")return r;if(e==null||e==="")return"none";if(Array.isArray(e)){const o=e.map(l=>Rs(l,n,s)).filter(Boolean);return o.length>0?o.join(", "):"none"}return typeof e=="object"?"updated":String(e)}function Mm(e){return Array.isArray(e)?e.map((n,s)=>{const r=n&&typeof n=="object"?n:{},o=Number(r.order);return{id:String(r.id||"").trim(),title:String(r.title||"").trim(),isCompleted:!!r.isCompleted,order:Number.isFinite(o)?o:s}}):[]}function AN(e){const n=Mm(e?.from),s=Mm(e?.to),r=new Map(n.map(c=>[c.id||c.title,c])),o=new Map(s.map(c=>[c.id||c.title,c]));for(const[c,p]of o.entries()){const g=r.get(c);if(!g)return p.title?`Checklist item added: ${p.title}`:"Checklist item added";if(g.isCompleted!==p.isCompleted)return p.title?p.isCompleted?`Checklist item completed: ${p.title}`:`Checklist item reopened: ${p.title}`:p.isCompleted?"Checklist item completed":"Checklist item reopened"}for(const[c,p]of r.entries())if(!o.has(c))return p.title?`Checklist item removed: ${p.title}`:"Checklist item removed";return n.length===s.length&&n.every(c=>o.has(c.id||c.title))&&n.some((p,g)=>{const w=s[g];return(p.id||p.title)!==(w?.id||w?.title)})?"Checklist reordered":"Checklist updated"}function ah(e,n,s){if(e==="checklistItems")return AN(n);const r=xN(e);if(e==="title")return`${r}: updated`;if(e==="description"){const o=Rs(n?.from,e,s)!=="none",l=Rs(n?.to,e,s)!=="none";return!o&&l?`${r}: added`:o&&!l?`${r}: cleared`:`${r}: updated`}return`${r}: ${Rs(n?.from,e,s)} -> ${Rs(n?.to,e,s)}`}function sh(e,n){const s=e.details?.changes||{},r=Object.keys(s);if(e.action==="task-created")return"Task created";if(e.action==="task-comment-added")return"Comment added";if(e.action==="task-archived")return"Task marked done";if(e.action==="task-cancelled")return"Task cancelled";if(e.action==="task-unarchived")return"Task restored";if(e.action==="task-status-changed"&&s.status)return`Status: ${Rs(s.status.from,"status",n)} -> ${Rs(s.status.to,"status",n)}`;if(e.action==="task-schedule-changed")return s.scheduledDate?`Scheduled: ${Rs(s.scheduledDate.from,"scheduledDate",n)} -> ${Rs(s.scheduledDate.to,"scheduledDate",n)}`:s.dueDate?`Due: ${Rs(s.dueDate.from,"dueDate",n)} -> ${Rs(s.dueDate.to,"dueDate",n)}`:"Schedule updated";if(e.action==="task-relationship-changed"&&s.workstreamId)return`Workstream: ${Rs(s.workstreamId.from,"workstreamId",n)} -> ${Rs(s.workstreamId.to,"workstreamId",n)}`;if(e.action==="task-attachments-changed")return"Attachments updated";if(r.length===1){const o=r[0],l=s[o];return ah(o,l,n)}return r.length>1?`${r.length} fields updated`:"Task updated"}function TN(e){const n=Array.isArray(e.activity)&&e.activity.length>0?e.activity:Array.isArray(e.comments)?e.comments.map(s=>({id:`comment:${s.id}`,type:"comment",timestamp:s.timestamp,comment:s})):[];return n.length===0?null:[...n].sort((s,r)=>{const o=Date.parse(String(s.timestamp||"")),l=Date.parse(String(r.timestamp||""));return Number.isFinite(o)&&Number.isFinite(l)&&o!==l?l-o:String(r.id||"").localeCompare(String(s.id||""))})[0]||null}function IN(e,n){return e?e.type==="comment"?e.comment.text:sh(e.event,n):""}const{MessageSquare:NN,User:jN,Bot:RN,Gauge:DN,ClipboardList:PN,HelpCircle:Bm,File:EN}=$s,LN=({task:e,searchQuery:n="",copiedId:s=null,taxonomies:r=[],types:o=[],priorities:l=[],categories:c=[],assigneeOptions:p=[],taskWorkstream:g=null,taskInitiative:w=null,isOverlay:C=!1,isArchived:_=!1,readOnlyMode:y=null,isRecentlyChanged:k=!1,onClick:b,onCopyId:E,onToggleInProgress:S,onToggleReview:W,onToggleComplete:Q,onToggleCancel:z,onSetStatus:K,onArchiveTask:V,onUnarchive:ne,onDelete:D,deleteActionTitle:Ae,onOpenTaskById:U,compressed:ee=!1,showStatusLabel:be=!0})=>{const me=bf(e),Y=me.label||(me.isProvisional?"Pending":""),R=me.isProvisional,B=!!me.label,fe=Hp(g)||g?.id||"",Ne=Vk(w)||w?.id||"",de=l.find(F=>String(F.value)===String(e.priority)),ae=de?de.label.toLowerCase().replace(/\s+/g,"-"):String(e.priority),Ve=c.find(F=>F.value===e.category||F.label===e.category),Re=typeof e.complexity=="number"?e.complexity:Number(e.complexity??3),Ce=Number.isFinite(Re)?Math.max(1,Math.min(5,Math.round(Re))):3,Fe={1:"Tiny",2:"Low",3:"Mid",4:"High",5:"Epic"},x={1:"tiny",2:"low",3:"medium",4:"high",5:"epic"},L=Fe[Ce],P=`var(--complexity-${x[Ce]})`,Z=Xg(e.priority,ae),M=!!u[`priorityItem_${Z}`],h=lu(e.assignee),A=wc(e.assignee,p),H=pt.useMemo(()=>TN(e),[e]),j=y||(e.isDeleted?"deleted":_?"archived":null),je=j!==null,O=pt.useMemo(()=>IN(H),[H]),ue=Array.isArray(e.activity)&&e.activity.length>0?e.activity.length:e.comments?.length||0,re=[Vt.taskItem,e.status==="on-hold"?Vt.onHold:"",e.status==="in-progress"?Vt.inProgress:"",e.status==="review"?Vt.readyForReview:"",e.status==="done"?Vt.completed:"",e.status==="cancelled"?Vt.cancelled:"",k?Vt.taskItemRecentlyChanged:"",u[`priorityItem_${Z}`]||"",C?Vt.kanbanCardOverlay:"",_?Vt.archived:"",ee?Vt.compressed:""].filter(Boolean).join(" "),pe=_a(de?.color),G=o.find(F=>F.value===e.type),q=_a(G?.color)||aS(e.type),ye=F=>{const Ke=typeof F=="string"?F:F.path,St=typeof F=="string"?"":(F.fsPath||"").trim(),Lt=typeof F=="string"?"":(F.displayName||"").trim(),xt=typeof F=="string"?"":(F.originalFilename||"").trim(),Zt=typeof F=="string"?"":(F.caption||"").trim();return[St,xt,Lt,Zt,Ke].some(on=>/\.(png|jpe?g|webp|gif)(\?|#|$)/i.test(on))},Be=F=>{const Ke=typeof F=="string"?F:F.path,St=Ke.includes("/api/taskforce/documents/"),Lt=typeof F=="string"?"":(F.displayName||"").trim();if(St&&typeof F!="string")return dN({displayName:F.displayName,originalFilename:F.originalFilename,fsPath:F.fsPath,assetId:F.assetId||null});const xt=typeof F=="string"?"":(F.caption||"").trim();if(xt)return xt;if(Lt)return Lt;const Zt=typeof F=="string"?"":(F.originalFilename||"").trim();return Zt||Ke.split("?")[0].split("#")[0].split("/").pop()||"Context file"},le=F=>{const Ke=typeof F=="string"?F:F.path,St=typeof F=="string"?"":(F.fsPath||"").trim(),Lt=typeof F=="string"?"":(F.caption||"").trim(),xt=typeof F=="string"?"":(F.originalFilename||"").trim(),Zt=[];if(St&&Zt.push(St),xt&&Zt.push(xt),Lt&&Zt.push(Lt),Ke.includes("/api/taskforce/context-link?path="))try{const on=new URL(Ke,"http://localhost").searchParams.get("path");on&&Zt.push(on)}catch{}Zt.push(Ke);for(const Jt of Zt){const cn=Jt.split("?")[0].split("#")[0].split("/").pop()||"",nn=cn.lastIndexOf(".");if(nn<=0||nn===cn.length-1)continue;const gn=cn.slice(nn+1);if(gn)return gn.slice(0,5).toUpperCase()}return"FILE"},ze={"--task-change-glow-color":pe||`var(--priority-${Z})`,...pe?{borderLeftColor:pe,[`--priority-${Z}`]:pe}:{},...!M&&pe?{borderLeft:`4px solid ${pe}`}:{}},Ye=F=>F.replace(/\b\w/g,Ke=>Ke.toUpperCase()),Xe=Gl(r,[e]),bt=e.checklistItems||[],d=bt.length,rt=d>0?bt.filter(F=>F.isCompleted).length:0,mt=(F,Ke)=>{F.stopPropagation(),E?.(F,Ke)};return t.jsxs("div",{className:re,onClick:()=>b?.(e),style:ze,"data-task-card":"true",children:[t.jsxs("div",{className:Vt.taskHeader,children:[t.jsxs("div",{className:Vt.taskReferenceCluster,children:[w?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:Vt.taskReferenceText,children:Ne}),t.jsx("span",{className:Vt.taskReferenceDivider,children:"/"})]}):null,g?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:Vt.taskReferenceText,children:fe}),t.jsx("span",{className:Vt.taskReferenceDivider,children:"/"})]}):null,Y?t.jsx(eu,{copied:B&&s===me.label,onClick:F=>mt(F,me.label),disabled:!B,title:B?"Copy task reference":"Task reference pending sync",className:_?Vt.archiveBadge:"",label:Jd(Y,n)}):null,R?t.jsx("span",{className:u.taskHierarchyMeta,title:"Temporary local reference until cloud sync assigns the final task number.",children:"Pending sync"}):null]}),t.jsx("div",{className:Vt.taskActions,onClick:F=>F.stopPropagation(),children:je?ne||D?t.jsxs(t.Fragment,{children:[ne&&t.jsx("button",{type:"button",className:u.actionBtn,onClick:()=>ne(e.id),title:j==="deleted"?"Restore deleted task":"Restore archived task",children:t.jsx(wp,{size:16})}),D&&t.jsx("button",{type:"button",className:`${u.actionBtn} ${u.deleteBtn}`,onClick:()=>D(e.id),title:Ae||(j==="deleted"?"Delete Permanently":"Move to Trash"),children:t.jsx(Fl,{size:16})})]}):null:t.jsx(nh,{task:e,compressed:ee,shortLabels:!0,showLabel:be,onSetStatus:(F,Ke)=>{if(K){K(F,Ke);return}if(Ke==="in-progress"){S?.(F);return}if(Ke==="review"){W?.(F);return}if(Ke==="done"){Q?.(F);return}Ke==="cancelled"&&z?.(F)},onArchiveTask:V})})]}),t.jsxs("div",{className:Vt.taskContent,children:[je&&t.jsx("div",{className:`${Vt.taskMeta} ${Vt.taskMetaCompact}`}),t.jsxs("div",{children:[t.jsxs("div",{className:Vt.taskTitle,style:ee?{fontSize:"13px",lineHeight:"1.4"}:{},children:[j==="archived"&&"✓ ",j==="deleted"&&"Deleted: ",Jd(e.title,n)]}),e.description&&!je&&!ee&&t.jsx("div",{className:Vt.taskDescription,children:t.jsx(Np,{onTaskIdClick:U,children:e.description})})]}),e.attachments&&e.attachments.length>0&&!je&&!ee&&t.jsxs("div",{className:Vt.attachmentThumbnails,children:[t.jsx("div",{className:Vt.attachmentImageRow,children:(e.attachments||[]).map((F,Ke)=>{const St=typeof F=="string"?F:F.path;return ye(F)?t.jsx("div",{className:Vt.attachmentThumbnail,onClick:Lt=>{Lt.stopPropagation(),!Rp(typeof F=="string"?{path:St}:F,{taskId:e.id,taskReferenceLabel:Y})&&window.open(St,"_blank")},children:t.jsx("img",{src:St,alt:`Attachment ${Ke}`})},Ke):null})}),t.jsx("div",{className:Vt.attachmentDocumentList,children:(e.attachments||[]).map((F,Ke)=>{const St=typeof F=="string"?F:F.path,Lt=typeof F=="string"?void 0:F.fsPath,xt=Be(F);if(ye(F))return null;const Zt=le(F);return t.jsxs("button",{type:"button",className:Vt.contextDocThumb,onClick:Jt=>{Jt.stopPropagation(),!jp(F,Lt)&&window.open(St,"_blank")},title:xt,style:{"--context-doc-accent":sS(Zt)},children:[t.jsxs("span",{className:Vt.contextDocMain,children:[t.jsx("span",{className:Vt.contextDocIcon,"aria-hidden":"true",children:t.jsx(EN,{size:13})}),t.jsx("span",{className:Vt.contextDocText,children:t.jsx("span",{className:Vt.contextDocName,children:xt})})]}),t.jsx("span",{className:Vt.contextDocType,children:Zt})]},Ke)})})]}),e.status==="cancelled"&&e.canceledReason&&!ee&&t.jsxs("div",{className:Vt.taskCancellationReason,children:[t.jsx("strong",{children:"Cancellation Reason:"})," ",Jd(e.canceledReason,n)]}),O&&!je&&!ee&&t.jsxs("div",{className:Vt.taskLatestComment,children:[t.jsx("strong",{children:"Latest Activity:"})," ",Jd(O.length>120?O.substring(0,120)+"...":O,n)]}),!je&&Xe.length>0&&!ee&&t.jsx("div",{className:`${Vt.taskSpecialists} ${Vt.taxonomiesList}`,children:Xe.map(F=>{const Ke=e.taxonomies?.[F.id];return Ke?(Array.isArray(Ke)?Ke:[Ke]).map(Lt=>{const xt=F.options.find(nn=>nn.value===Lt);if(!xt)return null;const Zt=$s[xt.icon||"Layers"]||bp,Jt=_a(xt.color)||"var(--text-primary)",on=F.status==="retired"?`${F.label} (Retired)`:F.label,cn=xt.status==="retired"?`${xt.label} (Retired)`:xt.label;return t.jsx("span",{className:u.specialistBadge,style:{borderColor:`${Jt}50`,backgroundColor:`${Jt}15`,color:Jt},title:`${on}: ${Ye(cn)}`,children:t.jsx(Zt,{size:10})},`${F.id}-${Lt}`)}):null})}),t.jsx("div",{className:Vt.taskMeta,children:je?t.jsx("span",{children:e.category}):t.jsx(t.Fragment,{children:t.jsxs("div",{className:Vt.taskMetaRow,style:ee?{marginBottom:0}:void 0,children:[t.jsxs("div",{className:Vt.taskMetaBadgeGroup,children:[(()=>{const F=_a(Ve?.color),Ke=Ve?.icon||"Folder",St=$s[Ke]||Ai;return t.jsx("span",{className:u.metaBadge,title:Ye(e.category),style:{color:F||"var(--text-secondary)",backgroundColor:F?`${F}15`:"var(--bg-tertiary)",borderColor:F?`${F}40`:"transparent"},children:t.jsx(St,{size:14})})})(),t.jsx("span",{className:`${u.metaBadge} ${u[`type_${e.type}`]||""}`,title:Ye(e.type||ms),style:{color:`var(--type-color, ${q})`,backgroundColor:`color-mix(in srgb, var(--type-color, ${q}), transparent 90%)`,borderColor:`color-mix(in srgb, var(--type-color, ${q}), transparent 75%)`},children:G?.icon?(()=>{const F=$s[G.icon]||Bm;return t.jsx(F,{size:14})})():Q0(e.type,14)}),de&&t.jsx("span",{className:u.metaBadge,style:{color:pe||"var(--text-secondary)",backgroundColor:pe?`${pe}15`:"var(--bg-tertiary)",borderColor:pe?`${pe}40`:"var(--border-color)"},title:`${de.label}`,children:(()=>{const F=de.icon||"AlertCircle",Ke=$s[F]||Kh;return t.jsx(Ke,{size:14})})()}),ue>0&&t.jsxs("span",{className:u.metaBadge,title:`${ue} activity items`,style:{color:"var(--text-muted)",backgroundColor:"var(--bg-tertiary)",borderColor:"var(--border-primary)",gap:"4px",padding:"0 8px"},children:[t.jsx(NN,{size:14}),t.jsx("span",{children:ue})]}),d>0&&t.jsxs("span",{className:u.metaBadge,title:`${rt}/${d} checklist items complete`,style:{color:"var(--text-muted)",backgroundColor:"var(--bg-tertiary)",borderColor:"var(--border-primary)",gap:"4px",padding:"0 8px"},children:[t.jsx(PN,{size:14}),t.jsx("span",{children:`${rt}/${d}`})]})]}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[t.jsxs("span",{className:u.metaBadge,title:`AI-estimated complexity: ${L} (${Ce}/5)`,style:{color:P,backgroundColor:`color-mix(in srgb, ${P}, transparent 88%)`,borderColor:`color-mix(in srgb, ${P}, transparent 72%)`,gap:"4px",padding:"0 8px"},children:[t.jsx(DN,{size:14}),!ee&&t.jsx("span",{children:L})]}),t.jsx("span",{className:u.metaBadge,title:`Assigned to: ${A}`,"aria-label":h==="unassigned"?"Unassigned":`Assigned to ${A}`,style:{backgroundColor:h==="agent"?"color-mix(in srgb, var(--color-violet-500, #8b5cf6), transparent 88%)":h==="member"?"color-mix(in srgb, var(--color-green-500, #22c55e), transparent 88%)":"color-mix(in srgb, var(--text-secondary, #888), transparent 88%)",padding:"0 8px",color:h==="agent"?"var(--color-violet-500, #8b5cf6)":h==="member"?"var(--color-green-500, #22c55e)":"var(--text-secondary, #888)",borderColor:h==="agent"?"color-mix(in srgb, var(--color-violet-500, #8b5cf6), transparent 72%)":h==="member"?"color-mix(in srgb, var(--color-green-500, #22c55e), transparent 72%)":"color-mix(in srgb, var(--text-secondary, #888), transparent 70%)",display:"flex",alignItems:"center"},children:h==="agent"?t.jsx(RN,{size:ee?14:16}):h==="member"?t.jsx(jN,{size:ee?14:16}):t.jsx(Bm,{size:ee?14:16})})]})]})})})]})]})},Ul=pt.memo(LN),mu="168px";function rh(){return t.jsx("span",{style:{fontSize:"12px",fontWeight:600,color:"var(--text-secondary)",marginRight:"4px"},children:xe("standalone.filtersCaps")})}function _i({label:e,options:n,selected:s,onChange:r,variant:o="label"}){return t.jsx(bi,{label:e,options:n,selected:s,onChange:r,variant:o,containerStyle:{flex:`0 0 ${mu}`,maxWidth:mu}})}function oh({onClick:e}){return t.jsxs("button",{onClick:e,style:{background:"none",border:"none",color:"var(--text-secondary)",cursor:"pointer",fontSize:"12px",display:"flex",alignItems:"center",gap:"4px"},children:[t.jsx(ji,{size:12})," ",xe("standalone.clearFilters")]})}function Wm({label:e,options:n,selected:s,onChange:r,allLabel:o,title:l}){const[c,p]=pt.useState(!1),g=pt.useRef(null),w=n.find(y=>y.value===s),C=w?.selectedLabel||w?.label||o;pt.useEffect(()=>{const y=k=>{g.current&&!g.current.contains(k.target)&&p(!1)};return document.addEventListener("mousedown",y),()=>document.removeEventListener("mousedown",y)},[]);const _=y=>{r(y),p(!1)};return t.jsxs("div",{className:u.filterContainer,ref:g,style:{flex:`0 0 ${mu}`,maxWidth:mu},children:[t.jsxs("button",{type:"button",className:`${u.filterButton} ${s?u.filterActive:""}`,onClick:()=>p(y=>!y),title:l||`Filter by ${e}`,"aria-haspopup":"listbox","aria-expanded":c,children:[t.jsx("span",{children:C}),t.jsx(jc,{size:14,style:{transform:c?"rotate(180deg)":"none",transition:"transform 0.2s",opacity:.5}})]}),c&&t.jsxs("div",{className:`${u.filterDropdown} ${u.appScrollbar} tf-scrollbar`,role:"listbox","aria-label":e,children:[t.jsxs("button",{type:"button",className:u.filterOption,onClick:()=>_(""),"aria-selected":!s,children:[t.jsx(so,{size:14,style:{opacity:s?0:1}}),t.jsx("span",{style:{fontWeight:s?500:600},children:o})]}),t.jsx("div",{className:u.filterDivider}),n.map(y=>{const k=y.value===s;return t.jsxs("button",{type:"button",className:u.filterOption,onClick:()=>_(y.value),"aria-selected":k,children:[t.jsx(so,{size:14,style:{opacity:k?1:0}}),t.jsx("span",{style:{fontWeight:k?600:500},children:y.label})]},y.value)})]})]})}function ih({scope:e,onScopeChange:n,className:s,labelClassName:r}){return t.jsxs("div",{className:s,children:[t.jsx("span",{className:r,children:"Scope"}),t.jsx("div",{className:u.taskScopeTabs,role:"tablist","aria-label":"Task scope",children:[{value:"open",label:"Open"},{value:"archived",label:"Archived"},{value:"deleted",label:"Deleted"}].map(o=>{const l=e===o.value;return t.jsx("button",{type:"button",className:`${u.taskScopeTab} ${l?u.taskScopeTabActive:""}`,onClick:()=>n(o.value),role:"tab","aria-selected":l,"aria-pressed":l,title:`Show ${o.label.toLowerCase()} tasks`,children:o.label},o.value)})})]})}function ch({onClick:e,disabled:n=!1,className:s,title:r="Permanently delete all deleted tasks",children:o="Delete All Permanently"}){return t.jsxs("button",{type:"button",className:s,onClick:e,disabled:n,title:r,children:[t.jsx(Fl,{size:14}),o]})}const{Search:Fm,ClipboardList:MN,ChevronRight:BN,ChevronDown:WN,Folder:FN,Archive:zN,RotateCcw:ON,X:$N,Plus:UN,ArrowUpDown:qN,Trash2:HN}=$s,lh=a.forwardRef((e,n)=>{const{tasks:s,archivedTasks:r,categories:o,types:l,priorities:c,taxonomyDisplayLabels:p,assigneeOptions:g=[],workstreams:w=[],initiatives:C=[],searchQuery:_,filterCategories:y,filterTypes:k,filterPriorities:b,filterStatus:E,filterAssignees:S=[],filterTaxonomies:W,sortBy:Q,sortOrder:z,showArchive:K,taskScope:V,collapsedCategories:ne,loadingTasks:D,filteredTasks:Ae,filteredArchive:U,groupedTasks:ee,filteredDeletedTasks:be=[],groupedDeletedTasks:me={},copiedId:Y,recentlyChangedTaskIds:R=[],showTaskCardStatusLabel:B=!0,onSearchChange:fe,onFilterCategoriesChange:Ne,onFilterTypesChange:de,onFilterPrioritiesChange:ae,onFilterStatusChange:Ve,onFilterAssigneesChange:Re,onTaxonomyFilterChange:Ce,onSortByChange:Fe,onSortOrderChange:x,onShowArchiveChange:L,onTaskScopeChange:P,onClearFilters:Z,onToggleCategory:M,onEditTask:h,onOpenTaskById:A,onCopyId:H,onToggleInProgress:j,onToggleReview:je,onToggleComplete:O,onToggleCancel:ue,onSetStatus:re,onArchiveTask:pe,onBulkArchive:G,onUnarchive:q,onDelete:ye,onDeleteAllDeleted:Be,onFetchArchive:le,onAddTaskToCategory:ze,supplementalTasks:Ye=[],taxonomies:Xe}=e,bt=new Set(R),d=pt.useMemo(()=>new Map(w.map(Se=>[Se.id,Se])),[w]),rt=pt.useMemo(()=>new Map(C.map(Se=>[Se.id,Se])),[C]),mt=pt.useCallback(Se=>{const Mt=Se.workstreamId&&d.get(Se.workstreamId)||null,Qt=Mt?.initiativeId&&rt.get(Mt.initiativeId)||null;return{taskWorkstream:Mt,taskInitiative:Qt}},[rt,d]),F=[...s,...r,...Ye],Ke=!!P,St=P,Lt=V??(K?"archived":"open"),xt=Ke?Lt==="archived"?U:Lt==="deleted"?be:Ae:Ae,Zt=Ke?Lt==="archived"?{Archived:U}:Lt==="deleted"?me:ee:ee,Jt=Ke?Lt==="deleted"?"deleted":Lt==="archived"?"archived":null:null,on=_?xe("taskList.noMatchingTasks"):Lt==="archived"?"No archived tasks found.":Lt==="deleted"?"No deleted tasks found.":xe("taskList.noActiveTasks"),cn=o.filter(Se=>!Se.disabled),nn=o.filter(Se=>Se.disabled&&F.some(Mt=>Mt.category===Se.value)),gn=[...cn,...nn.filter(Se=>!cn.some(Mt=>Mt.value===Se.value))].map(Se=>({value:Se.value,label:Se.disabled?`${Se.label} (Legacy)`:Se.label})),yn=l.filter(Se=>Se.status!=="retired"),an=l.filter(Se=>Se.status==="retired"&&F.some(Mt=>Mt.type===Se.value)),kn=[...yn,...an.filter(Se=>!yn.some(Mt=>Mt.value===Se.value))].map(Se=>({value:Se.value,label:Se.status==="retired"?`${Se.label} (Retired)`:Se.label})),Gn=Gl(Xe,F).filter(Se=>Se.filterEnabled!==!1).map(Se=>({...Se,options:Gp(Se,F)})),At=pt.useMemo(()=>[{value:"created",label:xe("taskList.sortCreated")},{value:"updated",label:xe("taskList.sortUpdated")},{value:"priority",label:xe("taskList.sortPriority")},...Vf(Xe,F)],[F,xe,Xe]);return t.jsxs("div",{className:u.viewTab,ref:n,children:[t.jsxs("div",{className:u.filterBar,children:[t.jsxs("div",{className:u.searchContainer,children:[t.jsx(Fm,{size:16,className:u.searchIcon}),t.jsx("input",{type:"text",className:u.searchInput,placeholder:xe("taskList.searchPlaceholder"),value:_,onChange:Se=>fe(Se.target.value)}),_&&t.jsx("button",{className:u.clearSearchBtn,onClick:()=>fe(""),title:xe("taskList.clearSearchTitle"),children:t.jsx($N,{size:14})})]}),t.jsxs("div",{className:u.filterRow,children:[t.jsx(bi,{label:p?.category||xe("taskList.categoryLabel"),options:gn,selected:y,onChange:Ne,variant:"value"}),t.jsx(bi,{label:p?.type||xe("taskList.typeLabel"),options:kn,selected:k,onChange:de,variant:"value"})]}),t.jsxs("div",{className:u.filterRow,children:[t.jsx(bi,{label:p?.priority||xe("taskList.priorityLabel"),options:c,selected:b,onChange:ae,variant:"value"}),t.jsx(bi,{label:xe("taskList.statusLabel"),options:no,selected:E,onChange:Ve,variant:"value"}),t.jsx(bi,{label:xe("taskList.assigneeLabel"),options:g,selected:S,onChange:Se=>Re?.(Se),variant:"value"})]}),Gn.map(Se=>t.jsx(bi,{label:Se.status==="retired"?`${Se.label} (Retired)`:Se.label,options:Se.options.map(Mt=>({...Mt,label:Mt.status==="retired"?`${Mt.label} (Retired)`:Mt.label})),selected:W[Se.id]||[],onChange:Mt=>Ce(Se.id,Mt),variant:"value"},Se.id)),t.jsxs("div",{className:u.filterRow,children:[t.jsxs("div",{className:u.sortLabel,children:[t.jsx(qN,{size:14,style:{marginRight:"4px"}})," ",xe("taskList.sortByLabel")]}),t.jsx("select",{value:Q,onChange:Se=>Fe(Se.target.value),className:`${u.filterSelect} ${u.filterSelectSort} `,children:At.map(Se=>t.jsx("option",{value:Se.value,children:Se.label},Se.value))}),t.jsx("button",{className:`${u.resetFiltersBtn} ${u.sortDirectionBtnWidget}`,onClick:x,title:xe(z==="desc"?"taskList.sortDirectionDescTitle":"taskList.sortDirectionAscTitle"),children:z==="desc"?t.jsx(tf,{size:14}):t.jsx(nf,{size:14})}),t.jsx("button",{className:u.resetFiltersBtn,onClick:Z,title:xe("taskList.resetFiltersTitle"),children:t.jsx(ON,{size:14})})]}),t.jsxs("div",{className:`${u.filterRow} ${u.archiveRow} `,children:[Lt==="open"?t.jsxs("button",{className:`${u.bulkArchiveBtn} ${s.some(Se=>Se.status==="done"||Se.status==="cancelled")?"":u.disabledBtn} `,onClick:()=>s.some(Se=>Se.status==="done"||Se.status==="cancelled")&&G(),disabled:!s.some(Se=>Se.status==="done"||Se.status==="cancelled"),title:s.some(Se=>Se.status==="done"||Se.status==="cancelled")?xe("taskList.archiveAllTitle"):xe("taskList.noTasksToArchiveTitle"),children:[t.jsx(zN,{size:12}),t.jsx("span",{children:xe("taskList.archiveFinished")})]}):Lt==="deleted"&&Be?t.jsx(ch,{className:`${u.bulkArchiveBtn} ${u.taskToolbarAction} ${u.bulkDeleteBtn} ${be.length===0?u.disabledBtn:""}`,onClick:()=>be.length>0&&Be(),disabled:be.length===0,title:be.length>0?"Empty trash":"Trash is already empty",children:"Empty Trash"}):t.jsx("div",{}),Ke?t.jsx(ih,{scope:Lt,onScopeChange:Se=>{St?.(Se),Se==="archived"?(L(!0),le()):K&&L(!1)},className:`${u.archiveToggle} ${u.taskScopeToggle}`}):t.jsxs("label",{className:u.archiveToggle,children:[t.jsx("input",{type:"checkbox","aria-label":"Archived",checked:K,onChange:Se=>{L(Se.target.checked),Se.target.checked&&le()}}),t.jsx("span",{children:"Include Archive"})]})]})]}),D&&s.length===0?t.jsx("div",{className:u.loading,children:t.jsx(Fa,{size:24,className:u.spinner})}):xt.length===0&&!D?t.jsxs("div",{className:u.emptyState,children:[_?t.jsx(Fm,{size:48}):Lt==="deleted"?t.jsx(HN,{size:48}):t.jsx(MN,{size:48}),t.jsx("p",{children:on})]}):t.jsx("div",{className:u.taskList,style:{opacity:D?.6:1,transition:"opacity 0.2s ease"},children:Object.entries(Zt).map(([Se,Mt])=>{if(Mt.length===0)return null;const Qt=ne[Se];return t.jsxs("div",{className:u.categoryGroup,children:[t.jsx("div",{className:u.categoryHeader,onClick:()=>M(Se),children:t.jsxs("div",{className:u.categoryTitle,children:[Qt?t.jsx(BN,{size:16}):t.jsx(WN,{size:16}),(()=>{const zt=o.find(J=>J.label===Se),Ge=zt?.icon&&Ni[zt.icon]?Ni[zt.icon]:FN,An=_a(zt?.color)||"var(--color-purple, #8b5cf6)";return t.jsx(Ge,{size:16,className:u.categoryTitleIcon,style:{color:An}})})(),Se,t.jsxs("span",{className:u.categoryCount,children:["(",Mt.length,")"]}),ze&&t.jsx("button",{className:u.kanbanQuickAdd,onClick:zt=>{zt.stopPropagation(),ze(Se)},title:xe("taskList.addTaskToCategoryTitle",{category:Se}),style:{marginLeft:"auto"},disabled:Jt!==null,children:t.jsx(UN,{size:14})})]})}),!Qt&&t.jsx("div",{className:u.categoryItems,children:Mt.map(zt=>(()=>{const{taskWorkstream:Ge,taskInitiative:An}=mt(zt);return t.jsx(Ul,{task:zt,taskWorkstream:Ge,taskInitiative:An,searchQuery:_,copiedId:Y,taxonomies:Xe,types:l,priorities:c,assigneeOptions:g,onClick:h,onOpenTaskById:A,onCopyId:H,onToggleInProgress:j,onToggleReview:je,onToggleComplete:O,onToggleCancel:ue,onSetStatus:re,onArchiveTask:pe,onUnarchive:Jt?q:void 0,onDelete:Jt?ye:void 0,categories:o,isRecentlyChanged:bt.has(zt.id),readOnlyMode:Jt,showStatusLabel:B},zt.id)})())})]},Se)})}),!Ke&&K&&U.length>0&&t.jsxs("div",{className:u.archiveList,children:[t.jsx("div",{className:u.archiveHeader,children:"Archived"}),U.map(Se=>(()=>{const{taskWorkstream:Mt,taskInitiative:Qt}=mt(Se);return t.jsx(Ul,{task:Se,taskWorkstream:Mt,taskInitiative:Qt,searchQuery:_,copiedId:Y,isArchived:!0,types:l,assigneeOptions:g,onClick:h,onCopyId:H,onSetStatus:re,onUnarchive:q,onDelete:ye,deleteActionTitle:"Delete Permanently",categories:o,showStatusLabel:B},Se.id)})())]})]})});lh.displayName="TaskList";const GN="_formNotice_1infv_1",VN="_assigneeIndicator_1infv_12",ZN="_assigneeIndicatorAgent_1infv_20",KN="_assigneeIndicatorUser_1infv_24",YN="_assigneeIndicatorUnassigned_1infv_28",JN="_markdownPreview_1infv_32",XN="_error_1infv_83",QN="_keyboardHint_1infv_92",ej="_taskFormLifecycle_1infv_109",tj="_taskFormMetaDivider_1infv_114",nj="_taskFormMetaGrid_1infv_121",aj="_compactMetaSection_1infv_127",sj="_createWorkstreamRow_1infv_133",rj="_createWorkstreamDropdown_1infv_139",oj="_compactMetaGrid_1infv_144",ij="_compactMetaField_1infv_150",cj="_compactMetaSpacer_1infv_154",lj="_compactMetaFieldHint_1infv_168",dj="_formFieldsetReset_1infv_172",uj="_taskFormDateRow_1infv_185",pj="_taskFormDateLabel_1infv_192",mj="_taskFormDateValue_1infv_200",fj="_taskFormMetaStack_1infv_208",hj="_taskFormMetaActor_1infv_214",gj="_taskFormDateWarning_1infv_226",yj="_taskFormDateError_1infv_232",kj="_helpHeader_1infv_238",Sj="_helpClose_1infv_249",vj="_markdownHelp_1infv_263",wj="_helpGrid_1infv_272",bj="_helpGridItem_1infv_278",_j="_settingsHint_1infv_290",Cj="_sectionBlock_1infv_296",xj="_softSectionSurface_1infv_306",Aj="_stackedList_1infv_313",Tj="_stackedListSpaced_1infv_318",Ij="_checklistRow_1infv_322",Nj="_checklistRowDragging_1infv_331",jj="_checklistHandleBtn_1infv_335",Rj="_checklistCheckboxBtn_1infv_358",Dj="_checklistCheckboxBtnChecked_1infv_378",Pj="_checklistItemText_1infv_383",Ej="_checklistItemTextCompleted_1infv_389",Lj="_checklistRemoveBtn_1infv_394",Mj="_specialistChip_1infv_457",Bj="_specialistChipActive_1infv_480",Wj="_commentPanel_1infv_561",Fj="_commentThread_1infv_575",zj="_emptyComments_1infv_584",Oj="_comment_1infv_561",$j="_activityEvent_1infv_602",Uj="_activityEventSystem_1infv_607",qj="_commentAi_1infv_611",Hj="_commentUser_1infv_615",Gj="_commentHeader_1infv_619",Vj="_activityEventHeader_1infv_636",Zj="_commentAuthor_1infv_642",Kj="_commentTime_1infv_650",Yj="_commentText_1infv_654",Jj="_activityEventText_1infv_690",Xj="_activityEventChanges_1infv_699",Qj="_activityEventChange_1infv_699",eR="_commentInputArea_1infv_717",tR="_commentInput_1infv_717",nR="_sendCommentBtn_1infv_749",aR="_taxonomyFieldsGrid_1infv_775",sR="_markdownPreviewContainer_1infv_782",rR="_descriptionSurface_1infv_787",Le={formNotice:GN,assigneeIndicator:VN,assigneeIndicatorAgent:ZN,assigneeIndicatorUser:KN,assigneeIndicatorUnassigned:YN,markdownPreview:JN,error:XN,keyboardHint:QN,taskFormLifecycle:ej,taskFormMetaDivider:tj,taskFormMetaGrid:nj,compactMetaSection:aj,createWorkstreamRow:sj,createWorkstreamDropdown:rj,compactMetaGrid:oj,compactMetaField:ij,compactMetaSpacer:cj,compactMetaFieldHint:lj,formFieldsetReset:dj,taskFormDateRow:uj,taskFormDateLabel:pj,taskFormDateValue:mj,taskFormMetaStack:fj,taskFormMetaActor:hj,taskFormDateWarning:gj,taskFormDateError:yj,helpHeader:kj,helpClose:Sj,markdownHelp:vj,helpGrid:wj,helpGridItem:bj,settingsHint:_j,sectionBlock:Cj,softSectionSurface:xj,stackedList:Aj,stackedListSpaced:Tj,checklistRow:Ij,checklistRowDragging:Nj,checklistHandleBtn:jj,checklistCheckboxBtn:Rj,checklistCheckboxBtnChecked:Dj,checklistItemText:Pj,checklistItemTextCompleted:Ej,checklistRemoveBtn:Lj,specialistChip:Mj,specialistChipActive:Bj,commentPanel:Wj,commentThread:Fj,emptyComments:zj,comment:Oj,activityEvent:$j,activityEventSystem:Uj,commentAi:qj,commentUser:Hj,commentHeader:Gj,activityEventHeader:Vj,commentAuthor:Zj,commentTime:Kj,commentText:Yj,activityEventText:Jj,activityEventChanges:Xj,activityEventChange:Qj,commentInputArea:eR,commentInput:tR,sendCommentBtn:nR,taxonomyFieldsGrid:aR,markdownPreviewContainer:sR,descriptionSurface:rR};function up({label:e,value:n,options:s,onChange:r,type:o="priority",hideLabel:l=!1,showSelectedLabel:c=!0}){const p=s.find(g=>String(g.value)===String(n));return t.jsxs("div",{className:u.field,children:[!l&&t.jsxs("div",{className:u.labelRow,children:[t.jsx("label",{className:u.label,children:e}),c&&p&&t.jsx("span",{className:u.levelLabel,style:{color:_a(p.color)||(o==="priority"?`var(--priority-${n})`:o==="complexity"?`var(--complexity-${n})`:"var(--text-secondary)"),backgroundColor:(_a(p.color)?`${_a(p.color)}25`:void 0)||(o==="priority"?`color-mix(in srgb, var(--priority-${n}), transparent 85%)`:o==="complexity"?`color-mix(in srgb, var(--complexity-${n}), transparent 85%)`:"rgba(255,255,255,0.05)")},children:p.label})]}),t.jsx("div",{className:u.levelSelect,children:s.map((g,w)=>{const C=s.findIndex(k=>String(k.value)===String(n)),_=w<=C,y=String(g.value)===String(n);return t.jsx("button",{type:"button",className:`${u.levelOption} ${_?u.levelOptionFilled:""} ${_?u[`levelOption_${o}_${g.value}`]:""} ${y?u.levelOptionSelected:""}`,onClick:()=>r(g.value),title:g.label,style:{opacity:_?1:.15,backgroundColor:_?_a(g.color)||(o==="priority"?`var(--priority-${g.value})`:o==="complexity"?`var(--complexity-${g.value})`:"var(--text-primary)"):void 0,color:_?o==="priority"&&String(g.value).toLowerCase()==="medium"?"black":"white":void 0,boxShadow:_&&(o==="priority"&&(String(g.value).toLowerCase()==="critical"||g.value===4)||o==="complexity"&&(String(g.value).toLowerCase()==="epic"||g.value===5))?`0 0 12px ${o==="priority"?"rgba(239, 68, 68, 0.6)":"rgba(217, 70, 239, 0.6)"}`:void 0}},String(g.value))})})]})}const zm=new Map;function oR(e){const n=e instanceof Date?e:new Date(e);return Number.isNaN(n.getTime())?null:n}function iR(e,n){const s=Object.entries(n).sort(([r],[o])=>r.localeCompare(o));return JSON.stringify([e,s])}function Nc(e,n,s){const r=oR(e);if(!r)return"";const o=s??Af(),l=iR(o,n);let c=zm.get(l);return c||(c=new Intl.DateTimeFormat(o,n),zm.set(l,c)),c.format(r)}const cR="D-";function lR(e){return Hl(cR,e)}const dh=[".png",".jpg",".jpeg",".webp",".gif",".pdf",".txt",".md",".csv",".json",".doc",".docx",".html",".js",".ts",".tsx",".css",".py",".java",".go",".rs",".sh"].join(","),dR=new Set(["image/png","image/jpeg","image/webp"]),uR=new Set(dh.split(",").map(e=>e.trim().toLowerCase())),pR=10*1024*1024,mR=3500;function uh(e){const n=e.trim().toLowerCase(),s=n.lastIndexOf(".");return s===-1?"":n.slice(s)}function pp(e){if(e.length===0)return"";const n=e.slice(0,3).join(", "),s=e.length-3;return s>0?`${n}, +${s} more`:n}function fR(e){return`${e.name.trim().toLowerCase()}::${e.size}::${e.lastModified}`}function hR(e){return new Promise((n,s)=>{const r=new FileReader;r.onload=()=>n(String(r.result||"")),r.onerror=()=>s(r.error||new Error("Failed to read file")),r.readAsDataURL(e)})}function Nl(e){return/\.(png|jpe?g|webp|gif)(\?|#|$)/i.test(e)}function gR(e){const n=e.types;if(!n)return null;for(const s of Array.from(n)){const r=String(s||"").trim().toLowerCase();if(dR.has(r))return r}return null}function Om(e,n){const s=e.includes("?")?"&":"?";return`${e}${s}download=1&filename=${encodeURIComponent(n)}`}function $m(e){return typeof e=="string"?e.split("/").pop()||"Context file":e.displayName||e.originalFilename||e.caption||e.fsPath||e.path.split("/").pop()||"Context file"}function yR(e){const n=typeof e=="string"?[e]:[e.originalFilename,e.displayName,e.caption,e.fsPath,e.path];for(const r of n){if(!r)continue;const o=uh(r);if(o)return o.replace(".","").slice(0,5).toUpperCase()}const s=typeof e=="string"?e:e.path;return/^https?:\/\//i.test(s)?"LINK":"FILE"}function kR(e){const{taskId:n,taskReferenceLabel:s,workspaceId:r,contextFiles:o,onAddContextFile:l,onRemoveContextFile:c,onUpdateContextCaption:p}=e,g=a.useRef(null),[w,C]=a.useState(!1),[_,y]=a.useState(null),[k,b]=a.useState(""),[E,S]=a.useState(null),[W,Q]=a.useState(null),[z,K]=a.useState(!1),[V,ne]=a.useState(!1),[D,Ae]=a.useState(0),U=a.useRef(new Set),ee=a.useRef(new Set),be=h=>(h||"").trim(),me=(h,A)=>{const H=[],j=be(h),je=be(A);return j&&H.push(`path:${j}`),je&&H.push(`fs:${je}`),H},Y=a.useMemo(()=>{const h=new Set;return o.forEach(A=>{if(typeof A=="string"){me(A).forEach(H=>h.add(H));return}me(A.path,A.fsPath).forEach(H=>h.add(H))}),h},[o]);a.useEffect(()=>{U.current=new Set(Y)},[Y]);const R=(h,A)=>A.some(H=>h.has(H)),B=(h,A)=>A.forEach(H=>h.add(H)),fe=String(r||"").trim(),Ne=(h="application/json")=>{const A={"Content-Type":h};return fe&&(A["x-taskforce-workspace-id"]=fe),A},de=(h,A=!0,H=U.current)=>{const j=h.trim();if(!j||!/^https?:\/\//i.test(j))return"invalid";const O=j,ue=me(O);if(R(H,ue))return"duplicate";const re=j.split(/[\\/]/).pop()||j;return l({path:O,caption:re,timestamp:new Date().toISOString()}),B(H,ue),A&&b(""),S(null),"added"};a.useEffect(()=>{if(!W)return;const h=window.setTimeout(()=>{Q(null)},mR);return()=>window.clearTimeout(h)},[W]);const ae=async h=>{if(h.length===0)return;y(null),Q(null);const A=h,H=[],j=[],je=[],O=[],ue=new Set(ee.current);A.forEach(q=>{const ye=uh(q.name);if(!uR.has(ye)){H.push(q.name);return}if(q.size>pR){j.push(q.name);return}const Be=fR(q);if(ue.has(Be)){je.push(q.name);return}ue.add(Be),O.push({file:q,fingerprint:Be})});const re=[];if(H.length>0&&re.push(`${H.length} unsupported file${H.length===1?"":"s"} skipped: ${pp(H)}.`),j.length>0&&re.push(`${j.length} file${j.length===1?"":"s"} over 10 MB skipped: ${pp(j)}.`),je.length>0&&re.push(`${je.length} local duplicate file${je.length===1?"":"s"} skipped before upload: ${pp(je)}.`),O.length===0){re.length>0&&Q(re.join(" ")),g.current&&(g.current.value="");return}C(!0);const pe=new Set(U.current);let G=0;try{for(const{file:ye,fingerprint:Be}of O){let le=null;const ze=await fetch("/api/taskforce/context-upload/init",{method:"POST",headers:Ne(),body:JSON.stringify({originalName:ye.name,mimeType:ye.type||"application/octet-stream",size:ye.size,taskId:n||null,workspaceId:fe||null})});if(ze.ok){const Xe=await ze.json();if(Xe?.success&&typeof Xe?.uploadUrl=="string"&&typeof Xe?.path=="string"){if(!(await fetch(Xe.uploadUrl,{method:String(Xe.method||"PUT"),headers:Xe.headers||{"Content-Type":ye.type||"application/octet-stream"},body:ye})).ok)throw new Error(`Upload failed for ${ye.name}`);const d=await fetch("/api/taskforce/context-upload/finalize",{method:"POST",headers:Ne(),body:JSON.stringify({relativePath:Xe.relativePath,mimeType:ye.type||"application/octet-stream",originalName:ye.name,size:ye.size,taskId:n||null,workspaceId:fe||null})});if(!d.ok){const rt=await d.json().catch(()=>({}));throw new Error(rt?.error||`Upload failed for ${ye.name}`)}le=await d.json().catch(()=>null)}else Xe?.success&&typeof Xe?.path=="string"&&(le=Xe)}if(!le){const Xe=await hR(ye),bt=await fetch("/api/taskforce/context-upload",{method:"POST",headers:Ne(),body:JSON.stringify({file:Xe,originalName:ye.name,taskId:n||null,workspaceId:fe||null})});if(!bt.ok)throw new Error(`Upload failed for ${ye.name}`);le=await bt.json()}if(!le?.success||!le?.path)throw new Error(`Upload failed for ${ye.name}`);const Ye=me(le.path,le.fsPath);if(R(pe,Ye)){G+=1;continue}l({path:le.path,fsPath:le.fsPath,caption:typeof le.caption=="string"&&le.caption.trim().length>0?le.caption:ye.name,displayName:typeof le.displayName=="string"?le.displayName:void 0,originalFilename:typeof le.originalFilename=="string"?le.originalFilename:ye.name,assetId:typeof le.assetId=="string"?le.assetId:void 0,referenceNumber:typeof le.referenceNumber=="number"?le.referenceNumber:null,referenceLabel:typeof le.referenceLabel=="string"?le.referenceLabel:void 0,taskId:typeof le.taskId=="string"?le.taskId:null,timestamp:new Date().toISOString()}),bk({workspaceId:fe||"default",taskId:n||null,reason:"upload"}),B(pe,Ye),ee.current.add(Be)}const q=[...re];G>0&&q.push(`${G} duplicate file${G===1?"":"s"} skipped.`),Q(q.length>0?q.join(" "):null),U.current=pe}catch(q){y(q instanceof Error?q.message:"Failed to upload context file")}finally{C(!1),g.current&&(g.current.value="")}},Ve=async h=>{!h||h.length===0||await ae(Array.from(h))},Re=async()=>{if(y(null),Q(null),!navigator.clipboard||typeof navigator.clipboard.read!="function"){y("Clipboard image paste is not available in this browser.");return}try{const h=await navigator.clipboard.read(),A=[];for(const H of h){const j=gR(H);if(!j)continue;const je=await H.getType(j),O=j.toLowerCase()==="image/png"?"png":j.toLowerCase()==="image/webp"?"webp":"jpg";A.push(new globalThis.File([je],`pasted-image-${Date.now()}.${O}`,{type:j}))}if(A.length===0){y("Clipboard does not currently contain a supported image.");return}await ae(A)}catch(h){y(h?.message||"Failed to read an image from the clipboard.")}},Ce=h=>{const A=new Set,H=h.dataTransfer.getData("text/uri-list")||"",j=h.dataTransfer.getData("text/plain")||"",je=`${H}
4
+ ${j}`.split(`
5
+ `).map(O=>O.trim()).filter(O=>!!O&&!O.startsWith("#"));for(const O of je){if(/^file:\/\//i.test(O)){try{const ue=new URL(O),re=decodeURIComponent(ue.pathname||"").trim();re&&A.add(re)}catch{}continue}A.add(O)}return Array.from(A)},Fe=h=>{if(h.preventDefault(),h.stopPropagation(),ne(!1),Ae(0),y(null),S(null),Q(null),h.dataTransfer.files&&h.dataTransfer.files.length>0){Ve(h.dataTransfer.files);return}const A=Ce(h);if(A.length===0){S("Drop a file or URL.");return}const H=new Set(U.current);let j=0,je=0,O=0;A.forEach(re=>{const pe=de(re,!1,H);pe==="duplicate"&&(j+=1),pe==="added"&&(je+=1),pe==="invalid"&&(O+=1)});const ue=[];j>0&&ue.push(`${j} duplicate link${j===1?"":"s"} skipped.`),O>0&&ue.push(`${O} local path${O===1?"":"s"} skipped. Upload files to attach them, or drop an http(s) URL to link.`),Q(ue.length>0?ue.join(" "):je>0?null:W),U.current=H},x=h=>{h.preventDefault(),h.stopPropagation(),Ae(A=>A+1),ne(!0)},L=h=>{h.preventDefault(),h.stopPropagation(),Ae(A=>{const H=Math.max(0,A-1);return H===0&&ne(!1),H})},P=h=>{h.preventDefault(),h.stopPropagation(),h.dataTransfer.dropEffect="copy"},Z=o.filter(h=>{const A=typeof h=="string"?h:h.path;return Nl(A)}),M=o.filter(h=>{const A=typeof h=="string"?h:h.path;return!Nl(A)});return t.jsxs("div",{className:u.specialistSection,children:[t.jsxs("div",{className:u.toggleHeading,onClick:()=>K(!z),title:z?"Hide context documents":"Show context documents",children:[t.jsxs("label",{className:u.label,children:["Context Documents ",o.length>0&&`(${o.length})`]}),z?t.jsx(jc,{size:14}):t.jsx(Ii,{size:14})]}),z&&t.jsxs(t.Fragment,{children:[t.jsx("p",{className:u.settingsHint,children:"Upload files into task context storage, or add an external http(s) URL."}),t.jsxs("div",{className:u.contextUploadPanel,children:[t.jsxs("div",{className:u.contextUploadActions,children:[t.jsxs("button",{type:"button",className:u.secondaryHeaderBtn,onClick:()=>g.current?.click(),disabled:w,children:[w?t.jsx(Fa,{size:12,className:u.spinner}):t.jsx(np,{size:12}),w?"Uploading...":"Upload File"]}),t.jsxs("button",{type:"button",className:u.secondaryHeaderBtn,onClick:()=>{Re()},disabled:w,children:[t.jsx(Ll,{size:12}),"Paste Image from Clipboard"]})]}),t.jsx("input",{ref:g,type:"file",accept:dh,multiple:!0,className:u.hiddenInput,onChange:h=>{Ve(h.target.files)}}),_&&t.jsx("div",{className:u.error,children:_}),t.jsxs("div",{className:u.contextLinkRow,children:[t.jsx("input",{type:"text",className:u.input,placeholder:"Add external URL (https://...)",value:k,onChange:h=>{b(h.target.value),E&&S(null),W&&Q(null)}}),t.jsx("button",{type:"button",className:u.secondaryHeaderBtn,onClick:()=>{if(!k.trim()){S("Enter an http(s) URL to link.");return}const h=de(k,!0);if(h==="invalid"){S("Only external http(s) URLs can be linked here. Upload files to attach them.");return}h==="duplicate"?Q("Link already exists in task context."):h==="added"&&Q(null)},children:"Add URL"})]}),t.jsxs("div",{className:`${u.contextDropzone} ${V?u.contextDropzoneActive:""}`,onDragEnter:x,onDragLeave:L,onDragOver:P,onDrop:Fe,children:[t.jsx(np,{size:14}),t.jsx("span",{children:"Drop files or URLs here"})]})]}),W&&t.jsx("div",{className:u.contextNotice,children:W}),E&&t.jsx("div",{className:u.error,children:E}),Z.length>0&&t.jsx("div",{className:u.attachmentGrid,children:o.map((h,A)=>{const H=typeof h=="string"?h:h.path;if(!Nl(H))return null;const j=typeof h=="string"?void 0:h.fsPath,je=typeof h=="string"?"":h.caption||"",O=$m(h),ue=Nl(H),re=/^https?:\/\//i.test(H),pe=eh(h);return t.jsxs("div",{className:u.attachmentCard,children:[t.jsxs("div",{className:u.attachmentPreviewContainer,children:[ue?t.jsx("img",{src:H,alt:je||`Context file ${A}`,onClick:()=>{Rp(h,{taskId:n,taskReferenceLabel:s})||window.open(H,"_blank")},onError:G=>{G.target.style.display="none",G.target.parentElement.classList.add(u.brokenImage)}}):t.jsxs("button",{type:"button",className:u.contextFileLink,onClick:()=>{jp(h,j)||window.open(H,"_blank")},title:"Open file",children:[t.jsx(np,{size:16}),t.jsx("span",{children:je||j||H.split("/").pop()||"Context file"})]}),t.jsxs("div",{className:u.brokenImagePlaceholder,children:[t.jsx(Rc,{size:16}),t.jsx("span",{children:"Preview unavailable"})]}),t.jsxs("div",{className:u.attachmentActions,children:[pe&&t.jsx("button",{type:"button",className:u.attachmentActionBtn,onClick:G=>{G.stopPropagation(),Rp(h,{taskId:n,taskReferenceLabel:s})},title:"Annotate",children:t.jsx(Yh,{size:12})}),j&&t.jsx("button",{type:"button",className:u.attachmentActionBtn,onClick:G=>{G.stopPropagation(),navigator.clipboard.writeText(j)},title:`Copy path: ${j}`,children:t.jsx(Ll,{size:12})}),!re&&t.jsx("button",{type:"button",className:u.attachmentActionBtn,onClick:G=>{G.stopPropagation(),window.open(Om(H,je||O),"_blank")},title:"Download",children:t.jsx(dm,{size:12})}),t.jsx("button",{type:"button",className:u.attachmentActionBtn,onClick:G=>{G.stopPropagation(),c(A)},title:"Delete",children:t.jsx(Fl,{size:12})})]})]}),t.jsx("input",{type:"text",className:u.attachmentCaptionInput,placeholder:"Add a label...",value:je,onChange:G=>p(A,G.target.value)})]},A)})}),M.length>0&&t.jsx("div",{className:u.documentAttachmentList,children:o.map((h,A)=>{const H=typeof h=="string"?h:h.path;if(Nl(H))return null;const j=typeof h=="string"?void 0:h.fsPath,je=typeof h=="string"?"":h.caption||"",O=$m(h),ue=yR(h),re=typeof h=="string"?"":lR(h),pe=/^https?:\/\//i.test(H);return t.jsxs("div",{className:u.documentAttachmentItem,children:[t.jsxs("div",{className:u.documentAttachmentRow,children:[t.jsxs("button",{type:"button",className:u.documentAttachmentLink,onClick:()=>{jp(h,j)||window.open(H,"_blank")},title:O,children:[t.jsxs("span",{className:u.documentAttachmentMain,children:[t.jsx("span",{className:u.documentAttachmentIcon,"aria-hidden":"true",children:t.jsx(Jh,{size:13})}),t.jsxs("span",{className:u.documentAttachmentText,children:[t.jsx("span",{className:u.documentAttachmentName,children:O}),re&&t.jsx("span",{className:u.taskIdBadge,children:re})]})]}),t.jsx("span",{className:u.documentAttachmentType,children:ue})]}),t.jsxs("div",{className:u.documentAttachmentActions,children:[j&&t.jsx("button",{type:"button",className:u.documentAttachmentActionBtn,onClick:()=>{navigator.clipboard.writeText(j)},title:`Copy path: ${j}`,children:t.jsx(Ll,{size:12})}),!pe&&t.jsx("button",{type:"button",className:u.documentAttachmentActionBtn,onClick:()=>{window.open(Om(H,je||O),"_blank")},title:"Download",children:t.jsx(dm,{size:12})}),t.jsx("button",{type:"button",className:u.documentAttachmentActionBtn,onClick:()=>c(A),title:"Delete",children:t.jsx(Fl,{size:12})})]})]}),t.jsx("input",{type:"text",className:u.documentAttachmentCaptionInput,placeholder:"Add a label...",value:je,onChange:G=>p(A,G.target.value)})]},A)})})]})]})}function SR({id:e,item:n,onToggle:s,onRemove:r}){const{attributes:o,listeners:l,setNodeRef:c,transform:p,transition:g,isDragging:w}=mf({id:e}),C={transform:Lp.Transform.toString(p),transition:g,opacity:w?.88:1};return t.jsxs("div",{ref:c,style:C,className:`${Le.checklistRow} ${w?Le.checklistRowDragging:""}`.trim(),children:[t.jsx("button",{type:"button",className:Le.checklistHandleBtn,title:"Reorder checklist item","aria-label":"Reorder checklist item",...o,...l,children:t.jsx(eg,{size:14})}),t.jsx("button",{type:"button",className:`${Le.checklistCheckboxBtn} ${n.isCompleted?Le.checklistCheckboxBtnChecked:""}`.trim(),onClick:s,title:n.isCompleted?"Mark incomplete":"Mark complete","aria-label":n.isCompleted?"Mark checklist item incomplete":"Mark checklist item complete",children:n.isCompleted?t.jsx(so,{size:14,strokeWidth:2.1}):null}),t.jsx("span",{className:`${Le.checklistItemText} ${n.isCompleted?Le.checklistItemTextCompleted:""}`.trim(),children:n.title}),t.jsx("button",{type:"button",className:Le.checklistRemoveBtn,onClick:r,title:"Remove checklist item","aria-label":"Remove checklist item",children:t.jsx(ji,{size:15,strokeWidth:1.9})})]})}function mp(e,n){const s=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(e);return s?`rgba(${parseInt(s[1],16)}, ${parseInt(s[2],16)}, ${parseInt(s[3],16)}, ${n})`:""}function ph(e){const{editingTaskId:n,error:s,title:r,description:o,category:l,type:c,priority:p,complexity:g,manualComplexityEnabled:w=!1,assignee:C,scheduledDate:_,dueDate:y,workstreamInput:k="",checklistItems:b,comments:E,newCommentText:S,contextFiles:W,currentWorkspaceId:Q,apiBaseUrl:z,descriptionFocused:K,showMarkdownHelp:V,showChecklist:ne=!1,checklistEnabled:D=!0,showComments:Ae,formTaxonomies:U,onTaxonomyChange:ee,onOpenSettings:be,categories:me,types:Y,priorities:R,taxonomyDisplayLabels:B,assigneeOptions:fe,taxonomies:Ne,workstreams:de=[],copiedId:ae,onTitleChange:Ve,onDescriptionChange:Re,onCategoryChange:Ce,onTypeChange:Fe,onPriorityChange:x,onComplexityChange:L,onAssigneeChange:P,onScheduledDateChange:Z,onDueDateChange:M,onWorkstreamInputChange:h=()=>{},onChecklistItemsChange:A,onNewCommentTextChange:H,onDescriptionFocusedChange:j,onShowMarkdownHelpChange:je,onShowChecklistChange:O=()=>{},onShowCommentsChange:ue,onSubmit:re,onAddComment:pe,onAddContextFile:G,onRemoveContextFile:q,onUpdateContextCaption:ye,onCopyId:Be,onToggleInProgress:le,onToggleReview:ze,onToggleComplete:Ye,onToggleCancel:Xe,onSetStatus:bt,onArchiveTask:d,onUnarchive:rt,onOpenTaskById:mt,currentTask:F,commentsEndRef:Ke}=e,St=Rr(F),Lt=pt.useMemo(()=>Kk(Ne,U),[Ne,U]),xt=pt.useMemo(()=>{const se=me.find(tt=>tt.value===Ic),He={value:Ic,label:se?.label||yu,icon:se?.icon||"HelpCircle",color:se?.color||"var(--text-secondary)"},Ee=me.find(tt=>tt.value===l),Me=me.filter(tt=>!tt.disabled||tt.value===Ee?.value).filter(tt=>tt.value!==Ic).map(tt=>({value:tt.value,label:tt.disabled?`${tt.label} (Legacy)`:tt.label,icon:tt.icon,color:tt.color}));return[He,...Me]},[me,l]),Zt=pt.useMemo(()=>{const se=Y.find(Ee=>Ee.value===c);return Y.filter(Ee=>Ee.status!=="retired"||Ee.value===se?.value).map(Ee=>({value:Ee.value,label:Ee.status==="retired"?`${Ee.label} (Retired)`:Ee.label,icon:Ee.icon||"Box",color:Ee.color||"violet-500"}))},[Y,c]),Jt=se=>se&&Nc(se,{month:"short",day:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit"})||null,on=Jt(F?.createdAt),cn=Jt(F?.updatedAt||F?.createdAt),nn=Jt(F?.completedAt),gn=pt.useMemo(()=>{const se=new Date,He=se.getFullYear(),Ee=String(se.getMonth()+1).padStart(2,"0"),De=String(se.getDate()).padStart(2,"0");return`${He}-${Ee}-${De}`},[]),yn=!!(y&&_&&y<_),an=!!(y&&y<gn&&(!F||F.status!=="done"&&F.status!=="cancelled")),kn=b.filter(se=>se.isCompleted).length,[Xt,Gn]=pt.useState(""),[At,Se]=pt.useState(!1),Mt=!!F?.isArchived,Qt=!!F?.isDeleted,zt=pt.useMemo(()=>de.map(se=>{const He=Hp(se);return{value:He||se.id,label:He?`${He} · ${se.title}`:se.title,icon:"Folder",color:"var(--text-secondary)"}}),[de]),Ge=pt.useMemo(()=>zt.some(se=>String(se.value)===String(k||"").trim()),[k,zt]);pt.useEffect(()=>{if(n){At&&Se(!1);return}if(k.trim()){if(Ge&&At){Se(!1);return}!Ge&&!At&&Se(!0)}},[n,Ge,At,k]);const An=Mt||Qt,J=pt.useRef(null),_e=cf(Cp(pf,{activationConstraint:{distance:6}}));pt.useLayoutEffect(()=>{const se=J.current;if(!se)return;const He=()=>{se.scrollTop=0;const De=se.parentElement;De&&(typeof De.scrollTo=="function"?De.scrollTo({top:0,left:0,behavior:"auto"}):De.scrollTop=0)};He();const Ee=window.requestAnimationFrame(He);return()=>window.cancelAnimationFrame(Ee)},[n,F?.id]);const we=()=>{const se=Xt.trim();if(!se)return;const He=new Date().toISOString();A([...b,{id:`checklist-draft-${He}-${b.length}`,taskId:n||"",title:se,isCompleted:!1,order:b.length,createdAt:He,updatedAt:He}]),Gn("")},Ie=pt.useCallback(se=>{const{active:He,over:Ee}=se;if(!Ee||He.id===Ee.id)return;const De=b.findIndex(Et=>Et.id===He.id),Me=b.findIndex(Et=>Et.id===Ee.id);if(De<0||Me<0)return;const tt=new Date().toISOString(),Nn=bg(b,De,Me).map((Et,ya)=>({...Et,order:ya,updatedAt:tt}));A(Nn)},[b,A]),We=se=>{const He=String(se||"").trim(),Ee=se.trim().replace(/^ai-profile-/i,"").replace(/[-_]+/g," ").replace(/\s+/g," ");return!Ee||Ee==="ai"||He.toLowerCase().startsWith("ai-profile-")?"AI Agent":`AI Agent - ${Ee.split(" ").map(Me=>Me.charAt(0).toUpperCase()+Me.slice(1)).join(" ")}`},Qe=Iy(fe,C),ot=lu(C),et=wc(C,Qe),_t=pt.useMemo(()=>new Map(Qe.map(se=>[String(se.value),se])),[Qe]),vt=_t.get(String(C||"unassigned")),Ot=F?.assigneeActor?.color||vt?.color,it=pt.useMemo(()=>{const se=[F?.assigneeActor,F?.createdByActor].filter(Boolean);return new Map(se.map(He=>[String(He.id),He]))},[F?.assigneeActor,F?.createdByActor]),It=pt.useMemo(()=>Array.isArray(F?.activity)&&F.activity.length>0?F.activity:E.map(se=>({id:`comment:${se.id}`,type:"comment",timestamp:se.timestamp,comment:se})),[E,F?.activity]),wt=(se,He)=>{if(se==="assignee")return wc(String(He||"").trim(),Qe)},_n=pt.useCallback((se,He,Ee)=>{if(Ee&&Ee.trim())return Ee.trim();const De=String(se||"").trim();if(!De)return He==="ai"?"AI Agent":xe("taskForm.you");const Me=it.get(De);if(Me?.label)return Me.label;const tt=_t.get(De)||_t.get(De.toLowerCase());return tt?.label?tt.label:He==="ai"?We(De):wc(De,Qe)||De},[it,_t,We,Qe]),Dn=pt.useMemo(()=>{const se=It[0];if(!se)return null;if(se.type==="comment"){const Ee=se.comment;return _n(Ee.author,Ee.actor?.kind==="ai"?"ai":Ee.actor?.kind==="human"?"human":null,Ee.actor?.label||null)}const He=se.event;return _n(He.actor,He.actorType,He.actorProfile?.label||null)},[_n,It]),Jn=pt.useMemo(()=>{if(!F?.completedAt)return null;for(const He of It){if(He.type!=="event")continue;const Ee=He.event,De=Ee.details?.changes?.status?.to;if(De==="done"||De==="cancelled")return _n(Ee.actor,Ee.actorType,Ee.actorProfile?.label||null)}return Dn},[F?.completedAt,Dn,_n,It]),ht=F?.createdByActor?.label||_n(F?.createdBy||null,F?.createdByActor?.kind==="ai"?"ai":F?.createdByActor?.kind==="human"?"human":null,F?.createdByActor?.label||null),gt=Dn,Xn=It.length;return t.jsxs("form",{ref:J,onSubmit:re,className:`${u.form} ${u.appScrollbar} tf-scrollbar`,children:[s&&t.jsx("div",{className:Le.error,children:s}),An&&t.jsx("div",{className:`${Le.formNotice} tf-text-helper`,children:Qt?"Deleted tasks are read-only. Restore the task to make changes.":"Archived tasks are read-only. Unarchive the task to make changes."}),t.jsxs("fieldset",{disabled:An,className:Le.formFieldsetReset,children:[t.jsxs("div",{className:u.field,children:[t.jsxs("div",{className:u.labelRow,children:[t.jsx("label",{className:u.label,children:"Title"}),C&&t.jsx("span",{title:`Assigned to: ${et}`,className:[Le.assigneeIndicator,ot==="agent"?Le.assigneeIndicatorAgent:ot==="member"?Le.assigneeIndicatorUser:Le.assigneeIndicatorUnassigned].join(" "),style:Ot?{color:Ot}:void 0,children:ot==="agent"?t.jsx(Xd,{size:20}):ot==="member"?t.jsx(Ac,{size:20}):t.jsx(xi,{size:20})})]}),t.jsx("input",{type:"text",value:r,onChange:se=>Ve(se.target.value),placeholder:"What needs to be done?",className:u.input,required:!0,maxLength:255,autoFocus:!0})]}),t.jsxs("div",{className:u.field,children:[t.jsxs("div",{className:u.labelRow,children:[t.jsx("label",{className:u.label,children:"Description"}),t.jsx("button",{type:"button",className:u.helpLink,onClick:()=>je(!V),title:"Markdown Help",tabIndex:-1,children:t.jsx(xi,{size:14})})]}),V&&t.jsxs("div",{className:Le.markdownHelp,children:[t.jsxs("div",{className:Le.helpHeader,children:[t.jsx("span",{children:"Markdown Guide"}),t.jsx("button",{onClick:()=>je(!1),className:Le.helpClose,children:t.jsx(ji,{size:12})})]}),t.jsxs("div",{className:Le.helpGrid,children:[t.jsx("div",{children:t.jsx("code",{children:"**bold**"})}),t.jsx("div",{children:t.jsx("code",{children:"_italic_"})}),t.jsx("div",{children:t.jsx("code",{children:"- list"})}),t.jsx("div",{children:t.jsx("code",{children:"1. list"})}),t.jsx("div",{className:Le.helpGridItem,children:t.jsx("code",{children:"`inline code`"})}),t.jsxs("div",{className:Le.helpGridItem,children:[t.jsx("code",{children:"```"}),t.jsx("br",{}),t.jsx("code",{children:"code block"}),t.jsx("br",{}),t.jsx("code",{children:"```"})]}),t.jsx("div",{children:t.jsx("code",{children:"[link](url)"})})]})]}),K||!o?t.jsx("textarea",{className:`${u.textarea} ${Le.descriptionSurface}`,placeholder:"What needs to be done? (Markdown supported)",value:o,onChange:se=>Re(se.target.value),onFocus:()=>j(!0),onBlur:()=>j(!1),rows:9,autoFocus:K}):t.jsx("div",{className:`${u.textarea} ${Le.descriptionSurface} ${Le.markdownPreview} ${Le.markdownPreviewContainer}`,onClick:()=>j(!0),children:t.jsx(Np,{onTaskIdClick:mt,children:o})})]}),t.jsxs("div",{className:Le.compactMetaSection,children:[t.jsxs("div",{className:Le.compactMetaGrid,children:[t.jsxs("div",{className:`${u.field} ${Le.compactMetaField}`,children:[t.jsx("label",{id:"category-label",className:u.label,children:B?.category||"Category"}),t.jsx(Rl,{value:l,options:xt,onChange:se=>Ce(String(se)),required:!0,ariaLabelledBy:"category-label"})]}),t.jsxs("div",{className:`${u.field} ${Le.compactMetaField}`,children:[t.jsx("label",{id:"type-label",className:u.label,children:B?.type||"Type"}),t.jsx(Rl,{value:c,options:Zt,onChange:se=>Fe(String(se)),ariaLabelledBy:"type-label"})]}),t.jsxs("div",{className:`${u.field} ${Le.compactMetaField}`,children:[t.jsx("label",{htmlFor:"task-form-scheduled-date",className:u.label,children:xe("taskForm.scheduledLabel")}),t.jsx("input",{id:"task-form-scheduled-date",type:"date",value:_,onChange:se=>Z(se.target.value),className:`${u.input} ${u.taskFormDateInput}`})]}),t.jsx("div",{className:Le.compactMetaSpacer,"aria-hidden":"true"}),t.jsxs("div",{className:`${u.field} ${Le.compactMetaField}`,children:[t.jsx("label",{id:"assignee-label",className:u.label,children:"Assigned To"}),t.jsx(Rl,{value:C||"unassigned",options:Qe,onChange:se=>P(String(se)),ariaLabelledBy:"assignee-label"})]}),t.jsx("div",{className:Le.compactMetaField,children:t.jsx(up,{label:B?.priority||"Priority",options:R,value:p,onChange:x,type:"priority",showSelectedLabel:!1})}),t.jsxs("div",{className:`${u.field} ${Le.compactMetaField}`,children:[t.jsx("label",{htmlFor:"task-form-due-date",className:u.label,children:xe("taskForm.dueLabel")}),t.jsx("input",{id:"task-form-due-date",type:"date",value:y,onChange:se=>M(se.target.value),className:`${u.input} ${u.taskFormDateInput}`}),yn&&t.jsx("span",{className:`${Le.taskFormDateWarning} ${Le.compactMetaFieldHint}`,children:xe("taskForm.dueBeforeScheduled")}),an&&t.jsx("span",{className:`${Le.taskFormDateError} ${Le.compactMetaFieldHint}`,children:xe("taskForm.overdue")})]}),w&&t.jsx("div",{className:Le.compactMetaField,children:t.jsx(up,{label:"Complexity",options:[{value:1,label:"Tiny",color:"#10b981",icon:"Gauge"},{value:2,label:"Low",color:"#14b8a6",icon:"Gauge"},{value:3,label:"Medium",color:"#3b82f6",icon:"Gauge"},{value:4,label:"High",color:"#8b5cf6",icon:"Gauge"},{value:5,label:"Epic",color:"#d946ef",icon:"Gauge"}],value:g,onChange:L,type:"general"})})]}),!n&&t.jsxs("div",{className:Le.createWorkstreamRow,children:[t.jsx("label",{className:u.label,children:"Attach to workstream"}),t.jsxs("div",{className:u.pathInputGroup,children:[At?t.jsx("input",{type:"text",className:u.input,value:k,onChange:se=>h(se.target.value),placeholder:"Type a workstream name or reference","aria-label":"Attach to workstream"}):t.jsx(Rl,{value:k,options:zt,onChange:se=>h(String(se)),placeholder:"Select workstream...",ariaLabel:"Attach to workstream",className:Le.createWorkstreamDropdown}),t.jsx("button",{type:"button",className:u.secondaryHeaderBtn,onClick:()=>{if(At){Se(!1),Ge||h("");return}Se(!0)},"aria-label":At?"Use workstream dropdown":"Enter workstream by name",title:At?"Use workstream dropdown":"Enter workstream by name",children:t.jsx(sr,{size:14})})]})]})]}),t.jsxs("div",{className:Le.sectionBlock,children:[t.jsx("div",{className:Le.taxonomyFieldsGrid,children:Lt.map(se=>{if(se.id==="approach"&&se.isSystem)return null;const He=U[se.id],Ee=Array.isArray(He)?He.map(Me=>String(Me)):He!=null&&He!==""?[String(He)]:[],De=se.options.filter(Me=>Me.status!=="retired"||Ee.includes(String(Me.value)));return t.jsxs("div",{className:u.field,children:[t.jsx("label",{className:u.label,children:se.label}),se.description&&t.jsx("div",{className:`${Le.settingsHint} tf-text-helper`,children:se.description}),se.widgetType==="level"?t.jsx(up,{label:se.label,options:De.map(Me=>({...Me,label:Me.status==="retired"?`${Me.label} (Retired)`:Me.label})),value:U[se.id]||"",onChange:Me=>ee(se.id,Me),type:"general",hideLabel:!0}):se.multiSelect?t.jsx("div",{className:`${u.dropdownList} ${Le.softSectionSurface}`,children:De.map(Me=>{const tt=String(Me.value),Nn=Ee.includes(tt);return t.jsxs("button",{type:"button",className:`${Le.specialistChip} ${Nn?Le.specialistChipActive:""}`,onClick:()=>{const Et=Nn?Ee.filter(ya=>ya!==tt):[...Ee,tt];ee(se.id,Et)},title:Nn?"Click to remove":"Click to add",children:[Nn&&t.jsx(so,{size:12}),Me.status==="retired"?`${Me.label} (Retired)`:Me.label]},tt)})}):t.jsxs("div",{className:u.fieldIconWrapper,style:{"--field-color":"var(--text-primary)","--field-border":"rgba(255, 255, 255, 0.1)","--field-bg":"rgba(255, 255, 255, 0.02)"},children:[(()=>{const Me=se.options.find(Et=>String(Et.value)===String(U[se.id])),tt=Me?.icon&&$s[Me.icon]?$s[Me.icon]:xi,Nn=Me?.color||"var(--text-secondary)";return t.jsx("div",{className:u.fieldIcon,style:{color:_a(Nn)},children:t.jsx(tt,{size:16})})})(),t.jsxs("select",{value:U[se.id]||"",onChange:Me=>ee(se.id,Me.target.value),className:`${u.select} ${u.field_dynamic}`,required:se.isRequired,children:[t.jsxs("option",{value:"",children:["Select ",se.label,"..."]}),De.map(Me=>t.jsx("option",{value:Me.value,children:Me.status==="retired"?`${Me.label} (Retired)`:Me.label},Me.value))]})]})]},se.id)})}),D&&t.jsxs("div",{className:u.specialistSection,children:[t.jsxs("div",{className:u.toggleHeading,onClick:()=>O(!ne),title:ne?"Hide checklist":"Show checklist",children:[t.jsxs("label",{className:u.label,children:["Checklist ",b.length>0&&`(${kn}/${b.length})`]}),ne?t.jsx(jc,{size:14}):t.jsx(Ii,{size:14})]}),ne&&t.jsxs("div",{className:`${u.dropdownList} ${Le.stackedList} ${Le.stackedListSpaced}`,children:[t.jsxs("div",{className:u.pathInputGroup,children:[t.jsx("input",{type:"text",className:u.input,placeholder:"Add checklist item",value:Xt,onChange:se=>Gn(se.target.value),onKeyDown:se=>{se.key==="Enter"&&(se.preventDefault(),we())}}),t.jsx("button",{type:"button",className:u.secondaryHeaderBtn,onClick:we,disabled:!Xt.trim(),children:"Add"})]}),b.length>0?t.jsx(lf,{sensors:_e,collisionDetection:_g,onDragEnd:Ie,children:t.jsx(df,{items:b.map(se=>se.id),strategy:uf,children:b.map((se,He)=>t.jsx(SR,{id:se.id||`checklist-${He}`,item:se,onToggle:()=>{const Ee=new Date().toISOString();A(b.map((De,Me)=>Me===He?{...De,isCompleted:!De.isCompleted,updatedAt:Ee}:De))},onRemove:()=>A(b.filter((Ee,De)=>De!==He).map((Ee,De)=>({...Ee,order:De})))},se.id||`checklist-${He}`))})}):t.jsx("div",{className:`${Le.settingsHint} tf-text-helper`,children:"No checklist items yet."})]})]})]}),t.jsxs("div",{children:[t.jsx(kR,{taskId:n,taskReferenceLabel:St,workspaceId:Q,apiBaseUrl:z,contextFiles:W,onAddContextFile:G,onRemoveContextFile:q,onUpdateContextCaption:ye}),n&&t.jsxs("div",{className:u.specialistSection,children:[t.jsxs("div",{className:u.toggleHeading,onClick:()=>ue(!Ae),title:xe(Ae?"taskForm.hideComments":"taskForm.showComments"),children:[t.jsxs("label",{className:u.label,children:[xe("taskForm.commentsSectionTitle")," ",Xn>0&&`(${Xn})`]}),Ae?t.jsx(jc,{size:14}):t.jsx(Ii,{size:14})]}),Ae&&t.jsxs("div",{className:Le.commentPanel,children:[t.jsxs("div",{className:Le.commentThread,children:[Xn===0&&t.jsx("div",{className:Le.emptyComments,children:xe("taskForm.noComments")}),It.map(se=>{if(se.type==="comment"){const Kt=se.comment,yt=String(Kt.author||"").trim(),qt=yt.toLowerCase(),Ht=it.get(yt),sn=_t.get(yt)||_t.get(qt),ft=Kt.actor||Ht||sn||null,Ze=Kt.actor?.kind==="human"?"member":Kt.actor?.kind==="ai"?"agent":Ht?.kind==="human"?"member":Ht?.kind==="ai"?"agent":sn?.kind||(qt===""||qt==="user"||qt==="human"?"member":"agent"),Vn=Kt.actor?.label||Ht?.label||sn?.label||(yt?wc(yt,Qe):"")||(Ze==="agent"?We(yt||"ai"):xe("taskForm.you")),pn=Kt.actor?.color||Ht?.color||sn?.color,$t=String(ft?.icon||(Ze==="agent"?"Bot":"User")),Wt=Ni[$t]||(Ze==="agent"?Xd:Ac);return t.jsxs("div",{className:`${Le.comment} ${Ze==="agent"?Le.commentAi:Le.commentUser}`,children:[t.jsxs("div",{className:Le.commentHeader,children:[t.jsx("span",{className:Le.commentAuthor,style:pn?{color:pn}:void 0,children:t.jsxs(t.Fragment,{children:[t.jsx(Wt,{size:12,strokeWidth:1.5})," ",Vn]})}),t.jsx("span",{className:Le.commentTime,children:Nc(Kt.timestamp,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})})]}),t.jsx("div",{className:Le.commentText,style:pn?{background:`linear-gradient(135deg, ${mp(pn,.18)} 0%, ${mp(pn,.1)} 100%)`,borderColor:mp(pn,.35)}:void 0,children:t.jsx(Np,{onTaskIdClick:mt,children:Kt.text})})]},Kt.id)}const He=se.event,Ee=String(He.actor||"").trim(),De=Ee.toLowerCase(),Me=it.get(Ee),tt=_t.get(Ee)||_t.get(De),Nn=He.actorProfile||Me||tt||null,Et=He.actorType==="ai"?"agent":He.actorType==="human"?"member":"system",ya=He.actorProfile?.label||Me?.label||tt?.label||(Et==="system"?"System":Ee?wc(Ee,Qe):Et==="agent"?We("ai"):xe("taskForm.you")),Pn=He.actorProfile?.color||Me?.color||tt?.color,Cn=String(Nn?.icon||(Et==="agent"?"Bot":Et==="member"?"User":"ClipboardList")),Sn=Ni[Cn]||(Et==="agent"?Xd:Et==="member"?Ac:Xh),ln=Object.entries(He.details?.changes||{});return t.jsxs("div",{className:`${Le.comment} ${Le.activityEvent} ${Et==="system"?Le.activityEventSystem:""}`,children:[t.jsxs("div",{className:`${Le.commentHeader} ${Le.activityEventHeader}`,children:[t.jsx("span",{className:Le.commentAuthor,style:Pn?{color:Pn}:void 0,children:t.jsxs(t.Fragment,{children:[t.jsx(Sn,{size:12,strokeWidth:1.5})," ",ya]})}),t.jsx("span",{className:Le.commentTime,children:Nc(He.createdAt,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})})]}),t.jsxs("div",{className:Le.activityEventText,children:[t.jsx("div",{children:sh(He,wt)}),ln.length>1&&t.jsx("div",{className:Le.activityEventChanges,children:ln.map(([Kt,yt])=>t.jsx("span",{className:Le.activityEventChange,children:ah(Kt,yt,wt)},Kt))})]})]},se.id)}),t.jsx("div",{ref:Ke})]}),t.jsxs("div",{className:Le.commentInputArea,children:[t.jsx("textarea",{className:Le.commentInput,placeholder:xe("taskForm.commentPlaceholder"),value:S,onChange:se=>H(se.target.value),onKeyDown:se=>{se.key==="Enter"&&!se.shiftKey&&(se.preventDefault(),pe())},rows:1}),t.jsx("button",{type:"button",className:Le.sendCommentBtn,onClick:pe,disabled:!S.trim(),children:t.jsx(Qh,{size:16})})]})]})]}),t.jsx("div",{className:`${Le.taskFormLifecycle} ${Le.taskFormMetaDivider}`,children:t.jsx("div",{className:Le.taskFormMetaGrid,children:F&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:Le.taskFormDateRow,children:[t.jsx("span",{className:Le.taskFormDateLabel,children:xe("taskForm.createdLabel")}),t.jsxs("span",{className:Le.taskFormMetaStack,children:[t.jsx("span",{className:Le.taskFormDateValue,children:on||xe("taskForm.emptyValue")}),t.jsx("span",{className:Le.taskFormMetaActor,children:ht?`by ${ht}`:xe("taskForm.emptyValue")})]})]}),t.jsxs("div",{className:Le.taskFormDateRow,children:[t.jsx("span",{className:Le.taskFormDateLabel,children:xe("taskForm.updatedLabel")}),t.jsxs("span",{className:Le.taskFormMetaStack,children:[t.jsx("span",{className:Le.taskFormDateValue,children:cn||xe("taskForm.emptyValue")}),t.jsx("span",{className:Le.taskFormMetaActor,children:gt?`by ${gt}`:xe("taskForm.emptyValue")})]})]}),t.jsxs("div",{className:Le.taskFormDateRow,children:[t.jsx("span",{className:Le.taskFormDateLabel,children:xe("taskForm.completedLabel")}),t.jsxs("span",{className:Le.taskFormMetaStack,children:[t.jsx("span",{className:Le.taskFormDateValue,children:nn||xe("taskForm.emptyValue")}),t.jsx("span",{className:Le.taskFormMetaActor,children:Jn?`by ${Jn}`:xe("taskForm.emptyValue")})]})]})]})})})]}),t.jsxs("div",{className:Le.keyboardHint,children:["Press ",t.jsx("kbd",{children:navigator.platform.includes("Mac")?"⌥":"Alt"})," to toggle"]})]})]})}function mh({editingTaskId:e,loading:n,autoSaveState:s="idle",title:r,handleSubmit:o,resetForm:l,handleCopyId:c,copiedId:p,tasks:g,currentTask:w,currentTaskWorkstream:C,currentTaskInitiative:_,workstreamInput:y="",onWorkstreamInputChange:k,onSetWorkstreamForCurrentTask:b,handleToggleInProgress:E,handleToggleReview:S,handleToggleComplete:W,handleToggleCancel:Q,handleSetStatus:z,handleArchiveTask:K,handleRestoreDeletedTask:V,handlePermanentlyDeleteDeletedTask:ne}){const[D,Ae]=pt.useState(!1),U=w??(e&&g.find(ae=>ae.id===e)||null),ee=!!U?.isArchived,be=!!U?.isDeleted,me=bf(U),Y=me.label||(me.isProvisional?"Pending":""),R=me.isProvisional,B=!!me.label,fe=C?Hp(C)||C.id:"",Ne=_?ar(_)||_.id:"";pt.useEffect(()=>{C&&Ae(!1)},[C?.id]);const de=pt.useCallback(()=>{y.trim()&&b?.()},[b,y]);return t.jsx("div",{className:u.stickyActionHeader,children:e?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:u.taskHierarchyHeader,children:[t.jsxs("div",{className:u.taskHierarchyBadgeRow,children:[_?t.jsxs(t.Fragment,{children:[t.jsx(eu,{copied:p===Ne,onClick:ae=>c(ae,Ne),disabled:n,title:"Copy initiative reference",label:Ne}),t.jsx("span",{className:u.taskHierarchyDivider,children:"/"})]}):null,C?t.jsxs(t.Fragment,{children:[t.jsx(eu,{copied:p===fe,onClick:ae=>c(ae,fe),disabled:n,title:"Copy workstream reference",label:fe}),t.jsx("span",{className:u.taskHierarchyDivider,children:"/"})]}):t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:`${u.taskIdBadge} ${u.taskHierarchyAddBtn}`,onClick:()=>{k?.(""),Ae(ae=>!ae)},disabled:n||ee||be,title:"Attach to workstream","aria-label":"Attach to workstream",children:t.jsx(sr,{size:13})}),t.jsx("span",{className:u.taskHierarchyDivider,children:"/"})]}),Y?t.jsx(eu,{copied:B&&p===me.label,onClick:ae=>c(ae,me.label),disabled:n||!B,title:B?xe("actionHeader.copyTaskIdTitle"):"Task reference pending sync",label:Y}):null,R?t.jsx("span",{className:u.taskHierarchyMeta,title:"Temporary local reference until cloud sync assigns the final task number.",children:"Pending sync"}):null]}),D&&!C?t.jsxs("div",{className:u.taskHierarchyEditor,children:[t.jsx("input",{type:"text",className:`${u.input} ${u.taskHierarchyInput}`,value:y,onChange:ae=>k?.(ae.target.value),placeholder:"WS-123","aria-label":"Attach workstream reference",onKeyDown:ae=>{ae.key==="Enter"&&(ae.preventDefault(),de()),ae.key==="Escape"&&(ae.preventDefault(),k?.(""),Ae(!1))}}),t.jsx("button",{type:"button",className:"tf-control-icon tf-control-icon-compact",onClick:de,disabled:!y.trim()||n,title:"Attach workstream","aria-label":"Attach workstream",children:t.jsx(so,{size:14})}),t.jsx("button",{type:"button",className:"tf-control-icon tf-control-icon-compact",onClick:()=>{k?.(""),Ae(!1)},disabled:n,title:"Cancel workstream attach","aria-label":"Cancel workstream attach",children:t.jsx(ji,{size:14})})]}):null]}),t.jsx("div",{className:u.taskSaveStatusCenter,children:t.jsx("div",{className:`${u.taskSaveStatus} ${s==="error"?u.taskSaveStatusError:""}`,"aria-live":"polite",children:s==="saving"?t.jsxs(t.Fragment,{children:[t.jsx(Fa,{size:14,className:u.spinner}),t.jsx("span",{children:"Saving…"})]}):s==="saved"?t.jsx("span",{children:"Saved"}):s==="error"?t.jsx("span",{children:"Save failed"}):null})}),t.jsx("div",{className:u.editActionsGroup,children:be&&U?.deletedRecordId?t.jsxs(t.Fragment,{children:[V&&t.jsx("button",{type:"button",className:u.actionBtn,onClick:()=>V(U.deletedRecordId||""),disabled:n,title:"Restore deleted task",children:t.jsx(wp,{size:16})}),ne&&t.jsx("button",{type:"button",className:`${u.actionBtn} ${u.deleteBtn}`,onClick:()=>ne(U.deletedRecordId||""),disabled:n,title:"Permanently delete deleted task",children:t.jsx(Fl,{size:16})})]}):t.jsx(nh,{task:U,disabled:n||ee,onSetStatus:(ae,Ve)=>{if(z){z(ae,Ve);return}if(Ve==="in-progress"){E(ae);return}if(Ve==="review"){S(ae);return}if(Ve==="done"){W(ae);return}Ve==="cancelled"&&Q(ae)},onArchiveTask:K})})]}):t.jsxs(t.Fragment,{children:[t.jsxs("button",{type:"button",onClick:l,disabled:n,className:u.secondaryHeaderBtn,title:xe("actionHeader.clearFormTitle"),children:[t.jsx(wp,{size:16}),xe("actionHeader.clear")]}),t.jsxs("button",{type:"button",onClick:ae=>o(ae),disabled:n||!r.trim(),className:u.primaryUpdateBtn,title:xe("actionHeader.addTaskTitle"),children:[n?t.jsx(Fa,{size:16,className:u.spinner}):t.jsx(sr,{size:16}),xe("actionHeader.addTask")]})]})})}const vR="_topNoticeLayer_1m6a1_1",wR="_topNotice_1m6a1_1",bR="_topNoticeMessage_1m6a1_32",_R="_topNoticeSuccess_1m6a1_38",CR="_topNoticeError_1m6a1_44",xR="_topNoticeInfo_1m6a1_50",AR="_topNoticeDismiss_1m6a1_56",vi={topNoticeLayer:vR,topNotice:wR,topNoticeMessage:bR,topNoticeSuccess:_R,topNoticeError:CR,topNoticeInfo:xR,topNoticeDismiss:AR};function fh({notice:e,onDismiss:n}){if(!e)return null;const s=e.tone==="error"?vi.topNoticeError:e.tone==="success"?vi.topNoticeSuccess:vi.topNoticeInfo,r=e.tone==="error"?"alert":"status";return t.jsx("div",{className:vi.topNoticeLayer,children:t.jsxs("div",{className:`${vi.topNotice} ${s}`,role:r,"aria-live":e.tone==="error"?"assertive":"polite",children:[e.tone==="error"?t.jsx(Rc,{size:14}):e.tone==="success"?t.jsx(so,{size:14}):t.jsx(tg,{size:14}),t.jsx("span",{className:vi.topNoticeMessage,children:e.message}),n&&t.jsx("button",{type:"button",className:vi.topNoticeDismiss,onClick:n,"aria-label":"Dismiss notice",title:"Dismiss notice",children:t.jsx(ji,{size:14})})]})})}const TR=pt.lazy(()=>Bo(()=>import("./TaskSettings-Bqd4cCzW.js"),__vite__mapDeps([0,1,2,3,4,5,6])).then(e=>({default:e.TaskSettings})));function IR(e){const{activeTab:n,setActiveTab:s,isOpen:r,setIsOpen:o,currentTheme:l,setCurrentTheme:c,saveSettings:p,pathSaved:g,keyShortcut:w,setKeyShortcut:C,jsonBackupEnabled:_,setJsonBackupEnabled:y,mcpHostRoot:k,setMcpHostRoot:b,settingsSection:E,setSettingsSection:S,projectRoot:W,projectName:Q,mcpScriptPath:z,serverHostRoot:K,showFolderBrowser:V,setShowFolderBrowser:ne,folders:D,files:Ae,currentBrowsePath:U,fetchFolders:ee,browserTarget:be,setBrowserTarget:me,handleSelectPath:Y,handleAddPath:R,handleRemovePath:B,tasks:fe,loadingTasks:Ne,archivedTasks:de,deletedTasks:ae,activeCategories:Ve,activeTypes:Re,priorities:Ce,taxonomyDisplayLabels:Fe,approaches:x,taxonomies:L,searchQuery:P,setSearchQuery:Z,filterCategories:M,setFilterCategories:h,filterTypes:A,setFilterTypes:H,filterPriorities:j,setFilterPriorities:je,filterStatus:O,setFilterStatus:ue,filterAssignees:re,setFilterAssignees:pe,assigneeOptions:G,filterTaxonomies:q,setFilterTaxonomies:ye,sortBy:Be,setSortBy:le,sortOrder:ze,toggleSortOrder:Ye,showArchive:Xe,setShowArchive:bt,taskScope:d,setTaskScope:rt,clearFilters:mt,filteredTasks:F,filteredArchive:Ke,groupedTasks:St,collapsedCategories:Lt,setCollapsedCategories:xt,handleEdit:Zt,handleDelete:Jt,handleCopyId:on,handleToggleComplete:cn,handleToggleCancel:nn,handleToggleInProgress:gn,handleToggleReview:yn,handleArchiveTask:an,handleBulkArchive:kn,handleUnarchive:Xt,handleRestoreDeletedTask:Gn,handlePermanentlyDeleteDeletedTask:At,handleEmptyDeletedTasks:Se,fetchArchive:Mt,editingTaskId:Qt,loading:zt,error:Ge,title:An,setTitle:J,description:_e,setDescription:we,checklistItems:Ie,setChecklistItems:We,category:Qe,setCategory:ot,type:et,setType:_t,priority:vt,setPriority:Ot,complexity:it,setComplexity:It,manualComplexityEnabled:wt,checklistDropdownEnabled:_n,showTaskCardStatusLabel:Dn,approach:Jn,setApproach:ht,assignee:gt,setAssignee:Xn,scheduledDate:se,setScheduledDate:He,dueDate:Ee,setDueDate:De,workstreamInput:Me,setWorkstreamInput:tt,formTaxonomies:Nn,setFormTaxonomies:Et,comments:ya,newCommentText:Pn,setNewCommentText:Cn,attachments:Sn,setAttachments:ln,setAttachmentsDirty:Kt,descriptionFocused:yt,setDescriptionFocused:qt,showMarkdownHelp:Ht,setShowMarkdownHelp:sn,showChecklist:ft,setShowChecklist:Ze,showComments:Vn,setShowComments:pn,handleSubmit:$t,resetForm:Wt,handleAddComment:Rt,handleSetWorkstreamForCurrentTask:fs,handleOpenTaskById:Ds,autoSaveState:aa,unsavedModalOpen:fn,setUnsavedModalOpen:sa,pendingNavigation:On,handleNavigation:$n,handleClose:Ka,scheduleWarningPrompt:Wn,confirmScheduleWarning:rn,cancelScheduleWarning:ra,uiNotice:Yt,clearNotice:Fn,taskReturnTrail:jn,clearReturnToParentTask:xn,returnToPreviousTask:fa,copiedId:nt,recentlyChangedTaskIds:vn,tasksScrollRef:dn,setTasksScrollPos:za,currentTask:oa,currentTaskWorkstream:Ya,currentTaskInitiative:Qn,exportEnvironment:Ta,setExportEnvironment:ka,exportWorkflowsPath:Zn,setExportWorkflowsPath:hs,exportResult:en,exportingResource:Ia,availableWorkflows:ha,onExportWorkflows:Ca,availableEnvironments:Na,handleUpdateCategory:Us,handleRemoveCategory:io,handleSaveCategory:Oa,handleUpdateCategoryIcon:oe,handleUpdateCategoryColor:lt,handleSaveType:Ft,handleRemoveType:Tt,handleUpdateTaxonomies:Tn,handleUpdatePriorities:dt,pathValidation:wn,validatePaths:ia,getCategoryPaths:ga,commentsEndRef:ja,currentWorkspaceId:Kn,settingsModel:ea,onHeaderMouseDown:rr,isDragging:Ra}=e,pa=a.useRef(null),[ca,Da]=pt.useState(0);a.useLayoutEffect(()=>{if(n==="tasks"&&dn.current&&ca>0){const qe=setTimeout(()=>{dn.current&&(dn.current.scrollTop=ca)},50);return()=>clearTimeout(qe)}},[n,ca,fe]);const Sa=qe=>{le(qe)},rs=()=>{$n(()=>{if(n==="add"||n==="settings"){if(n==="add"&&fa())return;n==="add"&&jn.length>0&&xn(),n==="add"&&Wt(),s("tasks")}else e.onClose?e.onClose():Ka()})},co=()=>{sa(!1),On?(n==="add"&&Wt(),On()):s("tasks")},Ri=async()=>{await $t({preventDefault:()=>{}}),sa(!1),On&&On()},qs=(qe,Gt)=>{Et(Pa=>({...Pa,[qe]:Gt})),qe==="approach"&&typeof Gt=="string"&&ht(Gt)},or=a.useCallback(qe=>{Wt(),ot(qe),$n(()=>{s("add")})},[Wt,ot,s,$n]),la=pt.useMemo(()=>ae.map(qe=>({...qe.taskSnapshot,isDeleted:!0,deletedRecordId:qe.id})),[ae]),da=pt.useMemo(()=>new globalThis.Map(ae.map(qe=>[qe.taskId,qe])),[ae]),Ps=pt.useMemo(()=>{const qe=P.toLowerCase(),Gt=Ve.every(Te=>M.includes(Te.value)),Pa=Re.every(Te=>A.includes(Te.value)),va=Array.from(new Set(j.map(Te=>Number(Te)).filter(Te=>Number.isFinite(Te)))),Pr=Ce.map(Te=>Number(Te.value)).filter(Te=>Number.isFinite(Te)).every(Te=>va.includes(Te)),I=["task","in-progress","review","done","cancelled","on-hold"].every(Te=>O.includes(Te)),ke=G.length>0&&G.every(Te=>re.includes(Te.value)),$e=Gl(L,la);return la.filter(Te=>{const X=Rr(Te).toLowerCase(),Pe=!qe||Te.title.toLowerCase().includes(qe)||(Te.description?.toLowerCase()||"").includes(qe)||Te.id.toLowerCase().includes(qe)||X.includes(qe),Dt=Gt||M.includes(Te.category),Nt=Pr||va.includes(ou(Te.priority)),Ja=Pa||A.includes(Te.type||ms),qn=I||O.includes(Te.status),En=ke||re.includes(Te.assignee||"unassigned"),os=Object.entries(q).every(([Es,uo])=>{const Ls=$e.find(cr=>cr.id===Es);if(!Ls||Gp(Ls,la).every(cr=>uo.includes(cr.value)))return!0;const Fo=Te.taxonomies?.[Es];return Fo?Array.isArray(Fo)?Fo.some(cr=>uo.includes(cr)):uo.includes(Fo):uo.includes("")});return Pe&&Dt&&Nt&&Ja&&qn&&En&&os}).sort((Te,X)=>uu(Te,X,Be,ze,L))},[Ve,Re,de,G,la,re,M,j,O,q,A,Ce,P,Be,ze,L,fe]),lo=pt.useMemo(()=>{const qe={};return Ps.forEach(Gt=>{const va=Ve.find(gs=>gs.value===Gt.category||gs.label===Gt.category)?.label||Gt.category||"General";qe[va]||(qe[va]=[]),qe[va].push(Gt)}),qe},[Ve,Ps]),ir=d==="archived"?Ke.length:d==="deleted"?Ps.length:F.length;return t.jsxs(t.Fragment,{children:[t.jsxs("div",{ref:pa,className:`${ut.modal} ${u.coreModal} ${n==="settings"?ut.settingsViewModal:""}`,"data-theme":l,children:[t.jsxs("div",{className:"tf-modal-header",onMouseDown:rr,style:{cursor:rr?Ra?"grabbing":"grab":"default"},children:[t.jsxs("div",{className:`tf-modal-title ${hn.headerTitleWidget}`,children:["Taskforce",Q&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:u.projectSlash,children:"/"}),t.jsx("span",{className:u.projectName,style:{fontSize:"14px",padding:"1px 6px"},children:Q})]}),t.jsx("span",{className:u.taskCountBadge,title:`${d.charAt(0).toUpperCase()+d.slice(1)} tasks`,children:ir})]}),t.jsxs("div",{className:ut.headerActions,children:[n==="tasks"&&t.jsx(t.Fragment,{children:t.jsx("button",{className:"tf-control-icon",onClick:()=>{$n(()=>{Wt(),s("add")})},title:"Add New Task",children:t.jsx(sr,{size:18})})}),t.jsx("button",{className:`tf-control-icon ${n==="settings"?"tf-control-icon-active":""}`,onClick:()=>{n!=="settings"&&$n(()=>{s("settings")})},title:"Settings",children:t.jsx(af,{size:18})}),t.jsx("button",{className:"tf-control-icon",onClick:rs,title:n==="tasks"?"Close":"Back to Tasks",children:n==="tasks"?t.jsx(ji,{size:20}):t.jsx(ng,{size:20})})]})]}),t.jsx(fh,{notice:Yt,onDismiss:Fn}),n==="add"&&t.jsx(mh,{editingTaskId:Qt,loading:zt,autoSaveState:aa,title:An,currentTask:oa,currentTaskWorkstream:Ya,currentTaskInitiative:Qn,workstreamInput:Me,onWorkstreamInputChange:tt,onSetWorkstreamForCurrentTask:fs,handleSubmit:$t,resetForm:Wt,handleCopyId:on,copiedId:nt,tasks:fe,handleToggleInProgress:gn,handleToggleReview:yn,handleToggleComplete:cn,handleToggleCancel:nn,handleArchiveTask:an,handleRestoreDeletedTask:qe=>{Gn(qe)},handlePermanentlyDeleteDeletedTask:qe=>{At(qe)}}),n==="tasks"&&t.jsx(lh,{ref:dn,tasks:fe,archivedTasks:de,categories:Ve,types:Re,priorities:Ce,taxonomyDisplayLabels:Fe,taxonomies:L,searchQuery:P,filterCategories:M,filterTypes:A,filterPriorities:j,filterStatus:O,filterAssignees:re,assigneeOptions:G,filterTaxonomies:q,sortBy:Be,sortOrder:ze,showArchive:Xe,taskScope:d,collapsedCategories:Lt,loadingTasks:Ne,filteredTasks:F,filteredArchive:Ke,groupedTasks:St,filteredDeletedTasks:Ps,groupedDeletedTasks:lo,copiedId:nt,recentlyChangedTaskIds:vn,showTaskCardStatusLabel:Dn,workstreams:e.workstreams,initiatives:e.initiatives,onSearchChange:Z,onFilterCategoriesChange:qe=>h(qe),onFilterTypesChange:qe=>H(qe),onFilterPrioritiesChange:je,onFilterStatusChange:ue,onFilterAssigneesChange:qe=>pe(qe),onTaxonomyFilterChange:(qe,Gt)=>ye(Pa=>({...Pa,[qe]:Gt})),onSortByChange:Sa,onSortOrderChange:Ye,onShowArchiveChange:bt,onTaskScopeChange:rt,onClearFilters:mt,onToggleCategory:qe=>xt(Gt=>({...Gt,[qe]:!Gt[qe]})),onEditTask:Zt,onOpenTaskById:Ds,onCopyId:on,onToggleInProgress:gn,onToggleReview:yn,onToggleComplete:cn,onToggleCancel:nn,onArchiveTask:an,onBulkArchive:kn,onUnarchive:qe=>{const Gt=da.get(qe);if(Gt){Gn(Gt.id);return}Xt(qe)},onDelete:qe=>{const Gt=da.get(qe);if(Gt){At(Gt.id);return}Jt(qe)},onDeleteAllDeleted:()=>{Se()},onFetchArchive:Mt,onAddTaskToCategory:or,supplementalTasks:la}),n==="add"&&t.jsx(ph,{editingTaskId:Qt,error:Ge,title:An,description:_e,checklistItems:Ie,category:Qe,type:et,priority:vt,complexity:it,manualComplexityEnabled:wt,approach:Jn,assignee:gt,scheduledDate:se,dueDate:Ee,workstreamInput:Me,formTaxonomies:Nn,onTaxonomyChange:qs,taxonomies:L,comments:ya,newCommentText:Pn,contextFiles:Sn,currentWorkspaceId:Kn,apiBaseUrl:"",descriptionFocused:yt,showMarkdownHelp:Ht,showChecklist:ft,checklistEnabled:_n,showComments:Vn,categories:Ve,types:Re,priorities:Ce,taxonomyDisplayLabels:Fe,assigneeOptions:G,workstreams:e.workstreams,copiedId:nt,onTitleChange:J,onDescriptionChange:we,onChecklistItemsChange:We,onCategoryChange:ot,onTypeChange:_t,onPriorityChange:Ot,onComplexityChange:It,onApproachChange:qe=>{ht(qe),Et(Gt=>({...Gt,approach:qe}))},onAssigneeChange:Xn,onScheduledDateChange:He,onDueDateChange:De,onWorkstreamInputChange:tt,onNewCommentTextChange:Cn,onDescriptionFocusedChange:qt,onShowMarkdownHelpChange:sn,onShowChecklistChange:Ze,onShowCommentsChange:pn,onOpenSettings:qe=>{$n(()=>{S(qe),s("settings")})},onSubmit:$t,commentsEndRef:ja,onAddComment:()=>Rt(Pn),onOpenTaskById:Ds,onAddContextFile:qe=>{Kt(!0),ln(Gt=>[...Gt,qe])},onRemoveContextFile:async qe=>{Kt(!0),ln(Gt=>Gt.filter((Pa,va)=>va!==qe))},onUpdateContextCaption:(qe,Gt)=>{Kt(!0),ln(Pa=>Pa.map((va,gs)=>gs!==qe?va:typeof va=="string"?{path:va,caption:Gt,timestamp:new Date().toISOString()}:{...va,caption:Gt}))},onCopyId:on,onToggleInProgress:gn,onToggleReview:yn,onToggleComplete:cn,onToggleCancel:nn,onArchiveTask:an,onUnarchive:qe=>{if(oa?.isDeleted){const Gt=da.get(qe);Gt&&Gn(Gt.id);return}Xt(qe)},currentTask:oa}),n==="settings"&&t.jsx(a.Suspense,{fallback:t.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"2rem"},children:t.jsx(Fa,{size:20,className:u.spinner})}),children:t.jsx(TR,{settingsModel:ea,onSectionChange:S})})]}),V&&Ci.createPortal(t.jsx("div",{className:zn.overlay,children:t.jsxs("div",{className:zn.browser,children:[t.jsxs("div",{className:zn.header,children:[t.jsxs("div",{className:zn.pathInfo,children:[t.jsx(Ai,{size:14}),t.jsx("span",{children:U||"Project Root"})]}),t.jsxs("div",{className:zn.actions,children:[U&&t.jsx("button",{className:u.helpLink,onClick:()=>{const qe=U.split("/").filter(Boolean);qe.pop(),ee(qe.length?qe.join("/")+"/":"")},children:"Back"}),t.jsx("button",{className:u.helpLink,onClick:()=>ne(!1),children:"Close"})]})]}),t.jsxs("div",{className:zn.list,children:[be&&typeof be=="object"&&t.jsxs("div",{className:`${zn.item} ${zn.itemCurrent}`,onClick:()=>Y(U),children:[t.jsx(so,{size:14})," Select Current: ./",U||"(root)"]}),D.map(qe=>t.jsxs("div",{className:zn.item,onClick:()=>ee(U+qe+"/"),children:[t.jsx(Ai,{size:14})," ",qe,"/"]},qe)),Ae.map(qe=>t.jsxs("div",{className:`${zn.item} ${zn.itemFile}`,onClick:()=>Y(U+qe),children:[t.jsx(_p,{size:14})," ",qe]},qe)),D.length===0&&Ae.length===0&&t.jsx("div",{className:`${zn.item} ${zn.empty}`,children:"No items found"})]})]})}),document.body),fn&&t.jsx("div",{className:`${ut.overlay} ${ut.unsavedOverlay}`,children:t.jsxs("div",{className:`tf-surface-modal tf-modal-shell ${ut.modal} ${ut.unsavedModal}`,"data-theme":l,children:[t.jsx("div",{className:`tf-modal-header ${ut.unsavedHeader}`,children:t.jsxs("div",{className:`tf-modal-title ${ut.unsavedTitle}`,children:[t.jsx(Rc,{size:20}),"Unsaved Changes"]})}),t.jsx("div",{className:`${ut.form} ${ut.unsavedContent}`,children:t.jsx("p",{className:ut.unsavedText,children:"You have unsaved changes. Would you like to save them?"})}),t.jsxs("div",{className:`${ut.formActions} ${ut.unsavedActions}`,children:[t.jsx("button",{className:u.cancelBtn,onClick:()=>sa(!1),title:"Close dialog and continue editing",children:"Keep Editing"}),t.jsx("button",{className:u.destructiveBtn,onClick:co,title:"Discard unsaved changes and leave",children:"Discard"}),t.jsxs("button",{className:u.submitBtn,onClick:Ri,disabled:zt,title:"Save changes and leave",children:[zt?t.jsx(Fa,{size:16,className:u.spinner}):t.jsx(sf,{size:16}),"Save"]})]})]})}),Wn&&t.jsx("div",{className:`${ut.overlay} ${ut.unsavedOverlay}`,children:t.jsxs("div",{className:`tf-surface-modal tf-modal-shell ${ut.modal} ${ut.unsavedModal}`,"data-theme":l,children:[t.jsx("div",{className:`tf-modal-header ${ut.unsavedHeader}`,children:t.jsxs("div",{className:`tf-modal-title ${ut.unsavedTitle}`,children:[t.jsx(Rc,{size:20}),"Date Warning"]})}),t.jsxs("div",{className:`${ut.form} ${ut.unsavedContent}`,children:[t.jsx("p",{className:ut.unsavedText,children:"Due date is before scheduled date."}),t.jsxs("p",{style:{margin:0,fontSize:"12px",color:"var(--text-muted)"},children:["Due: ",Wn.dueDate," · Scheduled: ",Wn.scheduledDate]})]}),t.jsxs("div",{className:`${ut.formActions} ${ut.unsavedActions}`,children:[t.jsx("button",{className:u.cancelBtn,onClick:ra,children:"Go Back"}),t.jsx("button",{className:u.submitBtn,onClick:rn,children:"Save Anyway"})]})]})})]})}const NR="_accountMenuWrap_1enss_1",jR="_avatarBtn_1enss_5",RR="_avatarBadge_1enss_9",DR="_avatarImage_1enss_24",PR="_accountMenu_1enss_1",ER="_accountMenuItem_1enss_44",LR="_accountMenuItemActive_1enss_64",MR="_accountMenuSection_1enss_69",BR="_accountMenuSectionLabel_1enss_75",WR="_accountMenuMeta_1enss_84",FR="_accountMenuHint_1enss_89",zR="_accountIdentityEmail_1enss_95",OR="_accountIdentityBlock_1enss_100",$R="_accountIdentityMetaLine_1enss_105",UR="_accountIdentityMetaAction_1enss_112",qR="_accountIdentityMetaValue_1enss_121",HR="_accountIdentityMetaLabel_1enss_126",GR="_accountMenuError_1enss_155",VR="_accountHubCard_1enss_161",ZR="_profileAvatarEditor_1enss_168",KR="_profileAvatarPreview_1enss_174",YR="_profileAvatarImage_1enss_190",JR="_profileAvatarActions_1enss_196",XR="_profileAvatarInput_1enss_202",at={accountMenuWrap:NR,avatarBtn:jR,avatarBadge:RR,avatarImage:DR,accountMenu:PR,accountMenuItem:ER,accountMenuItemActive:LR,accountMenuSection:MR,accountMenuSectionLabel:BR,accountMenuMeta:WR,accountMenuHint:FR,accountIdentityEmail:zR,accountIdentityBlock:OR,accountIdentityMetaLine:$R,accountIdentityMetaAction:UR,accountIdentityMetaValue:qR,accountIdentityMetaLabel:HR,accountMenuError:GR,accountHubCard:VR,profileAvatarEditor:ZR,profileAvatarPreview:KR,profileAvatarImage:YR,profileAvatarActions:JR,profileAvatarInput:XR},QR="_authBlockedBanner_1dg8p_1",eD="_loginView_1dg8p_10",tD="_loginCard_1dg8p_20",nD="_loginCloseBtn_1dg8p_34",aD="_loginLogo_1dg8p_56",sD="_authBrandRow_1dg8p_62",rD="_loginTitle_1dg8p_74",oD="_loginTitleAccent_1dg8p_85",iD="_loginSubtitle_1dg8p_89",cD="_loginError_1dg8p_95",lD="_loginInput_1dg8p_101",dD="_loginPrimaryBtn_1dg8p_117",uD="_registerConsent_1dg8p_122",pD="_registerConsentLink_1dg8p_130",mD="_authModeSwitch_1dg8p_140",fD="_authModeSwitchLink_1dg8p_147",hD="_authModeLinks_1dg8p_162",gD="_authModeLink_1dg8p_162",yD="_optionGrid_1dg8p_191",kD="_optionGroup_1dg8p_197",SD="_optionRow_1dg8p_202",vD="_inlineHint_1dg8p_209",wD="_actionRowEnd_1dg8p_215",ve={authBlockedBanner:QR,loginView:eD,loginCard:tD,loginCloseBtn:nD,loginLogo:aD,authBrandRow:sD,loginTitle:rD,loginTitleAccent:oD,loginSubtitle:iD,loginError:cD,loginInput:lD,loginPrimaryBtn:dD,registerConsent:uD,registerConsentLink:pD,authModeSwitch:mD,authModeSwitchLink:fD,authModeLinks:hD,authModeLink:gD,optionGrid:yD,optionGroup:kD,optionRow:SD,inlineHint:vD,actionRowEnd:wD};function bD(e={x:0,y:0}){const[n,s]=a.useState(e),[r,o]=a.useState(!1),[l,c]=a.useState({x:0,y:0}),[p,g]=a.useState(0),w=a.useRef(null),C=a.useCallback(k=>{const b=k.target;if(!(b.closest("button")||b.closest("input")||b.closest("select")||b.closest("textarea")||b.closest('[role="button"]')||b.closest(".no-drag"))){if(w.current){const E=w.current.getBoundingClientRect();g(E.top-n.y)}o(!0),c({x:k.clientX-n.x,y:k.clientY-n.y})}},[n]),_=a.useCallback(k=>{if(r){let b=k.clientX-l.x,E=k.clientY-l.y;E<-p&&(E=-p),s({x:b,y:E})}},[r,l,p]),y=a.useCallback(()=>{o(!1)},[]);return a.useEffect(()=>(r?(window.addEventListener("mousemove",_),window.addEventListener("mouseup",y)):(window.removeEventListener("mousemove",_),window.removeEventListener("mouseup",y)),()=>{window.removeEventListener("mousemove",_),window.removeEventListener("mouseup",y)}),[r,_,y]),{position:n,isDragging:r,handleMouseDown:C,modalRef:w,setPosition:s}}function oo({isOpen:e,onClose:n,title:s,children:r,footer:o,size:l="md",theme:c=ru,className:p,headerActions:g,draggable:w=!1,isSettings:C=!1,closeOnOverlayClick:_=!0}){const y=a.useRef(null),{position:k,isDragging:b,handleMouseDown:E,modalRef:S}=bD();if(a.useEffect(()=>{const Q=z=>{z.key==="Escape"&&e&&n()};return window.addEventListener("keydown",Q),()=>window.removeEventListener("keydown",Q)},[e,n]),a.useEffect(()=>(e?document.body.style.overflow="hidden":document.body.style.overflow="",()=>{document.body.style.overflow=""}),[e]),!e)return null;const W={sm:ut.modalSizeSm,md:ut.modalSizeMd,lg:ut.modalSizeLg,xl:ut.modalSizeXl,full:ut.modalSizeFull};return Ci.createPortal(t.jsx("div",{className:`${ut.overlay} ${p||""} ${ut.overlayHighZ}`,ref:y,onClick:Q=>{_&&Q.target===y.current&&n()},children:t.jsxs("div",{ref:S,className:`tf-surface-modal tf-modal-shell ${ut.modal} tf-scrollbar-scope ${W[l]} ${w?ut.draggableModal:""} ${C?ut.settingsViewModal:""}`,"data-theme":c,style:{transform:w?`translate(${k.x}px, ${k.y}px)`:void 0,transition:b?"none":"transform 0.3s cubic-bezier(0.16, 1, 0.3, 1), opacity 0.3s ease-out"},children:[t.jsxs("div",{className:`tf-modal-header ${w?ut.draggableHeader:""}`,onMouseDown:w?E:void 0,style:{cursor:w?b?"grabbing":"grab":"default"},children:[t.jsx("div",{className:"tf-modal-title",children:s}),t.jsxs("div",{className:ut.headerActions,children:[g,t.jsx("button",{className:"tf-control-icon",onClick:n,title:"Close",children:t.jsx(ji,{size:20})})]})]}),t.jsx("div",{className:ut.modalContent,children:r}),o&&t.jsx("div",{className:`${ut.formActions} ${ut.modalFooter}`,children:o})]})}),document.body)}const _D="_modalBody_1mute_1",CD="_mutedText_1mute_5",xD="_sectionText_1mute_10",AD="_sectionTextSpaced_1mute_15",TD="_sectionTextTop_1mute_20",ID="_errorText_1mute_25",ND="_inlineFieldLabel_1mute_29",jD="_wrapRow_1mute_35",RD="_actionRowEnd_1mute_42",DD="_modalActionsEnd_1mute_50",PD="_memberRow_1mute_56",ED="_memberTitle_1mute_62",LD="_memberActions_1mute_66",MD="_selectRole_1mute_73",BD="_selectPermission_1mute_77",WD="_inviteRow_1mute_81",FD="_listHeading_1mute_85",zD="_auditList_1mute_90",OD="_auditPager_1mute_96",$D="_labelFixed_1mute_103",st={modalBody:_D,mutedText:CD,sectionText:xD,sectionTextSpaced:AD,sectionTextTop:TD,errorText:ID,inlineFieldLabel:ND,wrapRow:jD,actionRowEnd:RD,modalActionsEnd:DD,memberRow:PD,memberTitle:ED,memberActions:LD,selectRole:MD,selectPermission:BD,inviteRow:WD,listHeading:FD,auditList:zD,auditPager:OD,labelFixed:$D};function UD({isOpen:e,theme:n,onClose:s,onConfirm:r}){return t.jsx(oo,{isOpen:e,onClose:s,title:"New Workspace",size:"sm",theme:n,draggable:!0,footer:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:u.cancelBtn,onClick:s,children:"Cancel"}),t.jsx("button",{type:"button",className:u.submitBtn,onClick:r,children:"Start Setup"})]}),children:t.jsx("div",{className:`${ut.form} ${st.modalBody}`,children:t.jsx("p",{className:st.sectionText,children:"Create and configure a new workspace."})})})}function qD({isOpen:e,theme:n,runtimeMode:s,authRequiredForApi:r,isAuthenticated:o,hasAuthIdentity:l,authIdentityLabel:c,billingLoading:p,billingError:g,billingActionError:w,billingNotice:C,billingActionBusy:_,billingIntervalChoice:y,billingStatus:k,currentWorkspaceId:b,canOpenTeamManagement:E,canManageWorkspaceSync:S,workspaceCloudSyncEnabled:W,syncStatusLabel:Q,workspaceSyncError:z,syncControlBusy:K,onClose:V,onOpenWorkspaceAudit:ne,onBillingIntervalChange:D,onRefreshBilling:Ae,onUpdateInterval:U,onManageBilling:ee,onStartCheckout:be,onToggleWorkspaceSync:me,onOpenHelp:Y}){return t.jsx(oo,{isOpen:e,onClose:V,title:"Account Hub",size:"md",theme:n,draggable:!0,children:t.jsxs("div",{className:`${ut.form} ${st.modalBody}`,children:[t.jsx("p",{className:st.mutedText,children:"Manage sign in, profile, and workspace controls from one place."}),t.jsxs("div",{className:at.accountHubCard,children:[t.jsx("strong",{children:"Authentication"}),t.jsx("p",{className:st.sectionText,children:s==="cloud"?r?o?"Signed in. API access is enabled.":"Cloud mode requires sign in before app usage.":"Cloud runtime with optional authentication.":"Local runtime allows guest usage without sign in."}),t.jsx("p",{className:st.sectionTextSpaced,children:o?l?t.jsxs(t.Fragment,{children:["Signed in as ",t.jsx("span",{className:at.accountIdentityEmail,children:c})]}):"Signed in":"Signed in as: not signed in"}),s==="cloud"&&r&&!o&&t.jsx("p",{className:st.sectionTextTop,children:"Use the `/login` screen to sign in."})]}),t.jsxs("div",{className:at.accountHubCard,children:[t.jsx("strong",{children:"Profile & Account"}),t.jsx("p",{className:st.sectionText,children:"Profile editing and account preferences will live here."})]}),t.jsxs("div",{className:at.accountHubCard,children:[t.jsx("strong",{children:"Billing"}),o?s!=="cloud"?t.jsx("p",{className:st.sectionText,children:"Billing remains cloud-backed in local runtime and uses your connected cloud account."}):t.jsxs(t.Fragment,{children:[p&&t.jsx("p",{className:st.sectionTextSpaced,children:"Loading billing status..."}),g&&t.jsx("p",{className:`${ve.loginError} ${st.errorText}`,children:g}),w&&t.jsx("p",{className:`${ve.loginError} ${st.errorText}`,children:w}),C&&t.jsx("p",{className:st.errorText,children:C}),t.jsxs("p",{className:st.sectionTextSpaced,children:["Plan: ",t.jsx("code",{children:String(k?.planId||"n/a")})," · ","Entitlement: ",t.jsx("code",{children:String(k?.entitlementState||"n/a")})]}),t.jsxs("p",{className:st.sectionText,children:["Stripe status: ",t.jsx("code",{children:String(k?.stripeStatus||"n/a")}),k?.effectiveUntil?` · Effective until ${new Date(k.effectiveUntil).toLocaleString()}`:""]}),t.jsx("div",{className:st.wrapRow,children:t.jsxs("label",{className:`${at.accountMenuMeta} ${st.inlineFieldLabel}`,children:["Interval",t.jsxs("select",{className:u.input,value:y,onChange:R=>D(R.target.value==="year"?"year":"month"),disabled:_,children:[t.jsx("option",{value:"month",children:"Monthly"}),t.jsx("option",{value:"year",children:"Yearly"})]})]})}),t.jsxs("div",{className:st.actionRowEnd,children:[t.jsx("button",{className:u.cancelBtn,onClick:Ae,disabled:_||p,children:"Refresh Billing"}),t.jsx("button",{className:u.cancelBtn,onClick:U,disabled:_||!k?.stripeSubscriptionId,children:"Update Interval"}),t.jsx("button",{className:u.cancelBtn,onClick:ee,disabled:_||!k?.stripeCustomerId,children:"Manage Billing"}),t.jsx("button",{className:u.submitBtn,onClick:be,disabled:_,children:_?"Working...":"Start Checkout"})]})]}):t.jsx("p",{className:st.sectionText,children:"Sign in to manage subscription billing."})]}),t.jsxs("div",{className:at.accountHubCard,children:[t.jsx("strong",{children:"Workspace Audit Log"}),t.jsx("p",{className:st.sectionText,children:"Audit entries are workspace-scoped for the active workspace, not global account history."}),t.jsxs("p",{className:st.sectionText,children:["Active workspace: ",t.jsx("code",{children:b})]}),t.jsx("div",{className:st.actionRowEnd,children:t.jsx("button",{className:u.cancelBtn,onClick:ne,disabled:!E,children:"Open Workspace Audit"})})]}),t.jsxs("div",{className:at.accountHubCard,children:[t.jsx("strong",{children:"Workspace Cloud Sync"}),t.jsx("p",{className:st.sectionText,children:S?W?`Enabled · ${Q}`:"Disabled":"Sign in to cloud account to enable workspace sync."}),z&&t.jsx("p",{className:`${ve.loginError} ${st.errorText}`,children:z}),t.jsx("div",{className:st.actionRowEnd,children:t.jsx("button",{className:u.cancelBtn,disabled:!S||K,onClick:()=>me(!W),children:W?"Disable Sync":"Enable Sync"})})]}),t.jsxs("div",{className:`${ut.formActions} ${st.modalActionsEnd}`,children:[t.jsx("button",{className:u.cancelBtn,onClick:Y,children:"Help & Tutorial"}),t.jsx("button",{className:u.submitBtn,onClick:V,children:"Close"})]})]})})}function HD({isOpen:e,theme:n,onClose:s,onSave:r,displayName:o,email:l,avatarDisplayUrl:c,accountBadgeInitial:p,avatarInputRef:g,avatarAccept:w,avatarDraftId:C,saveBusy:_,avatarBusy:y,saveError:k,saveNotice:b,onDisplayNameChange:E,onAvatarInputChange:S,onStartAvatarUpload:W,onDiscardUpload:Q,onRemovePhoto:z}){return t.jsx(oo,{isOpen:e,onClose:s,title:"Edit Profile",size:"sm",theme:n,draggable:!0,footer:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:u.secondaryButton,onClick:s,disabled:_||y,children:"Cancel"}),t.jsx("button",{type:"button",className:u.primaryUpdateBtn,onClick:r,disabled:_||y||!o.trim(),children:_?"Saving...":"Save Profile"})]}),children:t.jsxs("div",{className:`${ut.form} ${st.modalBody}`,children:[t.jsx("p",{className:st.sectionText,children:"Update the name shown around your account and shared workspace surfaces."}),t.jsxs("div",{className:at.profileAvatarEditor,children:[t.jsx("div",{className:at.profileAvatarPreview,"aria-label":"Profile photo preview",children:c?t.jsx("img",{src:c,alt:"",className:at.profileAvatarImage}):t.jsx("span",{children:p})}),t.jsxs("div",{className:at.profileAvatarActions,children:[t.jsx("input",{ref:g,type:"file","aria-label":"Upload profile photo",accept:w,className:at.profileAvatarInput,onChange:K=>S(K.target.files?.[0]||null),disabled:_||y}),t.jsx("button",{type:"button",className:u.secondaryButton,onClick:W,disabled:_||y,children:y?"Uploading...":"Upload Photo"}),C&&t.jsx("button",{type:"button",className:u.secondaryButton,onClick:Q,disabled:_||y,children:"Discard Upload"}),c&&t.jsx("button",{type:"button",className:u.secondaryButton,onClick:z,disabled:_||y,children:"Remove Photo"})]})]}),t.jsxs("label",{className:st.inlineFieldLabel,children:["Display name",t.jsx("input",{className:u.input,type:"text",value:o,onChange:K=>E(K.target.value),placeholder:"Display name",disabled:_})]}),t.jsxs("label",{className:st.inlineFieldLabel,children:["Email",t.jsx("input",{className:u.input,type:"email",value:l,readOnly:!0,disabled:!0})]}),k&&t.jsx("p",{className:`${ve.loginError} ${st.errorText}`,children:k}),b&&!k&&t.jsx("p",{className:st.errorText,children:b})]})})}function GD({isOpen:e,theme:n,onClose:s,onOpenSettings:r}){return t.jsx(oo,{isOpen:e,onClose:s,title:"Quick Start",size:"md",theme:n,draggable:!0,children:t.jsxs("div",{className:`${ut.form} ${st.modalBody}`,children:[t.jsx("p",{className:st.mutedText,children:"Use this quick guide to get productive in Taskforce dashboard mode."}),t.jsxs("div",{children:[t.jsx("strong",{children:"1. Capture work"}),t.jsxs("p",{className:st.sectionText,children:["Click ",t.jsx("code",{children:"Add Task"}),", write a short title, and save."]})]}),t.jsxs("div",{children:[t.jsx("strong",{children:"2. Plan the board"}),t.jsxs("p",{className:st.sectionText,children:["Use ",t.jsx("code",{children:"Sort"}),", ",t.jsx("code",{children:"Group"}),", and ",t.jsx("code",{children:"Filters"})," in the header."]})]}),t.jsxs("div",{children:[t.jsx("strong",{children:"3. Execute and stage"}),t.jsxs("p",{className:st.sectionText,children:["Move tasks through ",t.jsx("code",{children:"Task"}),", ",t.jsx("code",{children:"In Progress"}),", ",t.jsx("code",{children:"Review"}),", and ",t.jsx("code",{children:"Done"}),"."]})]}),t.jsxs("div",{children:[t.jsx("strong",{children:"4. Archive finished work"}),t.jsx("p",{className:st.sectionText,children:"Archive completed/cancelled tasks to keep active board signal high."})]}),t.jsxs("div",{className:`${ut.formActions} ${st.modalActionsEnd}`,children:[t.jsx("button",{className:u.cancelBtn,onClick:r,children:"Open Settings"}),t.jsx("button",{className:u.submitBtn,onClick:s,children:"Close Tutorial"})]})]})})}function VD({prompt:e,theme:n,onClose:s,onConfirm:r}){return t.jsx(oo,{isOpen:!!e,onClose:s,title:"Date Warning",size:"sm",theme:n,draggable:!1,closeOnOverlayClick:!1,children:t.jsxs("div",{className:`${u.form} tf-inline-stack-sm`,style:{padding:"16px",gap:"12px"},children:[t.jsx("p",{className:"tf-text-body",children:"Due date is before scheduled date."}),e&&t.jsxs("p",{className:"tf-text-helper",children:["Due: ",e.dueDate," · Scheduled: ",e.scheduledDate]}),t.jsxs("div",{className:u.formActions,children:[t.jsx("button",{className:u.cancelBtn,onClick:s,children:"Go Back"}),t.jsx("button",{className:u.submitBtn,onClick:r,children:"Save Anyway"})]})]})})}const ZD="_syncStatusModal_4pd1g_1",KD="_syncStatusTop_4pd1g_6",YD="_syncStatusMetaHeader_4pd1g_15",JD="_syncStatusHeaderInfo_4pd1g_22",XD="_syncToggle_4pd1g_43",QD="_syncStatusBadge_4pd1g_47",eP="_syncToggleControl_4pd1g_75",tP="_syncToggleControlEnabled_4pd1g_91",nP="_syncToggleControlDisabled_4pd1g_98",aP="_syncToggleControlBusy_4pd1g_102",sP="_syncToggleControlBlocked_4pd1g_107",rP="_syncToggleInput_4pd1g_112",oP="_syncToggleState_4pd1g_125",iP="_syncToggleStateOn_4pd1g_136",cP="_syncToggleStateOff_4pd1g_141",lP="_syncToggleThumb_4pd1g_146",dP="_syncStatusSummaryValue_4pd1g_173",uP="_syncStatusSummaryCompact_4pd1g_180",pP="_syncStatusRepairBanner_4pd1g_190",mP="_syncStatusRepairHeader_4pd1g_200",fP="_syncStatusRepairBadge_4pd1g_207",hP="_syncStatusRepairMeta_4pd1g_216",gP="_syncStatusRepairText_4pd1g_223",yP="_syncStatusLabel_4pd1g_257",kP="_syncStatusSectionHeader_4pd1g_265",SP="_syncStatusCompactGrid_4pd1g_278",vP="_syncStatusCompactItem_4pd1g_284",wP="_syncStatusValue_4pd1g_295",bP="_syncStatusValueError_4pd1g_325",_P="_syncStatusActions_4pd1g_329",CP="_syncStatusPanel_4pd1g_336",xP="_syncStatusPanelHeader_4pd1g_346",AP="_syncStatusPanelMeta_4pd1g_353",TP="_syncStatusEventsList_4pd1g_375",IP="_syncStatusEventItem_4pd1g_384",NP="_syncStatusEventItemError_4pd1g_391",jP="_syncStatusEventItemMuted_4pd1g_396",RP="_syncStatusEventLine_4pd1g_401",DP="_syncStatusSecondaryActions_4pd1g_411",PP="_syncStatusPrimaryActions_4pd1g_425",EP="_syncStatusPrimaryActionSlot_4pd1g_432",LP="_syncStatusActionPlaceholder_4pd1g_440",Ue={syncStatusModal:ZD,syncStatusTop:KD,syncStatusMetaHeader:YD,syncStatusHeaderInfo:JD,syncToggle:XD,syncStatusBadge:QD,syncToggleControl:eP,syncToggleControlEnabled:tP,syncToggleControlDisabled:nP,syncToggleControlBusy:aP,syncToggleControlBlocked:sP,syncToggleInput:rP,syncToggleState:oP,syncToggleStateOn:iP,syncToggleStateOff:cP,syncToggleThumb:lP,syncStatusSummaryValue:dP,syncStatusSummaryCompact:uP,syncStatusRepairBanner:pP,syncStatusRepairHeader:mP,syncStatusRepairBadge:fP,syncStatusRepairMeta:hP,syncStatusRepairText:gP,syncStatusLabel:yP,syncStatusSectionHeader:kP,syncStatusCompactGrid:SP,syncStatusCompactItem:vP,syncStatusValue:wP,syncStatusValueError:bP,syncStatusActions:_P,syncStatusPanel:CP,syncStatusPanelHeader:xP,syncStatusPanelMeta:AP,syncStatusEventsList:TP,syncStatusEventItem:IP,syncStatusEventItemError:NP,syncStatusEventItemMuted:jP,syncStatusEventLine:RP,syncStatusSecondaryActions:DP,syncStatusPrimaryActions:PP,syncStatusPrimaryActionSlot:EP,syncStatusActionPlaceholder:LP};function MP({isOpen:e,theme:n,currentWorkspaceLabel:s,syncStatusMeta:r,workspaceCloudSyncEnabled:o,syncControlBusy:l,canManageWorkspaceSync:c,workspaceSyncSummary:p,workspaceSyncRepairBusy:g,referenceMismatchCount:w,syncStageLabel:C,workspaceSyncPendingChanges:_,formattedLastSyncTime:y,formattedLastPullTime:k,formattedLastPushTime:b,syncLastError:E,workspaceSyncDiagnostics:S,activeReferenceMismatchSummaries:W,syncDiagnosticsSummary:Q,syncEventRows:z,syncEventsListRef:K,workspaceSyncRepairQueued:V,workspaceSyncBusy:ne,workspaceSyncCopied:D,runtimeMode:Ae,isAuthenticated:U,onClose:ee,onToggleWorkspaceSync:be,onRepairSync:me,onCopyReport:Y,onOpenLogin:R,onRetrySync:B}){return t.jsx(oo,{isOpen:e,onClose:ee,title:"Sync Manager",size:"md",theme:n,draggable:!0,children:t.jsxs("div",{className:`${ut.form} ${Ue.syncStatusModal}`,style:{gap:"10px"},children:[t.jsxs("div",{className:Ue.syncStatusTop,children:[t.jsx("div",{className:Ue.syncStatusHeaderInfo,children:t.jsxs("div",{className:Ue.syncStatusMetaHeader,children:[t.jsx("div",{className:Ue.syncStatusBadge,style:{borderColor:r.border,background:r.background,color:r.color},children:r.label}),t.jsxs("span",{className:Ue.syncStatusLabel,children:["Workspace: ",t.jsx("code",{children:s})]})]})}),t.jsx("label",{className:Ue.syncToggle,children:t.jsxs("span",{className:[Ue.syncToggleControl,o?Ue.syncToggleControlEnabled:Ue.syncToggleControlDisabled,l?Ue.syncToggleControlBusy:"",c?"":Ue.syncToggleControlBlocked].filter(Boolean).join(" "),children:[t.jsx("input",{className:Ue.syncToggleInput,type:"checkbox",role:"switch","aria-label":"Enable Sync",checked:o,disabled:!c||l,onChange:fe=>be(fe.target.checked)}),t.jsx("span",{className:`${Ue.syncToggleState} ${Ue.syncToggleStateOn}`,children:"On"}),t.jsx("span",{className:`${Ue.syncToggleState} ${Ue.syncToggleStateOff}`,children:"Off"}),t.jsx("span",{className:Ue.syncToggleThumb})]})})]}),t.jsxs("div",{className:Ue.syncStatusSummaryCompact,children:[t.jsx("span",{className:Ue.syncStatusLabel,children:"Health"}),t.jsx("span",{className:Ue.syncStatusSummaryValue,children:p})]}),g&&t.jsxs("div",{className:Ue.syncStatusRepairBanner,children:[t.jsxs("div",{className:Ue.syncStatusRepairHeader,children:[t.jsxs("div",{className:Ue.syncStatusRepairBadge,children:[t.jsx(Fa,{size:13,className:u.spinner}),t.jsx("span",{children:"Repair In Progress"})]}),t.jsx("span",{className:Ue.syncStatusRepairMeta,children:"Advanced recovery mode"})]}),t.jsx("span",{className:Ue.syncStatusRepairText,children:w>0?`Taskforce is clearing the saved sync cursor and reconciling workspace state from the cloud again, including ${w} detected reference mismatch${w===1?"":"es"}. The panel may stay busy for a while during large repairs.`:"Taskforce is clearing the saved sync cursor and reconciling workspace state from the cloud again. The panel may stay busy for a while during large repairs."})]}),t.jsx("div",{className:Ue.syncStatusSectionHeader,children:t.jsx("span",{className:Ue.syncStatusLabel,children:"Current Session"})}),t.jsxs("div",{className:Ue.syncStatusCompactGrid,children:[t.jsxs("div",{className:Ue.syncStatusCompactItem,children:[t.jsx("span",{className:Ue.syncStatusLabel,children:"Stage"}),t.jsx("span",{className:Ue.syncStatusValue,children:C})]}),t.jsxs("div",{className:Ue.syncStatusCompactItem,children:[t.jsx("span",{className:Ue.syncStatusLabel,children:"Local Changes"}),t.jsx("span",{className:Ue.syncStatusValue,children:_})]}),t.jsxs("div",{className:Ue.syncStatusCompactItem,children:[t.jsx("span",{className:Ue.syncStatusLabel,children:"Last Successful"}),t.jsx("span",{className:Ue.syncStatusValue,children:y})]})]}),t.jsx("div",{className:Ue.syncStatusSectionHeader,children:t.jsx("span",{className:Ue.syncStatusLabel,children:"Activity"})}),t.jsxs("div",{className:Ue.syncStatusCompactGrid,children:[t.jsxs("div",{className:Ue.syncStatusCompactItem,children:[t.jsx("span",{className:Ue.syncStatusLabel,children:"Last Pull"}),t.jsx("span",{className:Ue.syncStatusValue,children:k})]}),t.jsxs("div",{className:Ue.syncStatusCompactItem,children:[t.jsx("span",{className:Ue.syncStatusLabel,children:"Last Push"}),t.jsx("span",{className:Ue.syncStatusValue,children:b})]})]}),E!=="None"&&t.jsxs("div",{className:Ue.syncStatusPanel,style:{background:"rgba(239, 68, 68, 0.05)",borderColor:"rgba(239, 68, 68, 0.2)"},children:[t.jsxs("div",{className:Ue.syncStatusSectionHeader,style:{marginTop:0},children:[t.jsx(Rc,{size:12,color:"#fda4af"}),t.jsxs("span",{className:Ue.syncStatusLabel,style:{color:"#fda4af"},children:["Last Error (",S.lastErrorAt?new Date(S.lastErrorAt).toLocaleTimeString():"Recent",")"]})]}),t.jsx("span",{className:`${Ue.syncStatusValue} ${Ue.syncStatusValueError}`,children:E})]}),w>0&&t.jsxs("div",{className:Ue.syncStatusPanel,style:{background:"rgba(250, 204, 21, 0.08)",borderColor:"rgba(250, 204, 21, 0.22)"},children:[t.jsxs("div",{className:Ue.syncStatusPanelHeader,children:[t.jsx("span",{className:Ue.syncStatusLabel,style:{color:"#fde68a"},children:"Identifier Integrity"}),t.jsxs("span",{className:Ue.syncStatusPanelMeta,children:[w," mismatch",w===1?"":"es"," detected"]})]}),t.jsx("span",{className:Ue.syncStatusValue,children:"Task, document, or image reference numbers disagreed during normal sync. Cloud-backed sync preserves the incoming cloud reference and renumbers the displaced local item to the next available reference."}),W.length>0&&t.jsx("div",{style:{marginTop:"10px",display:"flex",flexDirection:"column",gap:"8px"},children:W.map(fe=>t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"2px",padding:"8px 10px",borderRadius:"8px",background:"rgba(15, 23, 42, 0.18)",border:"1px solid rgba(250, 204, 21, 0.16)"},children:[t.jsx("span",{className:Ue.syncStatusValue,style:{fontSize:"12px",wordBreak:"break-all"},children:fe.pathLabel}),fe.refsLabel?t.jsx("span",{className:Ue.syncStatusPanelMeta,children:fe.refsLabel}):null]},fe.key))})]}),t.jsxs("div",{className:Ue.syncStatusPanel,children:[t.jsxs("div",{className:Ue.syncStatusPanelHeader,children:[t.jsx("span",{className:Ue.syncStatusLabel,children:"Local Sync Diagnostics"}),t.jsx("span",{className:Ue.syncStatusPanelMeta,style:{fontSize:"10px"},children:"AI profiles & metadata"})]}),t.jsx("div",{className:Ue.syncStatusCompactGrid,style:{gridTemplateColumns:"repeat(2, 1fr)"},children:Q.map(fe=>t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline",gap:"8px"},children:[t.jsx("span",{className:Ue.syncStatusLabel,style:{fontSize:"9px",textTransform:"capitalize"},children:fe.label}),t.jsx("span",{className:Ue.syncStatusValue,style:{fontSize:"11px",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:fe.value})]},fe.label))})]}),t.jsxs("div",{className:Ue.syncStatusPanel,children:[t.jsx("div",{className:Ue.syncStatusPanelHeader,children:t.jsx("span",{className:Ue.syncStatusLabel,children:"Recent Events"})}),t.jsx("div",{ref:K,className:Ue.syncStatusEventsList,style:{height:"120px"},children:z.map(fe=>t.jsx("div",{className:[Ue.syncStatusEventItem,fe.tone==="error"?Ue.syncStatusEventItemError:"",fe.tone==="muted"?Ue.syncStatusEventItemMuted:""].filter(Boolean).join(" "),style:{padding:"6px 8px",borderRadius:"6px"},children:t.jsx("span",{className:Ue.syncStatusEventLine,style:{fontSize:"11px"},children:fe.text})},fe.key))})]}),t.jsxs("div",{className:`${ut.formActions} ${Ue.syncStatusActions}`,children:[t.jsxs("div",{className:Ue.syncStatusSecondaryActions,children:[t.jsx("button",{className:u.cancelBtn,onClick:me,disabled:g,title:g?"Repair is running now.":V?"Repair is queued and will start when the current sync finishes.":ne?"Queue a repair to start automatically when the current sync finishes.":"Advanced recovery: clear the saved pull cursor and re-fetch cloud state from the beginning.",children:g?t.jsxs(t.Fragment,{children:[t.jsx(Fa,{size:14,className:u.spinner}),t.jsx("span",{style:{marginLeft:"6px"},children:"Repairing..."})]}):V?"Repair Queued":"Repair"}),t.jsxs("button",{className:u.cancelBtn,onClick:Y,title:"Copy the current sync manager report for support or AI troubleshooting.",children:[t.jsx(Ll,{size:14}),t.jsx("span",{style:{marginLeft:"6px"},children:D?"Copied":"Copy Report"})]})]}),t.jsxs("div",{className:Ue.syncStatusPrimaryActions,children:[t.jsx("div",{className:Ue.syncStatusPrimaryActionSlot,children:Ae==="local"&&!U?t.jsx("button",{className:u.submitBtn,onClick:R,children:"Sign In / Register"}):t.jsx("div",{className:Ue.syncStatusActionPlaceholder,"aria-hidden":"true"})}),t.jsx("div",{className:Ue.syncStatusPrimaryActionSlot,children:t.jsx("button",{className:u.submitBtn,onClick:B,disabled:ne,children:ne?t.jsxs(t.Fragment,{children:[t.jsx(Fa,{size:14,className:u.spinner}),"Syncing..."]}):t.jsxs(t.Fragment,{children:[t.jsx(ag,{size:14}),"Sync"]})})})]})]})]})})}function BP({isOpen:e,theme:n,teamPlanMode:s,teamMgmtError:r,teamManagementTab:o,teamUsersLoading:l,teamUsers:c,teamActionBusyUserId:p,teamInviteFeedback:g,teamInviteEmail:w,teamInviteRole:C,teamInvitePermissionMode:_,teamInviteBusy:y,pendingInvites:k,teamAuditLoading:b,teamAuditEvents:E,teamAuditPage:S,teamAuditPages:W,teamAuditHasMore:Q,onClose:z,onOpenMembersTab:K,onOpenInvitesTab:V,onOpenAuditTab:ne,onMemberRoleChange:D,onMemberPermissionChange:Ae,onToggleMemberDisabled:U,onRevokeInvite:ee,onRemoveMember:be,onInviteEmailChange:me,onInviteRoleChange:Y,onInvitePermissionModeChange:R,onSubmitInvite:B,onLoadAuditPrevious:fe,onLoadAuditNext:Ne}){return t.jsx(oo,{isOpen:e,onClose:z,title:"Team Management",size:"md",theme:n,draggable:!0,children:t.jsxs("div",{className:`${ut.form} ${st.modalBody}`,children:[s==="personal"&&t.jsx("p",{className:ve.loginError,children:"Team management is only available in TEAM accounts."}),r&&t.jsx("p",{className:ve.loginError,children:r}),t.jsxs("div",{className:`${u.settingsTabs} tf-scrollbar tf-scrollbar--track-transparent tf-scrollbar--compact`,children:[t.jsx("button",{className:`${u.settingsTabBtn} ${o==="members"?u.settingsTabBtnActive:""}`,onClick:K,children:"Members"}),t.jsx("button",{className:`${u.settingsTabBtn} ${o==="invites"?u.settingsTabBtnActive:""}`,onClick:V,children:"Invites"}),t.jsx("button",{className:`${u.settingsTabBtn} ${o==="audit"?u.settingsTabBtnActive:""}`,onClick:ne,children:"Audit Log"})]}),o==="members"&&t.jsxs("div",{className:at.accountHubCard,children:[l&&t.jsx("p",{className:st.mutedText,children:"Loading members..."}),!l&&c.length===0&&t.jsx("p",{className:st.mutedText,children:"No users found."}),!l&&c.map(de=>t.jsxs("div",{className:st.memberRow,children:[t.jsx("div",{className:st.memberTitle,children:de.displayName||de.email}),t.jsxs("div",{className:at.accountMenuMeta,children:[de.email," · ",de.status,de.disabled?" · deactivated":""]}),t.jsxs("div",{className:st.memberActions,children:[t.jsxs("select",{className:`${u.input} ${st.selectRole}`,value:de.role,onChange:ae=>D(de.userId,ae.target.value),disabled:p===de.userId,children:[t.jsx("option",{value:"owner",children:"Owner"}),t.jsx("option",{value:"admin",children:"Admin"}),t.jsx("option",{value:"member",children:"Member"})]}),de.role==="member"&&t.jsxs("select",{className:`${u.input} ${st.selectPermission}`,value:de.permissionMode,onChange:ae=>Ae(de.userId,ae.target.value),disabled:p===de.userId,children:[t.jsx("option",{value:"read-write",children:"Read / Write"}),t.jsx("option",{value:"read-only",children:"Read Only"})]}),t.jsx("button",{className:u.cancelBtn,disabled:p===de.userId,onClick:()=>U(de.userId,!de.disabled),children:de.disabled?"Reactivate":"Deactivate"}),de.status==="invited"&&t.jsx("button",{className:u.cancelBtn,disabled:p===de.userId,onClick:()=>ee(de.userId),children:"Revoke Invite"}),t.jsx("button",{className:u.cancelBtn,disabled:p===de.userId,onClick:()=>be(de.userId),children:"Remove"})]})]},de.userId))]}),o==="invites"&&t.jsxs("div",{className:at.accountHubCard,children:[g&&t.jsx("p",{className:st.sectionText,children:g}),t.jsxs("div",{className:u.pathInputGroup,children:[t.jsx("label",{className:`${u.label} ${st.labelFixed}`,children:"Email"}),t.jsx("input",{className:u.input,value:w,onChange:de=>me(de.target.value),placeholder:"name@company.com"})]}),t.jsxs("div",{className:u.pathInputGroup,children:[t.jsx("label",{className:`${u.label} ${st.labelFixed}`,children:"Role"}),t.jsxs("select",{className:`${u.input} ${st.selectRole}`,value:C,onChange:de=>Y(de.target.value==="admin"?"admin":"member"),children:[t.jsx("option",{value:"member",children:"Member"}),t.jsx("option",{value:"admin",children:"Admin"})]}),C==="member"&&t.jsxs("select",{className:`${u.input} ${st.selectPermission}`,value:_,onChange:de=>R(de.target.value==="read-only"?"read-only":"read-write"),children:[t.jsx("option",{value:"read-write",children:"Read / Write"}),t.jsx("option",{value:"read-only",children:"Read Only"})]}),t.jsx("button",{className:u.submitBtn,disabled:y||!w.trim()||s!=="team",onClick:B,children:y?"Sending...":"Send Invite"})]}),t.jsxs("div",{className:st.inviteRow,children:[t.jsx("div",{className:st.listHeading,children:"Pending Invites"}),k.length===0&&t.jsx("p",{className:st.mutedText,children:"No pending invites."}),k.map(de=>t.jsxs("div",{className:st.memberRow,children:[t.jsx("div",{className:st.memberTitle,children:de.displayName||de.email}),t.jsxs("div",{className:at.accountMenuMeta,children:[de.email," · ",de.role]})]},de.userId))]})]}),o==="audit"&&t.jsxs("div",{className:at.accountHubCard,children:[b&&t.jsx("p",{className:st.mutedText,children:"Loading audit entries..."}),!b&&E.length===0&&t.jsx("p",{className:st.mutedText,children:"No audit events for this workspace."}),!b&&t.jsx("div",{className:st.auditList,children:E.map(de=>t.jsxs("div",{className:st.memberRow,children:[t.jsx("div",{className:at.accountMenuMeta,children:new Date(de.createdAt).toLocaleString()}),t.jsx("div",{className:st.memberTitle,children:de.action}),t.jsxs("div",{className:at.accountMenuMeta,children:[de.actorUserId," (",de.actorRole,")"]})]},de.id))}),t.jsxs("div",{className:st.auditPager,children:[t.jsx("button",{className:u.cancelBtn,disabled:b||S===0,onClick:fe,children:"Previous"}),t.jsxs("span",{className:at.accountMenuMeta,children:["Page ",S+1," of ",W]}),t.jsx("button",{className:u.cancelBtn,disabled:b||!Q||S+1>=W,onClick:Ne,children:"Next"})]})]}),t.jsx("div",{className:`${ut.formActions} ${st.modalActionsEnd}`,children:t.jsx("button",{className:u.cancelBtn,onClick:z,children:"Close"})})]})})}const tu="expired::";function WP({tasks:e,columns:n,groupBy:s,searchQuery:r,copiedId:o,taxonomies:l,types:c,priorities:p,approaches:g,assigneeOptions:w=[],onUpdateTask:C,onTaskClick:_,onOpenTaskById:y,onCopyId:k,onToggleInProgress:b,onToggleReview:E,onToggleComplete:S,onToggleCancel:W,onSetStatus:Q,onArchiveTask:z,onUnarchive:K,onDelete:V,allTasks:ne=[],onAddTaskToColumn:D,emptyColumnMode:Ae="show",filterCategories:U=[],filterTypes:ee=[],filterPriorities:be=[],filterStatus:me=[],filterAssignees:Y=[],scheduleFilteredTaskIds:R,categories:B=[],compressed:fe=!1,readOnlyMode:Ne=null,recentlyChangedTaskIds:de=[],scheduleDates:ae,onScheduleDaySelected:Ve,persistedScrollLeft:Re,onScrollLeftChange:Ce,sortBy:Fe="created",sortOrder:x="desc",planningDropTargets:L=null,onAssignTaskToWorkstream:P,onAssignWorkstreamToInitiative:Z,showTaskCardStatusLabel:M=!0,workstreams:h=[],initiatives:A=[]}){const[H,j]=a.useState(null),[je,O]=a.useState(!1),[ue,re]=a.useState(!1),pe=a.useMemo(()=>new Set(de),[de]),G=a.useMemo(()=>new Map(h.map(J=>[J.id,J])),[h]),q=a.useMemo(()=>new Map(A.map(J=>[J.id,J])),[A]),ye=a.useCallback(J=>{const _e=J.workstreamId&&G.get(J.workstreamId)||null,we=_e?.initiativeId&&q.get(_e.initiativeId)||null;return{taskWorkstream:_e,taskInitiative:we}},[q,G]),Be=a.useMemo(()=>new Set(e.map(J=>J.id)),[e]),le=a.useCallback(J=>J.startsWith(tu)?J.slice(tu.length):J,[]),ze=a.useCallback(J=>Be.has(le(J)),[Be,le]),Ye=a.useMemo(()=>new Set(R||[]),[R]),Xe=a.useRef(null),bt=a.useCallback(J=>{const _e=J?.data?.current||{},we=String(J?.id||"");let Ie=String(_e.taskId||""),We=String(_e.workstreamId||"");!Ie&&we&&ze(we)&&(Ie=le(we)),!We&&we.startsWith("planning-workstream:")&&(We=we.slice(20));let Qe=String(_e.type||"");return Qe||(Ie?Qe="task-card":We&&(Qe="planning-workstream")),{activeId:we,type:Qe,taskId:Ie,workstreamId:We}},[le,ze]),d=cf(Cp(pf,{activationConstraint:{distance:5}}),Cp(Tg,{coordinateGetter:Ag})),rt=J=>{const _e=J.status||"task";return _e==="done"||_e==="cancelled"?"completed":_e},mt=a.useMemo(()=>{const J=new Date,_e=J.getFullYear(),we=String(J.getMonth()+1).padStart(2,"0"),Ie=String(J.getDate()).padStart(2,"0");return`${_e}-${we}-${Ie}`},[]),F=a.useMemo(()=>{const J=Ie=>{const We=Ie.match(/^(\d{4})-(\d{2})-(\d{2})$/);if(!We)return null;const Qe=new Date(Date.UTC(Number(We[1]),Number(We[2])-1,Number(We[3]))),ot=Qe.getUTCDay()||7;Qe.setUTCDate(Qe.getUTCDate()+4-ot);const et=new Date(Date.UTC(Qe.getUTCFullYear(),0,1)),_t=Math.ceil(((Qe.getTime()-et.getTime())/864e5+1)/7);return`${Qe.getUTCFullYear()}-W${String(_t).padStart(2,"0")}`};return{dates:{...(()=>{const Ie=new Date,We=Ie.getDay(),Qe=We===0?-6:1-We,ot=new Date(Ie);ot.setDate(Ie.getDate()+Qe);const et=Ot=>{const it=Ot.getFullYear(),It=String(Ot.getMonth()+1).padStart(2,"0"),wt=String(Ot.getDate()).padStart(2,"0");return`${it}-${It}-${wt}`},_t={mon:"",tue:"",wed:"",thu:"",fri:"",sat:"",sun:""};return["mon","tue","wed","thu","fri","sat","sun"].forEach((Ot,it)=>{const It=new Date(ot);It.setDate(ot.getDate()+it),_t[Ot]=et(It)}),_t})(),...ae||{}},parseToIsoWeekKey:J}},[ae]),Ke=J=>{const _e=J.scheduledDate||null;return _e?new Map([[F.dates.mon,"mon"],[F.dates.tue,"tue"],[F.dates.wed,"wed"],[F.dates.thu,"thu"],[F.dates.fri,"fri"],[F.dates.sat,"sat"],[F.dates.sun,"sun"]]).get(_e)||"__offweek":"backlog"},St=a.useMemo(()=>{const J=new Map;for(const _e of n)J.set(String(_e.value),_e),J.has(_e.label)||J.set(_e.label,_e);return J},[n]),Lt=a.useMemo(()=>{const J={};return n.forEach(we=>{J[String(we.value)]=0}),(ne.length>0?ne:e).forEach(we=>{let Ie="";if(s==="status")Ie=rt(we);else if(s==="schedule")Ie=Ke(we);else{const Qe=we[s];Ie=String(Qe??"")}const We=St.get(Ie);if(We&&J[String(We.value)]++,s==="schedule"){const Qe=we.status==="done"||we.status==="cancelled";we.scheduledDate&&!Qe&&we.scheduledDate<mt&&St.has("expired")&&(J.expired=(J.expired||0)+1)}}),J},[ne,e,n,s,St,mt]),xt=a.useMemo(()=>{const J={};if(n.forEach(_e=>{J[String(_e.value)]=[]}),e.forEach(_e=>{let we="";if(s==="status")we=rt(_e);else if(s==="schedule")we=Ke(_e);else{const We=_e[s];we=String(We??"")}const Ie=St.get(we);if(Ie){if(s==="schedule"&&String(Ie.value)==="backlog"&&!Ye.has(_e.id))return;J[String(Ie.value)].push(_e)}if(s==="schedule"){const We=_e.status==="done"||_e.status==="cancelled";_e.scheduledDate&&!We&&_e.scheduledDate<mt&&J.expired&&J.expired.push(_e)}}),s==="schedule"){const _e=(Ie,We)=>{const Qe=typeof Ie.orderInDay=="number"?Ie.orderInDay:Number.MAX_SAFE_INTEGER,ot=typeof We.orderInDay=="number"?We.orderInDay:Number.MAX_SAFE_INTEGER;return Qe!==ot?Qe-ot:String(Ie.createdAt||"").localeCompare(String(We.createdAt||""))},we=(Ie,We)=>uu(Ie,We,Fe,x,l);Object.keys(J).forEach(Ie=>{if(Ie==="backlog"||Ie==="expired"){J[Ie].sort(we);return}J[Ie].sort(_e)})}return J},[e,ne,n,s,St,Ye,mt,Fe,x]),Zt=H?le(H):null,Jt=Zt?e.find(J=>J.id===Zt):null,on=a.useRef(null),cn=a.useRef(null),nn=a.useRef({pointerId:null,startX:0,startY:0,startScrollLeft:0,didPan:!1}),gn=a.useRef(-1),yn=(J,_e)=>s==="category"?!U.includes(String(J)):s==="type"?!ee.includes(String(J)):s==="priority"?!be.some(we=>Number(we)===Number(J)):s==="status"?String(J)==="completed"?!me.includes("done")&&!me.includes("cancelled"):!me.includes(String(J)):s==="assignee"?!Y.includes(String(J)):!1,an=a.useMemo(()=>{let Ie=0;return n.forEach((We,Qe)=>{const ot=xt[String(We.value)]||[],et=yn(We.value,We.label),_t=s!=="schedule"&&Ae==="hide"&&ot.length===0;if(et||_t)return;const vt=Ae==="collapse"&&ot.length===0;Ie+=vt?72:320,Ie+=4}),Ie},[n,xt,Ae,s,U,ee,be,me]),kn=a.useCallback(J=>{if(!Ce)return;const _e=Math.max(0,Math.round(J));_e!==gn.current&&(gn.current=_e,Ce(_e))},[Ce]);a.useEffect(()=>{const J=on.current,_e=cn.current;if(!J||!_e)return;let we=!1,Ie=!1;const We=()=>{!J||Ie||(we=!0,J.scrollLeft=_e.scrollLeft,kn(_e.scrollLeft),setTimeout(()=>we=!1,0))},Qe=()=>{!_e||we||(Ie=!0,_e.scrollLeft=J.scrollLeft,kn(J.scrollLeft),setTimeout(()=>Ie=!1,0))};return _e.addEventListener("scroll",We),J.addEventListener("scroll",Qe),()=>{_e.removeEventListener("scroll",We),J.removeEventListener("scroll",Qe)}},[kn]);const Xt=a.useRef(!1);a.useEffect(()=>{if(Xt.current)return;if(typeof Re!="number"||!Number.isFinite(Re)){Xt.current=!0;return}const J=on.current,_e=cn.current;if(!J||!_e)return;const we=Math.max(0,J.scrollWidth-J.clientWidth),Ie=Math.min(Math.max(0,Re),we);J.scrollLeft=Ie,_e.scrollLeft=Ie,Xt.current=!0},[Re,an]),a.useEffect(()=>{const J=()=>{const _e=on.current;if(!_e){re(!1);return}re(_e.scrollWidth>_e.clientWidth+4)};return J(),window.addEventListener("resize",J),()=>{window.removeEventListener("resize",J)}},[an,n.length,xt]),a.useEffect(()=>{const J=we=>{const Ie=nn.current;if(Ie.pointerId===null||Ie.pointerId!==we.pointerId)return;const We=we.clientX-Ie.startX,Qe=we.clientY-Ie.startY;if(!Ie.didPan){if(Math.abs(We)<7||Math.abs(We)<Math.abs(Qe))return;Ie.didPan=!0,O(!0),document.body.style.userSelect="none"}const ot=Ie.startScrollLeft-We;on.current&&(on.current.scrollLeft=ot),cn.current&&(cn.current.scrollLeft=ot),we.preventDefault()},_e=()=>{const we=nn.current;we.pointerId!==null&&(we.pointerId=null,we.didPan=!1,je&&(O(!1),document.body.style.userSelect=""))};return window.addEventListener("pointermove",J),window.addEventListener("pointerup",_e),window.addEventListener("pointercancel",_e),()=>{window.removeEventListener("pointermove",J),window.removeEventListener("pointerup",_e),window.removeEventListener("pointercancel",_e),document.body.style.userSelect=""}},[je]);const Gn=J=>{!ue||J.target?.closest('button, a, input, select, textarea, [role="button"], [data-no-header-pan="true"]')||(nn.current.pointerId=J.pointerId,nn.current.startX=J.clientX,nn.current.startY=J.clientY,nn.current.startScrollLeft=on.current?.scrollLeft||0,nn.current.didPan=!1)},At=J=>{j(J.active.id)},Se=J=>{const _e=bt(J.active),we=String(J.over?.data?.current?.type||"");_e.type==="task-card"&&we.startsWith("planning-")?Xe.current=`${String(J.over?.id||"")}:${we}`:Xe.current&&(Xe.current=null)},Mt=J=>{const{active:_e,over:we}=J;Xe.current=null,j(null);const Ie=bt(_e),We=Ie.type,Qe=String(we?.data?.current?.type||""),ot=Ie.taskId,et=Ie.workstreamId,_t=String(we?.data?.current?.workstreamId||""),vt=String(we?.data?.current?.initiativeId||"");if(We==="task-card"){if(Qe==="planning-workstream-target"&&ot&&_t){P?.(ot,_t);return}if(Qe==="planning-task-unlink"&&ot){P?.(ot,null);return}}if(We==="planning-workstream"){if(Qe==="planning-initiative-target"&&et&&vt){Z?.(et,vt);return}if(Qe==="planning-workstream-unlink"&&et){Z?.(et,null);return}return}const Ot=String(_e.id),it=we?String(we.id):null,It=le(Ot);it&&le(it);const wt=e.find(se=>se.id===It);if(!wt||!it)return;const _n=Qt(Ot),Jn=String(_e?.data?.current?.sortable?.containerId||"")||_n,gt=String(we?.data?.current?.sortable?.containerId||"")||Qt(it);if(!gt)return;const Xn=St.get(gt)||n.find(se=>String(se.value)===gt||se.label===gt);if(Xn){if(s==="schedule"){const Ee=String(Xn.value),De=["mon","tue","wed","thu","fri","sat","sun"],Me=Ee==="backlog"||Ee==="expired"||De.includes(Ee),tt=yt=>{let qt=yt.length;const Ht=it&&ze(it)?le(it):null;if(!Ht||!Be.has(Ht))return qt;const sn=Ht,ft=yt.findIndex(Wt=>Wt.id===sn);if(ft<0)return qt;const Ze=we?.rect,pn=_e.rect.current.translated||_e.rect.current.initial,$t=!!(Ze&&pn&&pn.top+pn.height/2>Ze.top+Ze.height/2);return ft+($t?1:0)},Nn=(yt,qt,Ht)=>{if(!yt||yt===qt)return;(xt[String(yt)]||[]).filter(ft=>ft.id!==It).forEach((ft,Ze)=>{Ht.set(ft.id,{...Ht.get(ft.id)||{},orderInDay:Ze})})};if(Ee==="expired"){if(Jn!=="expired")return;const yt=new Map,qt=(xt.expired||[]).filter(ft=>ft.id!==It),Ht=tt(qt),sn=[...qt];sn.splice(Ht,0,wt),sn.forEach((ft,Ze)=>{yt.set(ft.id,{...yt.get(ft.id)||{},orderInDay:Ze})}),yt.forEach((ft,Ze)=>C(Ze,ft));return}if(Ee==="backlog"){const yt=new Map,qt=(xt.backlog||[]).filter(ft=>ft.id!==It),Ht=tt(qt),sn=[...qt];sn.splice(Ht,0,wt),sn.forEach((ft,Ze)=>{ft.id===It?wt.scheduledDate?yt.set(ft.id,{...yt.get(ft.id)||{},scheduledDate:null,scheduledWeekKey:null,orderInDay:Ze}):yt.set(ft.id,{...yt.get(ft.id)||{},orderInDay:Ze}):yt.set(ft.id,{...yt.get(ft.id)||{},orderInDay:Ze})}),Nn(Jn,Ee,yt),yt.forEach((ft,Ze)=>C(Ze,ft));return}if(!Me||!De.includes(Ee))return;const Et=F.dates[Ee];if(!Et)return;if(!(wt.status==="done"||wt.status==="cancelled")&&Et<mt){window.alert("Only completed work can be scheduled in the past.");return}const Pn=F.parseToIsoWeekKey(Et),Cn=new Map,Sn=(xt[Ee]||[]).filter(yt=>yt.id!==It),ln=tt(Sn),Kt=[...Sn];Kt.splice(ln,0,wt),Kt.forEach((yt,qt)=>{yt.id===It?Cn.set(yt.id,{...Cn.get(yt.id)||{},scheduledDate:Et,scheduledWeekKey:Pn,orderInDay:qt}):Cn.set(yt.id,{...Cn.get(yt.id)||{},orderInDay:qt})}),Nn(Jn,Ee,Cn),Cn.forEach((yt,qt)=>C(qt,yt)),Ve?.(Et);return}let se=Xn.value;if(s==="status"){const Ee=rt(wt),De=String(se);if(Ee!==De){const Me={status:De};De==="task"||De==="on-hold"?(Me.inProgress=!1,Me.readyForReview=!1,Me.completed=!1,Me.cancelled=!1):De==="in-progress"?(Me.inProgress=!0,Me.readyForReview=!1,Me.completed=!1,Me.cancelled=!1):De==="review"?(Me.inProgress=!1,Me.readyForReview=!0,Me.completed=!1,Me.cancelled=!1):De==="done"||De==="completed"?(Me.status="done",Me.inProgress=!1,Me.readyForReview=!1,Me.completed=!0,Me.cancelled=!1,Me.completedAt=new Date().toISOString()):De==="cancelled"&&(Me.status="cancelled"),C(wt.id,Me)}return}(s==="priority"||s==="complexity")&&(se=Number(se));const He=wt[s];if(String(He??"")!==String(se??"")){const Ee={[s]:se};C(wt.id,Ee)}}},Qt=J=>{if(St.has(J)){const Ie=St.get(J);return Ie?String(Ie.value):J}if(s==="schedule"&&J.startsWith(tu))return"expired";const _e=le(J),we=e.find(Ie=>Ie.id===_e);if(we){let Ie="";s==="status"?Ie=rt(we):s==="schedule"?Ie=Ke(we):Ie=String(we[s]??"");const We=St.get(Ie);return We?String(We.value):null}return null},zt={sideEffects:Ig({styles:{active:{opacity:"0"}}})},Ge=J=>{try{const _e=xg(J);if(_e.length>0){const we=_e.find(_t=>String(_t.id).startsWith("planning-"));if(we)return[we];const Ie=J.pointerCoordinates;if(!Ie)return[_e[0]];const We=_e.filter(_t=>{const vt=String(_t.id);return ze(vt)&&vt!==H});if(We.length===0){const vt=_e.filter(It=>{const wt=String(It.id);return!ze(wt)}).find(It=>!!Qt(String(It.id)))||null,Ot=vt?Qt(String(vt.id)):null,it=(J.droppableContainers||[]).filter(It=>{const wt=String(It.id);return!ze(wt)||wt===H?!1:Ot?Qt(wt)===Ot:!0});if(it.length>0){const It=mm({...J,droppableContainers:it});if(It.length>0)return[It[0]]}return vt?[vt]:[_e[0]]}const Qe=We;let ot=Qe[0],et=Number.POSITIVE_INFINITY;for(const _t of Qe){const vt=J.droppableRects?.get(_t.id);if(!vt)continue;const Ot=vt.left+vt.width/2,it=vt.top+vt.height/2,It=Ie.x-Ot,wt=Ie.y-it,_n=It*It+wt*wt;_n<et&&(et=_n,ot=_t)}return[ot]}return mm(J)}catch(_e){return console.error("[TaskKanban] collision detection error",_e),[]}},An={searchQuery:r,copiedId:o,taxonomies:l,types:c,priorities:p,approaches:g,assigneeOptions:w,onCopyId:k,onToggleInProgress:b,onToggleReview:E,onToggleComplete:S,onToggleCancel:W,onSetStatus:Q,onArchiveTask:z,onUnarchive:K,onDelete:V,onOpenTaskById:y,categories:B,readOnlyMode:Ne,changedTaskIdSet:pe,resolveTaskHierarchy:ye,groupBy:s,showStatusLabel:M};return t.jsxs(lf,{sensors:d,collisionDetection:Ge,onDragStart:At,onDragOver:Se,onDragEnd:Mt,onDragCancel:J=>{Xe.current=null,j(null)},children:[L,t.jsxs("div",{className:u.kanbanWrapper,children:[t.jsx("div",{ref:cn,className:`${u.kanbanTopScroll} tf-scrollbar`,children:t.jsx("div",{className:u.kanbanTopScrollSpacer,style:{width:`${an}px`}})}),t.jsx("div",{className:u.kanbanContainer,ref:on,children:n.map(J=>{const _e=xt[String(J.value)]||[],we=yn(J.value,J.label),Ie=s!=="schedule"&&Ae==="hide"&&_e.length===0,We=s==="schedule",Qe=We&&n.some(wt=>String(wt.value)==="backlog"),ot=We&&String(J.value)==="backlog",et=We&&String(J.value)==="expired",_t=xt.backlog||[],Ot=Ae==="collapse"&&_t.length===0?72:320,it=ot?0:et?Qe?Ot+4:0:void 0,It=ot?6:et?5:void 0;return we||Ie?null:t.jsx(FP,{id:String(J.value),title:J.label,color:J.color,icon:J.icon,tasks:_e,activeId:H,activeTaskId:Zt,totalCount:Lt[String(J.value)],onAddTask:()=>D?.(s,J.value),onTaskClick:_,commonCardProps:An,collapseEmpty:Ae==="collapse",compressed:fe,onHeaderPointerDown:Gn,isHeaderPanning:je,headerPanEnabled:ue,stickyLeft:it,stickyZIndex:It,isPast:!!J.isPast,isSelected:!!J.isSelected,isWeekend:!!J.isWeekend,disableSorting:!1,scheduleDate:s==="schedule"?F.dates[String(J.value)]:void 0,onScheduleDaySelected:Ve},String(J.value))})})]}),Ci.createPortal(t.jsx(Cg,{dropAnimation:zt,children:Jt?(()=>{const{taskWorkstream:J,taskInitiative:_e}=ye(Jt);return t.jsx(Ul,{task:Jt,taskWorkstream:J,taskInitiative:_e,isOverlay:!0,...An,isArchived:Jt.isArchived,categories:B,compressed:fe,isRecentlyChanged:pe.has(Jt.id)})})():null}),document.body)]})}function FP({id:e,title:n,color:s,icon:r,tasks:o,activeId:l=null,activeTaskId:c=null,totalCount:p,onAddTask:g,onTaskClick:w,commonCardProps:C,collapseEmpty:_,compressed:y,onHeaderPointerDown:k,isHeaderPanning:b=!1,headerPanEnabled:E=!1,stickyLeft:S,stickyZIndex:W,isPast:Q=!1,isSelected:z=!1,isWeekend:K=!1,disableSorting:V=!1,scheduleDate:ne,onScheduleDaySelected:D}){const{setNodeRef:Ae}=ql({id:e,data:{type:"Column"}}),U=_&&o.length===0,ee=c?o.filter(B=>B.id!==c):o,be=typeof S=="number",me=a.useRef(null),Y=B=>e==="expired"?`${tu}${B}`:B,R=B=>{if(!ne||!D)return;const fe=B.target;fe&&(fe.closest('[data-task-card="true"]')||fe.closest(`.${u.kanbanCardWrapper}`)||D(ne))};return t.jsxs("div",{ref:Ae,className:`${u.kanbanColumn} ${U?u.kanbanColumnCollapsed:""} ${be?u.kanbanColumnSticky:""} ${Q?u.kanbanColumnPast:""} ${z?u.kanbanColumnSelectedDay:""} ${K?u.kanbanColumnWeekend:""}`,style:be?{left:`${S}px`,zIndex:W??4}:void 0,onClick:R,children:[t.jsxs("div",{className:`${u.kanbanHeader} ${E?u.kanbanHeaderDraggable:""} ${b?u.kanbanHeaderPanning:""}`,style:{borderTopColor:_a(s)||"var(--color-purple)"},onPointerDown:k,children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",minWidth:0,overflow:"hidden"},children:[(()=>{const B=r&&Ni[r]?Ni[r]:Ai,fe=_a(s)||"var(--color-purple)";return t.jsx(B,{size:16,style:{color:fe}})})(),!U&&t.jsx("span",{style:{whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:n})]}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",flexShrink:0},children:[(!U||p>0)&&t.jsx("span",{className:u.kanbanCount,children:U?p:`${o.length} / ${p}`}),!C.readOnlyMode&&t.jsx("button",{className:"tf-control-icon tf-control-icon-compact",onClick:B=>{B.stopPropagation(),g()},title:`Add task to ${n}`,"aria-label":`Add task to ${n}`,"data-no-header-pan":"true",children:t.jsx(sr,{size:14})})]})]}),t.jsx("div",{className:u.kanbanDroppable,children:t.jsx("div",{className:`${u.kanbanDroppableScroll} ${u.appScrollbar} tf-scrollbar`,ref:me,children:V?ee.map(B=>t.jsx("div",{className:u.kanbanCardWrapper,children:(()=>{const{taskWorkstream:fe,taskInitiative:Ne}=C.resolveTaskHierarchy?.(B)||{};return t.jsx(Ul,{task:B,taskWorkstream:fe,taskInitiative:Ne,onClick:w,...C,isArchived:B.isArchived,readOnlyMode:C.readOnlyMode||null,compressed:y,isRecentlyChanged:!1})})()},B.id)):t.jsx(df,{id:e,items:ee.map(B=>Y(B.id)),strategy:uf,children:ee.map(B=>t.jsx(zP,{sortableId:Y(B.id),task:B,onClick:w,commonCardProps:C,compressed:y,isRecentlyChanged:C.changedTaskIdSet?.has(B.id)},Y(B.id)))})})})]})}function zP({sortableId:e,task:n,onClick:s,commonCardProps:r,compressed:o,isRecentlyChanged:l=!1}){const c=!!r?.readOnlyMode,{attributes:p,listeners:g,setNodeRef:w,transform:C,transition:_,isDragging:y}=mf({id:e,disabled:c,data:{type:"task-card",taskId:n.id}}),k={transform:Lp.Transform.toString(C),transition:_,opacity:y?0:1,pointerEvents:y?"none":"auto"},b=r?.groupBy==="schedule",E=!b&&l;return t.jsx("div",{ref:w,style:k,...c?{}:p,...c?{}:g,className:`${u.kanbanCardWrapper} ${E?u.kanbanCardWrapperRaised:""}`,children:(()=>{const{taskWorkstream:S,taskInitiative:W}=r.resolveTaskHierarchy?.(n)||{};return t.jsx(Ul,{task:n,taskWorkstream:S,taskInitiative:W,onClick:s,...r,isArchived:n.isArchived,readOnlyMode:r?.readOnlyMode||null,compressed:o,isRecentlyChanged:b?!1:l})})()})}function OP(e,n,s){const r=String(n);if(e==="category"){const o=s.categories.find(l=>String(l.value)===r||l.label===r);return o?{category:o.label}:{}}if(e==="type")return{type:r};if(e==="priority")return Number.isFinite(Number(n))?{priority:Number(n)}:{};if(e==="complexity")return Number.isFinite(Number(n))?{complexity:Number(n)}:{};if(e==="approach"){const o=s.approaches.find(l=>String(l.value)===r||l.label===r);return o?{approach:o.value,taxonomyApproach:o.value}:{}}return e==="assignee"?r.trim().length>0?{assignee:r}:{}:e==="status"?r==="completed"?{status:"done"}:r==="task"||r==="on-hold"||r==="in-progress"||r==="review"||r==="done"||r==="cancelled"?{status:r}:{}:e==="schedule"?r==="backlog"||r==="expired"?{}:{scheduledDate:r}:{}}function $P(e){const n=e.runtimeMode==="local"&&e.isAuthenticated;return n?{actionable:n,status:e.workspaceSyncStatus,syncEnabledLabel:e.workspaceCloudSyncEnabled?"yes":"no",summary:e.workspaceSyncSummary,recommendedAction:e.workspaceSyncRecommendedAction,lastError:e.workspaceSyncError}:{actionable:n,status:"off",syncEnabledLabel:"no",summary:"Sign in to enable workspace sync controls on this device.",recommendedAction:"Sign in to manage workspace sync for this workspace.",lastError:"Sign in to enable workspace sync controls on this device."}}const UP=5e3,Dl=new Map;function fp(){return typeof performance<"u"?performance.now():Date.now()}function hh(e){return String(e||"").trim()}function Um(e){Dl.delete(hh(e))}async function qP(e,n){const s=hh(e);if(!s)return null;const r=Date.now(),o=Dl.get(s);if(o?.payload!==void 0&&r-o.fetchedAt<UP)return Bn("billing_status_cache_hit",{url:s,ageMs:r-o.fetchedAt}),o.payload;if(o?.promise)return Bn("billing_status_request_reused",{url:s}),o.promise;const l=fp(),c=(async()=>{const p=await fetch(s,{method:"GET",credentials:"include"});if(!p.ok)throw new Error(String((await p.json().catch(()=>({})))?.error||"Failed to load billing status."));const w=await p.json().catch(()=>({}))||null;return Dl.set(s,{payload:w,fetchedAt:Date.now(),promise:null}),Bn("billing_status_loaded",{url:s,durationMs:Math.round(fp()-l),fromCache:!1}),w})().catch(p=>{throw Dl.delete(s),Bn("billing_status_failed",{url:s,durationMs:Math.round(fp()-l),error:p instanceof Error?p.message:String(p||"Unknown error")}),p});return Dl.set(s,{payload:o?.payload??null,fetchedAt:o?.fetchedAt??0,promise:c}),c}const Dp="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjwhLS0gQ3JlYXRlZCB3aXRoIElua3NjYXBlIChodHRwOi8vd3d3Lmlua3NjYXBlLm9yZy8pIC0tPgoKPHN2ZwogICB3aWR0aD0iMzY2LjY3Nzg2IgogICBoZWlnaHQ9IjMzMS4zMDkzMyIKICAgdmlld0JveD0iMCAwIDk3LjAxNjg1IDg3LjY1ODkyMyIKICAgdmVyc2lvbj0iMS4xIgogICBpZD0ic3ZnMSIKICAgeG1sOnNwYWNlPSJwcmVzZXJ2ZSIKICAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogICB4bWxuczpzdmc9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZGVmcwogICAgIGlkPSJkZWZzMSIgLz48ZwogICAgIGlkPSJsYXllcjEiCiAgICAgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoMTMwLjk2ODgxLC04NzIuMDY2NjgpIj48ZwogICAgICAgaWQ9ImcxLTctMS02LTItMS05IgogICAgICAgdHJhbnNmb3JtPSJtYXRyaXgoNC45ODE1NDc5LDAsMCw0Ljk4NTU4MjIsLTYzNS4zODE5NiwxMzcuOTM1MTIpIj48cGF0aAogICAgICAgICBzdHlsZT0iZm9udC1zdHlsZTppdGFsaWM7Zm9udC13ZWlnaHQ6Ym9sZDtmb250LXNpemU6MTkuNDgxOXB4O2xpbmUtaGVpZ2h0OjIuNTtmb250LWZhbWlseTonUnVzc28gT25lJzstaW5rc2NhcGUtZm9udC1zcGVjaWZpY2F0aW9uOidSdXNzbyBPbmUgTWVkaXVtIEl0YWxpYyc7dGV4dC1hbGlnbjpjZW50ZXI7bGV0dGVyLXNwYWNpbmc6MHB4O3RleHQtYW5jaG9yOm1pZGRsZTtmaWxsOiNmZmZmZmY7ZmlsbC1ydWxlOmV2ZW5vZGQ7c3Ryb2tlOiNmZmZmZmY7c3Ryb2tlLXdpZHRoOjAuNjEzNjA0O3N0cm9rZS1saW5lY2FwOnJvdW5kO3N0cm9rZS1saW5lam9pbjpyb3VuZCIKICAgICAgICAgZD0ibSAxNDkuNDQwNjYsMTYxLjE5NTA1IGggLTMuNTA2NzQgdiAtMTAuOTA5ODYgaCAtNC4wOTEyIHYgLTIuNzI3NDcgaCAxMS42ODkxNCB2IDIuNzI3NDcgaCAtNC4wOTEyIHoiCiAgICAgICAgIGlkPSJ0ZXh0MS00LTMtMy0xLTAtMyIKICAgICAgICAgdHJhbnNmb3JtPSJza2V3WCgtMTUpIgogICAgICAgICBhcmlhLWxhYmVsPSJUIiAvPjxwYXRoCiAgICAgICAgIHN0eWxlPSJmb250LXN0eWxlOml0YWxpYztmb250LXdlaWdodDpib2xkO2ZvbnQtc2l6ZToxOS40ODE5cHg7bGluZS1oZWlnaHQ6Mi41O2ZvbnQtZmFtaWx5OidSdXNzbyBPbmUnOy1pbmtzY2FwZS1mb250LXNwZWNpZmljYXRpb246J1J1c3NvIE9uZSBNZWRpdW0gSXRhbGljJzt0ZXh0LWFsaWduOmVuZDtsZXR0ZXItc3BhY2luZzowcHg7dGV4dC1hbmNob3I6ZW5kO2ZpbGw6I2ZmOGEwMDtmaWxsLXJ1bGU6ZXZlbm9kZDtzdHJva2U6I2ZmOGEwMDtzdHJva2Utd2lkdGg6MC42MTM2MDQ7c3Ryb2tlLWxpbmVjYXA6cm91bmQ7c3Ryb2tlLWxpbmVqb2luOnJvdW5kIgogICAgICAgICBkPSJtIDE1My41Mzg4OCwxNjQuNTI2NiBoIC0zLjUwNjc0IHYgLTEzLjYzNzMzIGggMTAuODEyNDUgdiAyLjcyNzQ2IGggLTcuMzA1NzEgdiAzLjIxNDUyIGggNS43NDcxNiB2IDIuNzI3NDYgaCAtNS43NDcxNiB6IgogICAgICAgICBpZD0idGV4dDEtOS04LTQtMy03LTItNyIKICAgICAgICAgdHJhbnNmb3JtPSJza2V3WCgtMTUpIgogICAgICAgICBhcmlhLWxhYmVsPSJGIiAvPjwvZz48L2c+PC9zdmc+Cg==",gh="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjwhLS0gQ3JlYXRlZCB3aXRoIElua3NjYXBlIChodHRwOi8vd3d3Lmlua3NjYXBlLm9yZy8pIC0tPgoKPHN2ZwogICB3aWR0aD0iMzY2LjY3Nzg5IgogICBoZWlnaHQ9IjMzMS4zMDkzMyIKICAgdmlld0JveD0iMCAwIDk3LjAxNjg1OCA4Ny42NTg5MjMiCiAgIHZlcnNpb249IjEuMSIKICAgaWQ9InN2ZzEiCiAgIHhtbDpzcGFjZT0icHJlc2VydmUiCiAgIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICAgeG1sbnM6c3ZnPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PGRlZnMKICAgICBpZD0iZGVmczEiIC8+PGcKICAgICBpZD0ibGF5ZXIxIgogICAgIHRyYW5zZm9ybT0idHJhbnNsYXRlKDE4Ni4xOTU2MywtNzgwLjY1NTczKSI+PGcKICAgICAgIGlkPSJnMS03LTEtNi0yLTEiCiAgICAgICB0cmFuc2Zvcm09Im1hdHJpeCg0Ljk4MTU0NzksMCwwLDQuOTg1NTgyMiwtNjkwLjYwODc4LDQ2LjUyNDE0OCkiPjxwYXRoCiAgICAgICAgIHN0eWxlPSJmb250LXN0eWxlOml0YWxpYztmb250LXdlaWdodDpib2xkO2ZvbnQtc2l6ZToxOS40ODE5cHg7bGluZS1oZWlnaHQ6Mi41O2ZvbnQtZmFtaWx5OidSdXNzbyBPbmUnOy1pbmtzY2FwZS1mb250LXNwZWNpZmljYXRpb246J1J1c3NvIE9uZSBNZWRpdW0gSXRhbGljJzt0ZXh0LWFsaWduOmNlbnRlcjtsZXR0ZXItc3BhY2luZzowcHg7dGV4dC1hbmNob3I6bWlkZGxlO2ZpbGwtcnVsZTpldmVub2RkO3N0cm9rZTojMDAwMDAwO3N0cm9rZS13aWR0aDowLjYxMzYwNDtzdHJva2UtbGluZWNhcDpyb3VuZDtzdHJva2UtbGluZWpvaW46cm91bmQiCiAgICAgICAgIGQ9Im0gMTQ5LjQ0MDY2LDE2MS4xOTUwNSBoIC0zLjUwNjc0IHYgLTEwLjkwOTg2IGggLTQuMDkxMiB2IC0yLjcyNzQ3IGggMTEuNjg5MTQgdiAyLjcyNzQ3IGggLTQuMDkxMiB6IgogICAgICAgICBpZD0idGV4dDEtNC0zLTMtMS0wIgogICAgICAgICB0cmFuc2Zvcm09InNrZXdYKC0xNSkiCiAgICAgICAgIGFyaWEtbGFiZWw9IlQiIC8+PHBhdGgKICAgICAgICAgc3R5bGU9ImZvbnQtc3R5bGU6aXRhbGljO2ZvbnQtd2VpZ2h0OmJvbGQ7Zm9udC1zaXplOjE5LjQ4MTlweDtsaW5lLWhlaWdodDoyLjU7Zm9udC1mYW1pbHk6J1J1c3NvIE9uZSc7LWlua3NjYXBlLWZvbnQtc3BlY2lmaWNhdGlvbjonUnVzc28gT25lIE1lZGl1bSBJdGFsaWMnO3RleHQtYWxpZ246ZW5kO2xldHRlci1zcGFjaW5nOjBweDt0ZXh0LWFuY2hvcjplbmQ7ZmlsbDojZmY4YTAwO2ZpbGwtcnVsZTpldmVub2RkO3N0cm9rZTojZmY4YTAwO3N0cm9rZS13aWR0aDowLjYxMzYwNDtzdHJva2UtbGluZWNhcDpyb3VuZDtzdHJva2UtbGluZWpvaW46cm91bmQiCiAgICAgICAgIGQ9Im0gMTUzLjUzODg4LDE2NC41MjY2IGggLTMuNTA2NzQgdiAtMTMuNjM3MzMgaCAxMC44MTI0NSB2IDIuNzI3NDYgaCAtNy4zMDU3MSB2IDMuMjE0NTIgaCA1Ljc0NzE2IHYgMi43Mjc0NiBoIC01Ljc0NzE2IHoiCiAgICAgICAgIGlkPSJ0ZXh0MS05LTgtNC0zLTctMiIKICAgICAgICAgdHJhbnNmb3JtPSJza2V3WCgtMTUpIgogICAgICAgICBhcmlhLWxhYmVsPSJGIiAvPjwvZz48L2c+PC9zdmc+Cg==",qm="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZlcnNpb249IjEuMSIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIHdpZHRoPSIxMDAwIiBoZWlnaHQ9IjEwMDAiPjxzdHlsZT4KICAgICNsaWdodC1pY29uIHsKICAgICAgZGlzcGxheTogaW5saW5lOwogICAgfQogICAgI2RhcmstaWNvbiB7CiAgICAgIGRpc3BsYXk6IG5vbmU7CiAgICB9CgogICAgQG1lZGlhIChwcmVmZXJzLWNvbG9yLXNjaGVtZTogZGFyaykgewogICAgICAjbGlnaHQtaWNvbiB7CiAgICAgICAgZGlzcGxheTogbm9uZTsKICAgICAgfQogICAgICAjZGFyay1pY29uIHsKICAgICAgICBkaXNwbGF5OiBpbmxpbmU7CiAgICAgIH0KICAgIH0KICA8L3N0eWxlPjxnIGlkPSJsaWdodC1pY29uIj48c3ZnIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmVyc2lvbj0iMS4xIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgd2lkdGg9IjEwMDAiIGhlaWdodD0iMTAwMCI+PGc+PGcgdHJhbnNmb3JtPSJtYXRyaXgoMi43MjcxODkyNTA0ODkwMzI3LDAsMCwyLjcyNzE4OTI1MDQ4OTAzMjcsMCw0OC4yMjgzNzgzMTg2MzgxOSkiPjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB2ZXJzaW9uPSIxLjEiIHdpZHRoPSIzNjYuNjc3ODkiIGhlaWdodD0iMzMxLjMwOTMzIiB2aWV3Qm94PSIwIDAgOTcuMDE2ODU4IDg3LjY1ODkyMyIgaWQ9InN2ZzEiIHhtbDpzcGFjZT0icHJlc2VydmUiIHhtbG5zOnN2Zz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjxkZWZzIGlkPSJkZWZzMSI+PC9kZWZzPjxnIGlkPSJsYXllcjEiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDE4Ni4xOTU2MywtNzgwLjY1NTczKSI+PGcgaWQ9ImcxLTctMS02LTItMSIgdHJhbnNmb3JtPSJtYXRyaXgoNC45ODE1NDc5LDAsMCw0Ljk4NTU4MjIsLTY5MC42MDg3OCw0Ni41MjQxNDgpIj48cGF0aCBzdHlsZT0iZm9udC1zdHlsZTppdGFsaWM7Zm9udC13ZWlnaHQ6Ym9sZDtmb250LXNpemU6MTkuNDgxOXB4O2xpbmUtaGVpZ2h0OjIuNTtmb250LWZhbWlseTonUnVzc28gT25lJzstaW5rc2NhcGUtZm9udC1zcGVjaWZpY2F0aW9uOidSdXNzbyBPbmUgTWVkaXVtIEl0YWxpYyc7dGV4dC1hbGlnbjpjZW50ZXI7bGV0dGVyLXNwYWNpbmc6MHB4O3RleHQtYW5jaG9yOm1pZGRsZTtmaWxsLXJ1bGU6ZXZlbm9kZDtzdHJva2U6IzAwMDAwMDtzdHJva2Utd2lkdGg6MC42MTM2MDQ7c3Ryb2tlLWxpbmVjYXA6cm91bmQ7c3Ryb2tlLWxpbmVqb2luOnJvdW5kIiBkPSJtIDE0OS40NDA2NiwxNjEuMTk1MDUgaCAtMy41MDY3NCB2IC0xMC45MDk4NiBoIC00LjA5MTIgdiAtMi43Mjc0NyBoIDExLjY4OTE0IHYgMi43Mjc0NyBoIC00LjA5MTIgeiIgaWQ9InRleHQxLTQtMy0zLTEtMCIgdHJhbnNmb3JtPSJza2V3WCgtMTUpIiBhcmlhLWxhYmVsPSJUIj48L3BhdGg+PHBhdGggc3R5bGU9ImZvbnQtc3R5bGU6aXRhbGljO2ZvbnQtd2VpZ2h0OmJvbGQ7Zm9udC1zaXplOjE5LjQ4MTlweDtsaW5lLWhlaWdodDoyLjU7Zm9udC1mYW1pbHk6J1J1c3NvIE9uZSc7LWlua3NjYXBlLWZvbnQtc3BlY2lmaWNhdGlvbjonUnVzc28gT25lIE1lZGl1bSBJdGFsaWMnO3RleHQtYWxpZ246ZW5kO2xldHRlci1zcGFjaW5nOjBweDt0ZXh0LWFuY2hvcjplbmQ7ZmlsbDojZmY4YTAwO2ZpbGwtcnVsZTpldmVub2RkO3N0cm9rZTojZmY4YTAwO3N0cm9rZS13aWR0aDowLjYxMzYwNDtzdHJva2UtbGluZWNhcDpyb3VuZDtzdHJva2UtbGluZWpvaW46cm91bmQiIGQ9Im0gMTUzLjUzODg4LDE2NC41MjY2IGggLTMuNTA2NzQgdiAtMTMuNjM3MzMgaCAxMC44MTI0NSB2IDIuNzI3NDYgaCAtNy4zMDU3MSB2IDMuMjE0NTIgaCA1Ljc0NzE2IHYgMi43Mjc0NiBoIC01Ljc0NzE2IHoiIGlkPSJ0ZXh0MS05LTgtNC0zLTctMiIgdHJhbnNmb3JtPSJza2V3WCgtMTUpIiBhcmlhLWxhYmVsPSJGIj48L3BhdGg+PC9nPjwvZz48L3N2Zz48L2c+PC9nPjwvc3ZnPjwvZz48ZyBpZD0iZGFyay1pY29uIj48c3ZnIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmVyc2lvbj0iMS4xIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgd2lkdGg9IjEwMDAiIGhlaWdodD0iMTAwMCI+PGc+PGcgdHJhbnNmb3JtPSJtYXRyaXgoMi43MjcxODk0NzM2MTU4ODcsMCwwLDIuNzI3MTg5NDczNjE1ODg3LDAsNDguMjI4MzQxMzU2NjMzOTA1KSI+PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZlcnNpb249IjEuMSIgd2lkdGg9IjM2Ni42Nzc4NiIgaGVpZ2h0PSIzMzEuMzA5MzMiIHZpZXdCb3g9IjAgMCA5Ny4wMTY4NSA4Ny42NTg5MjMiIGlkPSJzdmcxIiB4bWw6c3BhY2U9InByZXNlcnZlIiB4bWxuczpzdmc9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZGVmcyBpZD0iZGVmczEiPjwvZGVmcz48ZyBpZD0ibGF5ZXIxIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSgxMzAuOTY4ODEsLTg3Mi4wNjY2OCkiPjxnIGlkPSJnMS03LTEtNi0yLTEtOSIgdHJhbnNmb3JtPSJtYXRyaXgoNC45ODE1NDc5LDAsMCw0Ljk4NTU4MjIsLTYzNS4zODE5NiwxMzcuOTM1MTIpIj48cGF0aCBzdHlsZT0iZm9udC1zdHlsZTppdGFsaWM7Zm9udC13ZWlnaHQ6Ym9sZDtmb250LXNpemU6MTkuNDgxOXB4O2xpbmUtaGVpZ2h0OjIuNTtmb250LWZhbWlseTonUnVzc28gT25lJzstaW5rc2NhcGUtZm9udC1zcGVjaWZpY2F0aW9uOidSdXNzbyBPbmUgTWVkaXVtIEl0YWxpYyc7dGV4dC1hbGlnbjpjZW50ZXI7bGV0dGVyLXNwYWNpbmc6MHB4O3RleHQtYW5jaG9yOm1pZGRsZTtmaWxsOiNmZmZmZmY7ZmlsbC1ydWxlOmV2ZW5vZGQ7c3Ryb2tlOiNmZmZmZmY7c3Ryb2tlLXdpZHRoOjAuNjEzNjA0O3N0cm9rZS1saW5lY2FwOnJvdW5kO3N0cm9rZS1saW5lam9pbjpyb3VuZCIgZD0ibSAxNDkuNDQwNjYsMTYxLjE5NTA1IGggLTMuNTA2NzQgdiAtMTAuOTA5ODYgaCAtNC4wOTEyIHYgLTIuNzI3NDcgaCAxMS42ODkxNCB2IDIuNzI3NDcgaCAtNC4wOTEyIHoiIGlkPSJ0ZXh0MS00LTMtMy0xLTAtMyIgdHJhbnNmb3JtPSJza2V3WCgtMTUpIiBhcmlhLWxhYmVsPSJUIj48L3BhdGg+PHBhdGggc3R5bGU9ImZvbnQtc3R5bGU6aXRhbGljO2ZvbnQtd2VpZ2h0OmJvbGQ7Zm9udC1zaXplOjE5LjQ4MTlweDtsaW5lLWhlaWdodDoyLjU7Zm9udC1mYW1pbHk6J1J1c3NvIE9uZSc7LWlua3NjYXBlLWZvbnQtc3BlY2lmaWNhdGlvbjonUnVzc28gT25lIE1lZGl1bSBJdGFsaWMnO3RleHQtYWxpZ246ZW5kO2xldHRlci1zcGFjaW5nOjBweDt0ZXh0LWFuY2hvcjplbmQ7ZmlsbDojZmY4YTAwO2ZpbGwtcnVsZTpldmVub2RkO3N0cm9rZTojZmY4YTAwO3N0cm9rZS13aWR0aDowLjYxMzYwNDtzdHJva2UtbGluZWNhcDpyb3VuZDtzdHJva2UtbGluZWpvaW46cm91bmQiIGQ9Im0gMTUzLjUzODg4LDE2NC41MjY2IGggLTMuNTA2NzQgdiAtMTMuNjM3MzMgaCAxMC44MTI0NSB2IDIuNzI3NDYgaCAtNy4zMDU3MSB2IDMuMjE0NTIgaCA1Ljc0NzE2IHYgMi43Mjc0NiBoIC01Ljc0NzE2IHoiIGlkPSJ0ZXh0MS05LTgtNC0zLTctMi03IiB0cmFuc2Zvcm09InNrZXdYKC0xNSkiIGFyaWEtbGFiZWw9IkYiPjwvcGF0aD48L2c+PC9nPjwvc3ZnPjwvZz48L2c+PC9zdmc+PC9nPjwvc3ZnPg==";function HP({projectName:e,currentWorkspaceId:n,brandLabel:s="TaskForce",runtimeMode:r="local",theme:o=ru,meta:l,actions:c}){const p=Sf(o)?gh:Dp;return t.jsxs("div",{className:`${u.header} ${hn.standaloneHeader}`,children:[t.jsxs("div",{className:`${u.headerTitle} ${hn.standaloneTitle}`,children:[t.jsx("img",{src:p,alt:"Taskforce Logo",className:u.brandIcon,onError:g=>{const w=g.currentTarget;w.src!==qm?w.src=qm:w.style.display="none"}}),t.jsx("span",{children:s}),r==="cloud"&&t.jsx("span",{className:u.brandCloudSuffix,children:"HQ"}),e&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:u.projectSlash,children:"/"}),t.jsx("span",{className:u.projectName,title:n?`Workspace ID: ${n}`:void 0,children:e})]}),l]}),t.jsx("div",{className:u.headerActions,style:{gap:"16px"},children:c})]})}function GP({value:e,placeholder:n,active:s=!1,onChange:r,onClear:o,clearTitle:l}){return t.jsxs("div",{className:u.searchContainer,style:{width:"240px"},children:[t.jsx(sg,{size:16,className:u.searchIcon}),t.jsx("input",{type:"text",className:`${u.searchInput} ${s?u.searchActive:""}`,placeholder:n,value:e,onChange:c=>r(c.target.value)}),e&&o&&t.jsx("button",{className:u.clearSearchBtn,onClick:o,title:l,children:t.jsx("span",{"aria-hidden":"true",children:"×"})})]})}function Hm({label:e,value:n,options:s,onChange:r,trailingAction:o,width:l}){return t.jsxs("div",{className:u.groupByContainer,style:l?{width:l}:void 0,children:[t.jsx("span",{className:u.groupByLabel,children:e}),t.jsx("select",{className:`${u.select} ${u.groupBySelect}`,value:n,onChange:c=>r(c.target.value),children:s.map(c=>t.jsx("option",{value:c.value,children:c.label},String(c.value)))}),o]})}function hp({actions:e}){return t.jsx(t.Fragment,{children:e.map(n=>t.jsx("button",{className:`tf-control-icon ${n.active?"tf-control-icon-active":""} ${n.className||""}`.trim(),onClick:n.onClick,title:n.title,disabled:n.disabled,"aria-disabled":n.ariaDisabled,children:n.icon},n.key))})}function Gm(){return t.jsx("div",{className:u.headerDivider})}function VP({icon:e,label:n,onClick:s,disabled:r=!1}){return t.jsxs("button",{className:u.primaryUpdateBtn,onClick:s,disabled:r,children:[e," ",n]})}function Zp({children:e}){return t.jsx("div",{className:u.filterToolbar,style:{padding:"8px 24px",borderBottom:"1px solid var(--border-primary)",background:"var(--bg-secondary)",boxShadow:"0 4px 18px rgba(8, 10, 24, 0.12)",display:"flex",alignItems:"center",gap:"12px",flexWrap:"wrap",position:"relative",zIndex:50},children:e})}function ZP(){return t.jsx(Zp,{children:t.jsx("div",{"aria-hidden":"true",style:{minHeight:"32px",flex:1}})})}function KP({categoryFilterOptions:e,typeFilterOptions:n,priorities:s,taxonomyDisplayLabels:r,filterCategories:o,setFilterCategories:l,filterTypes:c,setFilterTypes:p,filterPriorities:g,setFilterPriorities:w,filterStatus:C,setFilterStatus:_,filterAssignees:y,setFilterAssignees:k,assigneeOptions:b,initiativeFilterOptions:E=[],selectedInitiativeId:S="",setSelectedInitiativeId:W=()=>{},workstreamFilterOptions:Q=[],selectedWorkstreamId:z="",setSelectedWorkstreamId:K=()=>{},taskScope:V,setTaskScope:ne,showArchive:D,setShowArchive:Ae,fetchArchive:U,onDeleteAllDeleted:ee,clearFilters:be}){return t.jsxs(t.Fragment,{children:[t.jsx(rh,{}),t.jsx(_i,{label:r?.category||xe("standalone.categoryLabel"),options:e,selected:o,onChange:me=>l(me),variant:"value"}),t.jsx(_i,{label:r?.type||xe("standalone.typeLabel"),options:n,selected:c,onChange:me=>p(me),variant:"value"}),t.jsx(_i,{label:r?.priority||xe("standalone.priorityLabel"),options:s,selected:g,onChange:me=>w(me),variant:"value"}),t.jsx(_i,{label:xe("standalone.statusLabel"),options:no,selected:C,onChange:me=>_(me),variant:"value"}),t.jsx(_i,{label:xe("standalone.assigneeLabel"),options:b,selected:y,onChange:me=>k(me),variant:"value"}),t.jsx("div",{className:u.headerDivider,style:{height:"16px",margin:"0 8px"}}),t.jsx(Wm,{label:"Initiative",options:E,selected:S,onChange:W,allLabel:"All Initiatives",title:"Filter by initiative"}),t.jsx(Wm,{label:"Workstream",options:Q,selected:z,onChange:K,allLabel:"All Workstreams",title:"Filter by workstream"}),t.jsx(ih,{scope:V,onScopeChange:me=>{ne(me),me==="archived"?(Ae(!0),U()):D&&Ae(!1)},className:u.groupByContainer,labelClassName:u.groupByLabel}),t.jsx("div",{style:{flex:1}}),V==="deleted"&&ee&&t.jsx(ch,{onClick:ee,className:`${u.bulkArchiveBtn} ${u.taskToolbarAction} ${u.bulkDeleteBtn}`,title:"Empty trash",children:"Empty Trash"}),t.jsx(oh,{onClick:be})]})}function YP(e){return t.jsx(Zp,{children:t.jsx(KP,{...e})})}const nu=[{value:"implementation-plan",label:"Plans"},{value:"review",label:"Reviews"},{value:"walkthrough",label:"Walkthroughs"},{value:"planning",label:"Planning"},{value:"other",label:"Other"}],au=[{value:"attached",label:"Attached"},{value:"unattached",label:"Unattached"}];function JP({typeFilters:e,setTypeFilters:n,attachmentFilters:s,setAttachmentFilters:r,clearFilters:o}){return t.jsxs(Zp,{children:[t.jsx(rh,{}),t.jsx(_i,{label:"Attachment",options:au,selected:s,onChange:l=>r(l),variant:"value"}),t.jsx(_i,{label:"Type",options:nu,selected:e,onChange:l=>n(l),variant:"value"}),t.jsx("div",{style:{flex:1}}),t.jsx(oh,{onClick:o})]})}const XP="_drawerBody_126ut_1",QP="_paneShell_126ut_9",eE="_collapsedPaneShell_126ut_18",tE="_collapsedPaneHeader_126ut_27",nE="_collapsedPaneLabel_126ut_39",aE="_treePane_126ut_49",sE="_treePaneSplit_126ut_59",rE="_detailPane_126ut_63",oE="_paneHeader_126ut_73",iE="_paneHeaderLabel_126ut_87",cE="_paneContent_126ut_96",lE="_sectionTitle_126ut_105",dE="_sectionHeaderRow_126ut_113",uE="_sectionGroup_126ut_120",pE="_treeList_126ut_145",mE="_treeChildren_126ut_151",fE="_treeRow_126ut_159",hE="_treeRowDetailOpen_126ut_171",gE="_treeRowDropReady_126ut_177",yE="_treeRowDropActive_126ut_181",kE="_treeRowDropMode_126ut_187",SE="_treeChevron_126ut_187",vE="_rowButton_126ut_188",wE="_detailsButton_126ut_189",bE="_treeRowDragging_126ut_193",_E="_rowContent_126ut_234",CE="_rowTopRow_126ut_244",xE="_referenceBadgeButton_126ut_253",AE="_referenceBadgeStatic_126ut_259",TE="_rowTitle_126ut_280",IE="_rowMeta_126ut_294",NE="_detailsButtonActive_126ut_322",jE="_unlinkZone_126ut_329",RE="_unlinkZoneActive_126ut_340",DE="_emptyPanel_126ut_346",PE="_emptyPanelTitle_126ut_355",EE="_emptyPanelText_126ut_361",LE="_sectionNote_126ut_367",ME="_detailHero_126ut_374",BE="_detailReferenceRow_126ut_381",WE="_detailTitle_126ut_386",FE="_detailDescription_126ut_393",zE="_detailActionRow_126ut_404",OE="_metricGrid_126ut_411",$E="_metricCard_126ut_418",UE="_editorCard_126ut_423",qE="_editorField_126ut_430",HE="_editorLabel_126ut_436",GE="_editorHint_126ut_442",VE="_editorSubActions_126ut_447",ZE="_editorActions_126ut_452",KE="_metricValue_126ut_458",YE="_metricLabel_126ut_465",JE="_progressTrack_126ut_472",XE="_progressFill_126ut_480",QE="_listCard_126ut_486",eL="_sectionDropReady_126ut_495",tL="_sectionDropActive_126ut_500",nL="_sectionDropMode_126ut_506",aL="_attachReferenceRow_126ut_510",sL="_listItem_126ut_521",rL="_listItemButton_126ut_530",oL="_detailCardButton_126ut_539",iL="_listItemText_126ut_547",cL="_listItemTitle_126ut_554",lL="_listItemMeta_126ut_568",dL="_detailChildCard_126ut_573",uL="_detailChildCardTopRow_126ut_585",pL="_taskStatusIcon_126ut_594",ge={drawerBody:XP,paneShell:QP,collapsedPaneShell:eE,collapsedPaneHeader:tE,collapsedPaneLabel:nE,treePane:aE,treePaneSplit:sE,detailPane:rE,paneHeader:oE,paneHeaderLabel:iE,paneContent:cE,sectionTitle:lE,sectionHeaderRow:dE,sectionGroup:uE,treeList:pE,treeChildren:mE,treeRow:fE,treeRowDetailOpen:hE,treeRowDropReady:gE,treeRowDropActive:yE,treeRowDropMode:kE,treeChevron:SE,rowButton:vE,detailsButton:wE,treeRowDragging:bE,rowContent:_E,rowTopRow:CE,referenceBadgeButton:xE,referenceBadgeStatic:AE,rowTitle:TE,rowMeta:IE,detailsButtonActive:NE,unlinkZone:jE,unlinkZoneActive:RE,emptyPanel:DE,emptyPanelTitle:PE,emptyPanelText:EE,sectionNote:LE,detailHero:ME,detailReferenceRow:BE,detailTitle:WE,detailDescription:FE,detailActionRow:zE,metricGrid:OE,metricCard:$E,editorCard:UE,editorField:qE,editorLabel:HE,editorHint:GE,editorSubActions:VE,editorActions:ZE,metricValue:KE,metricLabel:YE,progressTrack:JE,progressFill:XE,listCard:QE,sectionDropReady:eL,sectionDropActive:tL,sectionDropMode:nL,attachReferenceRow:aL,listItem:sL,listItemButton:rL,detailCardButton:oL,listItemText:iL,listItemTitle:cL,listItemMeta:lL,detailChildCard:dL,detailChildCardTopRow:uL,taskStatusIcon:pL},Pl=332,jr=392,gp=56;function yh(e,n,s,r,o){return(e?gp:Pl)+(n?s?gp:jr:0)+(r?o?gp:jr:0)}function yp(e){return e?e.split(/[-_\s]+/g).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" "):"No status"}function su({label:e,entityType:n,interactive:s=!0}){const[r,o]=pt.useState(!1),l=pt.useCallback(async c=>{c.stopPropagation();try{await navigator.clipboard.writeText(e),o(!0),window.setTimeout(()=>o(!1),1200)}catch{o(!1)}},[e]);return s?t.jsx(Zf,{copied:r,label:e,onClick:l,title:`Copy ${n} reference`,ariaLabel:r?`Copied ${n} reference`:`Copy ${n} reference`,className:ge.referenceBadgeButton,children:e}):t.jsx("span",{className:`${u.taskIdBadge} ${ge.referenceBadgeStatic}`.trim(),children:t.jsx("span",{children:e})})}function kp({rowId:e,rowType:n,referenceLabel:s,title:r,meta:o,active:l,detailOpen:c=!1,canExpand:p=!1,expanded:g=!1,onToggleExpand:w,onToggleScope:C,onToggleDetails:_}){const{active:y}=gu(),k=String(y?.data?.current?.type||""),b=n==="workstream"&&k==="task-card",E=n==="initiative"&&k==="planning-workstream",S=n==="workstream"?"planning-workstream-target":"planning-initiative-target",{setNodeRef:W,isOver:Q}=ql({id:`${S}:${e}`,data:n==="workstream"?{type:S,workstreamId:e}:{type:S,initiativeId:e}}),z=n==="workstream",{attributes:K,listeners:V,setNodeRef:ne,transform:D,isDragging:Ae}=Ng({id:`planning-workstream:${e}`,data:{type:"planning-workstream",workstreamId:e},disabled:!z}),U=z&&D?{transform:Lp.Translate.toString(D)}:void 0,ee=b||E;return t.jsxs("div",{ref:W,style:U,className:`${ge.treeRow} ${c?ge.treeRowDetailOpen:""} ${ee?ge.treeRowDropReady:""} ${Q?ge.treeRowDropActive:""} ${Ae?ge.treeRowDragging:""} ${ee?ge.treeRowDropMode:""}`,children:[p?t.jsx("button",{type:"button",className:ge.treeChevron,onClick:w,title:g?"Collapse workstreams":"Expand workstreams",children:g?t.jsx(rf,{size:15}):t.jsx(rg,{size:15})}):t.jsx("span",{className:ge.treeChevron,"aria-hidden":"true",children:t.jsx(Ii,{size:14})}),t.jsxs("div",{className:ge.rowContent,children:[t.jsxs("div",{className:ge.rowTopRow,children:[s?t.jsx(su,{label:s,entityType:n}):t.jsx("span",{"aria-hidden":"true"}),t.jsx("button",{type:"button",className:`${ge.detailsButton} ${l?ge.detailsButtonActive:""}`,onClick:C,title:l?"Clear board scope":"Scope board to this item",children:t.jsx(of,{size:14})})]}),t.jsxs("button",{type:"button",ref:z?ne:void 0,className:ge.rowButton,onClick:_,...z?K:{},...z?V:{},children:[t.jsx("span",{className:ge.rowTitle,children:r}),t.jsx("span",{className:ge.rowMeta,children:o})]})]})]})}function Sp({label:e,onExpand:n}){return t.jsx("div",{className:`${ge.paneShell} ${ge.collapsedPaneShell}`.trim(),children:t.jsxs("div",{className:ge.collapsedPaneHeader,children:[t.jsx("button",{type:"button",className:"tf-control-icon",onClick:n,title:`Expand ${e}`,children:t.jsx(Ii,{size:16})}),t.jsx("span",{className:ge.collapsedPaneLabel,children:e})]})})}function mL({targetType:e,label:n}){const{active:s}=gu(),r=String(s?.data?.current?.type||""),o=e==="task"&&r==="task-card"||e==="workstream"&&r==="planning-workstream",{setNodeRef:l,isOver:c}=ql({id:e==="task"?"planning-task-unlink":"planning-workstream-unlink",data:{type:e==="task"?"planning-task-unlink":"planning-workstream-unlink"}});return o?t.jsx("div",{ref:l,className:`${ge.unlinkZone} ${c?ge.unlinkZoneActive:""}`,children:n}):null}function fL({initiatives:e,standaloneWorkstreams:n,activeInitiativeId:s,activeWorkstreamId:r,expandedInitiativeIds:o,detail:l,secondaryPane:c,onCreateInitiative:p,onCreateWorkstream:g,onToggleInitiative:w,onSelectInitiative:C,onSelectWorkstream:_,onOpenInitiativeDetails:y,onOpenWorkstreamDetails:k}){const{active:b}=gu(),S=String(b?.data?.current?.type||"")==="planning-workstream",{setNodeRef:W,isOver:Q}=ql({id:"planning-workstream-unlink",data:{type:"planning-workstream-unlink"}});return t.jsxs(t.Fragment,{children:[t.jsx(mL,{targetType:"task",label:"Drop here to make task standalone"}),t.jsxs("div",{className:ge.sectionGroup,children:[t.jsxs("div",{className:ge.sectionHeaderRow,children:[t.jsx("div",{className:ge.sectionTitle,children:"Initiatives"}),t.jsx("button",{type:"button",className:"tf-control-icon",title:"Create initiative","aria-label":"Create initiative",onClick:p,children:t.jsx(sr,{size:15})})]}),t.jsx("div",{className:ge.treeList,children:e.length===0?t.jsxs("div",{className:ge.emptyPanel,children:[t.jsx("div",{className:ge.emptyPanelTitle,children:"No initiatives yet"}),t.jsxs("div",{className:ge.emptyPanelText,children:["Initiatives give larger efforts a clear home without crowding the task board. Use the ",t.jsx("code",{children:"+"})," action above to create the first one."]})]}):e.map(z=>{const K=o.has(z.id),V=`${z.workstreamCount||0} workstreams • ${z.taskCount} tasks${z.isArchived?" • archived":""}`;return t.jsxs("div",{children:[t.jsx(kp,{rowId:z.id,rowType:"initiative",referenceLabel:ar(z),title:z.title,meta:V,active:s===z.id&&!r,detailOpen:l?.type==="initiative"&&l.item.id===z.id,canExpand:z.workstreams.length>0,expanded:K,onToggleExpand:()=>w(z.id),onToggleScope:()=>C(z.id),onToggleDetails:()=>{if(l?.type==="initiative"&&l.item.id===z.id){y("");return}y(z.id)}}),K&&z.workstreams.length>0&&t.jsx("div",{className:ge.treeChildren,children:z.workstreams.map(ne=>t.jsx(kp,{rowId:ne.id,rowType:"workstream",referenceLabel:to(ne),title:ne.title,meta:`${ne.taskCount} tasks • ${ne.progressPercent}% complete${ne.isArchived?" • archived":""}`,active:r===ne.id,detailOpen:l?.type==="workstream"&&l.item.id===ne.id||c?.kind==="detail"&&c.detail.item.id===ne.id,onToggleScope:()=>_(ne.id,z.id),onToggleDetails:()=>{if(c?.kind==="detail"&&c.detail.item.id===ne.id){k("");return}if(l?.type==="workstream"&&l.item.id===ne.id){k("");return}k(ne.id)}},ne.id))})]},z.id)})})]}),t.jsxs("div",{ref:W,className:`${ge.sectionGroup} ${S?ge.sectionDropReady:""} ${Q?ge.sectionDropActive:""}`.trim(),children:[t.jsxs("div",{className:ge.sectionHeaderRow,children:[t.jsx("div",{className:ge.sectionTitle,children:"Workstreams"}),t.jsx("button",{type:"button",className:"tf-control-icon",title:"Create workstream","aria-label":"Create workstream",onClick:g,children:t.jsx(sr,{size:15})})]}),t.jsx("div",{className:ge.treeList,children:n.length===0?t.jsxs("div",{className:ge.emptyPanel,children:[t.jsx("div",{className:ge.emptyPanelTitle,children:"No standalone workstreams yet"}),t.jsxs("div",{className:ge.emptyPanelText,children:["Smaller projects can still use workstreams without needing initiative-level structure. Use the ",t.jsx("code",{children:"+"})," action above to add one."]})]}):n.map(z=>t.jsx(kp,{rowId:z.id,rowType:"workstream",referenceLabel:to(z),title:z.title,meta:`${z.taskCount} tasks • ${z.progressPercent}% complete${z.isArchived?" • archived":""}`,active:r===z.id,detailOpen:l?.type==="workstream"&&l.item.id===z.id||c?.kind==="detail"&&c.detail.item.id===z.id,onToggleScope:()=>_(z.id,null),onToggleDetails:()=>{if(l?.type==="workstream"&&l.item.id===z.id){k("");return}k(z.id)}},z.id))})]})]})}function Vm({detail:e,onOpenNestedWorkstreamDetails:n,onEdit:s,onArchive:r,onUnarchive:o,onCreateTaskInWorkstream:l,onCreateWorkstreamInInitiative:c,onOpenTaskById:p,onAttachTaskToWorkstreamByReference:g,onAttachWorkstreamToInitiativeByReference:w}){const[C,_]=pt.useState(""),{active:y}=gu(),k=String(y?.data?.current?.type||""),b=e.type==="workstream"&&k==="task-card",E=e.type==="initiative"&&k==="planning-workstream",S=e.type==="initiative"?"planning-initiative-target":"planning-workstream-target",{setNodeRef:W,isOver:Q}=ql({id:`${S}:detail:${e.item.id}`,data:e.type==="initiative"?{type:S,initiativeId:e.item.id}:{type:S,workstreamId:e.item.id}}),z=e.type==="initiative"?"Workstreams":"Tasks",K=e.type==="initiative"?e.item.workstreams:[],V=e.type==="initiative"?"Initiative":"Workstream",ne=e.type==="initiative"?ar(e.item):to(e.item);return pt.useEffect(()=>{_("")},[e.item.id,e.type]),t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:ge.detailHero,children:[ne?t.jsx("div",{className:ge.detailReferenceRow,children:t.jsx(su,{label:ne,entityType:e.type})}):null,t.jsx("h3",{className:ge.detailTitle,children:e.item.title}),t.jsx("p",{className:ge.detailDescription,children:e.item.description?.trim()||(e.type==="initiative"?"A top-level planning container that groups related workstreams.":"A coordination lane that groups related tasks and keeps execution organized.")}),t.jsx("div",{className:ge.progressTrack,"aria-label":`${e.item.progressPercent}% complete`,children:t.jsx("div",{className:ge.progressFill,style:{width:`${e.item.progressPercent}%`}})}),t.jsxs("div",{className:ge.detailActionRow,children:[t.jsx("button",{type:"button",className:u.secondaryHeaderBtn,onClick:s,children:t.jsxs("span",{children:["Edit ",V]})}),e.item.isArchived?t.jsx("button",{type:"button",className:u.secondaryHeaderBtn,onClick:o,children:t.jsx("span",{children:"Unarchive"})}):t.jsx("button",{type:"button",className:u.secondaryHeaderBtn,onClick:r,children:t.jsx("span",{children:"Archive"})})]})]}),t.jsxs("div",{className:ge.metricGrid,children:[t.jsxs("div",{className:ge.metricCard,children:[t.jsx("span",{className:ge.metricValue,children:e.item.taskCount}),t.jsx("span",{className:ge.metricLabel,children:"Tasks in scope"})]}),t.jsxs("div",{className:ge.metricCard,children:[t.jsx("span",{className:ge.metricValue,children:e.item.completedTaskCount}),t.jsx("span",{className:ge.metricLabel,children:"Done / terminal"})]}),t.jsxs("div",{className:ge.metricCard,children:[t.jsx("span",{className:ge.metricValue,children:e.item.ownerLabel||"Unassigned"}),t.jsx("span",{className:ge.metricLabel,children:"Owner"})]}),t.jsxs("div",{className:ge.metricCard,children:[t.jsx("span",{className:ge.metricValue,children:(e.item.commentCount||0)+(e.item.attachmentCount||0)}),t.jsx("span",{className:ge.metricLabel,children:"Context items"})]})]}),t.jsxs("div",{ref:W,className:`${ge.listCard} ${b||E?ge.sectionDropReady:""} ${Q?ge.sectionDropActive:""} ${b||E?ge.sectionDropMode:""}`.trim(),children:[t.jsxs("div",{className:ge.sectionHeaderRow,children:[t.jsx("div",{className:ge.sectionTitle,children:z}),e.type==="initiative"?t.jsx("button",{type:"button",className:"tf-control-icon",title:"Create workstream in this initiative","aria-label":"Create workstream in this initiative",onClick:()=>c?.(e.item.id),children:t.jsx(sr,{size:15})}):t.jsx("button",{type:"button",className:"tf-control-icon",title:"Create task in this workstream","aria-label":"Create task in this workstream",onClick:()=>l?.(e.item.id),children:t.jsx(sr,{size:15})})]}),t.jsxs("div",{className:ge.attachReferenceRow,children:[t.jsx("input",{type:"text",className:u.input,placeholder:e.type==="initiative"?"Paste workstream reference (e.g. WS-123)":"Paste task reference (e.g. T-123)",value:C,onChange:D=>_(D.target.value)}),t.jsx("button",{type:"button",className:u.secondaryHeaderBtn,onClick:()=>{const D=C.trim();D&&(e.type==="initiative"?w?.(e.item.id,D):g?.(e.item.id,D),_(""))},children:"Attach"})]}),e.type==="initiative"?K.length>0?K.map(D=>t.jsx("button",{type:"button",className:`${ge.listItemButton} ${ge.detailCardButton}`.trim(),onClick:()=>n?.(D.id),children:t.jsxs("div",{className:`${ge.listItem} ${ge.detailChildCard}`.trim(),children:[t.jsx("div",{className:ge.detailChildCardTopRow,children:D.referenceNumber?t.jsx(su,{label:to(D),entityType:"workstream"}):t.jsx("span",{"aria-hidden":"true"})}),t.jsxs("div",{className:ge.listItemText,children:[t.jsx("span",{className:ge.listItemTitle,children:D.title}),t.jsxs("span",{className:ge.listItemMeta,children:[D.taskCount," tasks • ",D.progressPercent,"% complete"]})]})]})},D.id)):t.jsxs("div",{className:ge.emptyPanel,children:[t.jsx("div",{className:ge.emptyPanelTitle,children:"No workstreams yet"}),t.jsx("div",{className:ge.emptyPanelText,children:"Add the first workstream to break the initiative into clearer lanes of execution."})]}):e.item.tasks&&e.item.tasks.length>0?[...e.item.tasks].sort((D,Ae)=>{const U=Ml(D.status).value==="done",ee=Ml(Ae.status).value==="done";return U===ee?0:U?1:-1}).map(D=>{const Ae=D.referenceNumber?`T-${D.referenceNumber}`:"",U=Ml(D.status),ee=Ni[U.icon||"Square"],be=_a(U.color)||"var(--text-secondary)";return t.jsx("button",{type:"button",className:`${ge.listItemButton} ${ge.detailCardButton}`.trim(),onClick:()=>p?.(D.id),children:t.jsxs("div",{className:`${ge.listItem} ${ge.detailChildCard}`.trim(),children:[t.jsxs("div",{className:ge.detailChildCardTopRow,children:[Ae?t.jsx(su,{label:Ae,entityType:"task"}):t.jsx("span",{"aria-hidden":"true"}),t.jsx("span",{className:ge.taskStatusIcon,style:{color:be},"aria-label":U.shortLabel||yp(D.status),title:U.shortLabel||yp(D.status),children:ee?t.jsx(ee,{size:18,strokeWidth:2.4}):null})]}),t.jsxs("div",{className:ge.listItemText,children:[t.jsx("span",{className:ge.listItemTitle,children:D.title}),t.jsx("span",{className:ge.listItemMeta,children:yp(D.status)})]})]})},D.id)}):t.jsxs("div",{className:ge.sectionNote,children:["No tasks are linked to this workstream yet. Use the ",t.jsx("code",{children:"+"})," action above to add the first one."]})]}),t.jsxs("div",{className:ge.listCard,children:[t.jsx("div",{className:ge.sectionTitle,children:"Context"}),t.jsx("div",{className:ge.sectionNote,children:"Comments, attachments, and planning notes can live here without pushing that context down into task cards."})]})]})}function Zm({editor:e,draftTitle:n,draftDescription:s,draftOwner:r,draftInitiativeId:o,assigneeOptions:l,draftInitiativeSummary:c,onChangeDraftTitle:p,onChangeDraftDescription:g,onChangeDraftOwner:w,onChangeDraftInitiativeId:C,onCancel:_,onSubmit:y,onAssignInitiativeToWorkstream:k}){const b=e.entityType==="initiative"?"Initiative":"Workstream",E=e.mode==="create"?`Create ${b}`:`Save ${b}`;return t.jsx(t.Fragment,{children:t.jsxs("div",{className:ge.editorCard,children:[t.jsxs("div",{className:ge.editorField,children:[t.jsx("label",{className:ge.editorLabel,children:"Title"}),t.jsx("input",{className:u.input,value:n,onChange:S=>p(S.target.value),placeholder:e.entityType==="initiative"?"Q3 Product Launch":"Content Production"})]}),t.jsxs("div",{className:ge.editorField,children:[t.jsx("label",{className:ge.editorLabel,children:"Description"}),t.jsx("textarea",{className:u.textarea,value:s,onChange:S=>g(S.target.value),placeholder:e.entityType==="initiative"?"Describe the broader outcome this initiative is meant to achieve.":"Describe the lane of work this workstream will coordinate.",rows:5})]}),e.entityType==="workstream"&&t.jsxs("div",{className:ge.editorField,children:[t.jsx("label",{className:ge.editorLabel,children:"Initiative"}),c&&t.jsxs("div",{className:ge.editorHint,children:["Current: ",c.title]}),t.jsxs("div",{className:u.pathInputGroup,children:[t.jsx("input",{type:"text",className:u.input,placeholder:"Paste initiative reference (e.g. IN-123)",value:o,onChange:S=>C(S.target.value)}),e.mode==="edit"&&t.jsx("button",{type:"button",className:u.secondaryHeaderBtn,onClick:()=>k?.(e.targetId),children:"Set Initiative"})]}),e.mode==="edit"&&t.jsx("div",{className:ge.editorSubActions,children:t.jsx("button",{type:"button",className:u.secondaryHeaderBtn,onClick:()=>k?.(e.targetId,null),children:"Clear Initiative"})})]}),t.jsxs("div",{className:ge.editorField,children:[t.jsx("label",{className:ge.editorLabel,children:"Owner"}),t.jsxs("select",{className:`${u.select} ${u.groupBySelect}`,value:r,onChange:S=>w(S.target.value),children:[t.jsx("option",{value:"",children:"Unassigned"}),l.map(S=>t.jsx("option",{value:S.value,children:S.label},S.value))]})]}),t.jsxs("div",{className:ge.editorActions,children:[t.jsx("button",{type:"button",className:u.secondaryHeaderBtn,onClick:_,children:"Cancel"}),t.jsx("button",{type:"button",className:u.primaryUpdateBtn,onClick:y,children:E})]})]})})}function hL({open:e,leftOffset:n=0,initiatives:s,standaloneWorkstreams:r,activeInitiativeId:o,activeWorkstreamId:l,expandedInitiativeIds:c,detail:p,editor:g,secondaryPane:w,assigneeOptions:C,draftInitiativeSummary:_,draftTitle:y,draftDescription:k,draftOwner:b,draftInitiativeId:E,onChangeDraftTitle:S,onChangeDraftDescription:W,onChangeDraftOwner:Q,onChangeDraftInitiativeId:z,onCollapseTreePane:K,onExpandTreePane:V,onCollapsePrimaryPane:ne,onExpandPrimaryPane:D,onCollapseSecondaryPane:Ae,onExpandSecondaryPane:U,onBackFromSecondary:ee,treeCollapsed:be,primaryCollapsed:me,secondaryCollapsed:Y,onCancelEditor:R,onSubmitEditor:B,onCreateInitiative:fe,onCreateWorkstream:Ne,onToggleInitiative:de,onSelectInitiative:ae,onSelectWorkstream:Ve,onOpenInitiativeDetails:Re,onOpenWorkstreamDetails:Ce,onOpenNestedWorkstreamDetails:Fe,onEditInitiative:x,onEditWorkstream:L,onArchiveInitiative:P,onUnarchiveInitiative:Z,onArchiveWorkstream:M,onUnarchiveWorkstream:h,onCreateTaskInWorkstream:A,onCreateWorkstreamInInitiative:H,onAssignInitiativeToWorkstream:j,onOpenTaskById:je,onAttachTaskToWorkstreamByReference:O,onAttachWorkstreamToInitiativeByReference:ue}){const re=!!(p||g),pe=!!w,G=yh(be,re,me,pe,Y),q=g?g.entityType==="initiative"?g.mode==="create"?"New Initiative":"Edit Initiative":g.mode==="create"?"New Workstream":"Edit Workstream":p?.type==="initiative"?"Initiative":"Workstream",ye=w?.kind==="editor"?w.editor.mode==="create"?"New Workstream":"Edit Workstream":"Workstream";return t.jsx("aside",{style:{position:"absolute",top:0,left:e?`${n}px`:`${n-G-24}px`,bottom:0,width:`${G}px`,minWidth:`${G}px`,borderRight:"1px solid var(--border-color)",background:"var(--bg-secondary)",boxSizing:"border-box",display:"flex",flexDirection:"column",zIndex:35,overflow:"hidden",pointerEvents:e?"auto":"none",transition:"left 220ms cubic-bezier(0.4, 0, 0.2, 1)",willChange:"left"},children:t.jsxs("div",{className:ge.drawerBody,children:[be?t.jsx(Sp,{label:"Planning",onExpand:V}):t.jsxs("div",{className:`${ge.paneShell} ${u.appScrollbar} tf-scrollbar ${ge.treePane} ${re&&!me?ge.treePaneSplit:""}`.trim(),style:{flex:`0 0 ${Pl}px`,width:`${Pl}px`,minWidth:`${Pl}px`,maxWidth:`${Pl}px`},children:[t.jsxs("div",{className:ge.paneHeader,children:[t.jsx("span",{className:ge.paneHeaderLabel,children:"Planning"}),t.jsx("button",{type:"button",className:"tf-control-icon",onClick:K,children:t.jsx(Tc,{size:16})})]}),t.jsx("div",{className:ge.paneContent,children:t.jsx(fL,{initiatives:s,standaloneWorkstreams:r,activeInitiativeId:o,activeWorkstreamId:l,expandedInitiativeIds:c,detail:p,secondaryPane:w,onCreateInitiative:fe,onCreateWorkstream:Ne,onToggleInitiative:de,onSelectInitiative:ae,onSelectWorkstream:Ve,onOpenInitiativeDetails:Re,onOpenWorkstreamDetails:Ce})})]}),re&&(me?t.jsx(Sp,{label:q,onExpand:D}):t.jsxs("div",{className:`${ge.paneShell} ${u.appScrollbar} tf-scrollbar ${ge.detailPane}`.trim(),style:{flex:`0 0 ${jr}px`,width:`${jr}px`,minWidth:`${jr}px`,maxWidth:`${jr}px`},children:[t.jsxs("div",{className:ge.paneHeader,children:[t.jsx("span",{className:ge.paneHeaderLabel,children:q}),t.jsx("button",{type:"button",className:"tf-control-icon",onClick:ne,children:t.jsx(Tc,{size:16})})]}),t.jsx("div",{className:ge.paneContent,children:g?t.jsx(Zm,{editor:g,draftTitle:y,draftDescription:k,draftOwner:b,draftInitiativeId:E,assigneeOptions:C,draftInitiativeSummary:_,onChangeDraftTitle:S,onChangeDraftDescription:W,onChangeDraftOwner:Q,onChangeDraftInitiativeId:z,onCancel:R,onSubmit:B,onAssignInitiativeToWorkstream:j}):p?t.jsx(Vm,{detail:p,onOpenNestedWorkstreamDetails:p.type==="initiative"?Fe:void 0,onCreateTaskInWorkstream:p.type==="workstream"?A:void 0,onCreateWorkstreamInInitiative:p.type==="initiative"?H:void 0,onOpenTaskById:p.type==="workstream"?je:void 0,onAttachTaskToWorkstreamByReference:p.type==="workstream"?O:void 0,onAttachWorkstreamToInitiativeByReference:p.type==="initiative"?ue:void 0,onEdit:()=>p.type==="initiative"?x(p.item.id):L(p.item.id),onArchive:()=>p.type==="initiative"?P(p.item.id):M(p.item.id),onUnarchive:()=>p.type==="initiative"?Z(p.item.id):h(p.item.id)}):null})]})),pe&&(Y?t.jsx(Sp,{label:ye,onExpand:U}):t.jsxs("div",{className:`${ge.paneShell} ${u.appScrollbar} tf-scrollbar ${ge.detailPane}`.trim(),style:{flex:`0 0 ${jr}px`,width:`${jr}px`,minWidth:`${jr}px`,maxWidth:`${jr}px`},children:[t.jsxs("div",{className:ge.paneHeader,children:[t.jsx("span",{className:ge.paneHeaderLabel,children:ye}),t.jsx("button",{type:"button",className:"tf-control-icon",onClick:Ae,children:t.jsx(Tc,{size:16})})]}),t.jsx("div",{className:ge.paneContent,children:w?.kind==="editor"?t.jsx(Zm,{editor:w.editor,draftTitle:y,draftDescription:k,draftOwner:b,draftInitiativeId:E,assigneeOptions:C,draftInitiativeSummary:_,onChangeDraftTitle:S,onChangeDraftDescription:W,onChangeDraftOwner:Q,onChangeDraftInitiativeId:z,onCancel:ee,onSubmit:B,onAssignInitiativeToWorkstream:j}):w?t.jsx(Vm,{detail:w.detail,onCreateTaskInWorkstream:A,onOpenTaskById:je,onAttachTaskToWorkstreamByReference:O,onEdit:()=>L(w.detail.item.id),onArchive:()=>M(w.detail.item.id),onUnarchive:()=>h(w.detail.item.id)}):null})]}))]})})}const gL={"annotated_attachments.workspace_access":{enabled:!0,description:"Annotated Attachment workspace readiness gate.",owner:"taskforce",removalMilestone:"Annotated Attachment GA"},"documents.workspace_access":{enabled:!0,description:"Document Manager/editor workspace readiness gate.",owner:"taskforce",removalMilestone:"Document Manager GA"},"workflows.workspace_access":{enabled:!0,description:"Workflow workspace readiness gate.",owner:"taskforce",removalMilestone:"Workflow workspace GA"},"agents.workspace_access":{enabled:!0,description:"Agents workspace readiness gate.",owner:"taskforce",removalMilestone:"Agents workspace GA"},"initiatives.workspace_access":{enabled:!0,description:"Initiatives workspace readiness gate.",owner:"taskforce",removalMilestone:"Initiatives workspace GA"}},Bl="annotated_attachments.workspace_access",Wl="documents.workspace_access",fu="workflows.workspace_access",hu="agents.workspace_access",Km="initiatives.workspace_access",yL=Object.entries(gL).reduce((e,[n,s])=>(e[n]={key:n,enabled:!!s.enabled,description:String(s.description||""),owner:String(s.owner||""),removalMilestone:String(s.removalMilestone||"")},e),{});function kL(e){const n=String(e||"").trim();return n&&yL[n]||null}function SL(e){const n=kL(e);return n?n.enabled?{featureKey:e,allowed:!0,source:"app_gate",code:"OK"}:{featureKey:e,allowed:!1,source:"app_gate",code:"APP_GATE_DISABLED"}:{featureKey:e,allowed:!0,source:"none",code:"OK"}}function jl(e){return SL(e.featureKey)}const vL=["tasks","docs","annotate","workflows","agents"];function wL(e){const n=e?.featureAccess||{},s={tasks:{id:"tasks",label:"Tasks",featureKey:null,enabled:!0,fallbackModuleId:"tasks"},docs:{id:"docs",label:"Documents",featureKey:Wl,enabled:n[Wl]?.allowed??!0,fallbackModuleId:"tasks"},annotate:{id:"annotate",label:"Image Notes",featureKey:Bl,enabled:n[Bl]?.allowed??!1,fallbackModuleId:"tasks"},workflows:{id:"workflows",label:"Workflows",featureKey:fu,enabled:n[fu]?.allowed??!1,fallbackModuleId:"tasks"},agents:{id:"agents",label:"Agents",featureKey:hu,enabled:n[hu]?.allowed??!1,fallbackModuleId:"tasks"}};return vL.map(r=>s[r])}function bL(e){switch(e){case"docs":return{mode:e,moduleId:"docs",layoutVariant:"docs-minimal",headerSections:[],filterBar:{kind:"document-filters"},primaryAction:null};case"annotate":return{mode:e,moduleId:"annotate",layoutVariant:"annotated-module",headerSections:[],filterBar:{kind:"empty"},primaryAction:null};case"workflows":return{mode:e,moduleId:"workflows",layoutVariant:"workflows-module",headerSections:[],filterBar:{kind:"empty"},primaryAction:null};case"agents":return{mode:e,moduleId:"agents",layoutVariant:"agents-module",headerSections:[],filterBar:{kind:"empty"},primaryAction:null};default:return{mode:"tasks",moduleId:"tasks",layoutVariant:"tasks-default",headerSections:["search","sort","divider-primary","grouping","divider-secondary","task-display-actions"],filterBar:{kind:"task-filters"},primaryAction:"add-task"}}}function Ym(e,n){const s=n.find(r=>r.id===e);return s?s.enabled?s.id:s.fallbackModuleId:"tasks"}const _L="_weekLabel_vet2o_1",CL="_sectionTitle_vet2o_6",xL="_calendarHeader_vet2o_11",AL="_monthLabel_vet2o_18",TL="_weekdayGrid_vet2o_23",IL="_weekdayLabel_vet2o_30",NL="_calendarGrid_vet2o_36",jL="_calendarDay_vet2o_42",RL="_calendarDayDot_vet2o_55",DL="_jumpRow_vet2o_67",PL="_displaySection_vet2o_73",EL="_toggleLabel_vet2o_79",LL="_expiredSummary_vet2o_87",ML="_actionButton_vet2o_95",Aa={weekLabel:_L,sectionTitle:CL,calendarHeader:xL,monthLabel:AL,weekdayGrid:TL,weekdayLabel:IL,calendarGrid:NL,calendarDay:jL,calendarDayDot:RL,jumpRow:DL,displaySection:PL,toggleLabel:EL,expiredSummary:LL,actionButton:ML},Jm=["mon","tue","wed","thu","fri","sat","sun"],BL={mon:"Mon",tue:"Tue",wed:"Wed",thu:"Thu",fri:"Fri",sat:"Sat",sun:"Sun"};function xc(e){const n=e.getFullYear(),s=String(e.getMonth()+1).padStart(2,"0"),r=String(e.getDate()).padStart(2,"0");return`${n}-${s}-${r}`}function El(e){const n=e.match(/^(\d{4})-(\d{2})-(\d{2})$/);if(!n)return null;const s=new Date(Number(n[1]),Number(n[2])-1,Number(n[3]));return Number.isNaN(s.getTime())?null:s}function Pp(e,n){const s=e.getDay(),r=n==="sunday"?-s:s===0?-6:1-s,o=new Date(e);return o.setHours(0,0,0,0),o.setDate(o.getDate()+r),o}function WL(e,n){return n==="sunday"?{sun:0,mon:1,tue:2,wed:3,thu:4,fri:5,sat:6}[e]:{mon:0,tue:1,wed:2,thu:3,fri:4,sat:5,sun:6}[e]}function kh(e,n){const s=new Date(e);return s.setDate(e.getDate()+n),s}function FL(e){const n=e.match(/^(\d{4})-(\d{2})-(\d{2})$/);if(!n)return null;const s=new Date(Date.UTC(Number(n[1]),Number(n[2])-1,Number(n[3]))),r=s.getUTCDay()||7;s.setUTCDate(s.getUTCDate()+4-r);const o=new Date(Date.UTC(s.getUTCFullYear(),0,1)),l=Math.ceil(((s.getTime()-o.getTime())/864e5+1)/7);return`${s.getUTCFullYear()}-W${String(l).padStart(2,"0")}`}const Ep=320;function zL({open:e,onClose:n,scheduleSelectedDate:s,setScheduleSelectedDate:r,scheduleCalendarMonth:o,setScheduleCalendarMonth:l,scheduleShowWeekends:c,setScheduleShowWeekends:p,scheduleShowBacklog:g,setScheduleShowBacklog:w,scheduleOnlyExpired:C,setScheduleOnlyExpired:_,expiredScheduledCount:y,overdueDueCount:k,expiredLeafCandidates:b,expiredRecoveryCandidates:E,onMoveExpiredToSelectedWeek:S,onMoveExpiredToBacklog:W,scheduleBulkBusy:Q,globalWeekStartsOn:z,resolvedLocale:K,todayDateOnly:V,scheduleBaseTasks:ne,scheduleWeekStart:D,scheduleWeekLabel:Ae}){const U=pt.useMemo(()=>{const[R,B]=o.split("-"),fe=Number(R),Ne=Number(B);if(!Number.isInteger(fe)||!Number.isInteger(Ne)||Ne<1||Ne>12){const de=El(s)||new Date;return new Date(de.getFullYear(),de.getMonth(),1)}return new Date(fe,Ne-1,1)},[o,s]),ee=pt.useMemo(()=>Nc(U,{month:"long",year:"numeric"},K),[U,K]),be=pt.useMemo(()=>{const R=Pp(U,z);return Array.from({length:42},(B,fe)=>kh(R,fe))},[U,z]),me=pt.useMemo(()=>{const R=new Map;for(const B of ne){const fe=B.scheduledDate||"";if(!fe)continue;const de=!(B.status==="done"||B.status==="cancelled")&&fe<V,ae=R.get(fe);ae?(ae.count+=1,de&&(ae.hasExpired=!0)):R.set(fe,{count:1,hasExpired:de})}return R},[ne,V]),Y=pt.useMemo(()=>z==="sunday"?["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]:["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],[z]);return t.jsxs("aside",{className:`${u.appScrollbar} tf-scrollbar tf-sidebar-shell`,style:{transform:e?"translateX(0)":"translateX(108%)",pointerEvents:e?"auto":"none",transition:"transform 220ms cubic-bezier(0.4, 0, 0.2, 1)",willChange:"transform",width:`${Ep}px`,minWidth:`${Ep}px`},children:[t.jsxs("div",{className:"tf-sidebar-header",children:[t.jsxs("div",{className:"tf-sidebar-title",children:[t.jsx(og,{size:16}),t.jsx("span",{children:"Schedule Controls"})]}),t.jsx("button",{type:"button",className:"tf-control-icon",onClick:n,title:"Hide Schedule Sidebar",children:t.jsx(Ii,{size:16})})]}),t.jsxs("div",{className:Aa.weekLabel,children:["Week of ",Ae]}),t.jsxs("div",{className:"tf-sidebar-section tf-surface-panel",children:[t.jsxs("div",{className:Aa.calendarHeader,children:[t.jsx("button",{className:"tf-control-icon",onClick:()=>{const R=new Date(U);R.setMonth(U.getMonth()-1),l(`${R.getFullYear()}-${String(R.getMonth()+1).padStart(2,"0")}`)},title:"Previous month",children:t.jsx(Tc,{size:14})}),t.jsx("div",{className:Aa.monthLabel,children:ee}),t.jsx("button",{className:"tf-control-icon",onClick:()=>{const R=new Date(U);R.setMonth(U.getMonth()+1),l(`${R.getFullYear()}-${String(R.getMonth()+1).padStart(2,"0")}`)},title:"Next month",children:t.jsx(Ii,{size:14})})]}),t.jsx("div",{className:Aa.weekdayGrid,children:Y.map(R=>t.jsx("div",{className:Aa.weekdayLabel,children:R},R))}),t.jsx("div",{className:Aa.calendarGrid,children:be.map(R=>{const B=xc(R),fe=R.getMonth()!==U.getMonth(),Ne=Pp(R,z),de=xc(Ne)===xc(D),ae=B===s,Ve=B===V,Re=B<V,Ce=me.get(B),Fe=!!Ce,x=!!Ce?.hasExpired;return t.jsxs("button",{onClick:()=>{r(B),l(`${R.getFullYear()}-${String(R.getMonth()+1).padStart(2,"0")}`)},className:Aa.calendarDay,style:{"--calendar-day-border":ae?"1px solid #2563eb":Ve?"1px solid rgba(245, 158, 11, 0.95)":"1px solid transparent","--calendar-day-background":ae?"rgba(59,130,246,0.22)":Ve?"rgba(245,158,11,0.16)":de?"rgba(59,130,246,0.18)":"transparent","--calendar-day-color":fe?"var(--text-helper)":"var(--text-primary)","--calendar-day-font-weight":ae||Ve?700:500,"--calendar-day-opacity":Re?.42:1},title:`${Ve?`${B} (Today)`:B}`+(Fe?` • ${Ce?.count} scheduled`:"")+(x?" • includes expired":""),children:[R.getDate(),Fe&&t.jsx("span",{className:Aa.calendarDayDot,style:{"--calendar-dot-background":x?"#ef4444":"#3b82f6","--calendar-dot-opacity":fe?.6:.95}})]},B)})}),t.jsx("div",{className:Aa.jumpRow,children:t.jsx("button",{className:"tf-control-icon",onClick:()=>{const R=new Date;r(xc(R)),l(`${R.getFullYear()}-${String(R.getMonth()+1).padStart(2,"0")}`)},title:"Jump to current week",children:"Today"})})]}),t.jsxs("div",{className:`tf-sidebar-section tf-surface-panel ${Aa.displaySection}`,children:[t.jsx("div",{className:Aa.sectionTitle,children:"Display"}),t.jsxs("label",{className:Aa.toggleLabel,children:[t.jsx("input",{type:"checkbox",checked:c,onChange:R=>p(R.target.checked)}),"Show weekends"]}),t.jsxs("label",{className:Aa.toggleLabel,children:[t.jsx("input",{type:"checkbox",checked:g,onChange:R=>w(R.target.checked)}),"Show backlog"]}),t.jsxs("label",{className:Aa.toggleLabel,children:[t.jsx("input",{type:"checkbox",checked:C,onChange:R=>_(R.target.checked)}),"Only expired/overdue"]})]}),y>0&&t.jsxs("div",{className:"tf-sidebar-section tf-surface-panel",children:[t.jsx("div",{className:Aa.sectionTitle,children:"Expired Tasks"}),t.jsxs("div",{className:Aa.expiredSummary,children:[t.jsxs("span",{children:[y," expired"]}),t.jsxs("span",{children:[k," overdue"]})]}),t.jsx("button",{className:`tf-control-icon ${Aa.actionButton}`,onClick:S,disabled:Q||b.length===0,title:"Move expired leaf tasks to the selected week while keeping weekday alignment",children:Q?"Working...":"Schedule to selected week"}),t.jsx("button",{className:`tf-control-icon ${Aa.actionButton}`,onClick:W,disabled:Q||E.length===0,title:"Unschedule expired/overdue tasks back to backlog",children:Q?"Working...":"Unschedule to backlog"})]})]})}function Sh(e,n){return e&&(n==="owner"||n==="admin")}function OL(e,n,s){return Sh(e,n)&&s==="team"}const $L=pt.lazy(()=>Bo(()=>import("./TaskSettings-Bqd4cCzW.js"),__vite__mapDeps([0,1,2,3,4,5,6])).then(e=>({default:e.TaskSettings}))),UL=pt.lazy(()=>Bo(()=>import("./AnnotatedAttachmentWorkspace-Dvi02Y7q.js"),__vite__mapDeps([7,1,2,3,4,5,8])).then(e=>({default:e.AnnotatedAttachmentWorkspaceShell}))),qL=pt.lazy(()=>Bo(()=>import("./DocumentWorkspace-iys3zfca.js"),__vite__mapDeps([9,1,2,3,4,5,10])).then(e=>({default:e.DocumentWorkspaceShell}))),HL=pt.lazy(()=>Bo(()=>import("./WorkflowsModule-BguHeQaV.js"),__vite__mapDeps([11,1,2,3,4,5])).then(e=>({default:e.WorkflowsModule}))),GL=pt.lazy(()=>Bo(()=>import("./AgentsModule-JG5jc3he.js"),__vite__mapDeps([12,1,2,3,4,5])).then(e=>({default:e.AgentsModule})));pt.lazy(()=>Bo(()=>import("./InitiativesModule-DJvLJI3A.js"),__vite__mapDeps([13,1,2,3,4,5])).then(e=>({default:e.InitiativesModule})));const VL=pt.lazy(()=>Bo(()=>import("./PlansPage-BMPlpFpw.js"),__vite__mapDeps([14,1,2,5,3,4,15])).then(e=>({default:e.PlansPage}))),ZL="image/png,image/jpeg,image/webp,image/gif",KL=5*1024*1024;function Pc(e,n=0){const s=String(e.id??"").trim();return s?`id:${s}`:[String(e.occurredAt||"").trim()||"unknown-time",String(e.eventType||"").trim()||"sync",String(e.status||"").trim()||"unknown-status",String(e.statusCode??""),String(e.changeCount??""),String(e.requestMs??""),String(e.errorMessage||"").trim(),JSON.stringify(e.details||null),String(n)].join("|")}function YL(e,n,s=15){const r=new Map;for(const[o,l]of e.entries())r.set(Pc(l,o),l);for(const[o,l]of n.entries())r.set(Pc(l,o),l);return Array.from(r.values()).sort((o,l)=>String(l.occurredAt||"").localeCompare(String(o.occurredAt||""))).slice(0,Math.max(1,s))}function JL(e,n){if(e.length!==n.length)return!1;for(let s=0;s<e.length;s+=1)if(Pc(e[s],s)!==Pc(n[s],s))return!1;return!0}function XL(e){let n=0;for(const s of e){if(String(s.errorMessage||"").toLowerCase().includes("reference number mismatch")){n+=1;continue}if(String(s.status||"").toLowerCase()==="success")break}return n}function QL(e){const n=[];for(const s of e){if(String(s.errorMessage||"").toLowerCase().includes("reference number mismatch")){n.push(s);continue}if(String(s.status||"").toLowerCase()==="success")break}return n}function eM(e,n){const s=ku(e);if(s)return ym(s).label.toUpperCase();for(const r of n){const o=String(r||"").trim();if(!o)continue;const l=zp(o);if(l)return ym(l).label.toUpperCase();let c=o.toLowerCase();try{c=new URL(o.includes("://")?o:`https://${o}`).hostname.toLowerCase()}catch{c=o.toLowerCase()}if(!(c.includes("localhost")||c.includes("127.0.0.1")||c.includes("::1")))return c.toUpperCase()}return"UNKNOWN"}function Qr(){return typeof performance<"u"?performance.now():Date.now()}function tM(e){const r=ff(),o=hf(),l=a.useMemo(()=>new URLSearchParams(o.search),[o.search]),c=String(l.get("screen")||"").trim().toLowerCase()==="plans",p=a.useCallback(i=>{const f=new URLSearchParams(o.search);f.set("screen","plans");for(const[v,ie]of Object.entries(i||{}))ie==null||String(ie).trim()===""?f.delete(v):f.set(v,String(ie));r(`/?${f.toString()}${o.hash||""}`)},[o.hash,o.search,r]),g=a.useCallback(()=>{const i=new URLSearchParams(o.search);i.delete("screen"),i.delete("gate"),i.delete("checkout"),i.delete("planId"),i.delete("planVersionId"),i.delete("interval");const f=i.toString();r(`${o.pathname==="/"?"/":o.pathname}${f?`?${f}`:""}${o.hash||""}`)},[o.hash,o.pathname,o.search,r]),w=a.useCallback(()=>{g()},[g]),{activeTab:C,setActiveTab:_,activeCategories:y,groupBy:k,setGroupBy:b,activeWorkspaceModule:E,setActiveWorkspaceModule:S,emptyColumnMode:W,setEmptyColumnMode:Q,zenMode:z,setZenMode:K,filterStatus:V,setFilterStatus:ne,tasks:D,handleEdit:Ae,handleSubmit:U,resetForm:ee,handleUpdateTask:be,editingTaskId:me,loading:Y,error:R,title:B,setTitle:fe,description:Ne,setDescription:de,checklistItems:ae,setChecklistItems:Ve,category:Re,setCategory:Ce,type:Fe,setType:x,priority:L,setPriority:P,complexity:Z,setComplexity:M,setStatus:h,approach:A,setApproach:H,assignee:j,setAssignee:je,scheduledDate:O,setScheduledDate:ue,dueDate:re,setDueDate:pe,workstreamInput:G,setWorkstreamInput:q,manualComplexityEnabled:ye,checklistDropdownEnabled:Be,showTaskCardStatusLabel:le,formTaxonomies:ze,setFormTaxonomies:Ye,comments:Xe,newCommentText:bt,setNewCommentText:d,attachments:rt,setAttachments:mt,setAttachmentsDirty:F,descriptionFocused:Ke,setDescriptionFocused:St,showMarkdownHelp:Lt,setShowMarkdownHelp:xt,showChecklist:Zt,setShowChecklist:Jt,showComments:on,setShowComments:cn,handleAddComment:nn,handleSetWorkstreamForCurrentTask:gn,handleOpenTaskById:yn,taxonomies:an,activeTypes:kn,priorities:Xt,taxonomyDisplayLabels:Gn,approaches:At,copiedId:Se,handleCopyId:Mt,handleToggleInProgress:Qt,handleToggleComplete:zt,handleToggleReview:Ge,handleToggleCancel:An,handleArchiveTask:J,handleDelete:_e,handleUnarchive:we,handleRestoreDeletedTask:Ie,handlePermanentlyDeleteDeletedTask:We,handleEmptyDeletedTasks:Qe,fetchTasks:ot,searchQuery:et,setSearchQuery:_t,filterCategories:vt,setFilterCategories:Ot,filterTypes:it,setFilterTypes:It,filterPriorities:wt,setFilterPriorities:_n,filterAssignees:Dn,setFilterAssignees:Jn,assigneeOptions:ht,taskScope:gt,setTaskScope:Xn,sortBy:se,setSortBy:He,clearFilters:Ee,settingsModel:De,configLoaded:Me,currentTheme:tt,setCurrentTheme:Nn,pathSaved:Et,saveSettings:ya,keyShortcut:Pn,setKeyShortcut:Cn,globalWeekStartsOn:Sn,locale:ln,jsonBackupEnabled:Kt,setJsonBackupEnabled:yt,mcpHostRoot:qt,setMcpHostRoot:Ht,settingsSection:sn,setSettingsSection:ft,runtimeMode:Ze,workspaceSwitchingEnabled:Vn,cloudAuthConfigured:pn,authRequiredForApi:$t,authBlocked:Wt,isAuthenticated:Rt,authUserId:fs,authWorkspaceId:Ds,authUserEmail:aa,authUserDisplayName:fn,authUserAvatarUrl:sa,authSessionResolved:On,realtimeSyncEnabled:$n,realtimeSyncFlagSource:Ka,workspaceCloudSyncEnabled:Wn,workspaceSyncPhase:rn,workspaceSyncStatus:ra,workspaceSyncSummary:Yt,workspaceSyncRecommendedAction:Fn,workspaceSyncBusy:jn,workspaceSyncPendingChanges:xn,saveWorkspaceCloudSyncSettings:fa,pushNotice:nt,userGlobalSyncStatus:vn,workspaceLastSuccessfulSyncAt:dn,workspaceLastPullAt:za,workspaceLastPushAt:oa,workspaceLastErrorAt:Ya,userGlobalSyncError:Qn,workspaceLastErrorMessage:Ta,retryWorkspaceCloudSync:ka,resetWorkspaceSyncCursorAndPull:Zn,getWorkspaceSyncDiagnostics:hs,currentWorkspaceId:en,currentWorkspaceRole:Ia,availableWorkspaces:ha,switchWorkspace:Ca,updateCurrentUserProfile:Na,logout:Us,projectRoot:io,projectName:Oa,mcpScriptPath:oe,serverHostRoot:lt,showFolderBrowser:Ft,setShowFolderBrowser:Tt,folders:Tn,files:dt,currentBrowsePath:wn,fetchFolders:ia,browserTarget:ga,setBrowserTarget:ja,handleSelectPath:Kn,handleAddPath:ea,handleRemovePath:rr,handleUpdateCategory:Ra,handleRemoveCategory:pa,handleSaveCategory:ca,handleUpdateCategoryIcon:Da,handleUpdateCategoryColor:Sa,handleSaveType:rs,handleRemoveType:co,handleUpdateTaxonomies:Ri,handleUpdatePriorities:qs,pathValidation:or,exportEnvironment:la,setExportEnvironment:da,exportWorkflowsPath:Ps,setExportWorkflowsPath:lo,exportResult:ir,exportingResource:qe,availableWorkflows:Gt,onExportWorkflows:Pa,fetchWorkflows:va,availableEnvironments:gs,initiativeTemplates:Pr,fetchInitiativeTemplates:Wo,createInitiativeFromTemplate:I,uiNotice:ke,clearNotice:$e,taskReturnTrail:Te,clearReturnToParentTask:X,returnToPreviousTask:Pe,tasksScrollRef:Dt,setTasksScrollPos:Nt,commentsEndRef:Ja,autoSaveState:qn,unsavedModalOpen:En,setUnsavedModalOpen:os,pendingNavigation:Es,handleNavigation:uo,currentTask:Ls,currentTaskWorkstream:Vl,currentTaskInitiative:Di,scheduleWarningPrompt:Fo,confirmScheduleWarning:cr,cancelScheduleWarning:vu}=e,ta=ln||Af();a.useEffect(()=>{const i=String(Oa||"").trim();document.title=i?`Taskforce - ${i}`:"Taskforce"},[Oa]);const Er=()=>{os(!1),Es?(C==="add"&&ee(),Es()):(C==="add"&&ee(),_("tasks"))},is=async()=>{await U({preventDefault:()=>{}}),os(!1),Es&&Es()},[ys,Lc]=a.useState(!1),[ks,zo]=a.useState(!1),[lr,Pi]=a.useState(!0),[Hs,Zl]=a.useState(!1),[Gs,Ss]=a.useState(!0),[Lr,Mc]=a.useState(xc(new Date)),[Bc,Mr]=a.useState(()=>{const i=new Date;return`${i.getFullYear()}-${String(i.getMonth()+1).padStart(2,"0")}`}),[Oo,Xa]=a.useState(0),[dr,$o]=a.useState(!1),[Uo,Ei]=a.useState(!1),[Yn,$a]=a.useState(!1),[cs,ur]=a.useState(!1),[Br,Wr]=a.useState(!1),[Vs,vs]=a.useState(!1),[Rn,pr]=a.useState(""),[un,Fr]=a.useState(""),[Ms,ls]=a.useState(new Set),[mr,Bs]=a.useState(null),[po,Un]=a.useState(null),[zr,fr]=a.useState(null),[hr,Zs]=a.useState(null),[Ws,Qa]=a.useState(""),[qo,gr]=a.useState(""),[Li,yr]=a.useState(""),[Fs,ws]=a.useState(""),[Ua,bn]=a.useState(()=>nu.map(i=>i.value)),[In,es]=a.useState(()=>au.map(i=>i.value)),[Mi,Or]=a.useState(null),[na,Wc]=a.useState(null),[wa,$r]=a.useState(null),[Ks,Ho]=a.useState(null),[wu,Kl]=a.useState(0),[mo,bu]=a.useState({}),[Go,Yl]=a.useState(!1),Jl=a.useRef(""),Fc=a.useRef(null),Xl=a.useRef(null),zc=a.useRef(new Set),fo=a.useMemo(()=>{const i={},f=String(en||"").trim();return Ze==="cloud"&&f&&f!=="default"&&(i["x-taskforce-workspace-id"]=f),i},[Ze,en]),Vo=a.useMemo(()=>`${Ze}:${String(en||"default").trim()||"default"}`,[Ze,en]),Bi=a.useMemo(()=>`taskforce:annotate-layout:${Vo}`,[Vo]),ho=a.useMemo(()=>Ze==="cloud"?On:Me,[On,Me,Ze]);a.useEffect(()=>{Fc.current=wa},[wa]),a.useEffect(()=>{Xl.current=Ks},[Ks]);const Wi=a.useMemo(()=>({[Wl]:jl({featureKey:Wl}),[Bl]:jl({featureKey:Bl}),[fu]:jl({featureKey:fu}),[hu]:jl({featureKey:hu}),[Km]:jl({featureKey:Km})}),[Ze]),ds=a.useMemo(()=>wL({featureAccess:Wi}),[Wi]),ma=a.useMemo(()=>Ym(E,ds),[E,ds]),Zo=Wi[Wl]?.allowed??!1,Oc=Wi[Bl]?.allowed??!1,Ql="Documents is not available in this build yet.",Fi="Annotate is not available in this build yet.";a.useEffect(()=>{const i=f=>{const v=f,ie=v.detail?.fsPath,ce=String(v.detail?.assetId||"").trim()||null;if(!(!ie&&!ce)){if(v.preventDefault(),!Zo){nt(Ql,"error");return}Or(ie||null),Wc(ce),S("docs")}};return window.addEventListener("taskforce:open-markdown-document",i),()=>{window.removeEventListener("taskforce:open-markdown-document",i)}},[Zo,Ql,nt,S]),a.useEffect(()=>{ma!==E&&S(ma)},[E,ma,S]),a.useEffect(()=>{ma==="docs"&&Zo||(Or(null),Wc(null))},[Zo,ma]),a.useEffect(()=>{if(!(typeof window>"u"))try{const i=window.sessionStorage.getItem(Bi);if(!i)return;const f=JSON.parse(i);f?.annotatedTarget&&typeof f.annotatedTarget=="object"&&$r(f.annotatedTarget),typeof f?.annotatedSessionId=="string"&&Ho(f.annotatedSessionId.trim()||null)}catch{}},[Bi]),a.useEffect(()=>{if(Jl.current===Vo)return;Jl.current=Vo,Yl(!1);let i=!1;return(async()=>{try{const v=await fetch("/api/taskforce/ui-state?key=layout",{method:"GET",credentials:"include",headers:fo});if(!v.ok)return;const ie=await v.json().catch(()=>({})),ce=ie?.state&&typeof ie.state=="object"?ie.state:null;if(!ce||i)return;if(typeof ce.scheduleShowWeekends=="boolean"&&zo(ce.scheduleShowWeekends),typeof ce.scheduleShowBacklog=="boolean"&&Pi(ce.scheduleShowBacklog),typeof ce.scheduleOnlyExpired=="boolean"&&Zl(ce.scheduleOnlyExpired),typeof ce.scheduleSidebarOpen=="boolean"&&Ss(ce.scheduleSidebarOpen),typeof ce.scheduleSelectedDate=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(ce.scheduleSelectedDate)&&Mc(ce.scheduleSelectedDate),typeof ce.scheduleCalendarMonth=="string"&&/^\d{4}-\d{2}$/.test(ce.scheduleCalendarMonth)&&Mr(ce.scheduleCalendarMonth),typeof ce.scheduleScrollLeft=="number"&&Number.isFinite(ce.scheduleScrollLeft)&&ce.scheduleScrollLeft>=0&&Xa(ce.scheduleScrollLeft),typeof ce.showFilters=="boolean"&&$o(ce.showFilters),Array.isArray(ce.documentTypeFilters)&&bn(ce.documentTypeFilters),Array.isArray(ce.documentAttachmentFilters)&&es(ce.documentAttachmentFilters),typeof ce.planningDrawerOpen=="boolean"&&$a(ce.planningDrawerOpen),typeof ce.planningTreeCollapsed=="boolean"&&ur(ce.planningTreeCollapsed),typeof ce.planningPrimaryCollapsed=="boolean"&&Wr(ce.planningPrimaryCollapsed),typeof ce.planningSecondaryCollapsed=="boolean"&&vs(ce.planningSecondaryCollapsed),Array.isArray(ce.planningExpandedInitiativeIds)&&ls(new Set(ce.planningExpandedInitiativeIds.map(Ct=>String(Ct||"").trim()).filter(Boolean))),ce.planningDrawerDetail&&typeof ce.planningDrawerDetail=="object"&&(ce.planningDrawerDetail.type==="initiative"||ce.planningDrawerDetail.type==="workstream")&&typeof ce.planningDrawerDetail.id=="string"){const Ct=ce.planningDrawerDetail.id.trim();Bs(Ct?{type:ce.planningDrawerDetail.type,id:Ct}:null)}else ce.planningDrawerDetail===null&&Bs(null);typeof ce.planningNestedWorkstreamDetailId=="string"?Un(ce.planningNestedWorkstreamDetailId.trim()||null):ce.planningNestedWorkstreamDetailId===null&&Un(null);const Je=ce.annotatedTarget;Je&&typeof Je=="object"&&(Fc.current||$r(Je)),typeof ce.annotatedSessionId=="string"&&(Xl.current||Ho(ce.annotatedSessionId.trim()||null))}catch{}finally{i||Yl(!0)}})(),()=>{i=!0}},[Vo,fo]),a.useEffect(()=>{if(!Go)return;const i=window.setTimeout(async()=>{try{await fetch("/api/taskforce/ui-state",{method:"POST",headers:{"Content-Type":"application/json",...fo},credentials:"include",body:JSON.stringify({stateKey:"layout",patch:{scheduleShowWeekends:ks,scheduleShowBacklog:lr,scheduleOnlyExpired:Hs,scheduleSidebarOpen:Gs,scheduleSelectedDate:Lr,scheduleCalendarMonth:Bc,scheduleScrollLeft:Oo,showFilters:dr,documentTypeFilters:Ua,documentAttachmentFilters:In,planningDrawerOpen:Yn,planningTreeCollapsed:cs,planningPrimaryCollapsed:Br,planningSecondaryCollapsed:Vs,planningExpandedInitiativeIds:Array.from(Ms),planningDrawerDetail:mr,planningNestedWorkstreamDetailId:po,annotatedTarget:wa,annotatedSessionId:Ks}})})}catch{}},250);return()=>window.clearTimeout(i)},[Go,ks,lr,Hs,Gs,Lr,Bc,Oo,dr,Ua,In,Yn,cs,Br,Vs,Ms,mr,po,wa,Ks,fo]),a.useEffect(()=>{if(!(typeof window>"u"))try{window.sessionStorage.setItem(Bi,JSON.stringify({annotatedTarget:wa,annotatedSessionId:Ks}))}catch{}},[Bi,Ks,wa]),a.useEffect(()=>{k==="schedule"&&Ss(!0)},[k]);const{showArchive:kr,setShowArchive:zi,fetchArchive:Oi,filteredArchive:go}=e,Ys=a.useMemo(()=>go.map(i=>({...i,isArchived:!0})),[go]),ba=a.useMemo(()=>e.archivedTasks.map(i=>({...i,isArchived:!0})),[e.archivedTasks]),zs=a.useMemo(()=>[...e.searchAgnosticTasks,...ba],[ba,e.searchAgnosticTasks]),ed=a.useCallback(i=>{const f=String(i||"").trim();if(!f)return"";const v=zs.find(ie=>ie.id===f);return Rr(v)||""},[zs]),td=a.useCallback(i=>{const f=String(i||"").trim();if(!f)return"";const v=String(mo[f]||"").trim();if(v)return v;for(const ie of zs)for(const ce of ie.attachments||[]){if(!ce||typeof ce!="object"||String(ce.assetId||"").trim()!==f)continue;const Je=Xf({referenceNumber:typeof ce.referenceNumber=="number"?ce.referenceNumber:null,referenceLabel:String(ce.referenceLabel||"").trim()||null});if(Je)return Je}return""},[zs,mo]);a.useEffect(()=>{const i=f=>{const v=f,ie=Em(v.detail,zs);if(ie){if(v.preventDefault(),!Oc){nt(Fi,"error");return}$r(ie),Ho(null),Kl(ce=>ce+1),S("annotate")}};return window.addEventListener("taskforce:open-annotated-attachment",i),()=>{window.removeEventListener("taskforce:open-annotated-attachment",i)}},[zs,Oc,Fi,nt,S]),a.useEffect(()=>{if(!wa)return;const i=Em(wa,zs);i&&(i.taskReferenceLabel===wa.taskReferenceLabel&&i.imageReferenceLabel===wa.imageReferenceLabel||$r(i))},[zs,wa]),a.useEffect(()=>{const i=Fc.current,f=String(i?.assetId||"").trim();if(!f)return;const v=String(mo[f]||"").trim();v&&v!==String(i?.imageReferenceLabel||"").trim()&&$r(ie=>!ie||String(ie.assetId||"").trim()!==f?ie:{...ie,imageReferenceLabel:v})},[mo,wa]),a.useEffect(()=>{if(!ho)return;const f=String(wa?.assetId||"").trim();if(!f||zc.current.has(f)||String(mo[f]||"").trim())return;let v=!1;zc.current.add(f);const ie=String(en||"default").trim()||"default",ce=new URLSearchParams({workspaceId:ie});return(async()=>{try{const Ct=await fetch(`/api/taskforce/annotated-attachments/images/${encodeURIComponent(f)}?${ce.toString()}`,{method:"GET",credentials:"include",headers:fo});if(!Ct.ok)return;const Mn=await Ct.json().catch(()=>({})),mn=String(Mn?.target?.imageReferenceLabel||"").trim();if(!mn||v)return;bu(nr=>nr[f]===mn?nr:{...nr,[f]:mn})}catch{}finally{zc.current.delete(f)}})(),()=>{v=!0}},[ho,mo,en,wa,fo]);const qa=a.useMemo(()=>e.deletedTasks.map(i=>({...i.taskSnapshot,isDeleted:!0,deletedRecordId:i.id})),[e.deletedTasks]),$i=a.useMemo(()=>{const i=new Map;return e.deletedTasks.forEach(f=>{i.set(f.taskSnapshot.id,f)}),i},[e.deletedTasks]),Ui=a.useMemo(()=>{const i=qa,f=et.trim().toLowerCase(),v=y.every(mn=>vt.includes(mn.value)),ie=kn.every(mn=>it.includes(mn.value)),ce=new Set(wt.map(mn=>String(mn))),Je=Xt.every(mn=>ce.has(String(mn.value))),Ct=new Set(V.map(mn=>String(mn))),Mn=no.every(mn=>Ct.has(String(mn.value)));return i.filter(mn=>{const nr=(Rr(mn)||mn.id).toLowerCase(),Al=!f||mn.title.toLowerCase().includes(f)||String(mn.description||"").toLowerCase().includes(f)||mn.id.toLowerCase().includes(f)||nr.includes(f),tp=v||vt.includes(mn.category),jt=ie||it.includes(mn.type||ms),Ns=Je||ce.has(String(mn.priority)),Jr=Mn||Ct.has(String(mn.status)),js=Dn.length===0||Dn.includes(mn.assignee||"unassigned");return Al&&tp&&jt&&Ns&&Jr&&js})},[y,kn,qa,Dn,vt,wt,V,it,Xt,et]),Ko=a.useMemo(()=>[...e.tasks,...ba,...qa],[ba,qa,e.tasks]),$c=a.useMemo(()=>{const i=y.filter(v=>!v.disabled).map(v=>({value:v.value,label:v.label})),f=y.filter(v=>v.disabled&&Ko.some(ie=>ie.category===v.value)).map(v=>({value:v.value,label:`${v.label} (Legacy)`}));return[...i,...f]},[y,Ko]),Uc=a.useMemo(()=>{const i=kn.filter(v=>v.status!=="retired").map(v=>({value:v.value,label:v.label})),f=kn.filter(v=>v.status==="retired"&&Ko.some(ie=>(ie.type||ms)===v.value)).map(v=>({value:v.value,label:`${v.label} (Retired)`}));return[...i,...f]},[kn,Ko]),Ur=a.useMemo(()=>gt==="archived"?Ys:gt==="deleted"?Ui:kr?[...e.filteredTasks,...Ys]:e.filteredTasks,[Ys,Ui,e.filteredTasks,kr,gt]),qi=a.useMemo(()=>gt==="open"?e.tasks.filter(i=>!i.isArchived):Ur,[Ur,e.tasks,gt]),nd=a.useMemo(()=>new Set(Ur.map(i=>i.id)),[Ur]);a.useMemo(()=>gt==="archived"?ba:gt==="deleted"?qa:kr?[...e.searchAgnosticTasks,...ba]:e.searchAgnosticTasks,[ba,qa,e.searchAgnosticTasks,kr,gt]);const Yo=a.useMemo(()=>{const i=new Map;for(const f of ba)i.set(f.id,f);for(const f of qa)i.set(f.id,f);for(const f of e.tasks)i.set(f.id,f);return Array.from(i.values())},[ba,qa,e.tasks]),Jo=a.useMemo(()=>{const i=new Map;return Yo.forEach(f=>i.set(f.id,f)),i},[Yo]),Hi=a.useMemo(()=>{const i=new Map;return ht.forEach(f=>{i.set(String(f.value),f.label)}),i},[ht]),ct=a.useMemo(()=>{const i=gt==="archived"?ba:gt==="deleted"?qa:e.tasks.filter(jt=>!jt.isArchived),f=jt=>{const Ns=jt.length,Jr=jt.filter(js=>js.isArchived||js.status==="done"||js.status==="cancelled").length;return{progressPercent:Ns>0?Math.round(Jr/Ns*100):0,taskCount:Ns,completedTaskCount:Jr}},v=new Map,ie=new Map,ce=new Map,Je=new Map,Ct=new Map,Mn=jt=>{const Ns=i.filter(xa=>(xa.workstreamId||null)===jt.id),Jr=Ns.map(xa=>({id:xa.id,referenceNumber:xa.referenceNumber??null,title:xa.title,status:xa.status||null})),js={id:jt.id,referenceNumber:jt.referenceNumber??null,title:jt.title,description:String(jt.description||"").trim()||void 0,ownerLabel:jt.ownerId?Hi.get(String(jt.ownerId))||String(jt.ownerId):null,...f(Ns),initiativeId:jt.initiativeId||null,commentCount:Array.isArray(jt.comments)?jt.comments.length:0,attachmentCount:Array.isArray(jt.attachments)?jt.attachments.length:0,isArchived:!!jt.isArchived,tasks:Jr};return v.set(jt.id,Ns.map(xa=>xa.id)),jt.initiativeId&&ie.set(jt.id,jt.initiativeId),Je.set(js.id,js),js},mn=e.workstreams.map(Mn),nr=e.initiatives.map(jt=>{const Ns=mn.filter(xa=>(xa.initiativeId||null)===jt.id),Jr=Ns.flatMap(xa=>v.get(xa.id)||[]).map(xa=>Jo.get(xa)).filter(xa=>!!xa),js={id:jt.id,referenceNumber:jt.referenceNumber??null,title:jt.title,description:String(jt.description||"").trim()||void 0,ownerLabel:jt.ownerId?Hi.get(String(jt.ownerId))||String(jt.ownerId):null,...f(Jr),workstreamCount:Ns.length,workstreams:Ns,commentCount:Array.isArray(jt.comments)?jt.comments.length:0,attachmentCount:Array.isArray(jt.attachments)?jt.attachments.length:0,isArchived:!!jt.isArchived};return ce.set(jt.id,Jr.map(xa=>xa.id)),Ct.set(js.id,js),js}),Al=gt==="deleted"?[]:nr.filter(jt=>gt==="archived"?!!jt.isArchived:!jt.isArchived),tp=mn.filter(jt=>!jt.initiativeId).filter(jt=>gt==="deleted"?!1:gt==="archived"?!!jt.isArchived:!jt.isArchived);return{initiatives:Al,standaloneWorkstreams:tp,workstreamTaskIds:v,workstreamInitiativeIds:ie,initiativeTaskIds:ce,workstreamById:Je,initiativeById:Ct}},[ba,Hi,qa,Jo,e.initiatives,e.tasks,e.workstreams,gt]),qc=a.useMemo(()=>ct.initiatives.map(i=>{const f=ar(i);return{value:i.id,label:f?`${f} - ${i.title}`:i.title,selectedLabel:f||i.title}}),[ct.initiatives]),Gi=a.useMemo(()=>[...ct.initiatives.flatMap(i=>i.workstreams.map(f=>{const v=to(f);return{value:f.id,label:v?`${v} - ${f.title}`:f.title,selectedLabel:v||f.title}})),...ct.standaloneWorkstreams.map(i=>{const f=to(i);return{value:i.id,label:f?`${f} - ${i.title}`:i.title,selectedLabel:f||i.title}})],[ct.initiatives,ct.standaloneWorkstreams]),Xo=a.useMemo(()=>un?new Set(ct.workstreamTaskIds.get(un)||[]):Rn?new Set(ct.initiativeTaskIds.get(Rn)||[]):null,[ct.initiativeTaskIds,ct.workstreamTaskIds,Rn,un]),Vi=a.useMemo(()=>{if(!mr)return null;if(mr.type==="initiative"){const f=ct.initiativeById.get(mr.id);return f?{type:"initiative",item:f}:null}const i=ct.workstreamById.get(mr.id)||ct.standaloneWorkstreams.find(f=>f.id===mr.id);return i?{type:"workstream",item:i}:null},[mr,ct.initiativeById,ct.standaloneWorkstreams,ct.workstreamById]),Zi=a.useMemo(()=>{if(!po)return null;const i=ct.workstreamById.get(po)||ct.standaloneWorkstreams.find(f=>f.id===po);return i?{type:"workstream",item:i}:null},[po,ct.standaloneWorkstreams,ct.workstreamById]),Ki=a.useMemo(()=>hr?{kind:"editor",editor:hr}:Zi?{kind:"detail",detail:Zi}:null,[Zi,hr]),ad=yh(cs,!!(Vi||zr),Br,!!Ki,Vs),Hc=a.useMemo(()=>{if(!Fs.trim())return null;const i=ct.initiativeById.get(Fs);return i||cp(ct.initiatives,Fs)},[Fs,ct.initiativeById,ct.initiatives]);a.useEffect(()=>{Rn&&!ct.initiativeById.has(Rn)&&pr(""),un&&!ct.workstreamById.has(un)&&Fr("")},[ct.initiativeById,ct.workstreamById,Rn,un]);const ts=a.useMemo(()=>k==="schedule"?qi:Ur,[k,Ur,qi]),ua=a.useMemo(()=>{const i=new Date,f=i.getFullYear(),v=String(i.getMonth()+1).padStart(2,"0"),ie=String(i.getDate()).padStart(2,"0");return`${f}-${v}-${ie}`},[]),yo=a.useMemo(()=>k!=="schedule"||!Hs?ts:ts.filter(i=>{if(i.status==="done"||i.status==="cancelled")return!1;const v=!!i.scheduledDate&&i.scheduledDate<ua,ie=!!i.dueDate&&i.dueDate<ua;return v||ie}),[k,Hs,ts,ua]),sd=a.useMemo(()=>!Xo||Xo.size===0?yo:yo.filter(i=>Xo.has(i.id)),[yo,Xo]),ko=a.useMemo(()=>k!=="schedule"?[]:ts.filter(i=>{if(i.status==="done"||i.status==="cancelled")return!1;const v=!!i.scheduledDate&&i.scheduledDate<ua,ie=!!i.dueDate&&i.dueDate<ua;return v||ie}),[k,ts,ua]),_u=a.useMemo(()=>k!=="schedule"?0:ts.filter(i=>i.status==="done"||i.status==="cancelled"?!1:!!i.scheduledDate&&i.scheduledDate<ua).length,[k,ts,ua]),Gc=a.useMemo(()=>k!=="schedule"?0:ts.filter(i=>i.status==="done"||i.status==="cancelled"?!1:!!i.dueDate&&i.dueDate<ua).length,[k,ts,ua]),us=String(fs||"").trim(),Qo=a.useMemo(()=>!us||us==="anonymous"?0:D.filter(i=>i.status==="done"||i.status==="cancelled"?!1:String(i.assignee||"").trim()===us).length,[us,D]),rd=a.useMemo(()=>!us||us==="anonymous"?0:D.filter(i=>i.status==="done"||i.status==="cancelled"||String(i.assignee||"").trim()!==us?!1:!!i.dueDate&&i.dueDate<ua).length,[us,D,ua]),Yi=a.useMemo(()=>k!=="schedule"?[]:ts.filter(i=>i.status==="done"||i.status==="cancelled"?!1:!!i.scheduledDate&&i.scheduledDate<ua),[k,ts,ua]),ei=ko,[Sr,So]=a.useState(!1),Ji=()=>{uo(()=>{Pe()||(C==="add"&&Te.length>0&&X(),Ei(!1),C==="add"&&ee(),_("tasks"))})};a.useEffect(()=>{C!=="add"&&Ei(!1)},[C]);const Xi=a.useCallback((i,f)=>{if(i.status!==f){if(f==="in-progress"){Qt(i);return}if(f==="review"){Ge(i);return}if(f==="done"){zt(i);return}if(f==="cancelled"){An(i);return}be(i.id,{status:f,completedAt:null})}},[Qt,Ge,zt,An,be]),Vc=a.useCallback((i,f)=>{ee();const v=OP(i,f,{categories:y,approaches:At});v.category&&Ce(v.category),v.type&&x(v.type),typeof v.priority=="number"&&P(v.priority),typeof v.complexity=="number"&&M(v.complexity),v.approach&&H(v.approach);const ie=v.taxonomyApproach;typeof ie=="string"&&ie.length>0&&Ye(ce=>({...ce,approach:ie})),v.assignee&&je(v.assignee),v.status&&h(v.status),v.scheduledDate&&ue(v.scheduledDate),_("add")},[ee,y,At,Ce,x,P,M,h,H,je,ue,Ye,_]);pt.useEffect(()=>{V&&!V.includes("done")&&ne(i=>[...i,"done"])},[]);const[od,vo]=a.useState(!1),[bs,Ea]=a.useState(!1),[vr,wo]=a.useState(!1),[Zc,ti]=a.useState(!1),[Qi,ec]=a.useState(!1),[id,tc]=a.useState(!1),[Kc,nc]=a.useState(null),[wr,cd]=a.useState(!1),[ni,Yc]=a.useState(!1),[Jc,ac]=a.useState(!1),[Ha,ld]=a.useState([]),[dd,ud]=a.useState(!1),[Xc,pd]=a.useState(null),Qc=a.useRef(null),ai=a.useRef(null),[bo,md]=a.useState(!1),[fd,el]=a.useState(""),[Cu,tl]=a.useState(!1),[nl,sc]=a.useState(!1),[hd,_o]=a.useState("members"),[rc,br]=a.useState(null),[_s,Ga]=a.useState("unknown"),[gd,oc]=a.useState(!1),[yd,Co]=a.useState(null),[si,La]=a.useState(null),[ic,ri]=a.useState(!1),[xo,oi]=a.useState([]),[cc,lc]=a.useState(null),[Js,Xs]=a.useState(""),[ii,al]=a.useState("member"),[dc,xu]=a.useState("read-write"),[Au,kd]=a.useState(!1),[Tu,sl]=a.useState(null),[qr,Iu]=a.useState(0),[Nu,Sd]=a.useState(!1),[ju,rl]=a.useState([]),[ci,vd]=a.useState(!1),[wd,Hr]=a.useState(1),[Cs,Hn]=a.useState(null),[Ao,ns]=a.useState(!1),[To,ol]=a.useState(null),[Gr,as]=a.useState(!1),[Ru,_r]=a.useState(null),[bd,il]=a.useState(null),[Io,Du]=a.useState("month"),[cl,_d]=a.useState(""),[ll,No]=a.useState(""),[ss,jo]=a.useState(null),[Pu,Cd]=a.useState(!1),[Eu,dl]=a.useState(!1),[xd,xs]=a.useState(null),[Lu,As]=a.useState(null),Ad=25,Td=a.useRef(null),uc=a.useRef(null),li=a.useRef(null),ul=a.useRef({billing:!1,teamManagement:!1});a.useEffect(()=>{if(!bs)return;const i=f=>{Td.current?.contains(f.target)||Ea(!1)};return document.addEventListener("mousedown",i),()=>document.removeEventListener("mousedown",i)},[bs]);const Id=Ze==="cloud"&&Vn&&Rt,Ts=Rt&&(Ze==="cloud"||pn),di=Ze==="local"&&Rt,pl=a.useCallback(async i=>{if(!di)return;nc(null),tc(!0);const f=await fa({enabled:i});f.success||nc(f.error||(i?"Failed to enable sync.":"Failed to disable sync.")),tc(!1)},[di,fa]),pc=id,ml=a.useMemo(()=>{const i=ha.find(ie=>ie.id===en),f=String(i?.name||"").trim();if(f)return f;if(Ze==="local"){const ie=String(Oa||"").trim();if(ie)return ie}return String(en||"").trim()||"Workspace"},[ha,en,Oa,Ze]),ui=Sh(Ts,rc),mc=OL(Ts,rc,_s),fc=String(fn||"").trim(),Ma=String(sa||"").trim(),pi=String(aa||"").trim(),mi=fc||pi,fl=mi.length>0,Mu=pi.length>0,hl=(mi||pi||"U").trim().charAt(0).toUpperCase()||"U",gl=Ma,Nd=String(ll||Ma).trim(),hc=String(Cs?.planName||Cs?.planId||"").trim(),jd=hc.length>0,Cr=String(Ds||en||"").trim(),Rd=Ze==="cloud"?"CLOUD":"LOCAL",Dd=e.config?.apiBaseUrl||"",Ro=a.useMemo(()=>{const i=Ze==="local"?e.config?.cloudAuthBaseUrl||e.config?.apiBaseUrl||"":e.config?.apiBaseUrl||e.config?.cloudAuthBaseUrl||"";return String(i||"").trim().replace(/\/+$/,"")},[e.config?.apiBaseUrl,e.config?.cloudAuthBaseUrl,Ze]),Pd=a.useMemo(()=>{const i=Ze==="local"?e.config?.cloudAuthBaseUrl||e.config?.apiBaseUrl||"":e.config?.apiBaseUrl||e.config?.cloudAuthBaseUrl||"";return String(i||"").trim().replace(/\/+$/,"")},[e.config?.apiBaseUrl,e.config?.cloudAuthBaseUrl,Ze]),xr=a.useCallback(i=>{const f=String(i||"").trim();return Ro?`${Ro}${f.startsWith("/")?f:`/${f}`}`:f},[Ro]),Ed=a.useMemo(()=>eM(e.config?.cloudEnvironment,[String(e.config?.cloudBaseUrl||""),String(e.config?.cloudAuthBaseUrl||""),String(e.config?.apiBaseUrl||""),String(e.config?.baseUrl||"")]),[e.config?.cloudEnvironment,e.config?.cloudBaseUrl,e.config?.cloudAuthBaseUrl,e.config?.apiBaseUrl,e.config?.baseUrl]),Ld=pn&&!On;a.useEffect(()=>{Zc&&(_d(fc),No(Ma),jo(null),xs(null),As(null))},[Ma,fc,Zc]);const Ar=a.useCallback(async i=>{const f=String(i||"").trim();if(!(!f||!pn))try{const v=Ze==="local"?e.config?.cloudAuthBaseUrl||e.config?.apiBaseUrl||"":e.config?.apiBaseUrl||e.config?.cloudAuthBaseUrl||"";await Hd("/api/taskforce/auth/profile/avatar/discard",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({draftId:f})},v)}catch{}},[pn,e.config?.apiBaseUrl,e.config?.cloudAuthBaseUrl,Ze]),Md=a.useCallback(()=>{const i=ss;ti(!1),xs(null),As(null),jo(null),No(Ma),i&&Ar(i)},[Ma,Ar,ss]),fi=a.useCallback(async i=>{if(!(!i||!pn)){if(!i.type.startsWith("image/")){xs("Profile photo must be an image file."),As(null);return}if(i.size>KL){xs("Profile photo must be 5 MB or smaller."),As(null);return}Cd(!0),xs(null),As(null);try{const f=Ze==="local"?e.config?.cloudAuthBaseUrl||e.config?.apiBaseUrl||"":e.config?.apiBaseUrl||e.config?.cloudAuthBaseUrl||"",v=await Hd("/api/taskforce/auth/profile/avatar/init",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({originalName:i.name,mimeType:i.type,size:i.size})},f),ie=await v.json().catch(()=>({}));if(!v.ok||!ie?.success||typeof ie?.uploadUrl!="string"||typeof ie?.relativePath!="string")throw new Error(ie?.error||"Failed to start avatar upload.");if(!(await fetch(ie.uploadUrl,{method:String(ie.method||"PUT"),headers:ie.headers||{"Content-Type":i.type||"application/octet-stream"},body:i})).ok)throw new Error("Failed to upload avatar.");const Je=await Hd("/api/taskforce/auth/profile/avatar/finalize",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({draftId:ie.draftId,relativePath:ie.relativePath})},f),Ct=await Je.json().catch(()=>({}));if(!Je.ok||!Ct?.success||typeof Ct?.draftId!="string")throw new Error(Ct?.error||"Failed to finalize avatar upload.");const Mn=ss;jo(Ct.draftId),No(typeof Ct?.avatarUrl=="string"?Ct.avatarUrl:""),As("Profile photo ready to save."),Mn&&Mn!==Ct.draftId&&Ar(Mn)}catch(f){xs(f instanceof Error?f.message:"Failed to upload profile photo.")}finally{Cd(!1),uc.current&&(uc.current.value="")}}},[pn,Ar,ss,e.config?.apiBaseUrl,e.config?.cloudAuthBaseUrl,Ze]),Bd=a.useCallback(()=>{if(!ss)return;const i=ss;jo(null),No(Ma),As(null),xs(null),Ar(i)},[Ma,Ar,ss]),Wu=a.useCallback(()=>{const i=ss;jo(null),No(""),As(Ma?"Profile photo will be removed when you save.":null),xs(null),i&&Ar(i)},[Ma,Ar,ss]),Fu=a.useCallback(async()=>{const i=cl.trim();if(!i){xs("Display name is required."),As(null);return}dl(!0),xs(null),As(null);const f=await Na({displayName:i,avatarDraftId:ss,clearAvatar:!ss&&!ll&&!!Ma});if(!f.success){xs(f.error||"Failed to update profile."),dl(!1);return}As("Profile updated."),jo(null),No(""),dl(!1),ti(!1)},[Ma,ss,ll,cl,Na]),Ba=a.useCallback(()=>{const i={},f=String(Cr||"").trim();return f&&(i["x-taskforce-workspace-id"]=f),(Ia==="owner"||Ia==="admin"||Ia==="member"||Ia==="read-only")&&(i["x-taskforce-workspace-role"]=Ia),i},[Ia,Cr]),yl=a.useCallback(i=>{const f=Rt,v=Ts;li.current=Qr(),ul.current={billing:f,teamManagement:v},Bn("account_surface_opened",{surface:i,expectsBilling:f,expectsTeamManagement:v}),!f&&!v&&(Bn("account_surface_ready",{surface:i,durationMs:0,teamManagementVisible:!1,billingPlanId:null}),li.current=null)},[Ts,Rt]),Vr=a.useCallback(i=>{const f=ul.current;if(f[i]=!1,f.billing||f.teamManagement)return;const v=li.current;v!==null&&(Bn("account_surface_ready",{surface:vr?"account_hub":bs?"account_menu":"closed",durationMs:Math.round(Qr()-v),teamManagementVisible:mc,billingPlanId:String(Cs?.planId||"").trim()||null}),li.current=null)},[Cs?.planId,mc,vr,bs]),Zr=a.useCallback(async()=>{const f=xr("/api/taskforce/billing/status");if(!Rt)return Hn(null),ol(null),Um(f),Vr("billing"),null;const v=Qr();ns(!0),ol(null);try{const ie=await qP(f);return Hn(ie),Bn("account_billing_status_resolved",{durationMs:Math.round(Qr()-v),planId:String(ie?.planId||"").trim()||null,gate:String(ie?.gate||"").trim()||null}),ie}catch(ie){return Hn(null),ol(ie instanceof Error?ie.message:"Failed to load billing status."),Bn("account_billing_status_failed",{durationMs:Math.round(Qr()-v),error:ie instanceof Error?ie.message:"Failed to load billing status."}),null}finally{ns(!1),Vr("billing")}},[xr,Rt,Vr]),zu=a.useCallback(async()=>{const i=new URLSearchParams;i.set("screen","plans"),i.set("interval",Io),r(`/?${i.toString()}`)},[Io,r]),Ou=a.useCallback(async()=>{_r(null),il(null),as(!0);try{const i=await fetch(xr("/api/taskforce/billing/portal-session"),{method:"POST",credentials:"include"}),f=await i.json().catch(()=>({}));if(!i.ok){_r(String(f?.error||"Failed to create portal session."));return}const v=String(f?.url||"").trim();if(!v){_r("Portal session did not return a redirect URL.");return}window.location.assign(v)}catch{_r("Failed to open billing portal.")}finally{as(!1)}},[xr]),$u=a.useCallback(async()=>{_r(null),il(null),as(!0);try{const i=String(Cs?.planVersionId||"").trim();if(!i){_r("No active plan version is linked to this account.");return}const f=await fetch(xr("/api/taskforce/billing/subscription"),{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({planVersionId:i,interval:Io})}),v=await f.json().catch(()=>({}));if(!f.ok){_r(String(v?.error||"Failed to update subscription interval."));return}il("Subscription updated."),Um(xr("/api/taskforce/billing/status")),await Zr()}catch{_r("Failed to update subscription interval.")}finally{as(!1)}},[Io,Cs?.planVersionId,xr,Zr]),Tr=a.useCallback(async()=>{if(!Ts)return br(null),Ga("unknown"),oc(!1),Co(null),Vr("teamManagement"),{role:null,teamPlanMode:"unknown",allowed:!1};const i=Qr();oc(!0),Co(null);try{const f=await Hd("/api/taskforce/account/team-management-access",{method:"GET",credentials:"include",headers:Ba()},Ro),v=await f.json().catch(()=>({}));if(!f.ok)return br(null),Ga("unknown"),Co(String(v?.error||"Failed to load team management access.")),Bn("team_management_access_failed",{durationMs:Math.round(Qr()-i),status:f.status}),{role:null,teamPlanMode:"unknown",allowed:!1};const ie=v?.role==="owner"||v?.role==="admin"||v?.role==="member"||v?.role==="read-only"?v.role:null,ce=v?.teamPlanMode==="team"||v?.teamPlanMode==="personal"?v.teamPlanMode:"unknown",Je=v?.allowed===!0;return br(ie),Ga(ce),Co(null),Bn("team_management_access_loaded",{durationMs:Math.round(Qr()-i),role:ie,teamPlanMode:ce,allowed:Je}),{role:ie,teamPlanMode:ce,allowed:Je}}catch(f){return br(null),Ga("unknown"),Co(f instanceof Error?f.message:"Failed to load team management access."),Bn("team_management_access_failed",{durationMs:Math.round(Qr()-i),error:f instanceof Error?f.message:"Failed to load team management access."}),{role:null,teamPlanMode:"unknown",allowed:!1}}finally{oc(!1),Vr("teamManagement")}},[Ro,Ts,Vr,Ba]);a.useEffect(()=>{!bs&&!nl&&!vr||Tr()},[vr,bs,nl,Tr]),a.useEffect(()=>{if(!(!Rt||!On)){if(!Ts){br(null),Ga("unknown");return}Tr()}},[On,Ts,Rt,Tr]),a.useEffect(()=>{!Rt||!On||Zr()},[On,Rt,Zr]),a.useEffect(()=>{!vr&&!bs||Zr()},[Zr,vr,bs]);const Kr=a.useCallback(async()=>{if(ui){ri(!0),La(null);try{const i=await fetch("/api/taskforce/admin/users",{method:"GET",credentials:"include",headers:Ba()}),f=await i.json().catch(()=>({}));if(!i.ok){La(f?.error||"Failed to load workspace users.");return}const v=Array.isArray(f?.users)?f.users:[],ie={owner:0,admin:1,member:2,"read-only":3},ce=v.map(Je=>({userId:String(Je?.userId||""),email:String(Je?.email||""),displayName:typeof Je?.displayName=="string"?Je.displayName:null,role:Je?.role==="owner"||Je?.role==="admin"||Je?.role==="member"||Je?.role==="read-only"?Je.role:"member",permissionMode:Je?.permissionMode==="read-only"?"read-only":"read-write",status:String(Je?.status||"active"),disabled:Je?.disabled===!0}));ce.sort((Je,Ct)=>{const Mn=(ie[Je.role]??99)-(ie[Ct.role]??99);return Mn!==0?Mn:(Je.displayName||Je.email).localeCompare(Ct.displayName||Ct.email,void 0,{sensitivity:"base"})}),oi(ce)}catch{La("Failed to load workspace users.")}finally{ri(!1)}}},[ui,Ba]),Qs=a.useCallback(async i=>{if(!ui)return;const f=Math.max(0,Math.floor(i));Sd(!0),La(null);try{const v=f*Ad,ie=await fetch(`/api/taskforce/admin/workspace-audit-logs?limit=${Ad}&offset=${v}`,{method:"GET",credentials:"include",headers:Ba()}),ce=await ie.json().catch(()=>({}));if(!ie.ok){La(ce?.error||"Failed to load workspace audit log.");return}const Je=Array.isArray(ce?.events)?ce.events:[];rl(Je.map(Mn=>({id:String(Mn?.id||""),action:String(Mn?.action||""),actorUserId:String(Mn?.actorUserId||""),actorRole:String(Mn?.actorRole||""),createdAt:String(Mn?.createdAt||Mn?.ts||"")}))),Iu(f);const Ct=Math.max(1,Number(ce?.pages||1));Hr(Ct),vd(f+1<Ct)}catch{La("Failed to load workspace audit log.")}finally{Sd(!1)}},[ui,Ba]),Do=a.useCallback(async()=>{await Promise.all([Kr(),Qs(qr)])},[Kr,Qs,qr]),gc=a.useCallback((i="login")=>{const f=`${o.pathname}${o.search}${o.hash}`,v=!f||f==="/login"||!f.startsWith("/")?"/":f;Ea(!1),wo(!1),ec(!1),r(`/login?mode=${i}&next=${encodeURIComponent(v)}`)},[o.hash,o.pathname,o.search,r]),hi=a.useCallback(i=>{Ea(!1),tl(!1);const f=new URLSearchParams({step:"workspace"});i?.intent==="create-workspace"&&f.set("intent","create-workspace"),r(`/setup?${f.toString()}`,{replace:!0})},[r]),kl=a.useCallback(async i=>{if(!(!i||bo)){el(""),md(!0);try{const f=await Ca(i);if(!f.success){if(f.code==="WORKSPACE_NOT_FOUND"||f.code==="WORKSPACE_ID_REQUIRED"){hi();return}el(f.error||"Failed to switch workspace.");return}await ot(!0),Ea(!1)}finally{md(!1)}}},[Ca,bo,ot,hi]),Wd=a.useCallback(async()=>{Ea(!1),sc(!0),_o("members"),(await Tr()).allowed&&(await Kr(),await Qs(0))},[Qs,Tr,Kr]),gi=a.useCallback(async(i,f)=>{La(null),lc(i);try{const v=await f(),ie=await v.json().catch(()=>({}));if(!v.ok){La(ie?.error||"Team management action failed.");return}await Do()}catch{La("Team management action failed.")}finally{lc(null)}},[Do]),Uu=a.useCallback(async()=>{const i=Js.trim();if(i){kd(!0),La(null),sl(null);try{const f=await fetch("/api/taskforce/admin/users/invite",{method:"POST",headers:{"Content-Type":"application/json",...Ba()},credentials:"include",body:JSON.stringify({workspaceId:Cr,email:i,role:ii,permissionMode:ii==="member"?dc:"read-write"})}),v=await f.json().catch(()=>({}));if(!f.ok){La(v?.error||"Failed to send invite.");return}Xs(""),v?.inviteEmailSent===!1?sl(`Invite created, but email delivery failed${v?.inviteEmailError?`: ${String(v.inviteEmailError)}`:"."}`):sl("Invite sent."),await Do()}catch{La("Failed to send invite.")}finally{kd(!1)}}},[en,Do,Ba,Js,dc,ii]),Sl=a.useMemo(()=>et.trim().length>0,[et]),qu=a.useMemo(()=>xo.filter(i=>i.status==="invited"),[xo]),vl=a.useMemo(()=>{const i=vt.length!==y.length,f=it.length!==kn.length,v=wt.length!==Xt.length,ie=V.length!==no.length,ce=Dn.length!==ht.length,Je=Rn.length>0,Ct=un.length>0;return i||f||v||ie||ce||Je||Ct},[y.length,kn.length,ht.length,Dn.length,vt.length,wt.length,V.length,it.length,Xt.length,Rn,un]),wl=a.useMemo(()=>Ua.length!==nu.length||In.length!==au.length,[In.length,Ua.length]),Fd=ma,er=a.useMemo(()=>bL(Fd),[Fd]),zd=a.useMemo(()=>{switch(er.filterBar.kind){case"task-filters":return vl;case"document-filters":return wl;default:return!1}},[wl,vl,er.filterBar.kind]),yc=Sl||vl,Od=gt==="archived"?ba.length:gt==="deleted"?qa.length:D.length,Hu=gt==="archived"?Ys.length:gt==="deleted"?Ui.length:e.filteredTasks.length,Gu=yc?`${Hu}/${Od}`:`${Od}`,Vu=yc?`${gt.charAt(0).toUpperCase()+gt.slice(1)} tasks matching current filters`:`${gt.charAt(0).toUpperCase()+gt.slice(1)} tasks`,Zu=Ze==="local"&&Rt,Po=a.useCallback(i=>{if(!i)return"Never";const f=new Date(i);return Number.isNaN(f.getTime())?"Never":f.toLocaleString()},[]),kc=a.useMemo(()=>Po(dn),[Po,dn]),bl=a.useMemo(()=>Po(za),[Po,za]),_l=a.useMemo(()=>Po(oa),[Po,oa]),$d=Kc||Ta||Qn||"None",Yr=a.useMemo(()=>$P({runtimeMode:Ze,isAuthenticated:Rt,workspaceSyncStatus:ra,workspaceCloudSyncEnabled:Wn,workspaceSyncSummary:Yt,workspaceSyncRecommendedAction:Fn,workspaceSyncError:$d}),[Ze,Rt,ra,Wn,Yt,Fn,$d]),m=Yr.lastError,[T,N]=a.useState(Yr.status),$=a.useMemo(()=>{if(wr)return"Repairing";if(jn&&rn==="error")return"Recovering";switch(rn){case"provision-local":return"Initial cloud upload";case"attach-cloud":return"Initial cloud pull";case"active":return"Active";case"error":return"Error";default:return"Idle"}},[rn,wr]),te=hs(),he=a.useMemo(()=>[{label:"AI profile snapshot",value:`${te.aiProfileSnapshotCount} local profile${te.aiProfileSnapshotCount===1?"":"s"}`},{label:"AI profile raw response",value:`${te.aiProfileSnapshotRawCount} from route`},{label:"Last pushed AI profiles",value:`${te.lastPushedAiProfileCount} tracked`},{label:"AI watermark map",value:`${te.lastPushedAiProfileWatermarkCount} tracked`},{label:"Document snapshot",value:`${te.documentSnapshotCount} local doc${te.documentSnapshotCount===1?"":"s"}`},{label:"Asset snapshot",value:`${te.assetSnapshotCount} local asset${te.assetSnapshotCount===1?"":"s"}`},{label:"Queued full AI sync",value:te.forceFullAiProfilePushQueued?"Yes":"No"},{label:"AI snapshot last fetch",value:te.aiProfileSnapshotLastFetchAt?new Date(te.aiProfileSnapshotLastFetchAt).toLocaleString():"Never"},{label:"AI snapshot fetch error",value:te.aiProfileSnapshotLastFetchError||"None"},{label:"AI snapshot skip reason",value:te.aiProfileSnapshotLastSkipReason||"None"}],[te]),Oe=Yr.actionable&&ra==="syncing"&&rn==="active"&&xn===0;a.useEffect(()=>{if(!Oe){N(Yr.status);return}const i=window.setTimeout(()=>{N(Yr.status)},1200);return()=>window.clearTimeout(i)},[Yr.status,Oe]);const kt=a.useCallback(i=>{const f=typeof i.occurredAt=="string"&&i.occurredAt.trim().length>0?i.occurredAt:"unknown-time",v=typeof i.eventType=="string"&&i.eventType.trim().length>0?i.eventType.trim():"sync",ie=i.status==="error"?"failed":"succeeded",ce=Number(i.changeCount),Je=Number.isFinite(ce)?` (${Math.max(0,Math.floor(ce))} change${Math.floor(ce)===1?"":"s"})`:"",Ct=Number(i.requestMs),Mn=Number.isFinite(Ct)?` in ${Math.max(0,Math.floor(Ct))}ms`:"",mn=Number(i.statusCode),nr=Number.isFinite(mn)?` [${Math.floor(mn)}]`:"",Al=typeof i.errorMessage=="string"&&i.errorMessage.trim().length>0?`: ${i.errorMessage.trim()}`:"";return`${f} ${v} ${ie}${Je}${Mn}${nr}${Al}`},[]),Ut=a.useMemo(()=>dd&&Ha.length===0?[{key:"loading",text:"Loading recent sync events...",tone:"muted"}]:Xc?[{key:"error",text:Xc,tone:"error"}]:Ha.length===0?[{key:"empty",text:"No recent sync events recorded.",tone:"muted"}]:Ha.map((i,f)=>({key:Pc(i,f),text:kt(i),tone:i.status==="error"?"error":"default"})),[kt,Ha,Xc,dd]),Bt=a.useMemo(()=>XL(Ha),[Ha]),Pt=a.useMemo(()=>QL(Ha),[Ha]),tn=a.useMemo(()=>Pt.map((i,f)=>{const v=i.details&&typeof i.details=="object"?i.details:null,ie=String(v?.path||"").trim(),ce=String(v?.referenceLabel||"").trim(),Je=String(v?.taskTitle||v?.existingTaskTitle||"").trim(),Ct=Number(v?.existingReferenceNumber),Mn=Number(v?.incomingReferenceNumber),mn=ie||Je||ce||`Mismatch ${f+1}`,nr=Number.isFinite(Ct)||Number.isFinite(Mn)?`Existing ${Number.isFinite(Ct)?Ct:"?"} vs incoming ${Number.isFinite(Mn)?Mn:"?"}`:ce?`Both claimed ${ce}`:null;return{key:Pc(i,f),pathLabel:mn,refsLabel:nr}}),[Pt]);a.useLayoutEffect(()=>{const i=ai.current,f=Qc.current;if(!i||!f)return;const v=f.scrollHeight-i.scrollHeight;f.scrollTop=i.scrollTop+Math.max(0,v),ai.current=null},[Ha]);const Va=a.useCallback(async()=>{const i=await fetch(`/api/taskforce/sync/events?workspace_id=${encodeURIComponent(en)}&limit=15`,{method:"GET",credentials:"include"});if(!i.ok)throw new Error(`Failed to load sync events (${i.status})`);const f=await i.json().catch(()=>({}));return Array.isArray(f?.events)?f.events.filter(v=>v&&typeof v=="object"):[]},[en]);a.useEffect(()=>{if(!Qi)return;let i=!1;const f=Ha.length===0;return f&&ud(!0),Va().then(v=>{if(i)return;const ie=Qc.current;ai.current=ie&&ie.scrollTop>8?{scrollTop:ie.scrollTop,scrollHeight:ie.scrollHeight}:null,ld(ce=>{const Je=ce.length===0?v:YL(ce,v,15);return JL(ce,Je)?ce:Je}),pd(null)}).catch(v=>{if(i)return;const ie=v instanceof Error&&v.message.trim().length>0?v.message.trim():"Unable to load recent sync events.";pd(ie),f&&ld([])}).finally(()=>{i||f&&ud(!1)}),()=>{i=!0}},[Qi,Va,Ha.length,oa,za,Ya,ra]);const Wa=a.useMemo(()=>{switch(T){case"off":return{label:"Off",icon:"off",color:"#94a3b8",border:"rgba(148, 163, 184, 0.35)",background:"rgba(148, 163, 184, 0.12)"};case"syncing":return{label:"Syncing",icon:"cloud",color:"#60a5fa",border:"rgba(96, 165, 250, 0.35)",background:"rgba(59, 130, 246, 0.12)"};case"attention":return{label:"Needs Attention",icon:"cloud",color:"#fda4af",border:"rgba(253, 164, 175, 0.4)",background:"rgba(239, 68, 68, 0.12)"};default:return{label:"Healthy",icon:"cloud",color:"#86efac",border:"rgba(134, 239, 172, 0.4)",background:"rgba(34, 197, 94, 0.12)"}}},[T]),Is=a.useCallback(async()=>{const i=["Taskforce Sync Manager",`Workspace ID: ${en}`,`Status: ${Wa.label}`,`Summary: ${Yr.summary}`,`Last successful sync: ${kc}`,`Last pull from cloud: ${bl}`,`Last push to cloud: ${_l}`,`Last error at: ${te.lastErrorAt?new Date(te.lastErrorAt).toLocaleString():"Never"}`,`Pending local changes: ${xn}`,`Last error: ${m}`,`Sync stage: ${$}`,`AI profile snapshot: ${te.aiProfileSnapshotCount}`,`AI profile raw response: ${te.aiProfileSnapshotRawCount}`,`Last pushed AI profiles tracked: ${te.lastPushedAiProfileCount}`,`AI profile watermarks tracked: ${te.lastPushedAiProfileWatermarkCount}`,`AI snapshot last fetch: ${te.aiProfileSnapshotLastFetchAt?new Date(te.aiProfileSnapshotLastFetchAt).toLocaleString():"Never"}`,`AI snapshot fetch error: ${te.aiProfileSnapshotLastFetchError||"None"}`,`AI snapshot skip reason: ${te.aiProfileSnapshotLastSkipReason||"None"}`,`Document snapshot: ${te.documentSnapshotCount}`,`Asset snapshot: ${te.assetSnapshotCount}`,`Reference mismatches detected: ${Bt}`,`Queued full AI sync: ${te.forceFullAiProfilePushQueued?"Yes":"No"}`];try{const v=(Ha.length>0?Ha:await Va()).map(ce=>kt(ce)),ie=[...i,"","Recent sync events",...v.length>0?v:["No recent sync events recorded."]].join(`
6
+ `);await navigator.clipboard.writeText(ie),ac(!0),window.setTimeout(()=>{ac(!1)},1800),nt("Sync details copied to clipboard.","success")}catch{ac(!1),nt("Failed to copy sync details.","error")}},[en,Wa.label,Yr.summary,kc,bl,_l,te,xn,m,$,Bt,nt,Ha,Va,kt]),Ir=a.useCallback(async()=>{Yc(!1),cd(!0);try{await Zn()}finally{cd(!1)}},[Zn]),Ln=a.useCallback(()=>{if(!wr){if(jn){Yc(!0);return}Ir()}},[Ir,jn,wr]);a.useEffect(()=>{ni&&(jn||wr||Ir())},[Ir,jn,wr,ni]);const Sc=a.useMemo(()=>El(Lr)||new Date,[Lr]),Os=a.useMemo(()=>Pp(Sc,Sn),[Sc,Sn]),tr=a.useMemo(()=>{const i={mon:"",tue:"",wed:"",thu:"",fri:"",sat:"",sun:""};return Jm.forEach(f=>{const v=WL(f,Sn);i[f]=xc(kh(Os,v))}),i},[Os,Sn]),Cl=a.useCallback(i=>{const f=El(i);if(!f)return tr.mon;const v=f.getDay();return tr[v===1?"mon":v===2?"tue":v===3?"wed":v===4?"thu":v===5?"fri":v===6?ks?"sat":"fri":ks?"sun":"fri"]||tr.mon},[tr,ks]),wh=a.useCallback(async()=>{if(!(Sr||ei.length===0)){So(!0);try{for(const i of ei){const f=i.scheduledDate||i.dueDate||ua,v=Cl(f);await be(i.id,{scheduledDate:v,scheduledWeekKey:FL(v),orderInDay:null})}await ot(!0)}finally{So(!1)}}},[Sr,ei,ua,Cl,be,ot]),bh=a.useCallback(async()=>{if(!(Sr||ko.length===0)){So(!0);try{for(const i of ko)await be(i.id,{scheduledDate:null,scheduledWeekKey:null,orderInDay:null});await ot(!0)}finally{So(!1)}}},[Sr,ko,be,ot]),_h=a.useMemo(()=>Nc(Os,{month:"short",day:"numeric",year:"numeric"},ta),[Os,ta]),Kp=a.useMemo(()=>{const v=(ks?Sn==="sunday"?["sun","mon","tue","wed","thu","fri","sat"]:Jm:["mon","tue","wed","thu","fri"]).map(ce=>{const Je=El(tr[ce])||Os,Ct=tr[ce],Mn=ce==="sat"||ce==="sun";return{value:ce,label:`${BL[ce]} ${Nc(Je,{month:"short",day:"numeric"},ta)}`,color:Mn?"#1e3a8a":"#3b82f6",icon:"Calendar",date:Ct,isPast:Ct<ua,isSelected:Ct===Lr,isWeekend:Mn}}),ie=Yi.length>0;return[...lr?[{value:"backlog",label:"Backlog",color:"#64748b",icon:"Inbox"}]:[],...ie?[{value:"expired",label:"Expired",color:"#ef4444",icon:"AlertTriangle"}]:[],...v]},[ks,lr,tr,Os,Yi.length,ua,Lr,Sn,ta]),Yp=a.useMemo(()=>{switch(k){case"category":return y;case"type":return(kn||[]).map(i=>({...i,icon:i.icon||du[i.value]?.icon,color:i.color||du[i.value]?.color}));case"priority":return Xt;case"complexity":return[{value:1,label:"Tiny",icon:"Gauge",color:"#10b981"},{value:2,label:"Low",icon:"Gauge",color:"#14b8a6"},{value:3,label:"Medium",icon:"Gauge",color:"#3b82f6"},{value:4,label:"High",icon:"Gauge",color:"#8b5cf6"},{value:5,label:"Epic",icon:"Gauge",color:"#d946ef"}];case"approach":return At;case"assignee":return ht.map(i=>({value:i.value,label:i.label,icon:i.icon==="HelpCircle"?"Circle":i.icon,color:i.color}));case"status":return[...no.filter(i=>i.value!=="done"&&i.value!=="cancelled"),{value:"completed",label:"Completed",icon:Ml("done").icon,color:Ml("done").color}];case"schedule":return Kp;default:return y}},[k,y,kn,Xt,At,ht,Kp]),Ch=t.jsxs("div",{className:at.accountMenuWrap,ref:Td,children:[t.jsx("button",{className:`tf-control-icon ${at.avatarBtn}`,onClick:()=>{Ea(i=>{const f=!i;return f?yl("account_menu"):(li.current=null,ul.current={billing:!1,teamManagement:!1}),f})},title:Rt?"Account":"Account (Not signed in)","aria-label":Rt?"Account":"Account (Not signed in)","aria-haspopup":"menu","aria-expanded":bs,children:t.jsx("span",{className:at.avatarBadge,"aria-hidden":"true",children:Rt&&gl?t.jsx("img",{src:gl,alt:"",className:at.avatarImage}):Rt?hl:"?"})}),bs&&t.jsxs("div",{className:at.accountMenu,role:"menu","aria-label":"Account menu",children:[t.jsxs("div",{className:at.accountMenuSection,children:[t.jsx("div",{className:at.accountMenuSectionLabel,children:"Account"}),t.jsx("div",{className:at.accountMenuHint,children:Ld?"Checking sign-in status...":Rt?t.jsx(t.Fragment,{children:fl?t.jsx(t.Fragment,{children:t.jsxs("span",{className:at.accountIdentityBlock,children:[t.jsx("span",{className:at.accountIdentityEmail,children:mi}),Mu&&fc&&t.jsxs("span",{className:at.accountIdentityMetaLine,children:[t.jsx("span",{className:at.accountIdentityMetaLabel,children:"Email"}),t.jsx("span",{className:at.accountIdentityMetaValue,children:pi})]}),Ao?t.jsxs("span",{className:at.accountIdentityMetaLine,children:[t.jsx("span",{className:at.accountIdentityMetaLabel,children:"Subscription"}),t.jsx("span",{className:at.accountIdentityMetaValue,children:"Loading…"})]}):jd?t.jsxs("button",{"aria-label":`Subscription ${hc}`,className:`${at.accountIdentityMetaLine} ${at.accountIdentityMetaAction}`,onClick:()=>{Ea(!1),p()},type:"button",children:[t.jsx("span",{className:at.accountIdentityMetaLabel,children:"Subscription"}),t.jsx("span",{className:at.accountIdentityMetaValue,children:hc})]}):To?t.jsxs("span",{className:at.accountIdentityMetaLine,children:[t.jsx("span",{className:at.accountIdentityMetaLabel,children:"Subscription"}),t.jsx("span",{className:at.accountIdentityMetaValue,children:"Unavailable"})]}):null,t.jsxs("span",{className:at.accountIdentityMetaLine,children:[t.jsx("span",{className:at.accountIdentityMetaLabel,children:"Runtime"}),t.jsx("span",{className:at.accountIdentityMetaValue,children:Rd})]}),t.jsxs("span",{className:at.accountIdentityMetaLine,children:[t.jsx("span",{className:at.accountIdentityMetaLabel,children:"Environment"}),t.jsx("span",{className:at.accountIdentityMetaValue,children:Ed})]})]})}):"Signed in"}):"Not signed in"})]}),Id&&t.jsxs("div",{className:at.accountMenuSection,children:[t.jsx("div",{className:at.accountMenuSectionLabel,children:"Workspaces (Owned + Invited)"}),ha.length===0&&t.jsx("div",{className:at.accountMenuHint,children:"No workspaces found for this account yet."}),ha.map(i=>t.jsxs("button",{className:`${at.accountMenuItem} ${i.id===en?at.accountMenuItemActive:""}`,onClick:()=>kl(i.id),role:"menuitem",disabled:bo||i.id===en,title:i.description||i.name,children:[t.jsx(Ai,{size:15}),t.jsxs("span",{style:{display:"flex",flexDirection:"column",gap:"2px"},children:[t.jsx("span",{children:i.name}),t.jsx("span",{className:at.accountMenuMeta,children:i.role})]})]},i.id)),t.jsxs("button",{className:at.accountMenuItem,onClick:()=>{el(""),tl(!0),Ea(!1)},role:"menuitem",disabled:bo,children:[t.jsx(sr,{size:15}),"Create Workspace"]}),fd&&t.jsx("div",{className:at.accountMenuError,children:fd})]}),gd?t.jsx("div",{className:at.accountMenuHint,children:"Resolving team management access..."}):mc?t.jsxs("button",{className:at.accountMenuItem,onClick:()=>{Wd()},role:"menuitem",children:[t.jsx(ig,{size:15}),"Team Management"]}):yd?t.jsx("div",{className:at.accountMenuHint,children:"Team Management unavailable right now."}):null,Rt&&t.jsxs("button",{className:at.accountMenuItem,onClick:()=>{Ea(!1),ti(!0)},role:"menuitem",children:[t.jsx(Ac,{size:15}),"Edit Profile"]}),t.jsxs("button",{className:at.accountMenuItem,onClick:()=>{Ea(!1),p()},role:"menuitem",children:[t.jsx(bp,{size:15}),"Plans"]}),t.jsxs("button",{className:at.accountMenuItem,onClick:()=>{Ea(!1),yl("account_hub"),wo(!0)},role:"menuitem",children:[t.jsx(Ac,{size:15}),"Account Hub"]}),t.jsxs("button",{className:at.accountMenuItem,onClick:()=>{Ea(!1),vo(!0)},role:"menuitem",children:[t.jsx(xi,{size:15}),"Help & Tutorial"]}),Ze==="local"&&!Rt&&!Ld&&t.jsxs("button",{className:at.accountMenuItem,onClick:()=>{gc("login")},role:"menuitem",children:[t.jsx(Ac,{size:15}),"Sign In / Register"]}),Rt&&t.jsxs("button",{className:at.accountMenuItem,onClick:async()=>{Ea(!1),await Us()},role:"menuitem",children:[t.jsx(cg,{size:15}),"Sign Out"]})]})]}),Jp=a.useCallback(()=>{Q(i=>i==="show"?"collapse":i==="collapse"?"hide":"show")},[Q]),Xp=a.useCallback(()=>{ee(),S("tasks"),_("add")},[ee,_,S]),xh=a.useCallback(i=>{const f=e.workstreams.find(v=>v.id===i);ee(),q(to(f)||i),S("tasks"),_("add")},[e.workstreams,ee,_,S,q]),Qp=a.useCallback(i=>{fr(i),Wr(!1),Zs(null),vs(!1),Qa(""),gr(""),yr("");const f=i.entityType==="workstream"&&Rn&&ct.initiativeById.get(Rn)||null;ws(f?ar(f):""),Un(null)},[ct.initiativeById,Rn]),em=a.useCallback((i,f)=>{Zs(i),vs(!1),Qa(""),gr(""),yr("");const v=i.entityType==="workstream"&&((f?ct.initiativeById.get(f):null)||Rn&&ct.initiativeById.get(Rn))||null;ws(v?ar(v):""),Un(null)},[ct.initiativeById,Rn]),Ku=a.useCallback(()=>{fr(null),Qa(""),gr(""),yr(""),ws("")},[]),tm=a.useCallback(()=>{Zs(null),Qa(""),gr(""),yr(""),ws("")},[]),Ah=a.useCallback(async()=>{const i=hr||zr;if(!i)return;const f=!!hr,v=Li.trim()||null;try{if(i.entityType==="initiative")if(i.mode==="edit")await e.updateInitiative(i.targetId,{title:Ws.trim()||"Untitled Initiative",description:qo.trim()||null,ownerId:v}),Bs({type:"initiative",id:i.targetId}),Un(null),nt("Initiative updated","success");else{const ie=await e.createInitiative({title:Ws.trim()||"Untitled Initiative",description:qo.trim()||null,ownerId:v});Bs({type:"initiative",id:ie.id}),Un(null),nt("Initiative created","success")}else{const ie=Fs.trim(),ce=ie.length===0?null:cp(ct.initiatives,ie);if(ie.length>0&&!ce){nt("Initiative not found by that reference.","error");return}const Je={title:Ws.trim()||"Untitled Workstream",description:qo.trim()||null,ownerId:v,initiativeId:ce?.id||null};if(i.mode==="edit")await e.updateWorkstream(i.targetId,Je),f?Un(i.targetId):(Bs({type:"workstream",id:i.targetId}),Un(null)),nt("Workstream updated","success");else{const Ct=await e.createWorkstream(Je);f?Un(Ct.id):(Bs({type:"workstream",id:Ct.id}),Un(null)),nt("Workstream created","success")}}f?tm():Ku()}catch(ie){nt(ie instanceof Error?ie.message:"Failed to save planning item.","error")}},[Ku,tm,qo,Fs,Li,Ws,zr,hr,ct.initiatives,e,nt]),Th=a.useCallback(i=>{ls(f=>{const v=new Set(f);return v.has(i)?v.delete(i):v.add(i),v})},[]),Ih=a.useCallback(i=>{pr(f=>f===i?"":i),Fr("")},[]),Nh=a.useCallback((i,f)=>{Fr(v=>{const ie=v===i?"":i;return pr(ie&&f||""),ie})},[]),jh=a.useCallback(i=>{fr(null),Zs(null),Wr(!1),vs(!1),Bs(i?{type:"initiative",id:i}:null),Un(null)},[]),Rh=a.useCallback(i=>{fr(null),Zs(null),Wr(!1),vs(!1),Bs(i?{type:"workstream",id:i}:null),Un(null)},[]),Dh=a.useCallback(i=>{Zs(null),vs(!1),Un(i)},[]),Yu=a.useMemo(()=>{const i=new Map;return ht.forEach(f=>{i.set(f.label,String(f.value))}),i},[ht]),Ju=a.useCallback((i,f)=>{if(i==="workstream"&&f){em({mode:"create",entityType:"workstream"},f);return}if(Qp({mode:"create",entityType:i}),i==="workstream"){const v=(f?ct.initiativeById.get(f):null)||(Rn?ct.initiativeById.get(Rn):null)||null;ws(v?ar(v):"")}},[Qp,em,ct.initiativeById,Rn]),nm=a.useCallback((i,f)=>{if(i==="initiative"){const v=ct.initiativeById.get(f);if(!v)return;fr({mode:"edit",entityType:"initiative",targetId:f}),Qa(v.title),gr(v.description||""),yr(v.ownerLabel&&Yu.get(v.ownerLabel)||""),ws("")}else{const v=ct.workstreamById.get(f)||ct.standaloneWorkstreams.find(ce=>ce.id===f);if(!v)return;fr({mode:"edit",entityType:"workstream",targetId:f}),Qa(v.title),gr(v.description||""),yr(v.ownerLabel&&Yu.get(v.ownerLabel)||"");const ie=v.initiativeId&&ct.initiativeById.get(v.initiativeId)||null;ws(ie?ar(ie):"")}Un(null)},[Yu,ct.initiativeById,ct.standaloneWorkstreams,ct.workstreamById]),Ud=a.useCallback(async(i,f)=>{const v=e.workstreams.find(Ct=>Ct.id===i);if(!v){nt("Workstream not found.","error");return}const ie=typeof f=="string"?f.trim():f===null?"":Fs.trim(),ce=ie.length===0?null:cp(ct.initiatives,ie);if(ie.length>0&&!ce){nt("Initiative not found by that reference.","error");return}const Je=ce?.id||null;if((v.initiativeId||null)===Je){nt(Je?"Workstream already belongs to that initiative.":"Workstream is already standalone.","info");return}try{await e.updateWorkstream(i,{initiativeId:Je}),ws(ce?ar(ce):""),nt(Je?"Initiative set":"Initiative removed","success")}catch{nt("Failed to set initiative.","error")}},[Fs,ct.initiatives,e,nt]),Xu=a.useCallback(async(i,f)=>{const v=Jo.get(i);if(!v){nt("Task not found.","error");return}const ie=f||null;if(ct.initiativeById.has(i)||ct.workstreamById.has(i)){nt("Only execution tasks can be moved into workstreams.","error");return}if(ie&&!ct.workstreamById.has(ie)){nt("Workstream not found.","error");return}if((v.workstreamId||null)===ie){nt(ie?"Task already belongs to that workstream.":"Task is already standalone.","info");return}try{const ce=await fetch(`/api/taskforce/task/${i}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({workstreamId:ie})});if(!ce.ok){const Je=await ce.json().catch(()=>({}));nt(Je?.error||"Failed to set workstream.","error");return}await ce.json().catch(()=>null),await ot(!0),nt(ie?"Workstream set":"Workstream removed","success")}catch{nt("Failed to set workstream.","error")}},[ot,Jo,ct.initiativeById,ct.workstreamById,nt]),Ph=a.useCallback(async(i,f)=>{const v=f.trim();if(!v){nt("Enter a task reference.","error");return}const ie=wf(v),ce=Yo.find(Je=>Je.id===v||Rr(Je)===v||ie!==null&&Je.referenceNumber===ie);if(!ce){nt("Task not found by that reference.","error");return}await Xu(ce.id,i)},[Xu,Yo,nt]),Eh=a.useCallback(async(i,f)=>{const v=f.trim();if(!v){nt("Enter a workstream reference.","error");return}const ie=ct.initiativeById.get(i);if(!ie){nt("Initiative not found.","error");return}const ce=qf(v),Je=e.workstreams.find(Ct=>Ct.id===v||to(Ct)===v||ce!==null&&Ct.referenceNumber===ce);if(!Je){nt("Workstream not found by that reference.","error");return}await Ud(Je.id,ar(ie))},[Ud,ct.initiativeById,e.workstreams,nt]),am=a.useCallback(i=>{pr(i),Fr("")},[]),sm=a.useCallback(i=>{Fr(i),pr(i&&ct.workstreamInitiativeIds.get(i)||"")},[ct.workstreamInitiativeIds]),Qu=a.useCallback(i=>{const f=Ym(i,ds);if(f!==i){const v=ds.find(ie=>ie.id===i)?.label||"That module";nt(`${v} is not available in this build yet.`,"error");return}S(f)},[nt,S,ds]),rm=a.useCallback(()=>{if(ma==="tasks"&&Yn){$a(!1),Bs(null),Un(null),fr(null);return}if(ma!=="tasks"){S("tasks"),$a(!0);return}$a(i=>!i)},[Yn,ma,S]),Lh=a.useCallback(i=>{S("tasks"),yn(i)},[yn,S]),Mh=a.useCallback((i,f)=>{$r(i),Ho(f?.sessionId??null),Kl(v=>v+1),S("annotate")},[S]),Bh=a.useCallback(({target:i,sessionId:f})=>{$r(v=>!v&&!i||v&&i&&v.taskId===i.taskId&&v.taskReferenceLabel===i.taskReferenceLabel&&v.assetId===i.assetId&&v.imageReferenceLabel===i.imageReferenceLabel&&v.path===i.path&&v.displayName===i.displayName?v:i),Ho(v=>v===f?v:f)},[]),om=a.useMemo(()=>[{value:"created",label:xe("standalone.sortCreated")},{value:"updated",label:xe("standalone.sortUpdated")},{value:"priority",label:xe("standalone.sortPriority")},{value:"complexity",label:xe("standalone.sortComplexity")},...Vf(an,[...e.searchAgnosticTasks,...ba])],[ba,e.searchAgnosticTasks,an]),im=a.useMemo(()=>[{value:"category",label:xe("standalone.groupCategory")},{value:"type",label:xe("standalone.groupType")},{value:"priority",label:xe("standalone.groupPriority")},{value:"complexity",label:xe("standalone.groupComplexity")},{value:"assignee",label:xe("standalone.groupAssignee")},{value:"status",label:xe("standalone.groupStatus")},{value:"schedule",label:xe("standalone.groupSchedule")}],[]),cm=a.useMemo(()=>ds.filter(i=>i.enabled),[ds]),lm=a.useMemo(()=>[{key:"empty-columns",icon:W==="show"?t.jsx(um,{size:16}):W==="collapse"?t.jsx(pm,{size:16}):t.jsx(lg,{size:16}),title:xe(W==="show"?"standalone.showEmptyColumns":W==="collapse"?"standalone.compressEmptyColumns":"standalone.hideEmptyColumns"),onClick:Jp,active:W!=="show"},{key:"compressed-cards",icon:ys?t.jsx(rf,{size:16}):t.jsx(dg,{size:16}),title:xe(ys?"standalone.expandCards":"standalone.compressCards"),onClick:()=>Lc(!ys),active:ys}],[ys,Jp,W]),Wh=a.useMemo(()=>[{key:"filter-toggle",icon:t.jsx(of,{size:16}),title:xe("standalone.toggleFilters"),onClick:()=>$o(!dr),active:dr,className:zd?u.filterGlow:""}],[zd,$o,dr]),Fh=a.useMemo(()=>{switch(er.filterBar.kind){case"task-filters":return t.jsx(YP,{categoryFilterOptions:$c,typeFilterOptions:Uc,priorities:Xt,taxonomyDisplayLabels:Gn,filterCategories:vt,setFilterCategories:Ot,filterTypes:it,setFilterTypes:It,filterPriorities:wt,setFilterPriorities:_n,filterStatus:V,setFilterStatus:ne,filterAssignees:Dn,setFilterAssignees:Jn,assigneeOptions:ht,initiativeFilterOptions:qc,selectedInitiativeId:Rn,setSelectedInitiativeId:am,workstreamFilterOptions:Gi,selectedWorkstreamId:un,setSelectedWorkstreamId:sm,taskScope:gt,setTaskScope:Xn,showArchive:kr,setShowArchive:zi,fetchArchive:Oi,onDeleteAllDeleted:()=>{const i=qa.length;i===0||!window.confirm(`Permanently delete ${i} deleted task${i===1?"":"s"}? This cannot be undone.`)||Qe()},clearFilters:()=>{Ee(),pr(""),Fr("")}});case"document-filters":return t.jsx(JP,{typeFilters:Ua,setTypeFilters:bn,attachmentFilters:In,setAttachmentFilters:es,clearFilters:()=>{bn(nu.map(i=>i.value)),es(au.map(i=>i.value))}});default:return t.jsx(ZP,{})}},[ht,$c,Ee,qa.length,In,Ua,Dn,vt,wt,V,it,am,sm,qc,Xt,Rn,un,es,bn,Jn,Ot,_n,ne,It,pr,Fr,zi,Xn,kr,gt,Gn,Uc,Gi,er.filterBar.kind,Oi,Qe]),zh=a.useMemo(()=>[{key:"zen-toggle",icon:t.jsx(ug,{size:16,fill:z?"currentColor":"none"}),title:xe(z?"standalone.exitZenMode":"standalone.enterZenMode"),onClick:()=>K(),active:z}],[z,K]),Oh=a.useMemo(()=>({search:t.jsx(GP,{value:et,placeholder:xe("standalone.searchPlaceholder"),active:Sl,onChange:_t,onClear:()=>_t(""),clearTitle:xe("standalone.clearSearchTitle")}),sort:t.jsx(Hm,{label:t.jsxs(t.Fragment,{children:[t.jsx(pg,{size:12})," ",xe("standalone.sortLabel")]}),value:se,options:om,onChange:i=>He(i),trailingAction:t.jsx("button",{className:`tf-control-icon ${u.sortDirectionBtn}`,onClick:()=>e.toggleSortOrder(),title:e.sortOrder==="desc"?xe("standalone.sortDirectionDescTitle"):xe("standalone.sortDirectionAscTitle"),children:e.sortOrder==="desc"?t.jsx(tf,{size:14}):t.jsx(nf,{size:14})})}),"divider-primary":t.jsx(Gm,{}),grouping:t.jsx(Hm,{label:t.jsxs(t.Fragment,{children:[t.jsx(bp,{size:12})," ",xe("standalone.groupLabel")]}),value:k,options:im,onChange:i=>b(i)}),"divider-secondary":t.jsx(Gm,{}),"task-display-actions":t.jsx(hp,{actions:lm})}),[k,im,Qu,Sl,e,et,b,_t,He,se,om,lm,er.moduleId]),$h=a.useMemo(()=>({"add-task":t.jsx(VP,{icon:t.jsx(sr,{size:16}),label:xe("standalone.addTask"),onClick:Xp}),"add-document":null}),[Xp]),xl=a.useMemo(()=>{const i={tasks:t.jsx(kg,{size:18}),docs:t.jsx(_p,{size:18}),annotate:t.jsx(yg,{size:18}),workflows:t.jsx(gg,{size:18}),agents:t.jsx(Xd,{size:18})};return t.jsxs("aside",{className:hn.workspaceToolRail,"aria-label":"Workspace tools",children:[t.jsxs("div",{className:hn.workspaceToolRailMain,children:[t.jsx("button",{type:"button",className:`${hn.workspaceToolButton} ${ma==="tasks"&&Yn?hn.workspaceToolButtonActive:""}`.trim(),onClick:rm,title:ma==="tasks"&&Yn?"Collapse planning trays":"Planning","aria-label":ma==="tasks"&&Yn?"Collapse planning trays":"Planning",children:ma==="tasks"&&Yn?t.jsx(Tc,{size:18}):t.jsx(mg,{size:18})}),t.jsx("div",{className:hn.workspaceToolRailDivider}),cm.map(f=>t.jsx("button",{type:"button",className:`${hn.workspaceToolButton} ${ma===f.id?hn.workspaceToolButtonActive:""}`.trim(),onClick:()=>Qu(f.id),title:f.label,"aria-label":f.label,children:i[f.id]},f.id))]}),t.jsxs("div",{className:hn.workspaceToolRailBottom,children:[t.jsx("div",{className:hn.workspaceToolRailDivider}),t.jsx("button",{type:"button",className:`${hn.workspaceToolButton} ${C==="settings"?hn.workspaceToolButtonActive:""}`.trim(),onClick:()=>{ft("general"),_("settings")},title:"Workspace Settings","aria-label":"Workspace Settings",children:t.jsx(af,{size:18})})]})]})},[C,Qu,rm,Yn,ma,ft,_,cm]),ep=a.useRef(null),Uh=t.jsx(hL,{open:Yn,leftOffset:56,initiatives:ct.initiatives,standaloneWorkstreams:ct.standaloneWorkstreams,activeInitiativeId:Rn,activeWorkstreamId:un,expandedInitiativeIds:Ms,detail:Vi,editor:zr,secondaryPane:Ki,assigneeOptions:ht.map(i=>({value:String(i.value),label:i.label})),draftInitiativeSummary:Hc,draftTitle:Ws,draftDescription:qo,draftOwner:Li,draftInitiativeId:Fs,onChangeDraftTitle:Qa,onChangeDraftDescription:gr,onChangeDraftOwner:yr,onChangeDraftInitiativeId:ws,onCollapseTreePane:()=>ur(!0),onExpandTreePane:()=>ur(!1),onCollapsePrimaryPane:()=>Wr(!0),onExpandPrimaryPane:()=>Wr(!1),onCollapseSecondaryPane:()=>vs(!0),onExpandSecondaryPane:()=>vs(!1),onBackFromSecondary:()=>{Zs(null),Un(null)},treeCollapsed:cs,primaryCollapsed:Br,secondaryCollapsed:Vs,onCancelEditor:Ku,onSubmitEditor:Ah,onCreateInitiative:()=>Ju("initiative"),onCreateWorkstream:()=>Ju("workstream"),onCreateTaskInWorkstream:xh,onCreateWorkstreamInInitiative:i=>Ju("workstream",i),onAssignInitiativeToWorkstream:Ud,onOpenTaskById:yn,onAttachTaskToWorkstreamByReference:Ph,onAttachWorkstreamToInitiativeByReference:Eh,onToggleInitiative:Th,onSelectInitiative:Ih,onSelectWorkstream:Nh,onOpenInitiativeDetails:jh,onOpenWorkstreamDetails:Rh,onOpenNestedWorkstreamDetails:Dh,onEditInitiative:i=>nm("initiative",i),onEditWorkstream:i=>nm("workstream",i),onArchiveInitiative:i=>{e.archiveInitiative(i).then(()=>{nt("Initiative archived","success")}).catch(f=>{nt(f instanceof Error?f.message:"Failed to archive initiative.","error")})},onUnarchiveInitiative:i=>{e.unarchiveInitiative(i).then(()=>{nt("Initiative unarchived","success")}).catch(f=>{nt(f instanceof Error?f.message:"Failed to unarchive initiative.","error")})},onArchiveWorkstream:i=>{e.archiveWorkstream(i).then(()=>{nt("Workstream archived","success")}).catch(f=>{nt(f instanceof Error?f.message:"Failed to archive workstream.","error")})},onUnarchiveWorkstream:i=>{e.unarchiveWorkstream(i).then(()=>{nt("Workstream unarchived","success")}).catch(f=>{nt(f instanceof Error?f.message:"Failed to unarchive workstream.","error")})}}),qh=er.headerSections.map(i=>{const f=Oh[i];return f?t.jsx(pt.Fragment,{children:f},i):null}).filter(Boolean),Hh=er.primaryAction?$h[er.primaryAction]:null;return t.jsxs("div",{className:`${hn.standaloneWrapper} ${z?u.zenModeEnabled:""}`,"data-theme":tt,children:[t.jsx(HP,{projectName:Oa,currentWorkspaceId:en,runtimeMode:Ze,theme:tt,meta:c?null:t.jsxs(t.Fragment,{children:[t.jsx("span",{className:u.taskCountBadge,title:Vu,children:Gu}),us&&us!=="anonymous"&&t.jsxs(t.Fragment,{children:[t.jsxs("span",{className:u.taskCountBadge,title:"Open tasks assigned to you",children:["Mine ",Qo]}),t.jsxs("span",{className:u.taskCountBadge,title:"Your open tasks with overdue due dates",children:["Overdue ",rd]})]}),Zu&&t.jsx("button",{className:"tf-control-icon",onClick:()=>ec(!0),title:`Sync manager: ${Wa.label} | Last success: ${kc}`,style:{marginLeft:"6px",height:"24px",width:"24px",padding:0,borderRadius:"999px",border:`1px solid ${Wa.border}`,background:Wa.background,color:Wa.color,display:"inline-flex",alignItems:"center",justifyContent:"center"},children:Wa.icon==="off"?t.jsx(fg,{size:16}):t.jsx(hg,{size:16})})]}),actions:t.jsxs(t.Fragment,{children:[c&&t.jsx("button",{className:"tf-control-icon",onClick:w,title:"Back",children:"Back"}),!c&&t.jsxs(t.Fragment,{children:[qh,Hh]}),!c&&t.jsx(hp,{actions:zh}),!c&&t.jsx(hp,{actions:Wh}),Ch]})}),t.jsx(fh,{notice:ke,onDismiss:$e}),Wt&&t.jsx("div",{className:ve.authBlockedBanner,children:"Authentication required for this environment. Use the Account menu to sign in."}),!c&&dr&&Fh,c?t.jsx("div",{className:`${hn.standalonePage} ${hn.standaloneContent} ${u.appScrollbar} tf-scrollbar`,style:{position:"relative",display:"flex",flex:1,minHeight:0,overflowY:"auto",overflowX:"hidden",scrollbarGutter:"stable"},children:t.jsx(a.Suspense,{fallback:t.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",flex:1},children:t.jsx(Fa,{size:20,className:u.spinner})}),children:t.jsx(VL,{...e,currentTheme:tt,projectName:Oa,currentWorkspaceId:en,apiBaseUrl:Pd,connectedEnvironmentSource:e.config?.cloudAuthBaseUrl||e.config?.apiBaseUrl||"",embedded:!0,shellOwnsScroll:!0})})}):ma==="docs"&&Zo?t.jsxs("div",{className:`${hn.standalonePage} ${hn.standaloneContent}`,style:{position:"relative",display:"flex",flex:1,minHeight:0,overflow:"hidden",paddingLeft:"56px"},children:[xl,t.jsx(a.Suspense,{fallback:t.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",flex:1},children:t.jsx(Fa,{size:20,className:u.spinner})}),children:t.jsx(qL,{tasks:D,runtimeMode:Ze,apiBaseUrl:e.config?.apiBaseUrl||"",cloudAuthBaseUrl:e.config?.cloudAuthBaseUrl||"",typeFilters:Ua,attachmentFilters:In,onTypeFiltersChange:bn,onAttachmentFiltersChange:es,requestedDocPath:Mi,requestedDocAssetId:na,onRequestedDocHandled:()=>{Or(null),Wc(null)},enableTaskGeneration:!0})})]}):ma==="annotate"&&Oc?t.jsxs("div",{className:`${hn.standalonePage} ${hn.standaloneContent}`,style:{position:"relative",display:"flex",flex:1,minHeight:0,overflow:"hidden",paddingLeft:"56px"},children:[xl,t.jsx(a.Suspense,{fallback:t.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",flex:1},children:t.jsx(Fa,{size:20,className:u.spinner})}),children:t.jsx(UL,{runtimeMode:Ze,apiBaseUrl:e.config?.apiBaseUrl||"",cloudAuthBaseUrl:e.config?.cloudAuthBaseUrl||"",workspaceId:en,sessionLoadReady:ho,requestedTarget:wa,requestedSessionId:Ks,requestedOpenVersion:wu,resolveTaskReferenceLabel:ed,resolveImageReferenceLabel:td,onOpenTarget:Mh,onContextChange:Bh,onBackToTask:Lh})})]}):ma==="workflows"?t.jsxs("div",{className:`${hn.standalonePage} ${hn.standaloneContent}`,style:{position:"relative",display:"flex",flex:1,minHeight:0,overflow:"hidden",paddingLeft:"56px"},children:[xl,t.jsx(a.Suspense,{fallback:t.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",flex:1},children:t.jsx(Fa,{size:20,className:u.spinner})}),children:t.jsx(HL,{availableWorkflows:Gt,availableEnvironments:gs,exportEnvironment:la,exportWorkflowsPath:e.exportWorkflowsPath,exportingResource:qe,exportResult:ir,onExportEnvironmentChange:e.setExportEnvironment,onExportWorkflows:Pa,onRefreshWorkflows:va,onFetchWorkflowTemplate:e.fetchWorkflowTemplate,onFetchWorkflowOverrideNames:e.fetchWorkflowOverrideNames,onSaveWorkflowTemplateDraft:e.saveWorkflowTemplateDraft,onResetWorkflowTemplateDraft:e.resetWorkflowTemplateDraft})})]}):ma==="agents"?t.jsxs("div",{className:`${hn.standalonePage} ${hn.standaloneContent}`,style:{position:"relative",display:"flex",flex:1,minHeight:0,overflow:"hidden",paddingLeft:"56px"},children:[xl,t.jsx(a.Suspense,{fallback:t.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",flex:1},children:t.jsx(Fa,{size:20,className:u.spinner})}),children:t.jsx(GL,{workspaceId:en})})]}):t.jsxs("div",{className:`${hn.standalonePage} ${hn.standaloneContent} `,style:{position:"relative",opacity:e.loadingTasks?.7:1,transition:"opacity 0.2s ease, padding 220ms cubic-bezier(0.4, 0, 0.2, 1)",display:"flex",flex:1,minHeight:0,paddingLeft:Yn?`${56+ad+6}px`:"62px",paddingRight:k==="schedule"&&Gs?`${Ep}px`:0},children:[xl,t.jsx("div",{ref:ep,style:{position:"absolute",inset:0,zIndex:35,pointerEvents:"none"}}),t.jsxs("div",{style:{position:"relative",width:"100%",minWidth:0,flex:1,minHeight:0,display:"flex",flexDirection:"column",overflow:"hidden"},children:[e.loadingTasks&&yo.length>0&&t.jsx("div",{className:u.boardRefreshIndicator,"aria-live":"polite","aria-label":"Refreshing tasks",children:t.jsx(Fa,{size:14,className:u.spinner})}),t.jsx(WP,{tasks:sd,allTasks:[],columns:Yp,groupBy:k,scheduleDates:tr,searchQuery:et,filterCategories:vt,filterTypes:it,filterPriorities:wt,filterStatus:V,filterAssignees:Dn,assigneeOptions:ht,scheduleFilteredTaskIds:Array.from(nd),copiedId:Se,taxonomies:an,types:kn,priorities:Xt,onUpdateTask:be,onTaskClick:i=>Ae(i),onOpenTaskById:yn,onCopyId:Mt,onToggleInProgress:Qt,onToggleReview:Ge,onToggleComplete:zt,onToggleCancel:An,onSetStatus:Xi,onArchiveTask:J,onAddTaskToColumn:Vc,showTaskCardStatusLabel:le,onScheduleDaySelected:i=>{Mc(i);const f=El(i);f&&Mr(`${f.getFullYear()}-${String(f.getMonth()+1).padStart(2,"0")}`)},persistedScrollLeft:k==="schedule"?Oo:void 0,onScrollLeftChange:i=>{k==="schedule"&&Xa(i)},emptyColumnMode:W,categories:y,compressed:ys,readOnlyMode:gt==="deleted"?"deleted":gt==="archived"?"archived":null,recentlyChangedTaskIds:e.recentlyChangedTaskIds,sortBy:se,sortOrder:e.sortOrder,planningDropTargets:ep.current?Ci.createPortal(Uh,ep.current):null,onAssignTaskToWorkstream:Xu,onAssignWorkstreamToInitiative:Ud,workstreams:e.workstreams,initiatives:e.initiatives,onUnarchive:i=>{if(gt==="deleted"){const f=$i.get(i);if(!f)return;Ie(f.id);return}we(i)},onDelete:i=>{if(gt==="deleted"){const f=$i.get(i);if(!f||!window.confirm("Permanently delete this task? This cannot be undone."))return;We(f.id);return}_e(i)}},`${k}-${Yp.map(i=>String(i.value)).join("|")}-${tr.mon}`),k==="schedule"&&!Gs&&t.jsx("button",{type:"button",className:"tf-control-icon",onClick:()=>{Bs(null),Ss(!0)},title:"Show Schedule Sidebar",style:{position:"absolute",top:"10px",right:"10px",zIndex:20},children:t.jsx(Tc,{size:16})})]}),k==="schedule"&&t.jsx(zL,{open:Gs,onClose:()=>Ss(!1),scheduleSelectedDate:Lr,setScheduleSelectedDate:Mc,scheduleCalendarMonth:Bc,setScheduleCalendarMonth:Mr,scheduleShowWeekends:ks,setScheduleShowWeekends:zo,scheduleShowBacklog:lr,setScheduleShowBacklog:Pi,scheduleOnlyExpired:Hs,setScheduleOnlyExpired:Zl,expiredScheduledCount:_u,overdueDueCount:Gc,expiredLeafCandidates:ei,expiredRecoveryCandidates:ko,onMoveExpiredToSelectedWeek:wh,onMoveExpiredToBacklog:bh,scheduleBulkBusy:Sr,globalWeekStartsOn:Sn,resolvedLocale:ta,todayDateOnly:ua,scheduleBaseTasks:qi,scheduleWeekStart:Os,scheduleWeekLabel:_h})]}),t.jsxs(oo,{isOpen:C==="add",onClose:Ji,title:me?Ls?.isDeleted?"Deleted Task":"Edit Task":"New Task",size:Uo?"full":"xl",theme:tt,headerActions:t.jsx("button",{className:"tf-control-icon",onClick:()=>Ei(i=>!i),title:Uo?"Exit full screen":"Enter full screen","aria-label":Uo?"Exit full screen":"Enter full screen",children:Uo?t.jsx(pm,{size:18}):t.jsx(um,{size:18})}),draggable:!Uo,closeOnOverlayClick:!1,children:[t.jsx(mh,{editingTaskId:me,loading:Y,autoSaveState:qn,title:B,currentTask:Ls,currentTaskWorkstream:Vl,currentTaskInitiative:Di,workstreamInput:G,onWorkstreamInputChange:q,onSetWorkstreamForCurrentTask:gn,handleSubmit:U,resetForm:ee,handleCopyId:Mt,copiedId:Se,tasks:D,handleToggleInProgress:Qt,handleToggleReview:Ge,handleToggleComplete:zt,handleToggleCancel:An,handleSetStatus:Xi,handleArchiveTask:J,handleRestoreDeletedTask:Ls?.deletedRecordId?i=>{Ie(i)}:void 0,handlePermanentlyDeleteDeletedTask:Ls?.deletedRecordId?i=>{window.confirm("Permanently delete this task? This cannot be undone.")&&(We(i),ee(),_("tasks"))}:void 0}),t.jsx(ph,{editingTaskId:me,error:R,title:B,description:Ne,checklistItems:ae,category:Re,type:Fe,priority:L,complexity:Z,manualComplexityEnabled:ye,approach:A,assignee:j,scheduledDate:O,dueDate:re,workstreamInput:G,formTaxonomies:ze,onTaxonomyChange:(i,f)=>Ye(v=>({...v,[i]:f})),taxonomies:an,comments:Xe,newCommentText:bt,contextFiles:rt,currentWorkspaceId:en,apiBaseUrl:Dd,descriptionFocused:Ke,showMarkdownHelp:Lt,showChecklist:Zt,checklistEnabled:Be,showComments:on,categories:y,types:kn,priorities:Xt,taxonomyDisplayLabels:Gn,assigneeOptions:ht,workstreams:e.workstreams,copiedId:Se,onTitleChange:fe,onDescriptionChange:de,onChecklistItemsChange:Ve,onCategoryChange:Ce,onTypeChange:x,onPriorityChange:P,onComplexityChange:M,onApproachChange:i=>{H(i),Ye(f=>({...f,approach:i}))},onAssigneeChange:je,onScheduledDateChange:ue,onDueDateChange:pe,onWorkstreamInputChange:q,onNewCommentTextChange:d,onDescriptionFocusedChange:St,onShowMarkdownHelpChange:xt,onShowChecklistChange:Jt,onShowCommentsChange:cn,onOpenSettings:i=>{ft(i),_("settings")},onSubmit:U,commentsEndRef:Ja,onAddComment:()=>nn(bt),onOpenTaskById:yn,onAddContextFile:i=>{let f=rt;mt(v=>(f=[...v,i],f)),F(!0),me&&be(me,{attachments:f})},onRemoveContextFile:async i=>{let f=rt;mt(v=>(f=v.filter((ie,ce)=>ce!==i),f)),F(!0),me&&be(me,{attachments:f})},onUpdateContextCaption:(i,f)=>{let v=rt;mt(ie=>(v=ie.map((ce,Je)=>Je!==i?ce:typeof ce=="string"?{path:ce,caption:f,timestamp:new Date().toISOString()}:{...ce,caption:f}),v)),F(!0),me&&be(me,{attachments:v})},onCopyId:Mt,onToggleInProgress:Qt,onToggleReview:Ge,onToggleComplete:zt,onToggleCancel:An,onSetStatus:Xi,onArchiveTask:J,onUnarchive:i=>{if(Ls?.isDeleted){const f=$i.get(i);if(!f)return;Ie(f.id);return}we(i)},currentTask:Ls})]}),t.jsx(oo,{isOpen:C==="settings",onClose:Ji,title:"Settings",size:"xl",theme:tt,draggable:!0,isSettings:!0,closeOnOverlayClick:!1,children:t.jsx(a.Suspense,{fallback:t.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"2rem"},children:t.jsx(Fa,{size:20,className:u.spinner})}),children:t.jsx($L,{settingsModel:De,onSectionChange:ft})})}),t.jsx(VD,{prompt:Fo,theme:tt,onClose:vu,onConfirm:cr}),t.jsx(GD,{isOpen:od,theme:tt,onClose:()=>vo(!1),onOpenSettings:()=>{vo(!1),_("settings"),ft("general")}}),t.jsx(HD,{isOpen:Zc,theme:tt,onClose:Md,onSave:()=>{Fu()},displayName:cl,email:pi,avatarDisplayUrl:Nd,accountBadgeInitial:hl,avatarInputRef:uc,avatarAccept:ZL,avatarDraftId:ss,saveBusy:Eu,avatarBusy:Pu,saveError:xd,saveNotice:Lu,onDisplayNameChange:_d,onAvatarInputChange:i=>{fi(i)},onStartAvatarUpload:()=>uc.current?.click(),onDiscardUpload:Bd,onRemovePhoto:Wu}),t.jsx(qD,{isOpen:vr,theme:tt,runtimeMode:Ze,authRequiredForApi:$t,isAuthenticated:Rt,hasAuthIdentity:fl,authIdentityLabel:mi,billingLoading:Ao,billingError:To,billingActionError:Ru,billingNotice:bd,billingActionBusy:Gr,billingIntervalChoice:Io,billingStatus:Cs,currentWorkspaceId:en,canOpenTeamManagement:mc,canManageWorkspaceSync:di,workspaceCloudSyncEnabled:Wn,syncStatusLabel:Wa.label,workspaceSyncError:Kc,syncControlBusy:pc,onClose:()=>wo(!1),onOpenWorkspaceAudit:()=>{wo(!1),Wd(),_o("audit")},onBillingIntervalChange:Du,onRefreshBilling:()=>{Zr()},onUpdateInterval:()=>{$u()},onManageBilling:()=>{Ou()},onStartCheckout:()=>{zu()},onToggleWorkspaceSync:i=>{pl(i)},onOpenHelp:()=>{wo(!1),vo(!0)}}),t.jsx(BP,{isOpen:nl,theme:tt,teamPlanMode:_s,teamMgmtError:si,teamManagementTab:hd,teamUsersLoading:ic,teamUsers:xo,teamActionBusyUserId:cc,teamInviteFeedback:Tu,teamInviteEmail:Js,teamInviteRole:ii,teamInvitePermissionMode:dc,teamInviteBusy:Au,pendingInvites:qu,teamAuditLoading:Nu,teamAuditEvents:ju,teamAuditPage:qr,teamAuditPages:wd,teamAuditHasMore:ci,onClose:()=>sc(!1),onOpenMembersTab:()=>{_o("members"),Kr()},onOpenInvitesTab:()=>_o("invites"),onOpenAuditTab:()=>{_o("audit"),Qs(qr)},onMemberRoleChange:(i,f)=>{gi(i,async()=>fetch(`/api/taskforce/admin/users/${encodeURIComponent(i)}/role`,{method:"PATCH",headers:{"Content-Type":"application/json",...Ba()},credentials:"include",body:JSON.stringify({workspaceId:Cr,role:f})}))},onMemberPermissionChange:(i,f)=>{gi(i,async()=>fetch(`/api/taskforce/admin/users/${encodeURIComponent(i)}/permission-mode`,{method:"PATCH",headers:{"Content-Type":"application/json",...Ba()},credentials:"include",body:JSON.stringify({workspaceId:Cr,mode:f})}))},onToggleMemberDisabled:(i,f)=>{gi(i,async()=>fetch(`/api/taskforce/admin/users/${encodeURIComponent(i)}/disable`,{method:"PATCH",headers:{"Content-Type":"application/json",...Ba()},credentials:"include",body:JSON.stringify({workspaceId:Cr,disabled:f})}))},onRevokeInvite:i=>{gi(i,async()=>fetch(`/api/taskforce/admin/users/${encodeURIComponent(i)}/invite/revoke`,{method:"POST",headers:{"Content-Type":"application/json",...Ba()},credentials:"include",body:JSON.stringify({workspaceId:Cr})}))},onRemoveMember:i=>{gi(i,async()=>fetch(`/api/taskforce/admin/users/${encodeURIComponent(i)}?workspaceId=${encodeURIComponent(Cr)}`,{method:"DELETE",headers:Ba(),credentials:"include"}))},onInviteEmailChange:Xs,onInviteRoleChange:al,onInvitePermissionModeChange:xu,onSubmitInvite:()=>{Uu()},onLoadAuditPrevious:()=>{Qs(qr-1)},onLoadAuditNext:()=>{Qs(qr+1)}}),t.jsx(UD,{isOpen:Cu,theme:tt,onClose:()=>tl(!1),onConfirm:()=>hi({intent:"create-workspace"})}),t.jsx(MP,{isOpen:Qi,theme:tt,currentWorkspaceLabel:ml,syncStatusMeta:Wa,workspaceCloudSyncEnabled:Wn,syncControlBusy:pc,canManageWorkspaceSync:di,workspaceSyncSummary:Yt,workspaceSyncRepairBusy:wr,referenceMismatchCount:Bt,syncStageLabel:$,workspaceSyncPendingChanges:xn,formattedLastSyncTime:kc,formattedLastPullTime:bl,formattedLastPushTime:_l,syncLastError:m,workspaceSyncDiagnostics:te,activeReferenceMismatchSummaries:tn,syncDiagnosticsSummary:he,syncEventRows:Ut,syncEventsListRef:Qc,workspaceSyncRepairQueued:ni,workspaceSyncBusy:jn,workspaceSyncCopied:Jc,runtimeMode:Ze,isAuthenticated:Rt,onClose:()=>ec(!1),onToggleWorkspaceSync:i=>{pl(i)},onRepairSync:Ln,onCopyReport:()=>{Is()},onOpenLogin:()=>{gc("login")},onRetrySync:()=>{ka()}}),En&&Ci.createPortal(t.jsx("div",{className:`${ut.overlay} ${ut.unsavedOverlay}`,style:{zIndex:2e3},children:t.jsxs("div",{className:`tf-surface-modal tf-modal-shell ${ut.modal} ${ut.unsavedModal}`,"data-theme":tt,children:[t.jsx("div",{className:`tf-modal-header ${ut.unsavedHeader}`,children:t.jsxs("div",{className:`tf-modal-title ${ut.unsavedTitle}`,children:[t.jsx(Rc,{size:20}),"Unsaved Changes"]})}),t.jsx("div",{className:`${ut.form} ${ut.unsavedContent}`,children:t.jsx("p",{className:ut.unsavedText,children:"You have unsaved changes. Would you like to save them?"})}),t.jsxs("div",{className:`${ut.formActions} ${ut.unsavedActions}`,children:[t.jsx("button",{className:u.cancelBtn,onClick:()=>os(!1),title:"Close dialog and continue editing",children:"Keep Editing"}),t.jsx("button",{className:u.destructiveBtn,onClick:Er,title:"Discard unsaved changes and leave",children:"Discard"}),t.jsxs("button",{className:u.submitBtn,onClick:is,disabled:Y,title:"Save changes and leave",children:[Y?t.jsx(Fa,{size:16,className:u.spinner}):t.jsx(sf,{size:16}),"Save"]})]})]})}),document.body),Ft&&Ci.createPortal(t.jsx("div",{className:zn.overlay,children:t.jsxs("div",{className:zn.browser,children:[t.jsxs("div",{className:zn.header,children:[t.jsxs("div",{className:zn.pathInfo,children:[t.jsx(Ai,{size:14}),t.jsx("span",{children:wn||"Project Root"})]}),t.jsxs("div",{className:zn.actions,children:[wn&&t.jsx("button",{className:u.helpLink,onClick:()=>{const i=wn.split("/").filter(Boolean);i.pop(),ia(i.length?i.join("/")+"/":"")},children:"Back"}),t.jsx("button",{className:u.helpLink,onClick:()=>Tt(!1),children:"Close"})]})]}),t.jsxs("div",{className:zn.list,children:[ga&&typeof ga=="object"&&t.jsxs("div",{className:`${zn.item} ${zn.itemFile} ${zn.itemCurrent}`,onClick:()=>Kn(wn),children:[t.jsx(so,{size:14})," Select Current: ./",wn||"(root)"]}),Tn.map(i=>t.jsxs("div",{className:zn.item,onClick:()=>ia(wn+i+"/"),children:[t.jsx(Ai,{size:14})," ",i,"/"]},i)),dt.map(i=>t.jsxs("div",{className:`${zn.item} ${zn.itemFile}`,onClick:()=>Kn(wn+i),children:[t.jsx(_p,{size:14})," ",i]},i)),Tn.length===0&&dt.length===0&&t.jsx("div",{className:`${zn.item} ${zn.empty}`,children:"No items found"})]})]})}),document.body)]})}function nM(e){const n=e.setupState,s=e.runtimeMode,r=e.isAuthenticated,o=!!(n&&s==="cloud"&&r&&n.globalSetupState==="missing"),l=!!(n&&s==="local"&&n.globalSetupState==="missing"),c=!!(n&&s==="cloud"&&r&&n.workspaceSetupState==="missing"),p=!!(n&&s==="local"&&n.workspaceSetupState==="missing"),g=!!(n&&(n.forceSetup||n.forceGlobalSetup||n.forceWorkspaceSetup||o||c||l||p));if(!g)return{setupGateActive:!1,needsGlobalSetup:!1,needsWorkspaceSetup:!1,hasSetupReadError:!1,phase:"ready"};const w=!!(n&&(n.forceSetup||n.forceGlobalSetup||o||l)),C=!!(n&&(n.forceSetup||n.forceWorkspaceSetup||c||p)),_=!!(w&&n?.globalSetupState==="missing"),y=!!(C&&n?.workspaceSetupState==="missing"),k=!!(w&&n?.globalSetupState==="unreadable"),b=!!(C&&n?.workspaceSetupState==="unreadable"),E=k||b;return{setupGateActive:g,needsGlobalSetup:_,needsWorkspaceSetup:y,hasSetupReadError:E,phase:E?"setup-read-error":_?"needs-global-setup":y?"needs-workspace-setup":"ready"}}const vp="/taskforce/assets/taskforce-BxLPokNB.png";function Xm(e){return{categories:!!e?.categories?.length,types:!!e?.types?.length,priorities:!!e?.priorities?.length}}function Qm({config:e={},initialTaskId:n,onTaskCountChange:s,onHeaderMouseDown:r,isDragging:o,onClose:l,mode:c="standalone"}){const p=hf(),g=a.useMemo(()=>new URLSearchParams(p.search),[p.search]),w=String(g.get("planId")||"").trim(),C=String(g.get("planVersionId")||"").trim(),_=String(g.get("interval")||"").trim(),y=p.pathname==="/pricing",k=p.pathname==="/plans",b=p.pathname==="/"&&String(g.get("screen")||"").trim().toLowerCase()==="plans",E="/?screen=plans&gate=plan_selection_required",S=ff(),[W,Q]=a.useState(""),[z,K]=a.useState(""),[V,ne]=a.useState(""),[D,Ae]=a.useState("login"),[U,ee]=a.useState(""),[be,me]=a.useState(""),[Y,R]=a.useState(""),[B,fe]=a.useState(null),[Ne,de]=a.useState(null),[ae,Ve]=a.useState("unknown"),[Re,Ce]=a.useState(!1),[Fe,x]=a.useState(null),[L,P]=a.useState(null),[Z,M]=a.useState(null),[h,A]=a.useState(!1),[H,j]=a.useState(0),[je,O]=a.useState(0),[ue,re]=a.useState(()=>Date.now()),[pe,G]=a.useState("core"),[q,ye]=a.useState(!1),[Be,le]=a.useState(null),[ze,Ye]=a.useState(null),[Xe,bt]=a.useState(""),[d,rt]=a.useState(""),[mt,F]=a.useState("local"),[Ke,St]=a.useState([]),[Lt,xt]=a.useState(""),[Zt,Jt]=a.useState(!1),[on,cn]=a.useState(null),[nn,gn]=a.useState(!1),yn=a.useMemo(()=>Hf(),[]),[an,kn]=a.useState(yn),[Xt,Gn]=a.useState(()=>yn.find(oe=>oe.isDefaultStarter)?.id||yn[0]?.id||""),[At,Se]=a.useState(()=>Xm(yn.find(oe=>oe.isDefaultStarter)||yn[0]||null)),[Mt,Qt]=a.useState(!1),[zt,Ge]=a.useState(null),[An,J]=a.useState(!1),[_e,we]=a.useState(null),Ie=SS({config:e,initialTaskId:n,onTaskCountChange:s,onClose:l}),{runtimeMode:We,workspaceSwitchingEnabled:Qe,currentWorkspaceId:ot,configLoaded:et,cloudAuthConfigured:_t,authRequiredForApi:vt,authBlocked:Ot,isAuthenticated:it,hasBetaAccess:It,authSessionResolved:wt,workspaceBootstrapPending:_n,bootstrapPhase:Dn,bootstrapError:Jn,setupState:ht,runtimeCapabilities:gt,refreshSetupContext:Xn,retryBootstrapChecks:se,createWorkspace:He,saveWorkspaceProfile:Ee,fetchWorkspaces:De,applyWorkspaceSyncStateSnapshot:Me,settingsModel:tt,fetchTasks:Nn,loginWithCredentials:Et,registerWithCredentials:ya,requestEmailVerification:Pn,confirmEmailVerification:Cn,requestPasswordReset:Sn,confirmPasswordReset:ln,inspectInviteAcceptance:Kt,acceptInviteWithToken:yt,joinInviteWithToken:qt,authUserEmail:Ht,currentTheme:sn,logout:ft}=Ie,Ze=a.useMemo(()=>an.find(oe=>oe.id===Xt)||an.find(oe=>oe.isDefaultStarter)||an[0]||null,[Xt,an]);Sf(sn);const Vn=Dp,pn=a.useMemo(()=>{const oe=String(e.cloudAuthBaseUrl||e.apiBaseUrl||"").trim();return oe?oe.replace(/\/+$/,""):""},[e.apiBaseUrl,e.cloudAuthBaseUrl]),$t=We==="cloud"||gt?.runtimeMode==="cloud",Wt=!$t&&_t&&!!pn,Rt=typeof window<"u"&&/^app\./i.test(window.location.hostname),fs=We==="cloud"&&vt,Ds=We==="cloud"&&Ot,aa=p.pathname==="/login",fn=p.pathname==="/setup",sa=p.pathname==="/coming-soon",On=Rt?(!it||Ot)&&!y&&!k&&!b:(fs&&!it||Ds)&&!y&&!k&&!b,$n=We==="cloud"&&it&&!It&&!y&&!k&&!b,Ka=We==="cloud"&&it&&wt&&_e?.canAccessApp===!1&&_e?.canAccessPlans!==!1&&!y&&!k&&!b,Wn=_t,rn=a.useMemo(()=>String(new URLSearchParams(p.search).get("step")||"").trim().toLowerCase(),[p.search]),ra=a.useMemo(()=>String(new URLSearchParams(p.search).get("intent")||"").trim().toLowerCase(),[p.search]),Yt=fn&&rn==="workspace"&&ra==="create-workspace",Fn=c!=="widget"&&!wt&&!aa&&!fn&&!y&&!k&&!b&&(We==="cloud"||Rt),jn=a.useMemo(()=>nM({setupState:ht?{globalSetupState:ht.globalSetupState,workspaceSetupState:ht.workspaceSetupState,runtimeMode:ht.runtimeMode,workspaceId:ht.workspaceId,mode:ht.mode,forceSetup:ht.forceSetup,forceGlobalSetup:ht.forceGlobalSetup,forceWorkspaceSetup:ht.forceWorkspaceSetup}:null,runtimeMode:We,isAuthenticated:it}),[ht,We,it]),xn=jn.setupGateActive,fa=jn.needsGlobalSetup,nt=jn.needsWorkspaceSetup,vn=jn.hasSetupReadError,dn=c!=="widget"&&wt&&!On&&!$n&&!y&&!k&&!b&&(!et||_n||Dn==="stalled")&&(fn||We==="cloud"||Rt),za=a.useMemo(()=>Dn==="auth"?"Verifying session...":Dn==="workspace"?"Resolving workspace access...":Dn==="config"?"Loading configuration...":"Checking account, workspace access, and setup status...",[Dn]),oa=a.useCallback((oe,lt,Ft)=>{const Tt=String(oe||"").trim().toLowerCase(),Tn=String(lt||"").trim().toLowerCase();return!!(!Tt||Tt==="system default workspace"||Tn&&Tt===Tn)},[]);a.useEffect(()=>{const oe=ht?.mode==="operations"?"operations":"core";G(oe)},[ht?.mode]),a.useEffect(()=>{if(We!=="cloud"||!it||!wt){we(null);return}we(null);let oe=!1;return(async()=>{try{const lt=await fetch("/api/taskforce/account/access-status",{method:"GET",credentials:"include"}),Ft=await lt.json().catch(()=>({}));if(oe||!lt.ok)return;const Tt=String(Ft?.gate||"").trim().toLowerCase();if(Tt!=="ok"&&Tt!=="plan_selection_required"&&Tt!=="misconfigured"&&Tt!=="missing_entitlement"){we(null);return}we({gate:Tt,canAccessApp:Ft?.canAccessApp===!0,canAccessPlans:Ft?.canAccessPlans!==!1,message:typeof Ft?.message=="string"?Ft.message:null})}catch{oe||we(null)}})(),()=>{oe=!0}},[wt,it,We,p.pathname,p.search]),a.useEffect(()=>{if(Yt){bt(""),rt("");return}if(!ht)return;const oe=String(ht.workspace?.name||"").trim(),lt=String(ht.suggestedWorkspaceName||"").trim(),Ft=oa(oe,ht.workspaceId,ht.workspace?.description)?lt:oe;bt(Ft||lt||oe),rt(String(ht.workspace?.description||""))},[ht?.workspace?.name,ht?.workspace?.description,ht?.suggestedWorkspaceName,ht?.workspaceId,Yt,oa]),a.useEffect(()=>{if(!fn||rn!=="workspace")return;if(String(new URLSearchParams(p.search).get("source")||"").trim().toLowerCase()==="cloud"&&Wt){F("cloud"),gn(!1);return}F("local")},[Wt,fn,p.search,rn]);const Ya=a.useCallback(async()=>{if(!Wt||!it){St([]),xt("");return}Jt(!0),cn(null);try{const oe=await fetch(`${pn}/api/taskforce/workspaces`,{method:"GET",credentials:"include"}),lt=await oe.json().catch(()=>({}));if(!oe.ok||lt?.success===!1){St([]),xt(""),cn(lt?.error||`Failed to load cloud projects (${oe.status})`);return}const Ft=Array.isArray(lt?.workspaces)?lt.workspaces.map(Tt=>({id:String(Tt?.id||"").trim(),name:String(Tt?.name||Tt?.id||"").trim(),description:typeof Tt?.description=="string"?Tt.description:null})).filter(Tt=>Tt.id.length>0):[];St(Ft),xt(Tt=>Tt&&Ft.some(Tn=>Tn.id===Tt)?Tt:Ft[0]?.id||"")}catch{St([]),xt(""),cn("Failed to load cloud projects.")}finally{Jt(!1)}},[Wt,it,pn]);a.useEffect(()=>{mt==="cloud"&&Ya()},[Ya,mt]),a.useEffect(()=>{if(!fn||rn!=="workspace"||mt==="cloud")return;let oe=!1;return Qt(!0),Ge(null),fetch("/api/taskforce/taxonomy-library",{method:"GET",credentials:"include"}).then(async lt=>{if(!lt.ok)throw new Error(`Failed to load starter libraries (${lt.status})`);const Ft=await lt.json().catch(()=>({})),Tt=Array.isArray(Ft?.packs)?Ft.packs:[];oe||Tt.length===0||(kn(Tt),Gn(Tn=>Tt.some(dt=>dt.id===Tn)?Tn:Tt.find(dt=>dt.isDefaultStarter)?.id||Tt[0]?.id||""))}).catch(lt=>{oe||(kn(yn),Ge(lt instanceof Error?lt.message:"Failed to load starter libraries."))}).finally(()=>{oe||Qt(!1)}),()=>{oe=!0}},[yn,fn,rn,mt]),a.useEffect(()=>{Se(Xm(Ze))},[Xt,Ze]);const Qn=a.useMemo(()=>{const oe=new URLSearchParams(p.search).get("next")||"/";return!oe.startsWith("/")||oe==="/login"?"/":oe},[p.search]),Ta=a.useMemo(()=>{const oe=String(new URLSearchParams(p.search).get("mode")||"").trim().toLowerCase();return oe==="register"?Wn?"register":"login":oe==="verify"||oe==="forgot"||oe==="reset"||oe==="invite"?oe:"login"},[Wn,p.search]),ka=a.useMemo(()=>String(new URLSearchParams(p.search).get("token")||"").trim(),[p.search]),Zn=a.useCallback(oe=>{const lt=new URLSearchParams(p.search),Ft=oe==="register"&&!Wn?"login":oe;Ft==="login"?lt.delete("mode"):lt.set("mode",Ft);const Tt=lt.toString();S(`/login${Tt?`?${Tt}`:""}`,{replace:!0})},[Wn,p.search,S]),hs=a.useCallback(async oe=>{if(!Qe)return!1;const lt=await De();return lt.success?(Array.isArray(lt.workspaces)?lt.workspaces.length:0)===0?(S("/setup?step=workspace",{replace:!0}),!0):!1:oe?(S("/setup?step=workspace",{replace:!0}),!0):!1},[De,S,Qe]);a.useEffect(()=>{aa&&(Ae(Ta),Ta==="verify"&&ka&&ee(ka),Ta==="reset"&&ka&&me(ka),Ta==="invite"&&ka&&R(ka))},[aa,Ta,ka]),a.useEffect(()=>{if(!aa||D!=="invite"||!Y.trim())return;let oe=!0;return(async()=>{const lt=await Kt(Y);if(oe)if(lt.success){fe(lt.email||null),de(lt.workspaceId||null),Ce(lt.passwordRequired===!0);const Ft=!!(it&&Ht&&lt.email&&Ht.trim().toLowerCase()===lt.email.trim().toLowerCase()),Tt=lt.passwordRequired===!0?"new_user":Ft?"existing_user_ready":"existing_user_signed_out";Ve(Tt),x(Tt==="new_user"?"Create your account password to join this workspace.":Tt==="existing_user_ready"?"Invite ready. Confirm to join this workspace.":"Sign in with the invited account to join this workspace."),P(null),M(null)}else fe(null),de(null),Ve("invalid"),Ce(!1),P(Na(lt)),M(lt.code||lt.state||null)})(),()=>{oe=!1}},[aa,D,Y,Kt,it,Ht]),a.useEffect(()=>{D==="invite"&&ae==="existing_user_signed_out"&&B&&Q(oe=>oe.trim()?oe:B)},[D,ae,B]),a.useEffect(()=>{if(!(H>Date.now()||je>Date.now()))return;const lt=window.setInterval(()=>re(Date.now()),1e3);return()=>window.clearInterval(lt)},[H,je]);const en=Math.max(0,Math.ceil((H-ue)/1e3)),Ia=Math.max(0,Math.ceil((je-ue)/1e3)),ha=en>0,Ca=Ia>0,Na=oe=>{const lt=oe.error||"Request failed.",Ft=oe.code||oe.state;return Ft?`[${Ft}] ${lt}`:lt};a.useEffect(()=>{if(c!=="widget"&&!_n){if($n){sa||S("/coming-soon",{replace:!0});return}if(sa&&!$n){S("/",{replace:!0});return}if(On){if(!aa){const oe=`${p.pathname}${p.search}${p.hash}`;S(`/login?next=${encodeURIComponent(oe||"/")}`,{replace:!0});return}return}else{const oe=aa&&D==="invite"&&Y.trim().length>0;aa&&it&&!oe&&S(Qn,{replace:!0})}if(Ka){if(!b){const oe=encodeURIComponent(String(_e?.gate||"plan_selection_required"));S(`/?screen=plans&gate=${oe}`,{replace:!0})}return}if(xn){if(vn){(!fn||rn!=="error")&&S("/setup?step=error",{replace:!0});return}if(fa){(!fn||rn!=="global")&&S("/setup?step=global",{replace:!0});return}if(nt){(!fn||rn!=="workspace")&&S("/setup?step=workspace",{replace:!0});return}fn&&S("/",{replace:!0});return}fn&&ht&&!Yt&&S("/",{replace:!0})}},[c,On,$n,Ka,aa,fn,sa,k,b,_e?.gate,xn,ht,vn,Yt,fa,nt,rn,_n,p.pathname,p.search,p.hash,S,Qn]),a.useEffect(()=>{if(c==="widget"||We!=="local"||!et||aa||fn)return;const oe=String(ot||"").trim().toLowerCase();(!oe||oe==="default")&&S("/setup?step=workspace",{replace:!0})},[c,We,et,aa,fn,ot,S]);const Us=a.useCallback(async()=>{J(!0);try{await se()}finally{J(!1)}},[se]),io=a.useCallback(async()=>{await ft(),S("/login",{replace:!0})},[ft,S]);if(c==="widget")return t.jsx(IR,{...Ie,onHeaderMouseDown:r,isDragging:o,onClose:l});if(y){const oe=new URLSearchParams(p.search);return oe.set("screen","plans"),t.jsx(fm,{to:`/?${oe.toString()}${p.hash||""}`,replace:!0})}if(k){const oe=new URLSearchParams(p.search);return oe.set("screen","plans"),t.jsx(fm,{to:`/?${oe.toString()}${p.hash||""}`,replace:!0})}if(Fn)return t.jsx("div",{className:hn.standaloneWrapper,"data-theme":sn,children:t.jsx("div",{className:ve.loginView,children:t.jsxs("div",{className:ve.loginCard,children:[t.jsxs("div",{className:ve.authBrandRow,children:[t.jsx("img",{src:Vn,alt:"Taskforce",className:ve.loginLogo}),t.jsx("h1",{className:ve.loginTitle,children:"Loading Taskforce"})]}),t.jsx("p",{className:ve.loginSubtitle,children:"Checking your session..."})]})})});if(dn)return t.jsx("div",{className:hn.standaloneWrapper,"data-theme":sn,children:t.jsx("div",{className:ve.loginView,children:t.jsxs("div",{className:ve.loginCard,children:[t.jsxs("div",{className:ve.authBrandRow,children:[t.jsx("img",{src:Vn,alt:"Taskforce",className:ve.loginLogo}),t.jsx("h1",{className:ve.loginTitle,children:"Loading Taskforce"})]}),t.jsx("p",{className:ve.loginSubtitle,children:za}),Dn==="stalled"&&t.jsxs(t.Fragment,{children:[t.jsx("p",{className:ve.loginError,children:Jn||"Startup checks timed out."}),t.jsx("button",{className:u.submitBtn,disabled:An,onClick:Us,children:An?"Retrying...":"Retry checks"}),$t&&t.jsx("button",{className:u.cancelBtn,disabled:An,onClick:io,children:"Go to sign-in"})]})]})})});if(aa)return t.jsx("div",{className:hn.standaloneWrapper,"data-theme":sn,children:t.jsx("div",{className:ve.loginView,style:{backgroundImage:`linear-gradient(rgba(15, 15, 26, 0.88), rgba(15, 15, 26, 0.9)), url(${vp})`},children:t.jsxs("div",{className:ve.loginCard,children:[!$t&&!On&&t.jsx("button",{className:ve.loginCloseBtn,"aria-label":"Close sign in",onClick:()=>S(Qn,{replace:!0}),children:"×"}),t.jsxs("div",{className:ve.authBrandRow,children:[t.jsx("img",{src:Vn,alt:"Taskforce",className:ve.loginLogo}),t.jsxs("h1",{className:ve.loginTitle,children:["TASKFORCE ",t.jsx("span",{className:ve.loginTitleAccent,children:"HQ"})]})]}),t.jsxs("p",{className:ve.loginSubtitle,children:[D==="login"&&"Sign in with your account credentials.",D==="register"&&"Create your Taskforce account.",D==="verify"&&"Enter your verification token.",D==="forgot"&&"Request a password reset link.",D==="reset"&&"Set a new password using your reset token.",D==="invite"&&(ae==="existing_user_ready"?`You've been invited to join ${Ne||"this workspace"}.`:ae==="existing_user_signed_out"?"Sign in to join this workspace.":"Create your account to join this workspace.")]}),(D==="login"||D==="register"||D==="forgot"||D==="invite"&&ae==="existing_user_signed_out")&&t.jsx("input",{className:`${u.input} ${ve.loginInput}`,type:"email",value:W,placeholder:"Email",onChange:oe=>Q(oe.target.value)}),D==="register"&&t.jsx("input",{className:`${u.input} ${ve.loginInput}`,type:"text",value:z,placeholder:"Display name",onChange:oe=>K(oe.target.value)}),(D==="login"||D==="register"||D==="reset"||D==="invite"&&(Re||ae==="existing_user_signed_out"))&&t.jsx("input",{className:`${u.input} ${ve.loginInput}`,type:"password",value:V,placeholder:D==="reset"?"New password":D==="invite"&&Re?"Create password":"Password",onChange:oe=>ne(oe.target.value)}),D==="verify"&&t.jsx("input",{className:`${u.input} ${ve.loginInput}`,type:"text",value:U,placeholder:"Verification token",onChange:oe=>ee(oe.target.value)}),D==="reset"&&t.jsx("input",{className:`${u.input} ${ve.loginInput}`,type:"text",value:be,placeholder:"Reset token",onChange:oe=>me(oe.target.value)}),D==="invite"&&t.jsxs(t.Fragment,{children:[t.jsx("input",{className:`${u.input} ${ve.loginInput}`,type:"text",value:Y,placeholder:"Invite token",onChange:oe=>R(oe.target.value)}),B&&t.jsxs("p",{className:ve.loginSubtitle,children:["Invite for: ",t.jsx("strong",{children:B}),Ne?` · Workspace: ${Ne}`:""]})]}),Fe&&t.jsx("p",{className:ve.loginSubtitle,children:Fe}),L&&t.jsx("p",{className:ve.loginError,children:L}),D==="login"&&Z==="EMAIL_NOT_VERIFIED"&&W.trim()&&t.jsx("button",{className:ve.authModeLink,disabled:h||ha,onClick:async()=>{A(!0),x(null);const oe=await Pn(W);oe.success?(j(Date.now()+3e4),Zn("verify"),oe.verificationToken&&ee(oe.verificationToken),x("Verification email resent."),P(null),M(null)):P(Na(oe)),A(!1)},children:ha?`Resend in ${en}s`:"Resend Verification Email"}),t.jsx("button",{className:`${u.submitBtn} ${ve.loginPrimaryBtn}`,disabled:h||D==="verify"&&ha||D==="forgot"&&Ca,onClick:async()=>{if(A(!0),x(null),P(null),M(null),D==="register"&&!z.trim()){P("Display name is required."),A(!1);return}let oe={success:!1};if(D==="login"?oe=await Et(W,V):D==="register"?oe=await ya(W,V,{displayName:z,planId:w||void 0,planVersionId:C||void 0,interval:_||void 0}):D==="verify"?oe=await Cn(U):D==="forgot"?oe=await Sn(W):D==="reset"?oe=await ln(be,V):D==="invite"&&(ae==="existing_user_signed_out"?oe=await Et(W,V):oe=Re?await yt(Y,V):await qt(Y)),oe.success)if(D==="register"){if(await hs(oe.workspaceSetupRequired)){A(!1);return}oe.verificationRequired?(oe.verificationToken&&ee(oe.verificationToken),j(Date.now()+3e4),Zn("verify"),x(oe.emailSent===!1?`Account created, but verification email failed to send. ${oe.emailError||"Try Resend Verification again."}`:"Account created. Check your email for verification instructions.")):(Q(""),K(""),ne(""),S(Qn,{replace:!0}))}else if(D==="verify")await se(),Q(""),ne(""),S(Qn,{replace:!0});else if(D==="forgot")oe.resetToken&&me(oe.resetToken),O(Date.now()+3e4),Zn("reset"),x(oe.emailSent===!1?`Password reset email failed to send. ${oe.emailError||"Try again in a minute."}`:"Password reset instructions sent.");else if(D==="reset")Zn("login"),x("Password updated. Sign in with your new password.");else if(D==="invite"){if(ae==="existing_user_signed_out"){Ae("invite"),ne(""),x("Signed in. Review the invite details to continue."),A(!1);return}if(oe.workspaceSetupRequired){S("/setup?step=workspace",{replace:!0}),A(!1);return}S(Qn,{replace:!0})}else if(D==="login"){if(Y.trim()){Ae("invite"),ne(""),x("Signed in. Review the invite details to continue."),A(!1);return}if(oe.workspaceSetupRequired){S("/setup?step=workspace",{replace:!0}),A(!1);return}Q(""),K(""),ne(""),S(Qn,{replace:!0})}else Q(""),K(""),ne(""),S(Qn,{replace:!0});else{if(D==="register"&&(oe.code==="SIGNUP_PLAN_NOT_ENABLED"||oe.code==="SIGNUP_PLAN_VERSION_NOT_FOUND"||oe.code==="SIGNUP_PLAN_VERSION_REQUIRED")){S(E,{replace:!0}),A(!1);return}if(P(Na(oe)),M(oe.code||null),D==="login"&&(oe.code==="WORKSPACE_NOT_FOUND"||oe.code==="WORKSPACE_ID_REQUIRED")){S("/setup?step=workspace",{replace:!0}),A(!1);return}if(D==="login"&&oe.code==="EMAIL_NOT_VERIFIED"&&W.trim()){const lt=await Pn(W);lt.success&&(j(Date.now()+3e4),Zn("verify"),lt.verificationToken&&ee(lt.verificationToken),x("Email not verified. A verification token was sent."),P(null),M(null))}}A(!1)},children:h?"Working...":D==="login"?"Sign In":D==="register"?"Create Account":D==="verify"?ha?`Resend in ${en}s`:"Resend Verification":D==="forgot"?Ca?`Retry in ${Ia}s`:"Send Reset Link":D==="reset"?"Reset Password":ae==="existing_user_signed_out"?"Sign In to Continue":Re?"Create Account and Join":"Join Workspace"}),D==="register"&&t.jsxs("p",{className:ve.registerConsent,children:["By creating an account, you agree to the"," ",t.jsx("a",{className:ve.registerConsentLink,href:"https://taskforcehq.com/legal/terms",target:"_blank",rel:"noopener noreferrer",children:"Terms of Service"})," ","and acknowledge the"," ",t.jsx("a",{className:ve.registerConsentLink,href:"https://taskforcehq.com/legal/privacy",target:"_blank",rel:"noopener noreferrer",children:"Privacy Policy"}),"."]}),Wn&&(D==="login"||D==="register")&&t.jsxs("p",{className:ve.authModeSwitch,children:[D==="login"?"Need an account?":"Already have an account?"," ",t.jsx("button",{className:ve.authModeSwitchLink,disabled:h,onClick:()=>{P(null),M(null),x(null),Zn(D==="login"?"register":"login")},children:D==="login"?"Register":"Sign In"})]}),t.jsxs("div",{className:ve.authModeLinks,children:[(D==="login"||D==="register")&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:ve.authModeLink,disabled:h||Ca,onClick:()=>{P(null),M(null),x(null),Zn("forgot")},children:Ca?`Forgot Password (${Ia}s)`:"Forgot Password"}),t.jsx("button",{className:ve.authModeLink,disabled:h||ha,onClick:()=>{P(null),M(null),x(null),Zn("verify")},children:ha?`Resend Verification (${en}s)`:"Resend Verification"}),t.jsx("button",{className:ve.authModeLink,disabled:h,onClick:()=>{P(null),M(null),x(null),Zn("invite")},children:"Accept Invite"})]}),D!=="login"&&D!=="register"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:ve.authModeLink,disabled:h,onClick:()=>{P(null),M(null),x(null),Zn("login")},children:"Sign In"}),Wn&&t.jsx("button",{className:ve.authModeLink,disabled:h,onClick:()=>{P(null),M(null),x(null),Zn("register")},children:"Register"}),D==="reset"&&t.jsx("button",{className:ve.authModeLink,disabled:h||Ca,onClick:()=>{P(null),M(null),x(null),Zn("forgot")},children:Ca?`Forgot Password (${Ia}s)`:"Forgot Password"})]})]})]})})});if(On&&!aa)return t.jsx("div",{className:hn.standaloneWrapper,"data-theme":sn,children:t.jsx("div",{className:ve.loginView,children:t.jsxs("div",{className:ve.loginCard,children:[t.jsxs("div",{className:ve.authBrandRow,children:[t.jsx("img",{src:Vn,alt:"Taskforce",className:ve.loginLogo}),t.jsx("h1",{className:ve.loginTitle,children:"Loading Taskforce"})]}),t.jsx("p",{className:ve.loginSubtitle,children:"Redirecting to sign in..."})]})})});if(sa&&$n)return t.jsx("div",{className:hn.standaloneWrapper,"data-theme":sn,children:t.jsx("div",{className:ve.loginView,style:{backgroundImage:`linear-gradient(rgba(15, 15, 26, 0.88), rgba(15, 15, 26, 0.9)), url(${vp})`},children:t.jsxs("div",{className:ve.loginCard,children:[t.jsxs("div",{className:ve.authBrandRow,children:[t.jsx("img",{src:Vn,alt:"Taskforce",className:ve.loginLogo}),t.jsx("h1",{className:ve.loginTitle,children:"Private Beta"})]}),t.jsx("p",{className:ve.loginSubtitle,children:"You are signed in, but your account is not in the beta allowlist yet."}),t.jsx("p",{className:ve.loginSubtitle,children:"You will see the full app as soon as beta access is enabled."}),t.jsx("button",{className:u.cancelBtn,onClick:async()=>{await Ie.logout(),S("/login",{replace:!0})},children:"Sign Out"})]})})});if(Yt||fn&&xn&&(vn||fa||nt)){const oe=!Yt&&(vn||rn==="error"),lt=!Yt&&!oe&&(fa||rn==="global"),Ft=oe?xe("setup.headingCheckFailed"):lt?xe("setup.headingGlobalRequired"):Yt?"Create Workspace":xe("setup.headingWorkspaceRequired"),Tt=oe?xe("setup.subtitleUnreadable"):lt?xe("setup.subtitleGlobalRequired"):Yt?"Set up the new workspace before it is created.":xe("setup.subtitleWorkspaceRequired"),Tn=xe(pe==="operations"?"setup.workspaceTermMission":"setup.workspaceTermProject");return t.jsx("div",{className:hn.standaloneWrapper,"data-theme":sn,children:t.jsx("div",{className:ve.loginView,style:{backgroundImage:`linear-gradient(rgba(15, 15, 26, 0.88), rgba(15, 15, 26, 0.9)), url(${vp})`},children:t.jsxs("div",{className:ve.loginCard,children:[t.jsxs("div",{className:ve.authBrandRow,children:[t.jsx("img",{src:Vn,alt:"Taskforce",className:ve.loginLogo}),t.jsxs("h1",{className:ve.loginTitle,children:["TASKFORCE ",t.jsx("span",{className:ve.loginTitleAccent,children:"HQ"})]})]}),t.jsx("p",{className:ve.loginSubtitle,children:t.jsx("strong",{children:Ft})}),t.jsx("p",{className:ve.loginSubtitle,children:Tt}),gt&&t.jsxs("p",{className:ve.loginSubtitle,children:[xe("setup.runtimeLabel"),": ",t.jsx("strong",{children:gt.runtimeMode})]}),ze&&t.jsx("p",{className:ve.loginSubtitle,children:ze}),Be&&t.jsx("p",{className:ve.loginError,children:Be}),lt&&t.jsxs("div",{className:ve.optionGrid,children:[t.jsxs("label",{className:`${ve.authModeLink} ${ve.optionRow}`,children:[t.jsx("input",{type:"radio",name:"setup-mode",value:"core",checked:pe==="core",onChange:()=>G("core"),disabled:q}),t.jsx("span",{children:xe("setup.coreModeOption",{workspaceLabel:Tn})})]}),t.jsxs("label",{className:`${ve.authModeLink} ${ve.optionRow}`,children:[t.jsx("input",{type:"radio",name:"setup-mode",value:"operations",checked:pe==="operations",onChange:()=>G("operations"),disabled:q}),t.jsx("span",{children:xe("setup.operationsModeOption")})]})]}),!oe&&!lt&&t.jsxs("div",{className:ve.optionGrid,children:[!$t&&Wt&&t.jsxs("div",{className:ve.optionGroup,children:[t.jsxs("label",{className:`${ve.authModeLink} ${ve.optionRow}`,children:[t.jsx("input",{type:"radio",name:"workspace-setup-source",value:"local",checked:mt==="local",onChange:()=>F("local"),disabled:q}),t.jsxs("span",{children:["Create new local ",Tn.toLowerCase()]})]}),t.jsxs("label",{className:`${ve.authModeLink} ${ve.optionRow}`,children:[t.jsx("input",{type:"radio",name:"workspace-setup-source",value:"cloud",checked:mt==="cloud",onChange:()=>F("cloud"),disabled:q}),t.jsxs("span",{children:["Sync existing cloud ",Tn.toLowerCase()]})]})]}),!$t&&mt==="cloud"&&Wt?t.jsxs("div",{className:ve.optionGroup,children:[!it&&t.jsxs(t.Fragment,{children:[t.jsx("p",{className:ve.inlineHint,children:"Sign in to choose one of your cloud projects."}),t.jsx("button",{className:u.cancelBtn,disabled:q,onClick:()=>{S(`/login?mode=login&next=${encodeURIComponent("/setup?step=workspace&source=cloud")}`,{replace:!0})},children:"Sign In"})]}),it&&t.jsxs(t.Fragment,{children:[t.jsxs("select",{className:u.input,value:Lt,onChange:dt=>xt(dt.target.value),disabled:q||Zt||Ke.length===0,children:[Ke.length===0&&t.jsx("option",{value:"",children:Zt?"Loading cloud projects...":"No cloud projects found"}),Ke.map(dt=>t.jsxs("option",{value:dt.id,children:[dt.name," (",dt.id,")"]},dt.id))]}),t.jsx("div",{className:ve.actionRowEnd,children:t.jsx("button",{className:u.cancelBtn,disabled:q||Zt,onClick:()=>{Ya()},children:"Refresh Cloud Projects"})}),on&&t.jsx("p",{className:ve.loginError,children:on})]})]}):t.jsxs(t.Fragment,{children:[t.jsx("input",{className:u.input,type:"text",value:Xe,placeholder:xe("setup.workspaceNamePlaceholder",{workspaceLabel:Tn}),onChange:dt=>bt(dt.target.value),disabled:q}),t.jsx("textarea",{className:u.textarea,value:d,placeholder:xe("setup.workspaceDescriptionPlaceholder",{workspaceLabel:Tn}),onChange:dt=>rt(dt.target.value),disabled:q,rows:4}),t.jsxs("div",{className:ve.optionGroup,children:[t.jsx("p",{className:ve.loginSubtitle,children:"What are you working on?"}),t.jsx("p",{className:ve.inlineHint,children:"Choose a starter taxonomy library for this workspace. You can still edit categories, task types, and priorities later."}),an.map(dt=>{const wn=Ze?.id===dt.id;return t.jsxs("label",{className:`${ve.authModeLink} ${ve.optionRow}`,children:[t.jsx("input",{type:"radio",name:"workspace-taxonomy-library",checked:wn,onChange:()=>Gn(dt.id),disabled:q||Mt}),t.jsx("span",{children:dt.label})]},dt.id)}),Ze?t.jsxs(t.Fragment,{children:[t.jsx("p",{className:ve.inlineHint,children:Ze.description}),t.jsxs("p",{className:ve.inlineHint,children:["Includes ",Ze.categories.length," categories, ",Ze.types.length," task types, and ",Ze.priorities.length," priority levels."]})]}):null,t.jsxs("div",{className:ve.optionGroup,children:[t.jsx("p",{className:ve.loginSubtitle,children:"Apply Starter Sections"}),t.jsxs("label",{className:`${ve.authModeLink} ${ve.optionRow}`,children:[t.jsx("input",{type:"checkbox",checked:At.categories,onChange:()=>Se(dt=>({...dt,categories:!dt.categories})),disabled:q||!Ze?.categories.length}),t.jsx("span",{children:"Categories"})]}),t.jsxs("label",{className:`${ve.authModeLink} ${ve.optionRow}`,children:[t.jsx("input",{type:"checkbox",checked:At.types,onChange:()=>Se(dt=>({...dt,types:!dt.types})),disabled:q||!Ze?.types.length}),t.jsx("span",{children:"Task Types"})]}),t.jsxs("label",{className:`${ve.authModeLink} ${ve.optionRow}`,children:[t.jsx("input",{type:"checkbox",checked:At.priorities,onChange:()=>Se(dt=>({...dt,priorities:!dt.priorities})),disabled:q||!Ze?.priorities.length}),t.jsx("span",{children:"Priorities"})]})]}),Mt?t.jsx("p",{className:ve.inlineHint,children:"Loading starter libraries…"}):null,zt?t.jsx("p",{className:ve.loginError,children:zt}):null]}),!$t&&Wt&&it&&t.jsxs("div",{className:ve.optionGroup,children:[t.jsxs("label",{className:`${ve.authModeLink} ${ve.optionRow}`,children:[t.jsx("input",{type:"checkbox",checked:nn,onChange:dt=>gn(dt.target.checked),disabled:q}),t.jsx("span",{children:"Sync to cloud after setup"})]}),t.jsx("p",{className:ve.inlineHint,children:"When enabled, this project will connect to cloud sync as soon as setup finishes."})]})]})]}),t.jsxs("div",{className:ve.authModeLinks,children:[lt?t.jsx("button",{className:u.submitBtn,disabled:q,onClick:async()=>{ye(!0),Ye(null),le(null);try{const dt=await fetch("/api/taskforce/global-settings",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({setup:{mode:pe}})}),wn=await dt.json().catch(()=>({}));!dt.ok||wn?.success===!1?le(wn?.error||xe("setup.saveFailedWithStatus",{status:dt.status})):(Ye(xe("setup.globalSetupSaved")),await Xn())}catch{le(xe("setup.saveFailed"))}finally{ye(!1)}},children:xe(q?"setup.saving":"setup.saveGlobalSetup")}):oe?t.jsx("button",{className:u.submitBtn,disabled:q,onClick:Xn,children:xe("setup.retrySetupCheck")}):t.jsx("button",{className:u.submitBtn,disabled:q,onClick:async()=>{if(ye(!0),Ye(null),le(null),!$t&&mt==="cloud"&&Wt){if(!it){le("Sign in is required before syncing a cloud project."),ye(!1);return}const dt=Ke.find(Kn=>Kn.id===Lt);if(!dt){le("Select a cloud project to sync."),ye(!1);return}const wn=await Ee({workspaceId:dt.id,name:dt.name||dt.id,description:dt.description||void 0});if(!wn.success){le(wn.error||xe("setup.saveWorkspaceFailed")),ye(!1);return}const ia=String(wn.workspaceId||dt.id||"").trim();if(!ia){le("Failed to resolve workspace id for sync setup."),ye(!1);return}const ga=await fetch("/api/taskforce/ui-state",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({workspaceId:ia,stateKey:"workspace-sync",patch:{version:2,enabled:!0,phase:"attach-cloud",pullCursor:null,lastPullAt:null,lastPushAt:null,lastSyncedAt:null}})}),ja=await ga.json().catch(()=>({}));if(!ga.ok||ja?.success===!1){le(ja?.error||`Failed to configure workspace sync (${ga.status})`),ye(!1);return}Me({enabled:!0,phase:"attach-cloud",pullCursor:null}),await Xn(),Ye(`Cloud project synced setup ready: ${dt.name}`)}else{const dt=Yt||ht?.workspaceSetupState==="missing",wn=Yt?await He(Xe,d||void 0):null,ia=Yt?null:await Ee({workspaceId:dt?void 0:ht?.workspaceId,name:Xe,description:d}),ga=wn||ia;if(!ga?.success)le(ga?.error||xe("setup.saveWorkspaceFailed"));else{const ja=String(wn?.workspace?.id||ia?.workspaceId||ht?.workspaceId||"").trim();if(!ja){le("Failed to resolve workspace id for setup."),ye(!1);return}if(mt==="local"&&!!Ze&&(At.categories||At.types||At.priorities)&&Ze){const ca=await tt.onApplySystemTaxonomyPack({pack:Ze,sections:At,remapExistingValuesToDefault:!0,workspaceIdOverride:ja});if(!ca?.success){le(ca?.error||"Failed to apply starter taxonomy library."),ye(!1);return}}const ea=!!(!$t&&nn&&Wt&&it),Ra=await fetch("/api/taskforce/ui-state",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({workspaceId:ja,stateKey:"workspace-sync",patch:{version:2,enabled:ea,phase:ea?"provision-local":"idle",pullCursor:null,lastPullAt:null,lastPushAt:null,lastSyncedAt:null}})}),pa=await Ra.json().catch(()=>({}));if(!Ra.ok||pa?.success===!1){le(pa?.error||`Failed to configure workspace sync (${Ra.status})`),ye(!1);return}Me({enabled:ea,phase:ea?"provision-local":"idle",pullCursor:null}),Ye(ea?`${Tn} setup saved. Cloud sync enabled.`:xe("setup.workspaceSetupSaved",{workspaceLabel:Tn})),Yt&&(await Xn(),await Nn(!0),S("/",{replace:!0}))}}ye(!1)},children:q?xe("setup.saving"):xe("setup.saveWorkspaceSetup",{workspaceLabel:Tn})}),Yt?t.jsx("button",{className:u.cancelBtn,onClick:()=>{le(null),Ye(null),S("/",{replace:!0})},children:"Cancel"}):We==="cloud"?t.jsx("button",{className:u.cancelBtn,onClick:async()=>{await Ie.logout(),S("/login",{replace:!0})},children:xe("setup.signOut")}):null]})]})})})}return t.jsx(tM,{...Ie,onHeaderMouseDown:r,isDragging:o,onClose:l})}function aM(e){return jg()?t.jsx(Qm,{...e}):t.jsx(Rg,{children:t.jsx(Qm,{...e})})}const vh={},ef="STAGING_MARKER_2026_02_24";typeof window<"u"&&(window.__TASKFORCE_BUILD_MARKER=ef,console.info(`[Taskforce] Build marker: ${ef}`));function sM(){return Op(vh).apiBaseUrl||void 0}function rM(e){const n=Op(vh),s=n.cloudAuthBaseUrl;if(s)if(typeof window<"u"){const r=window.location.hostname.toLowerCase(),o=r==="localhost"||r==="127.0.0.1"||r==="::1",l="".trim().toLowerCase()==="true";if(!o&&!l)try{const c=new URL(s,window.location.origin);if(c.origin!==window.location.origin)console.warn(`[Taskforce] Ignoring cross-origin cloud auth base in hosted runtime: ${c.origin}`);else return s}catch{}else return s}else return s;if(n.baseUrl)return n.baseUrl;if(e)return e}function oM(){const e=sM(),n=rM(e);return t.jsx(Dg,{children:t.jsx(aM,{mode:"standalone",config:{apiEndpoint:"/api/taskforce/task",apiBaseUrl:e,cloudAuthBaseUrl:n}})})}Gh.createRoot(document.getElementById("root")).render(t.jsx(pt.StrictMode,{children:t.jsx(oM,{})}));export{yM as A,qP as B,HP as C,Ic as D,Ni as I,oo as M,kM as P,Zf as R,Rl as T,yu as a,ms as b,Sy as c,Ug as d,Bn as e,Hd as f,eu as g,lN as h,aS as i,SM as j,dN as k,Hf as l,lR as m,Le as n,Wy as o,zf as p,nu as q,_a as r,au as s,u as t,hM as u,mM as v,gM as w,fM as x,zp as y,Um as z};